system HF Staff commited on
Commit
24d97ce
ยท
verified ยท
1 Parent(s): a0cf3a8

Sync from felladrin/MiniSearch@165e4b2 (part 2)

Browse files
docs/search-history.md CHANGED
@@ -10,7 +10,7 @@ The `HistoryDatabase` Dexie instance stores three related tables:
10
 
11
  1. `searches` โ€“ canonical log of each query plus hydrated results payloads (text, image, run metadata, source, pin state).
12
  2. `llmResponses` โ€“ snapshot of every AI answer tied to its originating search run, enabling restoration of the assistant output.
13
- 3. `chatHistory` โ€“ chronological record of chat turns (user/assistant roles) scoped by `conversationId` (the `searchRunId`).
14
 
15
  A pinned search carries `pinned: true` and a `pinnedAt` timestamp, and `togglePin` writes both in one update. Schema version 3 indexes `pinnedAt` in place of `pinned`: IndexedDB does not index boolean values, so the `pinned` index never held an entry, while an entry without `pinnedAt` simply stays out of its index. The version 3 upgrade gives searches pinned before it a `pinnedAt` equal to their own `timestamp`, since their real pin time is unknown.
16
 
@@ -18,7 +18,7 @@ All three tables share a `searchRunId` foreign key so restoring a specific run c
18
 
19
  ## Disabled History
20
 
21
- When `enableHistory` is off, `isHistoryEnabled()` makes every history write (`addSearchToHistory`, `updateSearchResults`, `saveLlmResponseForQuery`, `saveChatMessageForQuery`, the follow-up question chat entries) and the `useSearchHistory` reads return without touching IndexedDB. Skipping `historyDatabase.open()` at startup is not enough on its own: Dexie opens a database that was never opened on its first query, so the setting, not the open state, decides.
22
 
23
  ## Cleanup Guarantees
24
 
 
10
 
11
  1. `searches` โ€“ canonical log of each query plus hydrated results payloads (text, image, run metadata, source, pin state).
12
  2. `llmResponses` โ€“ snapshot of every AI answer tied to its originating search run, enabling restoration of the assistant output.
13
+ 3. `chatHistory` โ€“ chronological record of chat turns (user/assistant roles) scoped by `conversationId` (the `searchRunId`). It is written only by `replaceChatConversation`, which replaces a conversation's rows in one transaction, so a regenerated answer, an edit or a failed send is stored exactly as the chat shows it. Regenerating or retrying the main answer keeps the `searchRunId`, so `searchAndRespond` clears that run's conversation once the new answer is saved (a stopped or failed regenerate keeps both), and a follow-up that started before the regenerate stores nothing.
14
 
15
  A pinned search carries `pinned: true` and a `pinnedAt` timestamp, and `togglePin` writes both in one update. Schema version 3 indexes `pinnedAt` in place of `pinned`: IndexedDB does not index boolean values, so the `pinned` index never held an entry, while an entry without `pinnedAt` simply stays out of its index. The version 3 upgrade gives searches pinned before it a `pinnedAt` equal to their own `timestamp`, since their real pin time is unknown.
16
 
 
18
 
19
  ## Disabled History
20
 
21
+ When `enableHistory` is off, `isHistoryEnabled()` makes every history write (`addSearchToHistory`, `updateSearchResults`, `saveLlmResponseForQuery`, `replaceChatConversation`) and the `useSearchHistory` reads return without touching IndexedDB. Skipping `historyDatabase.open()` at startup is not enough on its own: Dexie opens a database that was never opened on its first query, so the setting, not the open state, decides.
22
 
23
  ## Cleanup Guarantees
24
 
docs/ui-components.md CHANGED
@@ -378,6 +378,8 @@ const { restoreSearch } = useHistoryRestore(updateQuery, textAreaRef);
378
 
379
  `restoreSearch` marks the entry's query as handled in `modules/autoSearch.ts` before it changes the URL, the same mark the URL auto-search and a submit set, so an entry that restores empty (a failed search, zero results with AI off, an abandoned search) does not fall through to the URL auto-search and get a duplicate history entry.
380
 
 
 
381
  **Features:**
382
 
383
  - Fuzzy search through history
 
378
 
379
  `restoreSearch` marks the entry's query as handled in `modules/autoSearch.ts` before it changes the URL, the same mark the URL auto-search and a submit set, so an entry that restores empty (a failed search, zero results with AI off, an abandoned search) does not fall through to the URL auto-search and get a duplicate history entry.
380
 
381
+ It replaces the chat with the entry's stored conversation, except when the entry is the search already on screen and one of its follow-ups is still being answered: that chat stays mounted and saves the answer when it lands, so the stored list, which lacks the turn, is not published over it.
382
+
383
  **Features:**
384
 
385
  - Fuzzy search through history
package-lock.json CHANGED
@@ -96,9 +96,9 @@
96
  "license": "MIT"
97
  },
98
  "node_modules/@ai-sdk/gateway": {
99
- "version": "4.0.152",
100
- "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-4.0.152.tgz",
101
- "integrity": "sha512-8LYMe0uMPbT3XW/Urhca52TSgHXAlQok74EUkWL3qXWJI7naTxJGSF6B7hvIHur+V6ttSyLLZN0rJk+Qu9psqA==",
102
  "license": "Apache-2.0",
103
  "dependencies": {
104
  "@ai-sdk/provider": "4.0.39",
@@ -2839,12 +2839,12 @@
2839
  }
2840
  },
2841
  "node_modules/ai": {
2842
- "version": "7.0.179",
2843
- "resolved": "https://registry.npmjs.org/ai/-/ai-7.0.179.tgz",
2844
- "integrity": "sha512-WT2ad3qEQPLne/5RDE/utNMSKYUuNpnGkI46AO/6Lv+IbEJ3kRwbatLX3HNfk25Y7N8LpdqOcSnMLcdw11VyIQ==",
2845
  "license": "Apache-2.0",
2846
  "dependencies": {
2847
- "@ai-sdk/gateway": "4.0.152",
2848
  "@ai-sdk/provider": "4.0.39",
2849
  "@ai-sdk/provider-utils": "5.0.83"
2850
  },
 
96
  "license": "MIT"
97
  },
98
  "node_modules/@ai-sdk/gateway": {
99
+ "version": "4.0.154",
100
+ "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-4.0.154.tgz",
101
+ "integrity": "sha512-7noB6L/iZ55MRey35rrcbB/J+rAeyRafhJP6G/+/CkOSHxrcdFeMEbtvdIuXTr5S+AAMMQpka+xnD4zVwn04Sw==",
102
  "license": "Apache-2.0",
103
  "dependencies": {
104
  "@ai-sdk/provider": "4.0.39",
 
2839
  }
2840
  },
2841
  "node_modules/ai": {
2842
+ "version": "7.0.181",
2843
+ "resolved": "https://registry.npmjs.org/ai/-/ai-7.0.181.tgz",
2844
+ "integrity": "sha512-b38KYt7tb/dZkujHZTlLWmhohj2bVbWsZQwAJ8Lt6O2hC8saFfIUEFl1U3RwS8tbQ3cL9nAUpeJiiwhsHuBT3w==",
2845
  "license": "Apache-2.0",
2846
  "dependencies": {
2847
+ "@ai-sdk/gateway": "4.0.154",
2848
  "@ai-sdk/provider": "4.0.39",
2849
  "@ai-sdk/provider-utils": "5.0.83"
2850
  },
server/internalApiEndpointServerHook.test.ts CHANGED
@@ -45,7 +45,16 @@ function createRequest(
45
  method = "POST",
46
  contentType = "application/json",
47
  ): IncomingMessage {
48
- const request = Readable.from([JSON.stringify(body)]) as IncomingMessage;
 
 
 
 
 
 
 
 
 
49
  request.url = "/inference?token=abc";
50
  request.method = method;
51
  request.headers = {
@@ -122,6 +131,187 @@ function streamOf(
122
  };
123
  }
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  describe("internalApiEndpointServerHook", () => {
126
  beforeEach(() => {
127
  vi.resetAllMocks();
@@ -156,7 +346,7 @@ describe("internalApiEndpointServerHook", () => {
156
  await handler(request, response, vi.fn());
157
  expect(response.statusCode).toBe(405);
158
  expect(response.setHeader).toHaveBeenCalledWith("Allow", "POST");
159
- const payload = JSON.parse(response.end.mock.calls[0][0]);
160
  expect(payload.error).toBe("Method Not Allowed");
161
  });
162
 
@@ -166,7 +356,7 @@ describe("internalApiEndpointServerHook", () => {
166
  const request = createRequest({}, "POST", "text/plain");
167
  await handler(request, response, vi.fn());
168
  expect(response.statusCode).toBe(415);
169
- const payload = JSON.parse(response.end.mock.calls[0][0]);
170
  expect(payload.error).toBe("Unsupported Media Type");
171
  });
172
 
@@ -250,7 +440,7 @@ describe("internalApiEndpointServerHook", () => {
250
  const response = createResponse();
251
  await handler(createRequest(body), response, vi.fn());
252
  expect(response.statusCode).toBe(400);
253
- const payload = JSON.parse(response.end.mock.calls[0][0]);
254
  expect(payload.error).toContain(`Invalid request body: ${expectedPath}`);
255
  });
256
 
@@ -258,32 +448,20 @@ describe("internalApiEndpointServerHook", () => {
258
  const handler = getRegisteredHandler();
259
  const response = createResponse();
260
  const chunk600k = "x".repeat(600 * 1024);
261
- const request = Readable.from([chunk600k, chunk600k]) as IncomingMessage;
262
- request.url = "/inference?token=abc";
263
- request.method = "POST";
264
- request.headers = {
265
- host: "localhost:3000",
266
- "content-type": "application/json",
267
- };
268
  await handler(request, response, vi.fn());
269
  expect(response.statusCode).toBe(413);
270
- const payload = JSON.parse(response.end.mock.calls[0][0]);
271
  expect(payload.error).toBe("Request body too large");
272
  });
273
 
274
  it("responds 400 when body is not valid JSON", async () => {
275
  const handler = getRegisteredHandler();
276
  const response = createResponse();
277
- const request = Readable.from(["not json at all"]) as IncomingMessage;
278
- request.url = "/inference?token=abc";
279
- request.method = "POST";
280
- request.headers = {
281
- host: "localhost:3000",
282
- "content-type": "application/json",
283
- };
284
  await handler(request, response, vi.fn());
285
  expect(response.statusCode).toBe(400);
286
- const payload = JSON.parse(response.end.mock.calls[0][0]);
287
  expect(payload.error).toBe("Invalid request body");
288
  });
289
  });
@@ -292,15 +470,9 @@ describe("internalApiEndpointServerHook", () => {
292
  it("responds 500 when API configuration is missing", async () => {
293
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", undefined);
294
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", undefined);
295
- const handler = getRegisteredHandler();
296
- const response = createResponse();
297
- await handler(
298
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
299
- response,
300
- vi.fn(),
301
- );
302
  expect(response.statusCode).toBe(500);
303
- const payload = JSON.parse(response.end.mock.calls[0][0]);
304
  expect(payload.error).toBe("OpenAI API configuration is missing");
305
  });
306
  });
@@ -310,13 +482,7 @@ describe("internalApiEndpointServerHook", () => {
310
  vi.mocked(handleTokenVerification).mockResolvedValue({
311
  shouldContinue: false,
312
  });
313
- const handler = getRegisteredHandler();
314
- const response = createResponse();
315
- await handler(
316
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
317
- response,
318
- vi.fn(),
319
- );
320
  expect(handleTokenVerification).toHaveBeenCalledWith(
321
  "abc",
322
  expect.anything(),
@@ -327,32 +493,7 @@ describe("internalApiEndpointServerHook", () => {
327
  });
328
 
329
  describe("streaming path", () => {
330
- const setupStreaming = () => {
331
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", "http://test-api");
332
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", "test-key");
333
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "test-model");
334
- vi.mocked(createOpenAICompatible).mockReturnValue({
335
- chatModel: vi.fn().mockReturnValue("mock-chat-model"),
336
- } as never);
337
- };
338
-
339
- beforeEach(setupStreaming);
340
-
341
- async function callWithFakeTimers(response = createResponse()) {
342
- vi.useFakeTimers();
343
- try {
344
- const pending = getRegisteredHandler()(
345
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
346
- response,
347
- vi.fn(),
348
- );
349
- await vi.runAllTimersAsync();
350
- await pending;
351
- } finally {
352
- vi.useRealTimers();
353
- }
354
- return response;
355
- }
356
 
357
  function requestedModels() {
358
  const provider = vi.mocked(createOpenAICompatible).mock.results[0]
@@ -362,11 +503,9 @@ describe("internalApiEndpointServerHook", () => {
362
 
363
  it("sends the configured reasoning effort upstream", async () => {
364
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", " low ");
365
- vi.mocked(streamText).mockImplementation(
366
- () => streamOf([{ type: "finish" }]) as never,
367
- );
368
 
369
- await callWithFakeTimers();
370
 
371
  expect(vi.mocked(streamText).mock.calls[0][0].providerOptions).toEqual({
372
  openai: { reasoningEffort: "low" },
@@ -375,11 +514,9 @@ describe("internalApiEndpointServerHook", () => {
375
 
376
  it("leaves the reasoning effort to the upstream when unset", async () => {
377
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", "");
378
- vi.mocked(streamText).mockImplementation(
379
- () => streamOf([{ type: "finish" }]) as never,
380
- );
381
 
382
- await callWithFakeTimers();
383
 
384
  expect(
385
  vi.mocked(streamText).mock.calls[0][0].providerOptions,
@@ -390,20 +527,14 @@ describe("internalApiEndpointServerHook", () => {
390
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", " model-a , model-b ");
391
  vi.mocked(streamText)
392
  .mockImplementationOnce(() => streamOf([]) as never)
393
- .mockImplementationOnce(
394
- () =>
395
- streamOf([
396
- { type: "text-delta", text: "Recovered" },
397
- { type: "finish" },
398
- ]) as never,
399
- );
400
 
401
- const response = await callWithFakeTimers();
402
 
403
  expect(requestedModels()).toEqual(["model-a", "model-b"]);
404
  expect(listOpenAiCompatibleModels).not.toHaveBeenCalled();
405
  expect(selectRandomModel).not.toHaveBeenCalled();
406
- const writes = response.write.mock.calls.map((c) => c[0]).join("");
407
  expect(writes).toContain("Recovered");
408
  });
409
 
@@ -411,9 +542,9 @@ describe("internalApiEndpointServerHook", () => {
411
  // would end the request after two attempts instead of four.
412
  it("walks the configured list a second time before giving up", async () => {
413
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "model-a,model-b,");
414
- vi.mocked(streamText).mockImplementation(() => streamOf([]) as never);
415
 
416
- const response = await callWithFakeTimers();
417
 
418
  expect(requestedModels()).toEqual([
419
  "model-a",
@@ -429,36 +560,18 @@ describe("internalApiEndpointServerHook", () => {
429
  it("retries a single configured model once", async () => {
430
  vi.mocked(streamText)
431
  .mockImplementationOnce(() => streamOf([]) as never)
432
- .mockImplementationOnce(
433
- () =>
434
- streamOf([
435
- { type: "text-delta", text: "Second try" },
436
- { type: "finish" },
437
- ]) as never,
438
- );
439
 
440
- const response = await callWithFakeTimers();
441
 
442
  expect(requestedModels()).toEqual(["test-model", "test-model"]);
443
- const writes = response.write.mock.calls.map((c) => c[0]).join("");
444
  expect(writes).toContain("Second try");
445
  });
446
 
447
  it("emits SSE frames on successful stream", async () => {
448
- vi.mocked(streamText).mockImplementation(
449
- () =>
450
- streamOf([
451
- { type: "text-delta", text: "Hello" },
452
- { type: "finish" },
453
- ]) as never,
454
- );
455
- const handler = getRegisteredHandler();
456
- const response = createResponse();
457
- await handler(
458
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
459
- response,
460
- vi.fn(),
461
- );
462
  expect(response.setHeader).toHaveBeenCalledWith(
463
  "Content-Type",
464
  "text/event-stream",
@@ -471,7 +584,7 @@ describe("internalApiEndpointServerHook", () => {
471
  "Cache-Control",
472
  "no-cache",
473
  );
474
- const writeCalls = response.write.mock.calls.map((c) => c[0]);
475
  expect(
476
  writeCalls.some((s: string) => s.includes('"content":"Hello"')),
477
  ).toBe(true);
@@ -482,42 +595,26 @@ describe("internalApiEndpointServerHook", () => {
482
  });
483
 
484
  it("passes on why the upstream stopped, so a cut answer is not reported as complete", async () => {
485
- vi.mocked(streamText).mockImplementation(
486
- () =>
487
- streamOf([
488
- { type: "text-delta", text: "Cut" },
489
- { type: "finish", finishReason: "length" },
490
- ]) as never,
491
- );
492
- const response = createResponse();
493
-
494
- await getRegisteredHandler()(
495
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
496
- response,
497
- vi.fn(),
498
  );
 
499
 
500
- const writes = response.write.mock.calls.map((c) => c[0]).join("");
501
  expect(writes).toContain('"finish_reason":"length"');
502
  expect(writes).not.toContain('"finish_reason":"stop"');
503
  });
504
 
505
  it("spells the finish reason the way OpenAI does", async () => {
506
- vi.mocked(streamText).mockImplementation(
507
- () =>
508
- streamOf([
509
- { type: "finish", finishReason: "content-filter" },
510
- ]) as never,
511
- );
512
- const response = createResponse();
513
-
514
- await getRegisteredHandler()(
515
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
516
- response,
517
- vi.fn(),
518
  );
 
519
 
520
- const writes = response.write.mock.calls.map((c) => c[0]).join("");
521
  expect(writes).toContain('"finish_reason":"content_filter"');
522
  });
523
 
@@ -530,65 +627,25 @@ describe("internalApiEndpointServerHook", () => {
530
  async (maxTokens, expected) => {
531
  vi.stubEnv("MODEL_DEFAULT_MAX_TOKENS", maxTokens);
532
  vi.spyOn(console, "error").mockImplementation(() => {});
533
- vi.mocked(streamText).mockImplementation(
534
- () =>
535
- streamOf([
536
- { type: "text-delta", text: "Ok" },
537
- { type: "finish" },
538
- ]) as never,
539
- );
540
- const handler = getRegisteredHandler();
541
- const response = createResponse();
542
- await handler(
543
- createRequest({
544
- messages: [{ role: "user", content: "hi" }],
545
- max_tokens: 9999,
546
- }),
547
- response,
548
- vi.fn(),
549
- );
550
- const callArgs = vi.mocked(streamText).mock.calls[0][0];
551
  expect(callArgs.maxOutputTokens).toBe(expected);
552
  },
553
  );
554
 
555
  it("passes max_tokens unchanged when under cap", async () => {
556
- vi.mocked(streamText).mockImplementation(
557
- () =>
558
- streamOf([
559
- { type: "text-delta", text: "Ok" },
560
- { type: "finish" },
561
- ]) as never,
562
- );
563
- const handler = getRegisteredHandler();
564
- const response = createResponse();
565
- await handler(
566
- createRequest({
567
- messages: [{ role: "user", content: "hi" }],
568
- max_tokens: 100,
569
- }),
570
- response,
571
- vi.fn(),
572
- );
573
- const callArgs = vi.mocked(streamText).mock.calls[0][0];
574
  expect(callArgs.maxOutputTokens).toBe(100);
575
  });
576
 
577
  it("passes undefined maxOutputTokens when max_tokens not provided", async () => {
578
- vi.mocked(streamText).mockImplementation(
579
- () =>
580
- streamOf([
581
- { type: "text-delta", text: "Ok" },
582
- { type: "finish" },
583
- ]) as never,
584
- );
585
- const handler = getRegisteredHandler();
586
- const response = createResponse();
587
- await handler(
588
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
589
- response,
590
- vi.fn(),
591
- );
592
  const callArgs = vi.mocked(streamText).mock.calls[0][0];
593
  expect(callArgs.maxOutputTokens).toBeUndefined();
594
  });
@@ -612,20 +669,10 @@ describe("internalApiEndpointServerHook", () => {
612
  ])(
613
  "passes $param: 0 through instead of dropping it",
614
  async ({ reqKey, argKey }) => {
615
- vi.mocked(streamText).mockImplementation(
616
- () => streamOf([{ type: "finish" }]) as never,
617
- );
618
- const handler = getRegisteredHandler();
619
- const response = createResponse();
620
- await handler(
621
- createRequest({
622
- messages: [{ role: "user", content: "hi" }],
623
- [reqKey]: 0,
624
- }),
625
- response,
626
- vi.fn(),
627
- );
628
- const callArgs = vi.mocked(streamText).mock.calls[0][0];
629
  expect(callArgs[argKey]).toBe(0);
630
  },
631
  );
@@ -648,36 +695,20 @@ describe("internalApiEndpointServerHook", () => {
648
  ])(
649
  "clamps $param to its upper bound (reqValue=$reqValue โ†’ clampedTo=$clampedTo)",
650
  async ({ reqKey, reqValue, clampedTo, argKey }) => {
651
- vi.mocked(streamText).mockImplementation(
652
- () => streamOf([{ type: "finish" }]) as never,
653
- );
654
- const handler = getRegisteredHandler();
655
- const response = createResponse();
656
- await handler(
657
- createRequest({
658
- messages: [{ role: "user", content: "hi" }],
659
- [reqKey]: reqValue,
660
- }),
661
- response,
662
- vi.fn(),
663
- );
664
- const callArgs = vi.mocked(streamText).mock.calls[0][0];
665
  expect(callArgs[argKey]).toBe(clampedTo);
666
  },
667
  );
668
 
669
  it("emits error SSE when stream ends without finish", async () => {
670
- vi.mocked(streamText).mockImplementation(
671
- () => streamOf([{ type: "text-delta", text: "Partial" }]) as never,
672
  );
673
- const handler = getRegisteredHandler();
674
- const response = createResponse();
675
- await handler(
676
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
677
- response,
678
- vi.fn(),
679
- );
680
- const writeCalls = response.write.mock.calls.map((c) => c[0]);
681
  expect(
682
  writeCalls.some((s: string) => s.includes("Stream ended unexpectedly")),
683
  ).toBe(true);
@@ -691,39 +722,15 @@ describe("internalApiEndpointServerHook", () => {
691
  async (timeout, timeoutMs) => {
692
  vi.stubEnv("MODEL_REQUEST_TIMEOUT_MS", timeout);
693
  vi.mocked(streamText).mockImplementation(
694
- ({ abortSignal }: { abortSignal?: AbortSignal } = {}) => {
695
- // Yields one part, then yields an abort part when the signal fires โ€”
696
- // mirrors the AI SDK v7 pull handler behavior.
697
- return {
698
- stream: (async function* () {
699
- yield { type: "text-delta", text: "Half" } as never;
700
- await new Promise<void>((resolve) => {
701
- const check = () => {
702
- if (abortSignal?.aborted) {
703
- resolve();
704
- } else {
705
- abortSignal?.addEventListener("abort", () => resolve(), {
706
- once: true,
707
- });
708
- }
709
- };
710
- check();
711
- });
712
- yield { type: "abort" } as never;
713
- })(),
714
- } as never;
715
- },
716
  );
717
 
718
- const handler = getRegisteredHandler();
719
- const response = createResponse();
720
  vi.useFakeTimers();
721
  try {
722
- const pending = handler(
723
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
724
- response,
725
- vi.fn(),
726
- );
727
  // Not yet past the timeout โ€” signal should be clear.
728
  await vi.advanceTimersByTimeAsync(timeoutMs - 1);
729
  expect(
@@ -735,7 +742,7 @@ describe("internalApiEndpointServerHook", () => {
735
 
736
  // The abort is treated as an attempt failure: the stalled stream is
737
  // cut and the SSE error frame carries the message.
738
- const writes = response.write.mock.calls.map((c) => c[0] as string);
739
  expect(
740
  writes.some((s: string) => s.includes("Service unavailable")),
741
  ).toBe(true);
@@ -747,142 +754,55 @@ describe("internalApiEndpointServerHook", () => {
747
  );
748
 
749
  it("retries the next model when the first model stalls before any content", async () => {
750
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
751
- vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([
752
- { id: "model-a" },
753
- { id: "model-b" },
754
- ]);
755
- vi.mocked(selectRandomModel)
756
- .mockReturnValueOnce("model-a")
757
- .mockReturnValueOnce("model-b");
758
 
759
  vi.mocked(streamText).mockImplementationOnce(
760
- ({ abortSignal }: { abortSignal?: AbortSignal } = {}) => {
761
- return {
762
- stream: (async function* () {
763
- await new Promise<void>((resolve) => {
764
- const check = () => {
765
- if (abortSignal?.aborted) {
766
- resolve();
767
- } else {
768
- abortSignal?.addEventListener("abort", () => resolve(), {
769
- once: true,
770
- });
771
- }
772
- };
773
- check();
774
- });
775
- yield { type: "abort" } as never;
776
- })(),
777
- } as never;
778
- },
779
  );
780
  vi.mocked(streamText).mockImplementationOnce(
781
- () =>
782
- streamOf([
783
- { type: "text-delta", text: "Recovered" },
784
- { type: "finish" },
785
- ]) as never,
786
  );
787
 
788
- vi.useFakeTimers();
789
- try {
790
- const handler = getRegisteredHandler();
791
- const response = createResponse();
792
- const pending = handler(
793
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
794
- response,
795
- vi.fn(),
796
- );
797
- // Advance past the idle timeout; model-a stalls and aborts.
798
- await vi.runAllTimersAsync();
799
- await pending;
800
-
801
- expect(streamText).toHaveBeenCalledTimes(2);
802
- const writes = response.write.mock.calls.map((c) => c[0] as string);
803
- expect(writes.some((s: string) => s.includes("Recovered"))).toBe(true);
804
- expect(writes.some((s: string) => s.includes("stalled"))).toBe(false);
805
- } finally {
806
- vi.useRealTimers();
807
- }
808
  });
809
 
810
  it("responds 503 JSON when the stream ends before any content", async () => {
811
- vi.mocked(streamText).mockImplementation(() => streamOf([]) as never);
812
- const handler = getRegisteredHandler();
813
- const response = createResponse();
814
- await handler(
815
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
816
- response,
817
- vi.fn(),
818
- );
819
  expect(response.statusCode).toBe(503);
820
- const payload = JSON.parse(response.end.mock.calls[0][0]);
821
  expect(payload.lastError).toBe("Stream ended unexpectedly");
822
  expect(response.write).not.toHaveBeenCalled();
823
  });
824
 
825
  it("retries with another model when the stream ends before any content", async () => {
826
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
827
- vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([
828
- { id: "model-a" },
829
- { id: "model-b" },
830
- ]);
831
- vi.mocked(selectRandomModel)
832
- .mockReturnValueOnce("model-a")
833
- .mockReturnValueOnce("model-b");
834
-
835
- let callCount = 0;
836
- vi.mocked(streamText).mockImplementation(() => {
837
- callCount += 1;
838
- return (
839
- callCount === 1
840
- ? streamOf([])
841
- : streamOf([
842
- { type: "text-delta", text: "Recovered" },
843
- { type: "finish" },
844
- ])
845
- ) as never;
846
- });
847
 
848
- vi.useFakeTimers();
849
- try {
850
- const handler = getRegisteredHandler();
851
- const response = createResponse();
852
- const pending = handler(
853
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
854
- response,
855
- vi.fn(),
856
- );
857
- await vi.runAllTimersAsync();
858
- await pending;
859
 
860
- expect(streamText).toHaveBeenCalledTimes(2);
861
- const writes = response.write.mock.calls.map((c) => c[0]).join("");
862
- expect(writes).toContain("Recovered");
863
- expect(writes).not.toContain("Stream ended unexpectedly");
864
- } finally {
865
- vi.useRealTimers();
866
- }
867
  });
868
 
869
  it("returns early when response is no longer writable", async () => {
870
- vi.mocked(streamText).mockImplementation(
871
- () => streamOf([{ type: "text-delta", text: "Hello" }]) as never,
872
- );
873
- const handler = getRegisteredHandler();
874
- const response = createResponse();
875
- const mutable = response as {
876
- writableEnded: boolean;
877
- destroyed: boolean;
878
- };
879
- mutable.writableEnded = true;
880
- mutable.destroyed = true;
881
- await handler(
882
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
883
- response,
884
- vi.fn(),
885
- );
886
  expect(response.setHeader).not.toHaveBeenCalledWith(
887
  "Content-Type",
888
  "text/event-stream",
@@ -891,95 +811,37 @@ describe("internalApiEndpointServerHook", () => {
891
  });
892
 
893
  it("surfaces an error part instead of reporting unexpected stream end", async () => {
894
- vi.mocked(streamText).mockImplementation(
895
- () =>
896
- streamOf([
897
- { type: "text-delta", text: "Partial" },
898
- { type: "error", error: new Error("upstream exploded") },
899
- ]) as never,
900
- );
901
- const handler = getRegisteredHandler();
902
- const response = createResponse();
903
- await handler(
904
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
905
- response,
906
- vi.fn(),
907
  );
908
- const writes = response.write.mock.calls.map((c) => c[0]).join("");
 
909
  expect(writes).toContain("all models failed: upstream exploded");
910
  expect(writes).not.toContain("Stream ended unexpectedly");
911
  });
912
 
913
  it("retries with another model when the stream errors before any content", async () => {
914
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
915
- vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([
916
- { id: "model-a" },
917
- { id: "model-b" },
918
- ]);
919
- vi.mocked(selectRandomModel)
920
- .mockReturnValueOnce("model-a")
921
- .mockReturnValueOnce("model-b");
922
-
923
- let callCount = 0;
924
- vi.mocked(streamText).mockImplementation(() => {
925
- callCount += 1;
926
- return (
927
- callCount === 1
928
- ? streamOf([
929
- { type: "error", error: new Error("upstream exploded") },
930
- ])
931
- : streamOf([
932
- { type: "text-delta", text: "Recovered" },
933
- { type: "finish" },
934
- ])
935
- ) as never;
936
- });
937
 
938
- vi.useFakeTimers();
939
- try {
940
- const handler = getRegisteredHandler();
941
- const response = createResponse();
942
- const pending = handler(
943
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
944
- response,
945
- vi.fn(),
946
- );
947
- await vi.runAllTimersAsync();
948
- await pending;
949
 
950
- expect(streamText).toHaveBeenCalledTimes(2);
951
- const writes = response.write.mock.calls.map((c) => c[0]).join("");
952
- expect(writes).toContain("Recovered");
953
- expect(writes).not.toContain("all models failed");
954
- } finally {
955
- vi.useRealTimers();
956
- }
957
  });
958
 
959
  it("responds 503 JSON when the only model's stream fails before any content", async () => {
960
- vi.mocked(streamText).mockImplementation(
961
- () =>
962
- streamOf([
963
- { type: "error", error: new Error("upstream down") },
964
- ]) as never,
965
- );
966
- const handler = getRegisteredHandler();
967
- const response = createResponse();
968
- await handler(
969
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
970
- response,
971
- vi.fn(),
972
- );
973
- expect(response.statusCode).toBe(503);
974
- expect(response.setHeader).toHaveBeenCalledWith(
975
- "Content-Type",
976
- "application/json",
977
  );
978
- const payload = JSON.parse(response.end.mock.calls[0][0]);
979
- expect(payload).toEqual({
980
- error: "Service unavailable - all models failed",
981
- lastError: "upstream down",
982
- });
983
  expect(response.setHeader).not.toHaveBeenCalledWith(
984
  "Content-Type",
985
  "text/event-stream",
@@ -990,244 +852,139 @@ describe("internalApiEndpointServerHook", () => {
990
  });
991
 
992
  it("responds 503 JSON when the only model cannot start", async () => {
993
- vi.mocked(streamText).mockImplementation(() => {
994
  throw new Error("upstream down");
995
  });
996
- const handler = getRegisteredHandler();
997
- const response = createResponse();
998
- await handler(
999
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1000
- response,
1001
- vi.fn(),
1002
- );
1003
- expect(response.statusCode).toBe(503);
1004
- expect(response.setHeader).toHaveBeenCalledWith(
1005
- "Content-Type",
1006
- "application/json",
1007
- );
1008
- const payload = JSON.parse(response.end.mock.calls[0][0]);
1009
- expect(payload).toEqual({
1010
- error: "Service unavailable - all models failed",
1011
- lastError: "upstream down",
1012
- });
1013
  expect(response.write).not.toHaveBeenCalled();
1014
  expect(vi.mocked(streamText)).toHaveBeenCalledTimes(2);
1015
  });
1016
 
1017
  it("retries on model failure and succeeds on second attempt", async () => {
1018
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1019
 
1020
- vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([
1021
- { id: "model-a" },
1022
- { id: "model-b" },
1023
- ]);
1024
- vi.mocked(selectRandomModel)
1025
- .mockReturnValueOnce("model-a")
1026
- .mockReturnValueOnce("model-b");
1027
-
1028
- let callCount = 0;
1029
- vi.mocked(streamText).mockImplementation(() => {
1030
- callCount += 1;
1031
- if (callCount === 1) {
1032
  throw new Error("upstream down");
1033
- }
1034
- return streamOf([
1035
- { type: "text-delta", text: "Ok" },
1036
- { type: "finish" },
1037
- ]) as never;
1038
- });
1039
 
1040
- vi.useFakeTimers();
1041
- try {
1042
- const handler = getRegisteredHandler();
1043
- const response = createResponse();
1044
- const pending = handler(
1045
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1046
- response,
1047
- vi.fn(),
1048
- );
1049
- await vi.runAllTimersAsync();
1050
- await pending;
1051
-
1052
- expect(streamText).toHaveBeenCalledTimes(2);
1053
- const secondCallArgs = vi.mocked(selectRandomModel).mock.calls[1][1];
1054
- expect(secondCallArgs).toBeInstanceOf(Set);
1055
- expect((secondCallArgs as Set<string>).has("model-a")).toBe(true);
1056
- const writeCalls = response.write.mock.calls.map((c) => c[0]);
1057
- expect(writeCalls.some((s: string) => s.includes("[DONE]"))).toBe(true);
1058
- } finally {
1059
- vi.useRealTimers();
1060
- }
1061
  });
1062
 
1063
  it("does not retry after content was already sent to the client", async () => {
1064
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1065
- vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([
1066
- { id: "model-a" },
1067
- { id: "model-b" },
1068
- ]);
1069
- vi.mocked(selectRandomModel)
1070
- .mockReturnValueOnce("model-a")
1071
- .mockReturnValueOnce("model-b");
1072
-
1073
- let callCount = 0;
1074
- vi.mocked(streamText).mockImplementation(() => {
1075
- callCount += 1;
1076
- return (
1077
- callCount === 1
1078
- ? streamOf([
1079
- { type: "text-delta", text: "Half an answer" },
1080
- { type: "error", error: new Error("upstream exploded") },
1081
- ])
1082
- : streamOf([
1083
- { type: "text-delta", text: "A different answer" },
1084
- { type: "finish" },
1085
- ])
1086
- ) as never;
1087
- });
1088
 
1089
- const handler = getRegisteredHandler();
1090
- const response = createResponse();
1091
- await handler(
1092
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1093
- response,
1094
- vi.fn(),
 
1095
  );
1096
 
 
 
1097
  expect(streamText).toHaveBeenCalledTimes(1);
1098
- const writes = response.write.mock.calls.map((c) => c[0]).join("");
1099
  expect(writes).not.toContain("A different answer");
1100
  expect(writes).toContain("all models failed");
1101
  expect(writes).toContain("[DONE]");
1102
  });
1103
 
1104
  it("re-lists the model pool when every model has been attempted", async () => {
1105
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1106
- vi.mocked(listOpenAiCompatibleModels)
1107
- .mockResolvedValueOnce([{ id: "model-a" }])
1108
- .mockResolvedValueOnce([{ id: "model-b" }]);
1109
- vi.mocked(selectRandomModel)
1110
- .mockReturnValueOnce("model-a")
1111
- .mockReturnValueOnce("model-b");
1112
-
1113
- let callCount = 0;
1114
- vi.mocked(streamText).mockImplementation(() => {
1115
- callCount += 1;
1116
- return (
1117
- callCount === 1
1118
- ? streamOf([{ type: "error", error: new Error("upstream down") }])
1119
- : streamOf([
1120
- { type: "text-delta", text: "Recovered" },
1121
- { type: "finish" },
1122
- ])
1123
- ) as never;
1124
- });
1125
 
1126
- vi.useFakeTimers();
1127
- try {
1128
- const handler = getRegisteredHandler();
1129
- const response = createResponse();
1130
- const pending = handler(
1131
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1132
- response,
1133
- vi.fn(),
1134
- );
1135
- await vi.runAllTimersAsync();
1136
- await pending;
1137
 
1138
- expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);
1139
- expect(streamText).toHaveBeenCalledTimes(2);
1140
- const writes = response.write.mock.calls.map((c) => c[0]).join("");
1141
- expect(writes).toContain("Recovered");
1142
- expect(writes).not.toContain("all models failed");
1143
- } finally {
1144
- vi.useRealTimers();
1145
- }
1146
  });
1147
 
1148
  it("does not re-list when a model remains in the pool", async () => {
1149
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1150
- vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([
1151
- { id: "model-a" },
1152
- { id: "model-b" },
1153
- ]);
1154
- vi.mocked(selectRandomModel)
1155
- .mockReturnValueOnce("model-a")
1156
- .mockReturnValueOnce("model-b");
1157
-
1158
- let callCount = 0;
1159
- vi.mocked(streamText).mockImplementation(() => {
1160
- callCount += 1;
1161
- return (
1162
- callCount === 1
1163
- ? streamOf([{ type: "error", error: new Error("upstream down") }])
1164
- : streamOf([
1165
- { type: "text-delta", text: "Recovered" },
1166
- { type: "finish" },
1167
- ])
1168
- ) as never;
1169
- });
1170
 
1171
- vi.useFakeTimers();
1172
- try {
1173
- const handler = getRegisteredHandler();
1174
- const response = createResponse();
1175
- const pending = handler(
1176
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1177
- response,
1178
- vi.fn(),
1179
- );
1180
- await vi.runAllTimersAsync();
1181
- await pending;
1182
 
1183
- expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(1);
1184
- expect(streamText).toHaveBeenCalledTimes(2);
1185
- } finally {
1186
- vi.useRealTimers();
1187
- }
1188
  });
1189
 
1190
  it("re-lists only once even when both the original and refetched pools fail", async () => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1191
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1192
  vi.mocked(listOpenAiCompatibleModels)
1193
  .mockResolvedValueOnce([{ id: "model-a" }])
1194
- .mockResolvedValueOnce([{ id: "model-b" }]);
1195
- vi.mocked(selectRandomModel)
1196
- .mockReturnValueOnce("model-a")
1197
- .mockReturnValueOnce("model-b");
1198
 
1199
- vi.mocked(streamText).mockImplementation(
1200
- () =>
1201
- streamOf([
1202
- { type: "error", error: new Error("upstream down") },
1203
- ]) as never,
1204
  );
1205
 
1206
  const before = getInferenceStats();
1207
- vi.useFakeTimers();
1208
  try {
1209
- const handler = getRegisteredHandler();
1210
- const response = createResponse();
1211
- const pending = handler(
1212
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1213
- response,
1214
- vi.fn(),
1215
- );
1216
- await vi.runAllTimersAsync();
1217
- await pending;
1218
 
1219
- // The pool was refreshed once; even though both models failed we do not
1220
- // loop on a failing /models endpoint.
1221
  expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);
 
1222
  expect(vi.mocked(selectRandomModel).mock.calls[1][0]).toEqual([
1223
- { id: "model-b" },
1224
  ]);
 
1225
  expect(response.statusCode).toBe(503);
1226
- expect(getInferenceStats().modelsRefetched).toBe(
1227
- before.modelsRefetched + 1,
 
 
 
 
1228
  );
1229
  } finally {
1230
- vi.useRealTimers();
1231
  }
1232
  });
1233
 
@@ -1236,15 +993,9 @@ describe("internalApiEndpointServerHook", () => {
1236
  vi.mocked(listOpenAiCompatibleModels).mockRejectedValue(
1237
  new Error("network error"),
1238
  );
1239
- const handler = getRegisteredHandler();
1240
- const response = createResponse();
1241
- await handler(
1242
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1243
- response,
1244
- vi.fn(),
1245
- );
1246
  expect(response.statusCode).toBe(500);
1247
- const payload = JSON.parse(response.end.mock.calls[0][0]);
1248
  expect(payload.error).toBe("Failed to fetch available models");
1249
  });
1250
 
@@ -1252,59 +1003,40 @@ describe("internalApiEndpointServerHook", () => {
1252
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1253
  vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([]);
1254
  vi.mocked(selectRandomModel).mockReturnValue(null);
1255
- const handler = getRegisteredHandler();
1256
- const response = createResponse();
1257
- await handler(
1258
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1259
- response,
1260
- vi.fn(),
1261
- );
1262
  expect(response.statusCode).toBe(500);
1263
- const payload = JSON.parse(response.end.mock.calls[0][0]);
1264
  expect(payload.error).toBe("No model available");
1265
  });
1266
 
1267
  describe("error logging", () => {
1268
  it("logs only the error message when a stream fails", async () => {
1269
- vi.mocked(streamText).mockImplementation(
1270
- () =>
1271
- streamOf([
1272
- { type: "error", error: new Error("upstream exploded") },
1273
- ]) as never,
1274
  );
1275
  const errorSpy = vi
1276
  .spyOn(console, "error")
1277
  .mockImplementation(() => {});
1278
  try {
1279
- const handler = getRegisteredHandler();
1280
- const response = createResponse();
1281
- await handler(
1282
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1283
- response,
1284
- vi.fn(),
1285
- );
1286
- const streamingCall = errorSpy.mock.calls.find(
1287
- (call) => call[0] === "Error during streaming:",
1288
  );
1289
- expect(streamingCall).toBeDefined();
1290
- expect(streamingCall?.[1]).toBe("upstream exploded");
1291
- expect(
1292
- errorSpy.mock.calls.every((call) => !(call[1] instanceof Error)),
1293
- ).toBe(true);
1294
  } finally {
1295
  errorSpy.mockRestore();
1296
  }
1297
  });
1298
 
1299
  it("logs only the error message on unexpected endpoint failure", async () => {
1300
- vi.mocked(streamText).mockImplementation(() => {
1301
  throw new Error("upstream down");
1302
  });
1303
  const errorSpy = vi
1304
  .spyOn(console, "error")
1305
  .mockImplementation(() => {});
1306
  try {
1307
- const handler = getRegisteredHandler();
1308
  const response = createResponse();
1309
  let thrown = false;
1310
  response.setHeader.mockImplementation((name: string) => {
@@ -1313,19 +1045,12 @@ describe("internalApiEndpointServerHook", () => {
1313
  throw new Error("setHeader exploded");
1314
  }
1315
  });
1316
- await handler(
1317
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1318
- response,
1319
- vi.fn(),
 
1320
  );
1321
- const endpointCall = errorSpy.mock.calls.find(
1322
- (call) => call[0] === "Error in internal API endpoint:",
1323
- );
1324
- expect(endpointCall).toBeDefined();
1325
- expect(endpointCall?.[1]).toBe("setHeader exploded");
1326
- expect(
1327
- errorSpy.mock.calls.every((call) => !(call[1] instanceof Error)),
1328
- ).toBe(true);
1329
  expect(response.statusCode).toBe(500);
1330
  } finally {
1331
  errorSpy.mockRestore();
@@ -1333,29 +1058,17 @@ describe("internalApiEndpointServerHook", () => {
1333
  });
1334
 
1335
  it("logs only the error message when the model list fetch fails", async () => {
1336
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1337
- vi.mocked(listOpenAiCompatibleModels).mockRejectedValue(
1338
- new Error("registry timeout"),
1339
- );
1340
  const errorSpy = vi
1341
  .spyOn(console, "error")
1342
  .mockImplementation(() => {});
1343
  try {
1344
- const handler = getRegisteredHandler();
1345
- const response = createResponse();
1346
- await handler(
1347
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1348
- response,
1349
- vi.fn(),
1350
  );
1351
- const fetchCall = errorSpy.mock.calls.find(
1352
- (call) => call[0] === "Error fetching models:",
1353
- );
1354
- expect(fetchCall).toBeDefined();
1355
- expect(fetchCall?.[1]).toBe("registry timeout");
1356
- expect(
1357
- errorSpy.mock.calls.every((call) => !(call[1] instanceof Error)),
1358
- ).toBe(true);
1359
  expect(response.statusCode).toBe(500);
1360
  } finally {
1361
  errorSpy.mockRestore();
@@ -1364,26 +1077,7 @@ describe("internalApiEndpointServerHook", () => {
1364
  });
1365
  });
1366
  describe("inference counters", () => {
1367
- const setupStreaming = () => {
1368
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", "http://test-api");
1369
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", "test-key");
1370
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "test-model");
1371
- vi.mocked(createOpenAICompatible).mockReturnValue({
1372
- chatModel: vi.fn().mockReturnValue("mock-chat-model"),
1373
- } as never);
1374
- };
1375
-
1376
- async function callInference(response = createResponse()) {
1377
- const handler = getRegisteredHandler();
1378
- await handler(
1379
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1380
- response,
1381
- vi.fn(),
1382
- );
1383
- return response;
1384
- }
1385
-
1386
- beforeEach(setupStreaming);
1387
 
1388
  // Every case in this block goes through the handler, so this covers all of
1389
  // them rather than whichever one happened to run last.
@@ -1393,15 +1087,9 @@ describe("internalApiEndpointServerHook", () => {
1393
 
1394
  it("counts a finished answer under its model", async () => {
1395
  const before = getInferenceStats(["test-model"]);
1396
- vi.mocked(streamText).mockImplementation(
1397
- () =>
1398
- streamOf([
1399
- { type: "text-delta", text: "Hello" },
1400
- { type: "finish" },
1401
- ]) as never,
1402
- );
1403
 
1404
- await callInference();
1405
 
1406
  const after = getInferenceStats(["test-model"]);
1407
  expect(after.streamed).toBe(before.streamed + 1);
@@ -1417,18 +1105,10 @@ describe("internalApiEndpointServerHook", () => {
1417
 
1418
  it("counts a request the client walked away from", async () => {
1419
  const before = getInferenceStats();
1420
- vi.mocked(streamText).mockImplementation(
1421
- () => streamOf([{ type: "text-delta", text: "Hello" }]) as never,
1422
- );
1423
- const response = createResponse();
1424
- const mutable = response as {
1425
- writableEnded: boolean;
1426
- destroyed: boolean;
1427
- };
1428
- mutable.writableEnded = true;
1429
- mutable.destroyed = true;
1430
 
1431
- await callInference(response);
1432
 
1433
  // The only outcome with no response to observe it by, which is the
1434
  // reason it is worth counting at all.
@@ -1444,12 +1124,11 @@ describe("internalApiEndpointServerHook", () => {
1444
  writableEnded: boolean;
1445
  destroyed: boolean;
1446
  };
1447
- vi.mocked(streamText).mockImplementation(
1448
- () =>
1449
- streamOf([
1450
- { type: "text-delta", text: "Half an answer" },
1451
- { type: "text-delta", text: "never read" },
1452
- ]) as never,
1453
  );
1454
  response.write.mockImplementation(() => {
1455
  // Writable for the first part, gone before the second, which is the
@@ -1459,7 +1138,7 @@ describe("internalApiEndpointServerHook", () => {
1459
  return true;
1460
  });
1461
 
1462
- await callInference(response);
1463
 
1464
  const after = getInferenceStats(["test-model"]);
1465
  expect(after.failed.abandoned).toBe(before.failed.abandoned + 1);
@@ -1472,9 +1151,9 @@ describe("internalApiEndpointServerHook", () => {
1472
 
1473
  it("counts an exhausted ladder as a failure before the first token", async () => {
1474
  const before = getInferenceStats(["test-model"]);
1475
- vi.mocked(streamText).mockImplementation(() => streamOf([]) as never);
1476
 
1477
- const response = await callInference();
1478
 
1479
  expect(response.statusCode).toBe(503);
1480
  const after = getInferenceStats(["test-model"]);
@@ -1513,14 +1192,7 @@ describe("internalApiEndpointServerHook", () => {
1513
  }
1514
  const before = getInferenceStats().attemptFailures;
1515
 
1516
- vi.useFakeTimers();
1517
- try {
1518
- const pending = callInference();
1519
- await vi.runAllTimersAsync();
1520
- await pending;
1521
- } finally {
1522
- vi.useRealTimers();
1523
- }
1524
 
1525
  const after = getInferenceStats().attemptFailures;
1526
  expect(after.rateLimited).toBe(before.rateLimited + 1);
@@ -1532,15 +1204,14 @@ describe("internalApiEndpointServerHook", () => {
1532
 
1533
  it("counts a failure after content as a mid-stream failure", async () => {
1534
  const before = getInferenceStats();
1535
- vi.mocked(streamText).mockImplementation(
1536
- () =>
1537
- streamOf([
1538
- { type: "text-delta", text: "Half an answer" },
1539
- { type: "error", error: new Error("upstream died") },
1540
- ]) as never,
1541
  );
1542
 
1543
- await callInference();
1544
 
1545
  expect(getInferenceStats().failed.failedMidStream).toBe(
1546
  before.failed.failedMidStream + 1,
@@ -1549,40 +1220,13 @@ describe("internalApiEndpointServerHook", () => {
1549
 
1550
  it("counts a fallback to another model", async () => {
1551
  const before = getInferenceStats(["model-a", "model-b"]);
1552
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1553
- vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([
1554
- { id: "model-a" },
1555
- { id: "model-b" },
1556
- ]);
1557
- vi.mocked(selectRandomModel)
1558
- .mockReturnValueOnce("model-a")
1559
- .mockReturnValueOnce("model-b");
1560
- let calls = 0;
1561
- vi.mocked(streamText).mockImplementation(() => {
1562
- calls += 1;
1563
- return (
1564
- calls === 1
1565
- ? streamOf([])
1566
- : streamOf([
1567
- { type: "text-delta", text: "Recovered" },
1568
- { type: "finish" },
1569
- ])
1570
- ) as never;
1571
- });
1572
 
1573
- vi.useFakeTimers();
1574
- try {
1575
- const handler = getRegisteredHandler();
1576
- const pending = handler(
1577
- createRequest({ messages: [{ role: "user", content: "hi" }] }),
1578
- createResponse(),
1579
- vi.fn(),
1580
- );
1581
- await vi.runAllTimersAsync();
1582
- await pending;
1583
- } finally {
1584
- vi.useRealTimers();
1585
- }
1586
 
1587
  const after = getInferenceStats(["model-a", "model-b"]);
1588
  expect(after.modelFallbacks).toBe(before.modelFallbacks + 1);
@@ -1599,36 +1243,29 @@ describe("internalApiEndpointServerHook", () => {
1599
  [
1600
  "badRequest",
1601
  async () => {
1602
- const handler = getRegisteredHandler();
1603
- const request = Readable.from(["{invalid"]) as IncomingMessage;
1604
- request.url = "/inference?token=abc";
1605
- request.method = "POST";
1606
- request.headers = {
1607
- host: "localhost:3000",
1608
- "content-type": "application/json",
1609
- };
1610
- await handler(request, createResponse(), vi.fn());
1611
  },
1612
  ],
1613
  [
1614
  "notConfigured",
1615
  async () => {
1616
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", undefined);
1617
- await callInference();
1618
  },
1619
  ],
1620
  [
1621
  "modelListUnavailable",
1622
  async () => {
1623
- vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1624
- vi.mocked(listOpenAiCompatibleModels).mockRejectedValue(
1625
- new Error("registry timeout"),
1626
- );
1627
  const errorSpy = vi
1628
  .spyOn(console, "error")
1629
  .mockImplementation(() => {});
1630
  try {
1631
- await callInference();
1632
  } finally {
1633
  errorSpy.mockRestore();
1634
  }
@@ -1649,16 +1286,10 @@ describe("internalApiEndpointServerHook", () => {
1649
 
1650
  it("counts every request exactly once and classifies all of them", async () => {
1651
  const before = getInferenceStats();
1652
- vi.mocked(streamText).mockImplementation(
1653
- () =>
1654
- streamOf([
1655
- { type: "text-delta", text: "Hello" },
1656
- { type: "finish" },
1657
- ]) as never,
1658
- );
1659
 
1660
- await callInference();
1661
- await callInference();
1662
 
1663
  const stats = getInferenceStats();
1664
  const total =
@@ -1671,21 +1302,10 @@ describe("internalApiEndpointServerHook", () => {
1671
  });
1672
 
1673
  it("keeps no part of the conversation", async () => {
1674
- vi.mocked(streamText).mockImplementation(
1675
- () =>
1676
- streamOf([
1677
- { type: "text-delta", text: "borogoves" },
1678
- { type: "finish" },
1679
- ]) as never,
1680
- );
1681
- const handler = getRegisteredHandler();
1682
- await handler(
1683
- createRequest({
1684
- messages: [{ role: "user", content: "outgrabe mimsy-42" }],
1685
- }),
1686
- createResponse(),
1687
- vi.fn(),
1688
- );
1689
 
1690
  const serialized = JSON.stringify(getInferenceStats());
1691
  expect(serialized).not.toContain("outgrabe");
 
45
  method = "POST",
46
  contentType = "application/json",
47
  ): IncomingMessage {
48
+ return createRawRequest([JSON.stringify(body)], method, contentType);
49
+ }
50
+
51
+ /** A request whose body arrives as these chunks, sent as they are. */
52
+ function createRawRequest(
53
+ chunks: string[],
54
+ method = "POST",
55
+ contentType = "application/json",
56
+ ): IncomingMessage {
57
+ const request = Readable.from(chunks) as IncomingMessage;
58
  request.url = "/inference?token=abc";
59
  request.method = method;
60
  request.headers = {
 
131
  };
132
  }
133
 
134
+ const helloBody = { messages: [{ role: "user", content: "hi" }] };
135
+
136
+ /** Sends a request to the hook and returns the response with its pending run. */
137
+ function startRequest(body: unknown = helloBody, response = createResponse()) {
138
+ const pending = getRegisteredHandler()(
139
+ createRequest(body),
140
+ response,
141
+ vi.fn(),
142
+ );
143
+ return { response, pending };
144
+ }
145
+
146
+ async function sendRequest(
147
+ body: unknown = helloBody,
148
+ response = createResponse(),
149
+ ) {
150
+ const { pending } = startRequest(body, response);
151
+ await pending;
152
+ return response;
153
+ }
154
+
155
+ /** Runs the request with fake timers until it settles, so retries and stalls play out. */
156
+ async function sendRequestThroughTimers(body: unknown = helloBody) {
157
+ vi.useFakeTimers();
158
+ try {
159
+ const { response, pending } = startRequest(body);
160
+ await vi.runAllTimersAsync();
161
+ await pending;
162
+ return response;
163
+ } finally {
164
+ vi.useRealTimers();
165
+ }
166
+ }
167
+
168
+ /** A response the client already closed: nothing can be written to it. */
169
+ function closedResponse() {
170
+ return Object.assign(createResponse(), {
171
+ writableEnded: true,
172
+ destroyed: true,
173
+ });
174
+ }
175
+
176
+ function endPayload(response: ReturnType<typeof createResponse>) {
177
+ return JSON.parse(response.end.mock.calls[0][0]);
178
+ }
179
+
180
+ function writtenFrames(response: ReturnType<typeof createResponse>) {
181
+ return response.write.mock.calls.map((c) => c[0] as string);
182
+ }
183
+
184
+ function writtenText(response: ReturnType<typeof createResponse>) {
185
+ return response.write.mock.calls.map((c) => c[0]).join("");
186
+ }
187
+
188
+ /** A stream that answers `text` in one piece, then finishes. */
189
+ function answerStream(text: string) {
190
+ return streamOf([{ type: "text-delta", text }, { type: "finish" }]);
191
+ }
192
+
193
+ /**
194
+ * A stream that yields `before`, then waits for the request's abort and yields
195
+ * an abort part, as the AI SDK's pull handler does.
196
+ */
197
+ function stallUntilAborted(
198
+ abortSignal: AbortSignal | undefined,
199
+ before: Array<{ type: string; text?: string }> = [],
200
+ ) {
201
+ return {
202
+ stream: (async function* () {
203
+ for (const piece of before) yield piece as never;
204
+ await new Promise<void>((resolve) => {
205
+ if (abortSignal?.aborted) resolve();
206
+ else
207
+ abortSignal?.addEventListener("abort", () => resolve(), {
208
+ once: true,
209
+ });
210
+ });
211
+ yield { type: "abort" } as never;
212
+ })(),
213
+ };
214
+ }
215
+
216
+ /** The first upstream call streams `first()`; every later call, `then()`. */
217
+ function streamFirstThen(
218
+ first: () => ReturnType<typeof streamOf>,
219
+ then: () => ReturnType<typeof streamOf>,
220
+ ) {
221
+ vi.mocked(streamText)
222
+ .mockImplementationOnce(() => first() as never)
223
+ .mockImplementation(() => then() as never);
224
+ }
225
+
226
+ /** Every upstream call streams a fresh `makeStream()`. */
227
+ function streamEveryCall(makeStream: () => ReturnType<typeof streamOf>) {
228
+ vi.mocked(streamText).mockImplementation(() => makeStream() as never);
229
+ }
230
+
231
+ /** The internal API is configured, and the provider hands back a chat model. */
232
+ function configureStreamingApi() {
233
+ vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", "http://test-api");
234
+ vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", "test-key");
235
+ vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "test-model");
236
+ vi.mocked(createOpenAICompatible).mockReturnValue({
237
+ chatModel: vi.fn().mockReturnValue("mock-chat-model"),
238
+ } as never);
239
+ }
240
+
241
+ /** No configured model: each attempt picks model-a, then model-b. */
242
+ function useTwoRandomModels() {
243
+ vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
244
+ vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([
245
+ { id: "model-a" },
246
+ { id: "model-b" },
247
+ ]);
248
+ vi.mocked(selectRandomModel)
249
+ .mockReturnValueOnce("model-a")
250
+ .mockReturnValueOnce("model-b");
251
+ }
252
+
253
+ /** Each listing returns one model (model-a, then model-b), so a retry re-lists. */
254
+ function useSingleModelPoolThatRelists() {
255
+ vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
256
+ vi.mocked(listOpenAiCompatibleModels)
257
+ .mockResolvedValueOnce([{ id: "model-a" }])
258
+ .mockResolvedValueOnce([{ id: "model-b" }]);
259
+ vi.mocked(selectRandomModel)
260
+ .mockReturnValueOnce("model-a")
261
+ .mockReturnValueOnce("model-b");
262
+ }
263
+
264
+ function failModelListing() {
265
+ vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
266
+ vi.mocked(listOpenAiCompatibleModels).mockRejectedValue(
267
+ new Error("registry timeout"),
268
+ );
269
+ }
270
+
271
+ /** Sends a hello request with `extra` fields; returns what reached `streamText`. */
272
+ async function upstreamArgsFor(extra: Record<string, unknown>) {
273
+ await sendRequest({ ...helloBody, ...extra });
274
+ return vi.mocked(streamText).mock.calls[0][0];
275
+ }
276
+
277
+ /** Sends through timers; expects exactly two upstream calls and "Recovered" in the output. Returns the written text. */
278
+ async function sendExpectingSecondAttemptToRecover() {
279
+ const response = await sendRequestThroughTimers();
280
+ expect(streamText).toHaveBeenCalledTimes(2);
281
+ const writes = writtenText(response);
282
+ expect(writes).toContain("Recovered");
283
+ return writes;
284
+ }
285
+
286
+ function expectAllModelsFailedJson(
287
+ response: ReturnType<typeof createResponse>,
288
+ lastError: string,
289
+ ) {
290
+ expect(response.statusCode).toBe(503);
291
+ expect(response.setHeader).toHaveBeenCalledWith(
292
+ "Content-Type",
293
+ "application/json",
294
+ );
295
+ expect(endPayload(response)).toEqual({
296
+ error: "Service unavailable - all models failed",
297
+ lastError,
298
+ });
299
+ }
300
+
301
+ /** `label` was logged with the message only, and no Error object reached the log. */
302
+ function expectOnlyMessageLogged(
303
+ errorSpy: { mock: { calls: unknown[][] } },
304
+ label: string,
305
+ message: string,
306
+ ) {
307
+ const call = errorSpy.mock.calls.find((logged) => logged[0] === label);
308
+ expect(call).toBeDefined();
309
+ expect(call?.[1]).toBe(message);
310
+ expect(
311
+ errorSpy.mock.calls.every((logged) => !(logged[1] instanceof Error)),
312
+ ).toBe(true);
313
+ }
314
+
315
  describe("internalApiEndpointServerHook", () => {
316
  beforeEach(() => {
317
  vi.resetAllMocks();
 
346
  await handler(request, response, vi.fn());
347
  expect(response.statusCode).toBe(405);
348
  expect(response.setHeader).toHaveBeenCalledWith("Allow", "POST");
349
+ const payload = endPayload(response);
350
  expect(payload.error).toBe("Method Not Allowed");
351
  });
352
 
 
356
  const request = createRequest({}, "POST", "text/plain");
357
  await handler(request, response, vi.fn());
358
  expect(response.statusCode).toBe(415);
359
+ const payload = endPayload(response);
360
  expect(payload.error).toBe("Unsupported Media Type");
361
  });
362
 
 
440
  const response = createResponse();
441
  await handler(createRequest(body), response, vi.fn());
442
  expect(response.statusCode).toBe(400);
443
+ const payload = endPayload(response);
444
  expect(payload.error).toContain(`Invalid request body: ${expectedPath}`);
445
  });
446
 
 
448
  const handler = getRegisteredHandler();
449
  const response = createResponse();
450
  const chunk600k = "x".repeat(600 * 1024);
451
+ const request = createRawRequest([chunk600k, chunk600k]);
 
 
 
 
 
 
452
  await handler(request, response, vi.fn());
453
  expect(response.statusCode).toBe(413);
454
+ const payload = endPayload(response);
455
  expect(payload.error).toBe("Request body too large");
456
  });
457
 
458
  it("responds 400 when body is not valid JSON", async () => {
459
  const handler = getRegisteredHandler();
460
  const response = createResponse();
461
+ const request = createRawRequest(["not json at all"]);
 
 
 
 
 
 
462
  await handler(request, response, vi.fn());
463
  expect(response.statusCode).toBe(400);
464
+ const payload = endPayload(response);
465
  expect(payload.error).toBe("Invalid request body");
466
  });
467
  });
 
470
  it("responds 500 when API configuration is missing", async () => {
471
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", undefined);
472
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", undefined);
473
+ const response = await sendRequest();
 
 
 
 
 
 
474
  expect(response.statusCode).toBe(500);
475
+ const payload = endPayload(response);
476
  expect(payload.error).toBe("OpenAI API configuration is missing");
477
  });
478
  });
 
482
  vi.mocked(handleTokenVerification).mockResolvedValue({
483
  shouldContinue: false,
484
  });
485
+ const response = await sendRequest();
 
 
 
 
 
 
486
  expect(handleTokenVerification).toHaveBeenCalledWith(
487
  "abc",
488
  expect.anything(),
 
493
  });
494
 
495
  describe("streaming path", () => {
496
+ beforeEach(configureStreamingApi);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497
 
498
  function requestedModels() {
499
  const provider = vi.mocked(createOpenAICompatible).mock.results[0]
 
503
 
504
  it("sends the configured reasoning effort upstream", async () => {
505
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", " low ");
506
+ streamEveryCall(() => streamOf([{ type: "finish" }]));
 
 
507
 
508
+ await sendRequestThroughTimers();
509
 
510
  expect(vi.mocked(streamText).mock.calls[0][0].providerOptions).toEqual({
511
  openai: { reasoningEffort: "low" },
 
514
 
515
  it("leaves the reasoning effort to the upstream when unset", async () => {
516
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", "");
517
+ streamEveryCall(() => streamOf([{ type: "finish" }]));
 
 
518
 
519
+ await sendRequestThroughTimers();
520
 
521
  expect(
522
  vi.mocked(streamText).mock.calls[0][0].providerOptions,
 
527
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", " model-a , model-b ");
528
  vi.mocked(streamText)
529
  .mockImplementationOnce(() => streamOf([]) as never)
530
+ .mockImplementationOnce(() => answerStream("Recovered") as never);
 
 
 
 
 
 
531
 
532
+ const response = await sendRequestThroughTimers();
533
 
534
  expect(requestedModels()).toEqual(["model-a", "model-b"]);
535
  expect(listOpenAiCompatibleModels).not.toHaveBeenCalled();
536
  expect(selectRandomModel).not.toHaveBeenCalled();
537
+ const writes = writtenText(response);
538
  expect(writes).toContain("Recovered");
539
  });
540
 
 
542
  // would end the request after two attempts instead of four.
543
  it("walks the configured list a second time before giving up", async () => {
544
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "model-a,model-b,");
545
+ streamEveryCall(() => streamOf([]));
546
 
547
+ const response = await sendRequestThroughTimers();
548
 
549
  expect(requestedModels()).toEqual([
550
  "model-a",
 
560
  it("retries a single configured model once", async () => {
561
  vi.mocked(streamText)
562
  .mockImplementationOnce(() => streamOf([]) as never)
563
+ .mockImplementationOnce(() => answerStream("Second try") as never);
 
 
 
 
 
 
564
 
565
+ const response = await sendRequestThroughTimers();
566
 
567
  expect(requestedModels()).toEqual(["test-model", "test-model"]);
568
+ const writes = writtenText(response);
569
  expect(writes).toContain("Second try");
570
  });
571
 
572
  it("emits SSE frames on successful stream", async () => {
573
+ streamEveryCall(() => answerStream("Hello"));
574
+ const response = await sendRequest();
 
 
 
 
 
 
 
 
 
 
 
 
575
  expect(response.setHeader).toHaveBeenCalledWith(
576
  "Content-Type",
577
  "text/event-stream",
 
584
  "Cache-Control",
585
  "no-cache",
586
  );
587
+ const writeCalls = writtenFrames(response);
588
  expect(
589
  writeCalls.some((s: string) => s.includes('"content":"Hello"')),
590
  ).toBe(true);
 
595
  });
596
 
597
  it("passes on why the upstream stopped, so a cut answer is not reported as complete", async () => {
598
+ streamEveryCall(() =>
599
+ streamOf([
600
+ { type: "text-delta", text: "Cut" },
601
+ { type: "finish", finishReason: "length" },
602
+ ]),
 
 
 
 
 
 
 
 
603
  );
604
+ const response = await sendRequest();
605
 
606
+ const writes = writtenText(response);
607
  expect(writes).toContain('"finish_reason":"length"');
608
  expect(writes).not.toContain('"finish_reason":"stop"');
609
  });
610
 
611
  it("spells the finish reason the way OpenAI does", async () => {
612
+ streamEveryCall(() =>
613
+ streamOf([{ type: "finish", finishReason: "content-filter" }]),
 
 
 
 
 
 
 
 
 
 
614
  );
615
+ const response = await sendRequest();
616
 
617
+ const writes = writtenText(response);
618
  expect(writes).toContain('"finish_reason":"content_filter"');
619
  });
620
 
 
627
  async (maxTokens, expected) => {
628
  vi.stubEnv("MODEL_DEFAULT_MAX_TOKENS", maxTokens);
629
  vi.spyOn(console, "error").mockImplementation(() => {});
630
+ streamEveryCall(() => answerStream("Ok"));
631
+ const callArgs = await upstreamArgsFor({
632
+ max_tokens: 9999,
633
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
634
  expect(callArgs.maxOutputTokens).toBe(expected);
635
  },
636
  );
637
 
638
  it("passes max_tokens unchanged when under cap", async () => {
639
+ streamEveryCall(() => answerStream("Ok"));
640
+ const callArgs = await upstreamArgsFor({
641
+ max_tokens: 100,
642
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643
  expect(callArgs.maxOutputTokens).toBe(100);
644
  });
645
 
646
  it("passes undefined maxOutputTokens when max_tokens not provided", async () => {
647
+ streamEveryCall(() => answerStream("Ok"));
648
+ await sendRequest();
 
 
 
 
 
 
 
 
 
 
 
 
649
  const callArgs = vi.mocked(streamText).mock.calls[0][0];
650
  expect(callArgs.maxOutputTokens).toBeUndefined();
651
  });
 
669
  ])(
670
  "passes $param: 0 through instead of dropping it",
671
  async ({ reqKey, argKey }) => {
672
+ streamEveryCall(() => streamOf([{ type: "finish" }]));
673
+ const callArgs = await upstreamArgsFor({
674
+ [reqKey]: 0,
675
+ });
 
 
 
 
 
 
 
 
 
 
676
  expect(callArgs[argKey]).toBe(0);
677
  },
678
  );
 
695
  ])(
696
  "clamps $param to its upper bound (reqValue=$reqValue โ†’ clampedTo=$clampedTo)",
697
  async ({ reqKey, reqValue, clampedTo, argKey }) => {
698
+ streamEveryCall(() => streamOf([{ type: "finish" }]));
699
+ const callArgs = await upstreamArgsFor({
700
+ [reqKey]: reqValue,
701
+ });
 
 
 
 
 
 
 
 
 
 
702
  expect(callArgs[argKey]).toBe(clampedTo);
703
  },
704
  );
705
 
706
  it("emits error SSE when stream ends without finish", async () => {
707
+ streamEveryCall(() =>
708
+ streamOf([{ type: "text-delta", text: "Partial" }]),
709
  );
710
+ const response = await sendRequest();
711
+ const writeCalls = writtenFrames(response);
 
 
 
 
 
 
712
  expect(
713
  writeCalls.some((s: string) => s.includes("Stream ended unexpectedly")),
714
  ).toBe(true);
 
722
  async (timeout, timeoutMs) => {
723
  vi.stubEnv("MODEL_REQUEST_TIMEOUT_MS", timeout);
724
  vi.mocked(streamText).mockImplementation(
725
+ ({ abortSignal }: { abortSignal?: AbortSignal } = {}) =>
726
+ stallUntilAborted(abortSignal, [
727
+ { type: "text-delta", text: "Half" },
728
+ ]) as never,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
729
  );
730
 
 
 
731
  vi.useFakeTimers();
732
  try {
733
+ const { response, pending } = startRequest();
 
 
 
 
734
  // Not yet past the timeout โ€” signal should be clear.
735
  await vi.advanceTimersByTimeAsync(timeoutMs - 1);
736
  expect(
 
742
 
743
  // The abort is treated as an attempt failure: the stalled stream is
744
  // cut and the SSE error frame carries the message.
745
+ const writes = writtenFrames(response);
746
  expect(
747
  writes.some((s: string) => s.includes("Service unavailable")),
748
  ).toBe(true);
 
754
  );
755
 
756
  it("retries the next model when the first model stalls before any content", async () => {
757
+ useTwoRandomModels();
758
+ const before = getInferenceStats().attemptFailures;
 
 
 
 
 
 
759
 
760
  vi.mocked(streamText).mockImplementationOnce(
761
+ ({ abortSignal }: { abortSignal?: AbortSignal } = {}) =>
762
+ stallUntilAborted(abortSignal) as never,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
763
  );
764
  vi.mocked(streamText).mockImplementationOnce(
765
+ () => answerStream("Recovered") as never,
 
 
 
 
766
  );
767
 
768
+ // Past the idle timeout, model-a stalls and aborts.
769
+ const response = await sendRequestThroughTimers();
770
+
771
+ const after = getInferenceStats().attemptFailures;
772
+ expect(after.stalled).toBe(before.stalled + 1);
773
+ expect(after.other).toBe(before.other);
774
+
775
+ expect(streamText).toHaveBeenCalledTimes(2);
776
+ const writes = writtenFrames(response);
777
+ expect(writes.some((s: string) => s.includes("Recovered"))).toBe(true);
778
+ expect(writes.some((s: string) => s.includes("stalled"))).toBe(false);
 
 
 
 
 
 
 
 
 
779
  });
780
 
781
  it("responds 503 JSON when the stream ends before any content", async () => {
782
+ streamEveryCall(() => streamOf([]));
783
+ const response = await sendRequest();
 
 
 
 
 
 
784
  expect(response.statusCode).toBe(503);
785
+ const payload = endPayload(response);
786
  expect(payload.lastError).toBe("Stream ended unexpectedly");
787
  expect(response.write).not.toHaveBeenCalled();
788
  });
789
 
790
  it("retries with another model when the stream ends before any content", async () => {
791
+ useTwoRandomModels();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792
 
793
+ streamFirstThen(
794
+ () => streamOf([]),
795
+ () => answerStream("Recovered"),
796
+ );
 
 
 
 
 
 
 
797
 
798
+ const writes = await sendExpectingSecondAttemptToRecover();
799
+ expect(writes).not.toContain("Stream ended unexpectedly");
 
 
 
 
 
800
  });
801
 
802
  it("returns early when response is no longer writable", async () => {
803
+ streamEveryCall(() => streamOf([{ type: "text-delta", text: "Hello" }]));
804
+ const response = closedResponse();
805
+ await sendRequest(helloBody, response);
 
 
 
 
 
 
 
 
 
 
 
 
 
806
  expect(response.setHeader).not.toHaveBeenCalledWith(
807
  "Content-Type",
808
  "text/event-stream",
 
811
  });
812
 
813
  it("surfaces an error part instead of reporting unexpected stream end", async () => {
814
+ streamEveryCall(() =>
815
+ streamOf([
816
+ { type: "text-delta", text: "Partial" },
817
+ { type: "error", error: new Error("upstream exploded") },
818
+ ]),
 
 
 
 
 
 
 
 
819
  );
820
+ const response = await sendRequest();
821
+ const writes = writtenText(response);
822
  expect(writes).toContain("all models failed: upstream exploded");
823
  expect(writes).not.toContain("Stream ended unexpectedly");
824
  });
825
 
826
  it("retries with another model when the stream errors before any content", async () => {
827
+ useTwoRandomModels();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
828
 
829
+ streamFirstThen(
830
+ () =>
831
+ streamOf([{ type: "error", error: new Error("upstream exploded") }]),
832
+ () => answerStream("Recovered"),
833
+ );
 
 
 
 
 
 
834
 
835
+ const writes = await sendExpectingSecondAttemptToRecover();
836
+ expect(writes).not.toContain("all models failed");
 
 
 
 
 
837
  });
838
 
839
  it("responds 503 JSON when the only model's stream fails before any content", async () => {
840
+ streamEveryCall(() =>
841
+ streamOf([{ type: "error", error: new Error("upstream down") }]),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
842
  );
843
+ const response = await sendRequest();
844
+ expectAllModelsFailedJson(response, "upstream down");
 
 
 
845
  expect(response.setHeader).not.toHaveBeenCalledWith(
846
  "Content-Type",
847
  "text/event-stream",
 
852
  });
853
 
854
  it("responds 503 JSON when the only model cannot start", async () => {
855
+ streamEveryCall(() => {
856
  throw new Error("upstream down");
857
  });
858
+ const response = await sendRequest();
859
+ expectAllModelsFailedJson(response, "upstream down");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
860
  expect(response.write).not.toHaveBeenCalled();
861
  expect(vi.mocked(streamText)).toHaveBeenCalledTimes(2);
862
  });
863
 
864
  it("retries on model failure and succeeds on second attempt", async () => {
865
+ useTwoRandomModels();
866
 
867
+ streamFirstThen(
868
+ () => {
 
 
 
 
 
 
 
 
 
 
869
  throw new Error("upstream down");
870
+ },
871
+ () => answerStream("Ok"),
872
+ );
 
 
 
873
 
874
+ const response = await sendRequestThroughTimers();
875
+
876
+ expect(streamText).toHaveBeenCalledTimes(2);
877
+ const secondCallArgs = vi.mocked(selectRandomModel).mock.calls[1][1];
878
+ expect(secondCallArgs).toBeInstanceOf(Set);
879
+ expect((secondCallArgs as Set<string>).has("model-a")).toBe(true);
880
+ const writeCalls = writtenFrames(response);
881
+ expect(writeCalls.some((s: string) => s.includes("[DONE]"))).toBe(true);
 
 
 
 
 
 
 
 
 
 
 
 
 
882
  });
883
 
884
  it("does not retry after content was already sent to the client", async () => {
885
+ useTwoRandomModels();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
886
 
887
+ streamFirstThen(
888
+ () =>
889
+ streamOf([
890
+ { type: "text-delta", text: "Half an answer" },
891
+ { type: "error", error: new Error("upstream exploded") },
892
+ ]),
893
+ () => answerStream("A different answer"),
894
  );
895
 
896
+ const response = await sendRequest();
897
+
898
  expect(streamText).toHaveBeenCalledTimes(1);
899
+ const writes = writtenText(response);
900
  expect(writes).not.toContain("A different answer");
901
  expect(writes).toContain("all models failed");
902
  expect(writes).toContain("[DONE]");
903
  });
904
 
905
  it("re-lists the model pool when every model has been attempted", async () => {
906
+ useSingleModelPoolThatRelists();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
907
 
908
+ streamFirstThen(
909
+ () => streamOf([{ type: "error", error: new Error("upstream down") }]),
910
+ () => answerStream("Recovered"),
911
+ );
 
 
 
 
 
 
 
912
 
913
+ const writes = await sendExpectingSecondAttemptToRecover();
914
+ expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);
915
+ expect(writes).not.toContain("all models failed");
 
 
 
 
 
916
  });
917
 
918
  it("does not re-list when a model remains in the pool", async () => {
919
+ useTwoRandomModels();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
920
 
921
+ streamFirstThen(
922
+ () => streamOf([{ type: "error", error: new Error("upstream down") }]),
923
+ () => answerStream("Recovered"),
924
+ );
 
 
 
 
 
 
 
925
 
926
+ await sendRequestThroughTimers();
927
+
928
+ expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(1);
929
+ expect(streamText).toHaveBeenCalledTimes(2);
 
930
  });
931
 
932
  it("re-lists only once even when both the original and refetched pools fail", async () => {
933
+ useSingleModelPoolThatRelists();
934
+
935
+ streamEveryCall(() =>
936
+ streamOf([{ type: "error", error: new Error("upstream down") }]),
937
+ );
938
+
939
+ const before = getInferenceStats();
940
+ const response = await sendRequestThroughTimers();
941
+
942
+ // The pool was refreshed once; even though both models failed we do not
943
+ // loop on a failing /models endpoint.
944
+ expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);
945
+ expect(vi.mocked(selectRandomModel).mock.calls[1][0]).toEqual([
946
+ { id: "model-b" },
947
+ ]);
948
+ expect(response.statusCode).toBe(503);
949
+ expect(getInferenceStats().modelsRefetched).toBe(
950
+ before.modelsRefetched + 1,
951
+ );
952
+ });
953
+
954
+ it("still answers 503 when the mid-retry re-list fails", async () => {
955
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
956
  vi.mocked(listOpenAiCompatibleModels)
957
  .mockResolvedValueOnce([{ id: "model-a" }])
958
+ .mockRejectedValueOnce(new Error("models endpoint down"));
959
+ vi.mocked(selectRandomModel).mockReturnValueOnce("model-a");
 
 
960
 
961
+ streamEveryCall(() =>
962
+ streamOf([{ type: "error", error: new Error("upstream down") }]),
 
 
 
963
  );
964
 
965
  const before = getInferenceStats();
966
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
967
  try {
968
+ const response = await sendRequestThroughTimers();
 
 
 
 
 
 
 
 
969
 
970
+ // The re-list failed, so the picker hands out nothing and the request
971
+ // ends in the all-models-failed answer, not an internal error.
972
  expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);
973
+ // The failed re-list left the old pool in place.
974
  expect(vi.mocked(selectRandomModel).mock.calls[1][0]).toEqual([
975
+ { id: "model-a" },
976
  ]);
977
+ expect(streamText).toHaveBeenCalledTimes(1);
978
  expect(response.statusCode).toBe(503);
979
+ expect(getInferenceStats().failed.failedBeforeFirstToken).toBe(
980
+ before.failed.failedBeforeFirstToken + 1,
981
+ );
982
+ expect(warnSpy).toHaveBeenCalledWith(
983
+ "Failed to refetch models:",
984
+ "models endpoint down",
985
  );
986
  } finally {
987
+ warnSpy.mockRestore();
988
  }
989
  });
990
 
 
993
  vi.mocked(listOpenAiCompatibleModels).mockRejectedValue(
994
  new Error("network error"),
995
  );
996
+ const response = await sendRequest();
 
 
 
 
 
 
997
  expect(response.statusCode).toBe(500);
998
+ const payload = endPayload(response);
999
  expect(payload.error).toBe("Failed to fetch available models");
1000
  });
1001
 
 
1003
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1004
  vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([]);
1005
  vi.mocked(selectRandomModel).mockReturnValue(null);
1006
+ const response = await sendRequest();
 
 
 
 
 
 
1007
  expect(response.statusCode).toBe(500);
1008
+ const payload = endPayload(response);
1009
  expect(payload.error).toBe("No model available");
1010
  });
1011
 
1012
  describe("error logging", () => {
1013
  it("logs only the error message when a stream fails", async () => {
1014
+ streamEveryCall(() =>
1015
+ streamOf([{ type: "error", error: new Error("upstream exploded") }]),
 
 
 
1016
  );
1017
  const errorSpy = vi
1018
  .spyOn(console, "error")
1019
  .mockImplementation(() => {});
1020
  try {
1021
+ await sendRequest();
1022
+ expectOnlyMessageLogged(
1023
+ errorSpy,
1024
+ "Error during streaming:",
1025
+ "upstream exploded",
 
 
 
 
1026
  );
 
 
 
 
 
1027
  } finally {
1028
  errorSpy.mockRestore();
1029
  }
1030
  });
1031
 
1032
  it("logs only the error message on unexpected endpoint failure", async () => {
1033
+ streamEveryCall(() => {
1034
  throw new Error("upstream down");
1035
  });
1036
  const errorSpy = vi
1037
  .spyOn(console, "error")
1038
  .mockImplementation(() => {});
1039
  try {
 
1040
  const response = createResponse();
1041
  let thrown = false;
1042
  response.setHeader.mockImplementation((name: string) => {
 
1045
  throw new Error("setHeader exploded");
1046
  }
1047
  });
1048
+ await sendRequest(helloBody, response);
1049
+ expectOnlyMessageLogged(
1050
+ errorSpy,
1051
+ "Error in internal API endpoint:",
1052
+ "setHeader exploded",
1053
  );
 
 
 
 
 
 
 
 
1054
  expect(response.statusCode).toBe(500);
1055
  } finally {
1056
  errorSpy.mockRestore();
 
1058
  });
1059
 
1060
  it("logs only the error message when the model list fetch fails", async () => {
1061
+ failModelListing();
 
 
 
1062
  const errorSpy = vi
1063
  .spyOn(console, "error")
1064
  .mockImplementation(() => {});
1065
  try {
1066
+ const response = await sendRequest();
1067
+ expectOnlyMessageLogged(
1068
+ errorSpy,
1069
+ "Error fetching models:",
1070
+ "registry timeout",
 
1071
  );
 
 
 
 
 
 
 
 
1072
  expect(response.statusCode).toBe(500);
1073
  } finally {
1074
  errorSpy.mockRestore();
 
1077
  });
1078
  });
1079
  describe("inference counters", () => {
1080
+ beforeEach(configureStreamingApi);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1081
 
1082
  // Every case in this block goes through the handler, so this covers all of
1083
  // them rather than whichever one happened to run last.
 
1087
 
1088
  it("counts a finished answer under its model", async () => {
1089
  const before = getInferenceStats(["test-model"]);
1090
+ streamEveryCall(() => answerStream("Hello"));
 
 
 
 
 
 
1091
 
1092
+ await sendRequest();
1093
 
1094
  const after = getInferenceStats(["test-model"]);
1095
  expect(after.streamed).toBe(before.streamed + 1);
 
1105
 
1106
  it("counts a request the client walked away from", async () => {
1107
  const before = getInferenceStats();
1108
+ streamEveryCall(() => streamOf([{ type: "text-delta", text: "Hello" }]));
1109
+ const response = closedResponse();
 
 
 
 
 
 
 
 
1110
 
1111
+ await sendRequest(helloBody, response);
1112
 
1113
  // The only outcome with no response to observe it by, which is the
1114
  // reason it is worth counting at all.
 
1124
  writableEnded: boolean;
1125
  destroyed: boolean;
1126
  };
1127
+ streamEveryCall(() =>
1128
+ streamOf([
1129
+ { type: "text-delta", text: "Half an answer" },
1130
+ { type: "text-delta", text: "never read" },
1131
+ ]),
 
1132
  );
1133
  response.write.mockImplementation(() => {
1134
  // Writable for the first part, gone before the second, which is the
 
1138
  return true;
1139
  });
1140
 
1141
+ await sendRequest(helloBody, response);
1142
 
1143
  const after = getInferenceStats(["test-model"]);
1144
  expect(after.failed.abandoned).toBe(before.failed.abandoned + 1);
 
1151
 
1152
  it("counts an exhausted ladder as a failure before the first token", async () => {
1153
  const before = getInferenceStats(["test-model"]);
1154
+ streamEveryCall(() => streamOf([]));
1155
 
1156
+ const response = await sendRequest();
1157
 
1158
  expect(response.statusCode).toBe(503);
1159
  const after = getInferenceStats(["test-model"]);
 
1192
  }
1193
  const before = getInferenceStats().attemptFailures;
1194
 
1195
+ await sendRequestThroughTimers();
 
 
 
 
 
 
 
1196
 
1197
  const after = getInferenceStats().attemptFailures;
1198
  expect(after.rateLimited).toBe(before.rateLimited + 1);
 
1204
 
1205
  it("counts a failure after content as a mid-stream failure", async () => {
1206
  const before = getInferenceStats();
1207
+ streamEveryCall(() =>
1208
+ streamOf([
1209
+ { type: "text-delta", text: "Half an answer" },
1210
+ { type: "error", error: new Error("upstream died") },
1211
+ ]),
 
1212
  );
1213
 
1214
+ await sendRequest();
1215
 
1216
  expect(getInferenceStats().failed.failedMidStream).toBe(
1217
  before.failed.failedMidStream + 1,
 
1220
 
1221
  it("counts a fallback to another model", async () => {
1222
  const before = getInferenceStats(["model-a", "model-b"]);
1223
+ useTwoRandomModels();
1224
+ streamFirstThen(
1225
+ () => streamOf([]),
1226
+ () => answerStream("Recovered"),
1227
+ );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1228
 
1229
+ await sendRequestThroughTimers();
 
 
 
 
 
 
 
 
 
 
 
 
1230
 
1231
  const after = getInferenceStats(["model-a", "model-b"]);
1232
  expect(after.modelFallbacks).toBe(before.modelFallbacks + 1);
 
1243
  [
1244
  "badRequest",
1245
  async () => {
1246
+ await getRegisteredHandler()(
1247
+ createRawRequest(["{invalid"]),
1248
+ createResponse(),
1249
+ vi.fn(),
1250
+ );
 
 
 
 
1251
  },
1252
  ],
1253
  [
1254
  "notConfigured",
1255
  async () => {
1256
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", undefined);
1257
+ await sendRequest();
1258
  },
1259
  ],
1260
  [
1261
  "modelListUnavailable",
1262
  async () => {
1263
+ failModelListing();
 
 
 
1264
  const errorSpy = vi
1265
  .spyOn(console, "error")
1266
  .mockImplementation(() => {});
1267
  try {
1268
+ await sendRequest();
1269
  } finally {
1270
  errorSpy.mockRestore();
1271
  }
 
1286
 
1287
  it("counts every request exactly once and classifies all of them", async () => {
1288
  const before = getInferenceStats();
1289
+ streamEveryCall(() => answerStream("Hello"));
 
 
 
 
 
 
1290
 
1291
+ await sendRequest();
1292
+ await sendRequest();
1293
 
1294
  const stats = getInferenceStats();
1295
  const total =
 
1302
  });
1303
 
1304
  it("keeps no part of the conversation", async () => {
1305
+ streamEveryCall(() => answerStream("borogoves"));
1306
+ await sendRequest({
1307
+ messages: [{ role: "user", content: "outgrabe mimsy-42" }],
1308
+ });
 
 
 
 
 
 
 
 
 
 
 
1309
 
1310
  const serialized = JSON.stringify(getInferenceStats());
1311
  expect(serialized).not.toContain("outgrabe");
server/internalApiModelPicker.test.ts CHANGED
@@ -36,6 +36,17 @@ describe("createModelPicker", () => {
36
  expect(listOpenAiCompatibleModels).not.toHaveBeenCalled();
37
  });
38
 
 
 
 
 
 
 
 
 
 
 
 
39
  it("never hands out the same random model twice", async () => {
40
  // Always the first model left, so a missing exclusion repeats it every
41
  // time instead of only by chance.
 
36
  expect(listOpenAiCompatibleModels).not.toHaveBeenCalled();
37
  });
38
 
39
+ // The throw is the contract the hook's 500 "Failed to fetch available
40
+ // models" depends on; the refetch path below catches its own failure.
41
+ it("throws when the initial listing fails", async () => {
42
+ vi.mocked(listOpenAiCompatibleModels).mockRejectedValueOnce(
43
+ new Error("models endpoint down"),
44
+ );
45
+ const picker = createModelPicker({ ...connection, models: [] });
46
+
47
+ await expect(picker.first()).rejects.toThrow("models endpoint down");
48
+ });
49
+
50
  it("never hands out the same random model twice", async () => {
51
  // Always the first model left, so a missing exclusion repeats it every
52
  // time instead of only by chance.
server/internalApiModelPicker.ts CHANGED
@@ -9,6 +9,9 @@ import { recordModelsRefetched } from "./inferencesSinceLastRestart.ts";
9
  * configured models, it walks them in order of preference and then once
10
  * more, so a single configured model also gets one retry. Without them, it
11
  * picks at random from the API's `/models`, never the same model twice.
 
 
 
12
  */
13
  export function createModelPicker({
14
  models,
@@ -22,8 +25,10 @@ export function createModelPicker({
22
  const ladder = [...models, ...models];
23
  let position = 0;
24
  let availableModels: { id: string }[] = [];
25
- // Every model handed out counts as attempted: the hook runs each one it
26
- // gets, so marking here keeps the exclusion from depending on the caller.
 
 
27
  const attemptedModels = new Set<string>();
28
  let hasRefetched = false;
29
 
 
9
  * configured models, it walks them in order of preference and then once
10
  * more, so a single configured model also gets one retry. Without them, it
11
  * picks at random from the API's `/models`, never the same model twice.
12
+ * Create one per request, call `first()` once, then `next()` after each
13
+ * failed attempt: it keeps its own position and pool, so the calls must
14
+ * come in that order.
15
  */
16
  export function createModelPicker({
17
  models,
 
25
  const ladder = [...models, ...models];
26
  let position = 0;
27
  let availableModels: { id: string }[] = [];
28
+ // Marked on hand-out, not when the attempt runs: this set is only read in
29
+ // next(), after the previous attempt has finished, and every exit between
30
+ // a hand-out and the next read ends the request, so it holds the same
31
+ // models it would if marked at attempt time.
32
  const attemptedModels = new Set<string>();
33
  let hasRefetched = false;
34
 
server/thumbnailEndpointServerHook.test.ts CHANGED
@@ -88,6 +88,73 @@ function requestUrlFor(thumbnailUrl: string): string {
88
  return `/thumbnail?u=${encodeURIComponent(thumbnailUrl)}&token=abc`;
89
  }
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  // Shaped like the IncomingMessage the pinned request resolves with: the
92
  // fields the hook reads, plus the async iteration readCappedStream drives.
93
  function fakeIncoming(
@@ -136,10 +203,7 @@ describe("thumbnailEndpointServerHook", () => {
136
  });
137
 
138
  it("passes through requests that aren't under /thumbnail", async () => {
139
- const handler = getRegisteredHandler();
140
- const next = vi.fn();
141
-
142
- await handler(createRequest("/status"), createResponse(), next);
143
 
144
  expect(next).toHaveBeenCalled();
145
  expect(pinnedRequestMock).not.toHaveBeenCalled();
@@ -150,11 +214,7 @@ describe("thumbnailEndpointServerHook", () => {
150
  "/thumbnailX?token=abc",
151
  "/thumbnail/extra?token=abc",
152
  ])("passes through %s, which is not the /thumbnail route", async (url) => {
153
- const handler = getRegisteredHandler();
154
- const next = vi.fn();
155
- const response = createResponse();
156
-
157
- await handler(createRequest(url), response, next);
158
 
159
  expect(next).toHaveBeenCalledTimes(1);
160
  expect(response.end).not.toHaveBeenCalled();
@@ -166,23 +226,15 @@ describe("thumbnailEndpointServerHook", () => {
166
  vi.mocked(handleTokenVerification).mockResolvedValue({
167
  shouldContinue: false,
168
  });
169
- const handler = getRegisteredHandler();
170
 
171
- await handler(
172
- createRequest(requestUrlFor(publicThumbnailUrl())),
173
- createResponse(),
174
- vi.fn(),
175
- );
176
 
177
  expect(pinnedRequestMock).not.toHaveBeenCalled();
178
  expect(recordThumbnailRequested).not.toHaveBeenCalled();
179
  });
180
 
181
  it("responds 400 when the thumbnail URL is missing", async () => {
182
- const handler = getRegisteredHandler();
183
- const response = createResponse();
184
-
185
- await handler(createRequest("/thumbnail?token=abc"), response, vi.fn());
186
 
187
  expect(response.statusCode).toBe(400);
188
  expect(response.end).toHaveBeenCalledWith(
@@ -196,14 +248,7 @@ describe("thumbnailEndpointServerHook", () => {
196
  pinnedRequestMock.mockResolvedValue(
197
  imageResponse(new Uint8Array([1, 2, 3]), "IMAGE/JPEG; charset=binary"),
198
  );
199
- const handler = getRegisteredHandler();
200
- const response = createResponse();
201
-
202
- await handler(
203
- createRequest(requestUrlFor(publicThumbnailUrl())),
204
- response,
205
- vi.fn(),
206
- );
207
 
208
  expect(response.statusCode).toBe(200);
209
  expect(response.setHeader).toHaveBeenCalledWith(
@@ -233,13 +278,8 @@ describe("thumbnailEndpointServerHook", () => {
233
  it("verifies through the thumbnail's own rate-limit budget", async () => {
234
  pinnedRequestMock.mockResolvedValue(imageResponse());
235
  const { thumbnailRateLimiter } = await import("./verifyTokenAndRateLimit");
236
- const handler = getRegisteredHandler();
237
 
238
- await handler(
239
- createRequest(requestUrlFor(publicThumbnailUrl())),
240
- createResponse(),
241
- vi.fn(),
242
- );
243
 
244
  // The whole separate-budget design rests on this wiring: delete the
245
  // options argument and the grid's 30 tile loads draw from the search
@@ -256,10 +296,9 @@ describe("thumbnailEndpointServerHook", () => {
256
  const url = publicThumbnailUrl();
257
  // A fresh response per call: a body can only be read once.
258
  pinnedRequestMock.mockImplementation(async () => imageResponse());
259
- const handler = getRegisteredHandler();
260
 
261
- await handler(createRequest(requestUrlFor(url)), createResponse(), vi.fn());
262
- await handler(createRequest(requestUrlFor(url)), createResponse(), vi.fn());
263
 
264
  expect(pinnedRequestMock).toHaveBeenCalledTimes(1);
265
  // Both requests are demand, so both count even though only one fetched.
@@ -268,43 +307,21 @@ describe("thumbnailEndpointServerHook", () => {
268
 
269
  it("refuses a URL that resolves into a private address", async () => {
270
  lookupMock.mockResolvedValue([{ address: "192.168.1.5", family: 4 }]);
271
- const handler = getRegisteredHandler();
272
- const response = createResponse();
273
-
274
- await handler(
275
- createRequest(requestUrlFor(publicThumbnailUrl())),
276
- response,
277
- vi.fn(),
278
- );
279
 
280
- expect(response.statusCode).toBe(403);
281
- expect(pinnedRequestMock).not.toHaveBeenCalled();
282
- expect(recordThumbnailBlocked).toHaveBeenCalledTimes(1);
283
- expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
284
  });
285
 
286
  it("refuses a URL with a non-HTTP scheme", async () => {
287
- const handler = getRegisteredHandler();
288
- const response = createResponse();
289
-
290
- await handler(
291
- createRequest(requestUrlFor("file:///etc/passwd")),
292
- response,
293
- vi.fn(),
294
- );
295
 
296
- expect(response.statusCode).toBe(403);
297
- expect(pinnedRequestMock).not.toHaveBeenCalled();
298
- expect(recordThumbnailBlocked).toHaveBeenCalledTimes(1);
299
- expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
300
  });
301
 
302
  it("refuses a URL longer than the cap", async () => {
303
- const handler = getRegisteredHandler();
304
- const response = createResponse();
305
- const longUrl = `https://thumbs.example.com/${"a".repeat(2050)}`;
306
-
307
- await handler(createRequest(requestUrlFor(longUrl)), response, vi.fn());
308
 
309
  expect(response.statusCode).toBe(400);
310
  expect(pinnedRequestMock).not.toHaveBeenCalled();
@@ -320,14 +337,7 @@ describe("thumbnailEndpointServerHook", () => {
320
  .mockResolvedValueOnce([{ address: "93.184.216.34", family: 4 }])
321
  .mockResolvedValue([{ address: "10.0.0.7", family: 4 }]);
322
  pinnedRequestMock.mockResolvedValue(imageResponse());
323
- const handler = getRegisteredHandler();
324
- const response = createResponse();
325
-
326
- await handler(
327
- createRequest(requestUrlFor(publicThumbnailUrl())),
328
- response,
329
- vi.fn(),
330
- );
331
 
332
  expect(response.statusCode).toBe(200);
333
  expect(pinnedRequestMock).toHaveBeenCalledTimes(1);
@@ -346,14 +356,7 @@ describe("thumbnailEndpointServerHook", () => {
346
  location: "http://10.0.0.7/thumb.jpg",
347
  }),
348
  );
349
- const handler = getRegisteredHandler();
350
- const response = createResponse();
351
-
352
- await handler(
353
- createRequest(requestUrlFor(publicThumbnailUrl())),
354
- response,
355
- vi.fn(),
356
- );
357
 
358
  expect(response.statusCode).toBe(403);
359
  // The redirect target was refused at validation: its socket was never
@@ -367,38 +370,18 @@ describe("thumbnailEndpointServerHook", () => {
367
  pinnedRequestMock.mockResolvedValue(
368
  fakeIncoming(new Uint8Array(), 404, {}),
369
  );
370
- const handler = getRegisteredHandler();
371
- const response = createResponse();
372
-
373
- await handler(
374
- createRequest(requestUrlFor(publicThumbnailUrl())),
375
- response,
376
- vi.fn(),
377
- );
378
 
379
- expect(response.statusCode).toBe(502);
380
- expect(response.setHeader).toHaveBeenCalledWith(
381
- "Cache-Control",
382
- "no-store",
383
- );
384
- expect(response.end).toHaveBeenCalledWith(
385
- JSON.stringify({ error: "Thumbnail could not be fetched" }),
386
- );
387
- expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
388
  });
389
 
390
  it("logs why a fetch failed, never the thumbnail URL or its host", async () => {
391
  pinnedRequestMock.mockResolvedValue(
392
  fakeIncoming(new Uint8Array(), 403, {}),
393
  );
394
- const handler = getRegisteredHandler();
395
  const thumbnailUrl = publicThumbnailUrl();
396
 
397
- await handler(
398
- createRequest(requestUrlFor(thumbnailUrl)),
399
- createResponse(),
400
- vi.fn(),
401
- );
402
 
403
  const output = logLines.join("\n");
404
  expect(output).toContain("Thumbnail fetch failed: HTTP 403");
@@ -411,14 +394,7 @@ describe("thumbnailEndpointServerHook", () => {
411
  "content-type": "text/html",
412
  }),
413
  );
414
- const handler = getRegisteredHandler();
415
- const response = createResponse();
416
-
417
- await handler(
418
- createRequest(requestUrlFor(publicThumbnailUrl())),
419
- response,
420
- vi.fn(),
421
- );
422
 
423
  expect(response.statusCode).toBe(502);
424
  expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
@@ -433,14 +409,7 @@ describe("thumbnailEndpointServerHook", () => {
433
  { "content-type": "image/svg+xml" },
434
  ),
435
  );
436
- const handler = getRegisteredHandler();
437
- const response = createResponse();
438
-
439
- await handler(
440
- createRequest(requestUrlFor(publicThumbnailUrl())),
441
- response,
442
- vi.fn(),
443
- );
444
 
445
  expect(response.statusCode).toBe(502);
446
  expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
@@ -450,14 +419,7 @@ describe("thumbnailEndpointServerHook", () => {
450
  pinnedRequestMock.mockResolvedValueOnce(
451
  fakeIncoming(new Uint8Array(), 302, { location: "http://[" }),
452
  );
453
- const handler = getRegisteredHandler();
454
- const response = createResponse();
455
-
456
- await handler(
457
- createRequest(requestUrlFor(publicThumbnailUrl())),
458
- response,
459
- vi.fn(),
460
- );
461
 
462
  expect(response.statusCode).toBe(502);
463
  expect(pinnedRequestMock).toHaveBeenCalledTimes(1);
@@ -469,30 +431,15 @@ describe("thumbnailEndpointServerHook", () => {
469
  pinnedRequestMock
470
  .mockResolvedValueOnce(fakeIncoming(new Uint8Array(), 404, {}))
471
  .mockResolvedValueOnce(imageResponse());
472
- const handler = getRegisteredHandler();
473
-
474
- const first = createResponse();
475
- await handler(createRequest(requestUrlFor(url)), first, vi.fn());
476
- expect(first.statusCode).toBe(502);
477
 
478
- const second = createResponse();
479
- await handler(createRequest(requestUrlFor(url)), second, vi.fn());
480
- expect(second.statusCode).toBe(200);
481
- expect(pinnedRequestMock).toHaveBeenCalledTimes(2);
482
  });
483
 
484
  it("answers 502 when the upstream body is empty", async () => {
485
  pinnedRequestMock.mockResolvedValue(
486
  fakeIncoming(new Uint8Array(), 200, { "content-type": "image/jpeg" }),
487
  );
488
- const handler = getRegisteredHandler();
489
- const response = createResponse();
490
-
491
- await handler(
492
- createRequest(requestUrlFor(publicThumbnailUrl())),
493
- response,
494
- vi.fn(),
495
- );
496
 
497
  expect(response.statusCode).toBe(502);
498
  expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
@@ -500,20 +447,11 @@ describe("thumbnailEndpointServerHook", () => {
500
 
501
  it("bounds a hanging DNS lookup with the same deadline", async () => {
502
  // A resolver that never settles must not add its own timeout on top of
503
- // the documented one. Matches THUMBNAIL_TIMEOUT_MS.
504
- const thumbnailTimeoutMs = 3000;
505
  lookupMock.mockImplementation(() => new Promise(() => {}));
506
  vi.useFakeTimers();
507
  try {
508
- const handler = getRegisteredHandler();
509
- const response = createResponse();
510
- const handled = handler(
511
- createRequest(requestUrlFor(publicThumbnailUrl())),
512
- response,
513
- vi.fn(),
514
- );
515
- await vi.advanceTimersByTimeAsync(thumbnailTimeoutMs);
516
- await handled;
517
 
518
  expect(response.statusCode).toBe(502);
519
  expect(pinnedRequestMock).not.toHaveBeenCalled();
@@ -524,8 +462,6 @@ describe("thumbnailEndpointServerHook", () => {
524
  });
525
 
526
  it("answers 502 when the host never answers within the timeout", async () => {
527
- // Matches THUMBNAIL_TIMEOUT_MS in thumbnailEndpointServerHook.ts.
528
- const thumbnailTimeoutMs = 3000;
529
  vi.useFakeTimers();
530
  try {
531
  pinnedRequestMock.mockImplementation(
@@ -536,15 +472,7 @@ describe("thumbnailEndpointServerHook", () => {
536
  );
537
  }),
538
  );
539
- const handler = getRegisteredHandler();
540
- const response = createResponse();
541
- const handled = handler(
542
- createRequest(requestUrlFor(publicThumbnailUrl())),
543
- response,
544
- vi.fn(),
545
- );
546
- await vi.advanceTimersByTimeAsync(thumbnailTimeoutMs);
547
- await handled;
548
 
549
  expect(response.statusCode).toBe(502);
550
  expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
@@ -559,14 +487,7 @@ describe("thumbnailEndpointServerHook", () => {
559
  location: "https://thumbs.example.com/loop.jpg",
560
  }),
561
  );
562
- const handler = getRegisteredHandler();
563
- const response = createResponse();
564
-
565
- await handler(
566
- createRequest(requestUrlFor(publicThumbnailUrl())),
567
- response,
568
- vi.fn(),
569
- );
570
 
571
  expect(response.statusCode).toBe(502);
572
  // One request per hop, four hops for three redirects.
@@ -579,24 +500,9 @@ describe("thumbnailEndpointServerHook", () => {
579
  // as a damaged image.
580
  const bigBody = new Uint8Array(600_000).fill(7);
581
  pinnedRequestMock.mockResolvedValue(imageResponse(bigBody));
582
- const handler = getRegisteredHandler();
583
- const response = createResponse();
584
-
585
- await handler(
586
- createRequest(requestUrlFor(publicThumbnailUrl())),
587
- response,
588
- vi.fn(),
589
- );
590
 
591
- expect(response.statusCode).toBe(502);
592
- expect(response.setHeader).toHaveBeenCalledWith(
593
- "Cache-Control",
594
- "no-store",
595
- );
596
- expect(response.end).toHaveBeenCalledWith(
597
- JSON.stringify({ error: "Thumbnail could not be fetched" }),
598
- );
599
- expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
600
  expect(logLines.join("\n")).toContain(
601
  "Thumbnail fetch failed: larger than 500000 bytes",
602
  );
@@ -607,29 +513,14 @@ describe("thumbnailEndpointServerHook", () => {
607
  pinnedRequestMock
608
  .mockResolvedValueOnce(imageResponse(new Uint8Array(600_000).fill(7)))
609
  .mockResolvedValueOnce(imageResponse());
610
- const handler = getRegisteredHandler();
611
-
612
- const first = createResponse();
613
- await handler(createRequest(requestUrlFor(url)), first, vi.fn());
614
- expect(first.statusCode).toBe(502);
615
 
616
- const second = createResponse();
617
- await handler(createRequest(requestUrlFor(url)), second, vi.fn());
618
- expect(second.statusCode).toBe(200);
619
- expect(pinnedRequestMock).toHaveBeenCalledTimes(2);
620
  });
621
 
622
  it("serves a body of exactly the byte cap", async () => {
623
  const capSizedBody = new Uint8Array(500_000).fill(7);
624
  pinnedRequestMock.mockResolvedValue(imageResponse(capSizedBody));
625
- const handler = getRegisteredHandler();
626
- const response = createResponse();
627
-
628
- await handler(
629
- createRequest(requestUrlFor(publicThumbnailUrl())),
630
- response,
631
- vi.fn(),
632
- );
633
 
634
  expect(response.statusCode).toBe(200);
635
  const body = response.end.mock.calls[0][0] as Buffer;
@@ -640,36 +531,33 @@ describe("thumbnailEndpointServerHook", () => {
640
  it("evicts the least recently used entry, not the least recently loaded one", async () => {
641
  // A fresh response per call: a body can only be read once.
642
  pinnedRequestMock.mockImplementation(async () => imageResponse());
643
- const handler = getRegisteredHandler();
644
  // A clean slate, so the eviction side is exactly where this test puts it.
645
  resetThumbnailCache();
646
  const firstUrl = publicThumbnailUrl();
647
  const secondUrl = publicThumbnailUrl();
648
  const maxEntries = getThumbnailCacheLimits().entries;
649
- const load = (url: string) =>
650
- handler(createRequest(requestUrlFor(url)), createResponse(), vi.fn());
651
  const fetched = (url: string) =>
652
  pinnedRequestMock.mock.calls.filter((call) => String(call[0]) === url)
653
  .length;
654
 
655
- await load(firstUrl);
656
- await load(secondUrl);
657
 
658
  // Re-reading firstUrl promotes it, so secondUrl is the eviction candidate.
659
- await load(firstUrl);
660
 
661
  for (let i = 0; i < maxEntries - 2; i += 1) {
662
- await load(publicThumbnailUrl());
663
  }
664
  // This insert pushes the cache past the cap: exactly one entry is evicted.
665
- await load(publicThumbnailUrl());
666
 
667
  // firstUrl (promoted by the re-read) survived and serves from the cache.
668
  // A cache without promote-on-hit would have evicted it, being the oldest
669
  // load.
670
- await load(firstUrl);
671
  expect(fetched(firstUrl)).toBe(1);
672
- await load(secondUrl);
673
  expect(fetched(secondUrl)).toBe(2);
674
  });
675
  });
 
88
  return `/thumbnail?u=${encodeURIComponent(thumbnailUrl)}&token=abc`;
89
  }
90
 
91
+ /**
92
+ * Sends `path` through the hook; returns the response and the `next` it was
93
+ * given. Registers a fresh hook per call; the cache is module state, so calls
94
+ * still share it.
95
+ */
96
+ async function requestPath(path: string) {
97
+ const response = createResponse();
98
+ const next = vi.fn();
99
+ await getRegisteredHandler()(createRequest(path), response, next);
100
+ return { response, next };
101
+ }
102
+
103
+ /**
104
+ * Requests the thumbnail at `thumbnailUrl` through the hook; returns the
105
+ * response. The default is a new URL each time, so it never hits the cache.
106
+ */
107
+ async function requestThumbnail(thumbnailUrl = publicThumbnailUrl()) {
108
+ return (await requestPath(requestUrlFor(thumbnailUrl))).response;
109
+ }
110
+
111
+ // Matches THUMBNAIL_TIMEOUT_MS in thumbnailEndpointServerHook.ts, which does
112
+ // not export it.
113
+ const THUMBNAIL_TIMEOUT_MS = 3000;
114
+
115
+ /**
116
+ * Requests a thumbnail and lets `ms` of fake time pass while the hook waits.
117
+ * Needs `vi.useFakeTimers()`.
118
+ */
119
+ async function requestThumbnailPast(ms: number) {
120
+ const response = createResponse();
121
+ const handled = getRegisteredHandler()(
122
+ createRequest(requestUrlFor(publicThumbnailUrl())),
123
+ response,
124
+ vi.fn(),
125
+ );
126
+ await vi.advanceTimersByTimeAsync(ms);
127
+ await handled;
128
+ return response;
129
+ }
130
+
131
+ /** Refused at validation: no socket opened, counted as blocked and dropped. */
132
+ function expectRefusedBeforeFetch(response: ReturnType<typeof createResponse>) {
133
+ expect(response.statusCode).toBe(403);
134
+ expect(pinnedRequestMock).not.toHaveBeenCalled();
135
+ expect(recordThumbnailBlocked).toHaveBeenCalledTimes(1);
136
+ expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
137
+ }
138
+
139
+ /** The generic 502, never cached by the browser, counted as dropped. */
140
+ function expectCouldNotFetch(response: ReturnType<typeof createResponse>) {
141
+ expect(response.statusCode).toBe(502);
142
+ expect(response.setHeader).toHaveBeenCalledWith("Cache-Control", "no-store");
143
+ expect(response.end).toHaveBeenCalledWith(
144
+ JSON.stringify({ error: "Thumbnail could not be fetched" }),
145
+ );
146
+ expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
147
+ }
148
+
149
+ /** The first load of `url` fails; the second fetches again and succeeds. */
150
+ async function expectFailureIsRetried(url: string) {
151
+ const first = await requestThumbnail(url);
152
+ expect(first.statusCode).toBe(502);
153
+ const second = await requestThumbnail(url);
154
+ expect(second.statusCode).toBe(200);
155
+ expect(pinnedRequestMock).toHaveBeenCalledTimes(2);
156
+ }
157
+
158
  // Shaped like the IncomingMessage the pinned request resolves with: the
159
  // fields the hook reads, plus the async iteration readCappedStream drives.
160
  function fakeIncoming(
 
203
  });
204
 
205
  it("passes through requests that aren't under /thumbnail", async () => {
206
+ const { next } = await requestPath("/status");
 
 
 
207
 
208
  expect(next).toHaveBeenCalled();
209
  expect(pinnedRequestMock).not.toHaveBeenCalled();
 
214
  "/thumbnailX?token=abc",
215
  "/thumbnail/extra?token=abc",
216
  ])("passes through %s, which is not the /thumbnail route", async (url) => {
217
+ const { response, next } = await requestPath(url);
 
 
 
 
218
 
219
  expect(next).toHaveBeenCalledTimes(1);
220
  expect(response.end).not.toHaveBeenCalled();
 
226
  vi.mocked(handleTokenVerification).mockResolvedValue({
227
  shouldContinue: false,
228
  });
 
229
 
230
+ await requestThumbnail();
 
 
 
 
231
 
232
  expect(pinnedRequestMock).not.toHaveBeenCalled();
233
  expect(recordThumbnailRequested).not.toHaveBeenCalled();
234
  });
235
 
236
  it("responds 400 when the thumbnail URL is missing", async () => {
237
+ const { response } = await requestPath("/thumbnail?token=abc");
 
 
 
238
 
239
  expect(response.statusCode).toBe(400);
240
  expect(response.end).toHaveBeenCalledWith(
 
248
  pinnedRequestMock.mockResolvedValue(
249
  imageResponse(new Uint8Array([1, 2, 3]), "IMAGE/JPEG; charset=binary"),
250
  );
251
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
252
 
253
  expect(response.statusCode).toBe(200);
254
  expect(response.setHeader).toHaveBeenCalledWith(
 
278
  it("verifies through the thumbnail's own rate-limit budget", async () => {
279
  pinnedRequestMock.mockResolvedValue(imageResponse());
280
  const { thumbnailRateLimiter } = await import("./verifyTokenAndRateLimit");
 
281
 
282
+ await requestThumbnail();
 
 
 
 
283
 
284
  // The whole separate-budget design rests on this wiring: delete the
285
  // options argument and the grid's 30 tile loads draw from the search
 
296
  const url = publicThumbnailUrl();
297
  // A fresh response per call: a body can only be read once.
298
  pinnedRequestMock.mockImplementation(async () => imageResponse());
 
299
 
300
+ await requestThumbnail(url);
301
+ await requestThumbnail(url);
302
 
303
  expect(pinnedRequestMock).toHaveBeenCalledTimes(1);
304
  // Both requests are demand, so both count even though only one fetched.
 
307
 
308
  it("refuses a URL that resolves into a private address", async () => {
309
  lookupMock.mockResolvedValue([{ address: "192.168.1.5", family: 4 }]);
310
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
311
 
312
+ expectRefusedBeforeFetch(response);
 
 
 
313
  });
314
 
315
  it("refuses a URL with a non-HTTP scheme", async () => {
316
+ const response = await requestThumbnail("file:///etc/passwd");
 
 
 
 
 
 
 
317
 
318
+ expectRefusedBeforeFetch(response);
 
 
 
319
  });
320
 
321
  it("refuses a URL longer than the cap", async () => {
322
+ const response = await requestThumbnail(
323
+ `https://thumbs.example.com/${"a".repeat(2050)}`,
324
+ );
 
 
325
 
326
  expect(response.statusCode).toBe(400);
327
  expect(pinnedRequestMock).not.toHaveBeenCalled();
 
337
  .mockResolvedValueOnce([{ address: "93.184.216.34", family: 4 }])
338
  .mockResolvedValue([{ address: "10.0.0.7", family: 4 }]);
339
  pinnedRequestMock.mockResolvedValue(imageResponse());
340
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
341
 
342
  expect(response.statusCode).toBe(200);
343
  expect(pinnedRequestMock).toHaveBeenCalledTimes(1);
 
356
  location: "http://10.0.0.7/thumb.jpg",
357
  }),
358
  );
359
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
360
 
361
  expect(response.statusCode).toBe(403);
362
  // The redirect target was refused at validation: its socket was never
 
370
  pinnedRequestMock.mockResolvedValue(
371
  fakeIncoming(new Uint8Array(), 404, {}),
372
  );
373
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
374
 
375
+ expectCouldNotFetch(response);
 
 
 
 
 
 
 
 
376
  });
377
 
378
  it("logs why a fetch failed, never the thumbnail URL or its host", async () => {
379
  pinnedRequestMock.mockResolvedValue(
380
  fakeIncoming(new Uint8Array(), 403, {}),
381
  );
 
382
  const thumbnailUrl = publicThumbnailUrl();
383
 
384
+ await requestThumbnail(thumbnailUrl);
 
 
 
 
385
 
386
  const output = logLines.join("\n");
387
  expect(output).toContain("Thumbnail fetch failed: HTTP 403");
 
394
  "content-type": "text/html",
395
  }),
396
  );
397
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
398
 
399
  expect(response.statusCode).toBe(502);
400
  expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
 
409
  { "content-type": "image/svg+xml" },
410
  ),
411
  );
412
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
413
 
414
  expect(response.statusCode).toBe(502);
415
  expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
 
419
  pinnedRequestMock.mockResolvedValueOnce(
420
  fakeIncoming(new Uint8Array(), 302, { location: "http://[" }),
421
  );
422
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
423
 
424
  expect(response.statusCode).toBe(502);
425
  expect(pinnedRequestMock).toHaveBeenCalledTimes(1);
 
431
  pinnedRequestMock
432
  .mockResolvedValueOnce(fakeIncoming(new Uint8Array(), 404, {}))
433
  .mockResolvedValueOnce(imageResponse());
 
 
 
 
 
434
 
435
+ await expectFailureIsRetried(url);
 
 
 
436
  });
437
 
438
  it("answers 502 when the upstream body is empty", async () => {
439
  pinnedRequestMock.mockResolvedValue(
440
  fakeIncoming(new Uint8Array(), 200, { "content-type": "image/jpeg" }),
441
  );
442
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
443
 
444
  expect(response.statusCode).toBe(502);
445
  expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
 
447
 
448
  it("bounds a hanging DNS lookup with the same deadline", async () => {
449
  // A resolver that never settles must not add its own timeout on top of
450
+ // the documented one.
 
451
  lookupMock.mockImplementation(() => new Promise(() => {}));
452
  vi.useFakeTimers();
453
  try {
454
+ const response = await requestThumbnailPast(THUMBNAIL_TIMEOUT_MS);
 
 
 
 
 
 
 
 
455
 
456
  expect(response.statusCode).toBe(502);
457
  expect(pinnedRequestMock).not.toHaveBeenCalled();
 
462
  });
463
 
464
  it("answers 502 when the host never answers within the timeout", async () => {
 
 
465
  vi.useFakeTimers();
466
  try {
467
  pinnedRequestMock.mockImplementation(
 
472
  );
473
  }),
474
  );
475
+ const response = await requestThumbnailPast(THUMBNAIL_TIMEOUT_MS);
 
 
 
 
 
 
 
 
476
 
477
  expect(response.statusCode).toBe(502);
478
  expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
 
487
  location: "https://thumbs.example.com/loop.jpg",
488
  }),
489
  );
490
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
491
 
492
  expect(response.statusCode).toBe(502);
493
  // One request per hop, four hops for three redirects.
 
500
  // as a damaged image.
501
  const bigBody = new Uint8Array(600_000).fill(7);
502
  pinnedRequestMock.mockResolvedValue(imageResponse(bigBody));
503
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
504
 
505
+ expectCouldNotFetch(response);
 
 
 
 
 
 
 
 
506
  expect(logLines.join("\n")).toContain(
507
  "Thumbnail fetch failed: larger than 500000 bytes",
508
  );
 
513
  pinnedRequestMock
514
  .mockResolvedValueOnce(imageResponse(new Uint8Array(600_000).fill(7)))
515
  .mockResolvedValueOnce(imageResponse());
 
 
 
 
 
516
 
517
+ await expectFailureIsRetried(url);
 
 
 
518
  });
519
 
520
  it("serves a body of exactly the byte cap", async () => {
521
  const capSizedBody = new Uint8Array(500_000).fill(7);
522
  pinnedRequestMock.mockResolvedValue(imageResponse(capSizedBody));
523
+ const response = await requestThumbnail();
 
 
 
 
 
 
 
524
 
525
  expect(response.statusCode).toBe(200);
526
  const body = response.end.mock.calls[0][0] as Buffer;
 
531
  it("evicts the least recently used entry, not the least recently loaded one", async () => {
532
  // A fresh response per call: a body can only be read once.
533
  pinnedRequestMock.mockImplementation(async () => imageResponse());
 
534
  // A clean slate, so the eviction side is exactly where this test puts it.
535
  resetThumbnailCache();
536
  const firstUrl = publicThumbnailUrl();
537
  const secondUrl = publicThumbnailUrl();
538
  const maxEntries = getThumbnailCacheLimits().entries;
 
 
539
  const fetched = (url: string) =>
540
  pinnedRequestMock.mock.calls.filter((call) => String(call[0]) === url)
541
  .length;
542
 
543
+ await requestThumbnail(firstUrl);
544
+ await requestThumbnail(secondUrl);
545
 
546
  // Re-reading firstUrl promotes it, so secondUrl is the eviction candidate.
547
+ await requestThumbnail(firstUrl);
548
 
549
  for (let i = 0; i < maxEntries - 2; i += 1) {
550
+ await requestThumbnail(publicThumbnailUrl());
551
  }
552
  // This insert pushes the cache past the cap: exactly one entry is evicted.
553
+ await requestThumbnail(publicThumbnailUrl());
554
 
555
  // firstUrl (promoted by the re-read) survived and serves from the cache.
556
  // A cache without promote-on-hit would have evicted it, being the oldest
557
  // load.
558
+ await requestThumbnail(firstUrl);
559
  expect(fetched(firstUrl)).toBe(1);
560
+ await requestThumbnail(secondUrl);
561
  expect(fetched(secondUrl)).toBe(2);
562
  });
563
  });
server/validateAccessKeyServerHook.test.ts CHANGED
@@ -55,84 +55,66 @@ function makeValidAccessKeyHash(suffix: string): string {
55
  return `$argon2id$v=19$m=512,t=16,p=1$${salt}$${digest}`;
56
  }
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  describe("validateAccessKeyServerHook", () => {
59
  it("should skip non-matching URLs", async () => {
60
- const { validateAccessKeyServerHook } = await import(
61
- "./validateAccessKeyServerHook"
62
- );
63
- const use = vi.fn();
64
- validateAccessKeyServerHook({
65
- middlewares: { use },
66
- } as never);
67
- const handler = use.mock.calls[0][0] as (
68
- req: { url: string; method: string },
69
- res: unknown,
70
- next: () => void,
71
- ) => void;
72
  const next = vi.fn();
73
- handler({ url: "/other", method: "POST" }, {}, next);
74
  expect(next).toHaveBeenCalled();
75
  });
76
 
77
  it("should skip non-POST methods", async () => {
78
- const { validateAccessKeyServerHook } = await import(
79
- "./validateAccessKeyServerHook"
80
- );
81
- const use = vi.fn();
82
- validateAccessKeyServerHook({
83
- middlewares: { use },
84
- } as never);
85
- const handler = use.mock.calls[0][0] as (
86
- req: { url: string; method: string },
87
- res: unknown,
88
- next: () => void,
89
- ) => void;
90
  const next = vi.fn();
91
- handler({ url: "/api/validate-access-key", method: "GET" }, {}, next);
 
 
 
 
92
  expect(next).toHaveBeenCalled();
93
  });
94
 
95
  it("should return valid: true for a matching access key", async () => {
96
  process.env.ACCESS_KEYS = "test-key";
97
  mockArgon2Verify.mockResolvedValue(true);
98
- const { validateAccessKeyServerHook } = await import(
99
- "./validateAccessKeyServerHook"
100
- );
101
- const use = vi.fn();
102
- validateAccessKeyServerHook({
103
- middlewares: { use },
104
- } as never);
105
- const handler = use.mock.calls[0][0] as (
106
- req: {
107
- url: string;
108
- method: string;
109
- on: (event: string, cb: (chunk: string) => void) => void;
110
- },
111
- res: {
112
- setHeader: ReturnType<typeof vi.fn>;
113
- end: ReturnType<typeof vi.fn>;
114
- },
115
- next: () => void,
116
- ) => void;
117
-
118
- const res = makeMockResponse();
119
- const req = makeMockRequest(
120
- "/api/validate-access-key",
121
- "POST",
122
- JSON.stringify({ accessKeyHash: makeValidAccessKeyHash("valid") }),
123
- );
124
-
125
- await new Promise<void>((resolve) => {
126
- void handler(req as never, res as never, () => {});
127
- // The handler consumes a rate-limit point (async) before it registers its
128
- // end listener, so trigger it on a later macrotask.
129
- setImmediate(() => {
130
- for (const cb of req.endCallbacks) {
131
- cb();
132
- }
133
- setTimeout(resolve, 50);
134
- });
135
- });
136
 
137
  expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true }));
138
  expect(mockConsumeRateLimitPoint).toHaveBeenCalledTimes(1);
@@ -146,42 +128,7 @@ describe("validateAccessKeyServerHook", () => {
146
  return password === "other-key";
147
  },
148
  );
149
- const { validateAccessKeyServerHook } = await import(
150
- "./validateAccessKeyServerHook"
151
- );
152
- const use = vi.fn();
153
- validateAccessKeyServerHook({
154
- middlewares: { use },
155
- } as never);
156
- const handler = use.mock.calls[0][0] as (
157
- req: {
158
- url: string;
159
- method: string;
160
- on: (event: string, cb: (chunk: string) => void) => void;
161
- },
162
- res: {
163
- setHeader: ReturnType<typeof vi.fn>;
164
- end: ReturnType<typeof vi.fn>;
165
- },
166
- next: () => void,
167
- ) => void;
168
-
169
- const res = makeMockResponse();
170
- const req = makeMockRequest(
171
- "/api/validate-access-key",
172
- "POST",
173
- JSON.stringify({ accessKeyHash: makeValidAccessKeyHash("valid") }),
174
- );
175
-
176
- await new Promise<void>((resolve) => {
177
- void handler(req as never, res as never, () => {});
178
- setImmediate(() => {
179
- for (const cb of req.endCallbacks) {
180
- cb();
181
- }
182
- setTimeout(resolve, 50);
183
- });
184
- });
185
 
186
  expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true }));
187
  const verifiedPasswords = mockArgon2Verify.mock.calls.map(
@@ -193,38 +140,7 @@ describe("validateAccessKeyServerHook", () => {
193
  it("responds 429 and skips the argon2 loop when the limiter refuses", async () => {
194
  process.env.ACCESS_KEYS = "test-key";
195
  mockConsumeRateLimitPoint.mockResolvedValue(false);
196
- const { validateAccessKeyServerHook } = await import(
197
- "./validateAccessKeyServerHook"
198
- );
199
- const use = vi.fn();
200
- validateAccessKeyServerHook({
201
- middlewares: { use },
202
- } as never);
203
- const handler = use.mock.calls[0][0] as (
204
- req: {
205
- url: string;
206
- method: string;
207
- on: (event: string, cb: (chunk: string) => void) => void;
208
- },
209
- res: {
210
- setHeader: ReturnType<typeof vi.fn>;
211
- end: ReturnType<typeof vi.fn>;
212
- statusCode: number;
213
- },
214
- next: () => void,
215
- ) => void;
216
-
217
- const res = makeMockResponse();
218
- const req = makeMockRequest(
219
- "/api/validate-access-key",
220
- "POST",
221
- JSON.stringify({ accessKeyHash: makeValidAccessKeyHash("valid") }),
222
- );
223
-
224
- await new Promise<void>((resolve) => {
225
- handler(req as never, res as never, () => {});
226
- setTimeout(resolve, 50);
227
- });
228
 
229
  expect(res.statusCode).toBe(429);
230
  expect(res.end).toHaveBeenCalledWith(
@@ -237,89 +153,18 @@ describe("validateAccessKeyServerHook", () => {
237
  it("should return valid: false when no access keys match", async () => {
238
  process.env.ACCESS_KEYS = "test-key";
239
  mockArgon2Verify.mockResolvedValue(false);
240
- const { validateAccessKeyServerHook } = await import(
241
- "./validateAccessKeyServerHook"
242
- );
243
- const use = vi.fn();
244
- validateAccessKeyServerHook({
245
- middlewares: { use },
246
- } as never);
247
- const handler = use.mock.calls[0][0] as (
248
- req: {
249
- url: string;
250
- method: string;
251
- on: (event: string, cb: (chunk: string) => void) => void;
252
- },
253
- res: {
254
- setHeader: ReturnType<typeof vi.fn>;
255
- end: ReturnType<typeof vi.fn>;
256
- },
257
- next: () => void,
258
- ) => void;
259
-
260
- const res = makeMockResponse();
261
- const req = makeMockRequest(
262
- "/api/validate-access-key",
263
- "POST",
264
- JSON.stringify({ accessKeyHash: makeValidAccessKeyHash("wrong") }),
265
- );
266
-
267
- await new Promise<void>((resolve) => {
268
- void handler(req as never, res as never, () => {});
269
- setImmediate(() => {
270
- for (const cb of req.endCallbacks) {
271
- cb();
272
- }
273
- setTimeout(resolve, 50);
274
- });
275
- });
276
 
277
  expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: false }));
278
  });
279
 
280
  it("refuses a hash whose parameter block differs from the client's before argon2Verify runs", async () => {
281
  process.env.ACCESS_KEYS = "test-key";
282
- const { validateAccessKeyServerHook } = await import(
283
- "./validateAccessKeyServerHook"
284
- );
285
- const use = vi.fn();
286
- validateAccessKeyServerHook({
287
- middlewares: { use },
288
- } as never);
289
- const handler = use.mock.calls[0][0] as (
290
- req: {
291
- url: string;
292
- method: string;
293
- on: (event: string, cb: (chunk: string) => void) => void;
294
- },
295
- res: {
296
- setHeader: ReturnType<typeof vi.fn>;
297
- end: ReturnType<typeof vi.fn>;
298
- statusCode: number;
299
- },
300
- next: () => void,
301
- ) => void;
302
-
303
- const res = makeMockResponse();
304
  // A hash with inflated parameters: m=4194304 would force a multi-gigabyte
305
  // allocation if argon2Verify ever saw it.
306
  const malicious =
307
  "$argon2id$v=19$m=4194304,t=1000,p=1$xJaao6+z/VEA4+CU/+LAKg$JCE6vg7EHYLNv+EfNk1R6oJsEoDOsv2zNAXzQrrvI0E";
308
- const req = makeMockRequest(
309
- "/api/validate-access-key",
310
- "POST",
311
- JSON.stringify({ accessKeyHash: malicious }),
312
- );
313
-
314
- await new Promise<void>((resolve) => {
315
- void handler(req as never, res as never, () => {});
316
- setImmediate(() => {
317
- for (const cb of req.endCallbacks) {
318
- cb();
319
- }
320
- setTimeout(resolve, 50);
321
- });
322
- });
323
 
324
  expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: false }));
325
  expect(mockArgon2Verify).not.toHaveBeenCalled();
@@ -327,39 +172,7 @@ describe("validateAccessKeyServerHook", () => {
327
 
328
  it("should return 400 for invalid JSON body", async () => {
329
  process.env.ACCESS_KEYS = "test-key";
330
- const { validateAccessKeyServerHook } = await import(
331
- "./validateAccessKeyServerHook"
332
- );
333
- const use = vi.fn();
334
- validateAccessKeyServerHook({
335
- middlewares: { use },
336
- } as never);
337
- const handler = use.mock.calls[0][0] as (
338
- req: {
339
- url: string;
340
- method: string;
341
- on: (event: string, cb: (chunk: string) => void) => void;
342
- },
343
- res: {
344
- setHeader: ReturnType<typeof vi.fn>;
345
- end: ReturnType<typeof vi.fn>;
346
- statusCode: { value: number };
347
- },
348
- next: () => void,
349
- ) => void;
350
-
351
- const res = makeMockResponse();
352
- const req = makeMockRequest("/api/validate-access-key", "POST", "not-json");
353
-
354
- await new Promise<void>((resolve) => {
355
- void handler(req as never, res as never, () => {});
356
- setImmediate(() => {
357
- for (const cb of req.endCallbacks) {
358
- cb();
359
- }
360
- setTimeout(resolve, 50);
361
- });
362
- });
363
 
364
  expect(res.statusCode).toBe(400);
365
  expect(res.end).toHaveBeenCalledWith(
@@ -371,16 +184,7 @@ describe("validateAccessKeyServerHook", () => {
371
  describe("request body cap", () => {
372
  it("answers 413 once and ignores the rest of the body", async () => {
373
  process.env.ACCESS_KEYS = "test-key";
374
- const { validateAccessKeyServerHook } = await import(
375
- "./validateAccessKeyServerHook"
376
- );
377
- const use = vi.fn();
378
- validateAccessKeyServerHook({ middlewares: { use } } as never);
379
- const handler = use.mock.calls[0][0] as (
380
- req: unknown,
381
- res: unknown,
382
- next: () => void,
383
- ) => void;
384
 
385
  const destroy = vi.fn();
386
  const dataCallbacks: Array<(chunk: Buffer) => void> = [];
@@ -400,7 +204,7 @@ describe("request body cap", () => {
400
  const res = { statusCode: 200, setHeader: vi.fn(), end: vi.fn() };
401
 
402
  await new Promise<void>((resolve) => {
403
- void handler(req, res, vi.fn());
404
  setImmediate(() => {
405
  // Two chunks, each within the cap on its own, over it together.
406
  for (const cb of dataCallbacks) cb(Buffer.alloc(3 * 1024, "x"));
 
55
  return `$argon2id$v=19$m=512,t=16,p=1$${salt}$${digest}`;
56
  }
57
 
58
+ /** Imports the hook, registers it, and returns its middleware. */
59
+ async function getRegisteredHandler() {
60
+ const { validateAccessKeyServerHook } = await import(
61
+ "./validateAccessKeyServerHook"
62
+ );
63
+ const use = vi.fn();
64
+ validateAccessKeyServerHook({ middlewares: { use } } as never);
65
+ return use.mock.calls[0][0] as (
66
+ req: never,
67
+ res: never,
68
+ next: () => void,
69
+ ) => unknown;
70
+ }
71
+
72
+ /** Posts `body` to the endpoint, lets the request end, waits 50 ms, and returns the response. */
73
+ async function postAccessKeyRequest(body: string) {
74
+ const handler = await getRegisteredHandler();
75
+ const res = makeMockResponse();
76
+ const req = makeMockRequest("/api/validate-access-key", "POST", body);
77
+ await new Promise<void>((resolve) => {
78
+ void handler(req as never, res as never, () => {});
79
+ // The handler consumes a rate-limit point (async) before it registers its
80
+ // end listener, so trigger it on a later macrotask.
81
+ setImmediate(() => {
82
+ for (const cb of req.endCallbacks) {
83
+ cb();
84
+ }
85
+ setTimeout(resolve, 50);
86
+ });
87
+ });
88
+ return res;
89
+ }
90
+
91
+ function postAccessKeyHash(accessKeyHash: string) {
92
+ return postAccessKeyRequest(JSON.stringify({ accessKeyHash }));
93
+ }
94
+
95
  describe("validateAccessKeyServerHook", () => {
96
  it("should skip non-matching URLs", async () => {
97
+ const handler = await getRegisteredHandler();
 
 
 
 
 
 
 
 
 
 
 
98
  const next = vi.fn();
99
+ handler({ url: "/other", method: "POST" } as never, {} as never, next);
100
  expect(next).toHaveBeenCalled();
101
  });
102
 
103
  it("should skip non-POST methods", async () => {
104
+ const handler = await getRegisteredHandler();
 
 
 
 
 
 
 
 
 
 
 
105
  const next = vi.fn();
106
+ handler(
107
+ { url: "/api/validate-access-key", method: "GET" } as never,
108
+ {} as never,
109
+ next,
110
+ );
111
  expect(next).toHaveBeenCalled();
112
  });
113
 
114
  it("should return valid: true for a matching access key", async () => {
115
  process.env.ACCESS_KEYS = "test-key";
116
  mockArgon2Verify.mockResolvedValue(true);
117
+ const res = await postAccessKeyHash(makeValidAccessKeyHash("valid"));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true }));
120
  expect(mockConsumeRateLimitPoint).toHaveBeenCalledTimes(1);
 
128
  return password === "other-key";
129
  },
130
  );
131
+ const res = await postAccessKeyHash(makeValidAccessKeyHash("valid"));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
  expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true }));
134
  const verifiedPasswords = mockArgon2Verify.mock.calls.map(
 
140
  it("responds 429 and skips the argon2 loop when the limiter refuses", async () => {
141
  process.env.ACCESS_KEYS = "test-key";
142
  mockConsumeRateLimitPoint.mockResolvedValue(false);
143
+ const res = await postAccessKeyHash(makeValidAccessKeyHash("valid"));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
  expect(res.statusCode).toBe(429);
146
  expect(res.end).toHaveBeenCalledWith(
 
153
  it("should return valid: false when no access keys match", async () => {
154
  process.env.ACCESS_KEYS = "test-key";
155
  mockArgon2Verify.mockResolvedValue(false);
156
+ const res = await postAccessKeyHash(makeValidAccessKeyHash("wrong"));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: false }));
159
  });
160
 
161
  it("refuses a hash whose parameter block differs from the client's before argon2Verify runs", async () => {
162
  process.env.ACCESS_KEYS = "test-key";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  // A hash with inflated parameters: m=4194304 would force a multi-gigabyte
164
  // allocation if argon2Verify ever saw it.
165
  const malicious =
166
  "$argon2id$v=19$m=4194304,t=1000,p=1$xJaao6+z/VEA4+CU/+LAKg$JCE6vg7EHYLNv+EfNk1R6oJsEoDOsv2zNAXzQrrvI0E";
167
+ const res = await postAccessKeyHash(malicious);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
  expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: false }));
170
  expect(mockArgon2Verify).not.toHaveBeenCalled();
 
172
 
173
  it("should return 400 for invalid JSON body", async () => {
174
  process.env.ACCESS_KEYS = "test-key";
175
+ const res = await postAccessKeyRequest("not-json");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
  expect(res.statusCode).toBe(400);
178
  expect(res.end).toHaveBeenCalledWith(
 
184
  describe("request body cap", () => {
185
  it("answers 413 once and ignores the rest of the body", async () => {
186
  process.env.ACCESS_KEYS = "test-key";
187
+ const handler = await getRegisteredHandler();
 
 
 
 
 
 
 
 
 
188
 
189
  const destroy = vi.fn();
190
  const dataCallbacks: Array<(chunk: Buffer) => void> = [];
 
204
  const res = { statusCode: 200, setHeader: vi.fn(), end: vi.fn() };
205
 
206
  await new Promise<void>((resolve) => {
207
+ void handler(req as never, res as never, vi.fn());
208
  setImmediate(() => {
209
  // Two chunks, each within the cap on its own, over it together.
210
  for (const cb of dataCallbacks) cb(Buffer.alloc(3 * 1024, "x"));