Spaces:
Running
Running
Sync from felladrin/MiniSearch@165e4b2 (part 2)
Browse filesFiles changed (8)
9 unmodified lines101112131415161 unmodified line181920212223249 unmodified lines1. `searches` โ canonical log of each query plus hydrated results payloads (text, image, run metadata, source, pin state).2. `llmResponses` โ snapshot of every AI answer tied to its originating search run, enabling restoration of the assistant output.3. `chatHistory` โ chronological record of chat turns (user/assistant roles) scoped by `conversationId` (the `searchRunId`).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.1 unmodified line## Disabled HistoryWhen `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.## Cleanup Guarantees9 unmodified lines101112131415161 unmodified line181920212223249 unmodified lines1. `searches` โ canonical log of each query plus hydrated results payloads (text, image, run metadata, source, pin state).2. `llmResponses` โ snapshot of every AI answer tied to its originating search run, enabling restoration of the assistant output.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.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.1 unmodified line## Disabled HistoryWhen `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.## Cleanup Guarantees
377 unmodified lines378379380381382383377 unmodified lines`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.**Features:**- Fuzzy search through history377 unmodified lines378379380381382383384385377 unmodified lines`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.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.**Features:**- Fuzzy search through history
95 unmodified lines969798991001011021031042734 unmodified lines28392840284128422843284428452846284728482849285095 unmodified lines"license": "MIT"},"node_modules/@ai-sdk/gateway": {"version": "4.0.152","resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-4.0.152.tgz","integrity": "sha512-8LYMe0uMPbT3XW/Urhca52TSgHXAlQok74EUkWL3qXWJI7naTxJGSF6B7hvIHur+V6ttSyLLZN0rJk+Qu9psqA==","license": "Apache-2.0","dependencies": {"@ai-sdk/provider": "4.0.39",2734 unmodified lines}},"node_modules/ai": {"version": "7.0.179","resolved": "https://registry.npmjs.org/ai/-/ai-7.0.179.tgz","integrity": "sha512-WT2ad3qEQPLne/5RDE/utNMSKYUuNpnGkI46AO/6Lv+IbEJ3kRwbatLX3HNfk25Y7N8LpdqOcSnMLcdw11VyIQ==","license": "Apache-2.0","dependencies": {"@ai-sdk/gateway": "4.0.152","@ai-sdk/provider": "4.0.39","@ai-sdk/provider-utils": "5.0.83"},95 unmodified lines969798991001011021031042734 unmodified lines28392840284128422843284428452846284728482849285095 unmodified lines"license": "MIT"},"node_modules/@ai-sdk/gateway": {"version": "4.0.154","resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-4.0.154.tgz","integrity": "sha512-7noB6L/iZ55MRey35rrcbB/J+rAeyRafhJP6G/+/CkOSHxrcdFeMEbtvdIuXTr5S+AAMMQpka+xnD4zVwn04Sw==","license": "Apache-2.0","dependencies": {"@ai-sdk/provider": "4.0.39",2734 unmodified lines}},"node_modules/ai": {"version": "7.0.181","resolved": "https://registry.npmjs.org/ai/-/ai-7.0.181.tgz","integrity": "sha512-b38KYt7tb/dZkujHZTlLWmhohj2bVbWsZQwAJ8Lt6O2hC8saFfIUEFl1U3RwS8tbQ3cL9nAUpeJiiwhsHuBT3w==","license": "Apache-2.0","dependencies": {"@ai-sdk/gateway": "4.0.154","@ai-sdk/provider": "4.0.39","@ai-sdk/provider-utils": "5.0.83"},
44 unmodified lines4546474849505170 unmodified lines12212312412512612728 unmodified lines1561571581591601611623 unmodified lines16616716816917017117277 unmodified lines2502512522532542552561 unmodified line2582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892 unmodified lines2922932942952962972982993003013023033043053063 unmodified lines3103113123133143153163173183193203213224 unmodified lines3273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583 unmodified lines3623633643653663673683693703713722 unmodified lines3753763773783793803813823833843854 unmodified lines3903913923933943953963973983994004014024034044054064074084091 unmodified line4114124134144154164174184199 unmodified lines4294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634646 unmodified lines4714724734744754764774 unmodified lines4824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225236 unmodified lines53053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359417 unmodified lines61261361461561661761861962062162262362462562662762862963063116 unmodified lines6486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826837 unmodified lines6916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287295 unmodified lines7357367377387397407415 unmodified lines7477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878882 unmodified lines8918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849854 unmodified lines9909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212332 unmodified lines1236123712381239124012411242124312441245124612471248124912501 unmodified line125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913102 unmodified lines13131314131513161317131813191320132113221323132413251326132713281329133013311 unmodified line133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013612 unmodified lines136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813893 unmodified lines1393139413951396139713981399140014011402140314041405140614079 unmodified lines1417141814191420142114221423142414251426142714281429143014311432143314349 unmodified lines1444144514461447144814491450145114521453145414553 unmodified lines14591460146114621463146414656 unmodified lines14721473147414751476147714781479148032 unmodified lines151315141515151615171518151915201521152215231524152515265 unmodified lines1532153315341535153615371538153915401541154215431544154515462 unmodified lines154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158810 unmodified lines15991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163414 unmodified lines16491650165116521653165416551656165716581659166016611662166316646 unmodified lines16711672167316741675167616771678167916801681168216831684168516861687168816891690169144 unmodified linesmethod = "POST",contentType = "application/json",): IncomingMessage {const request = Readable.from([JSON.stringify(body)]) as IncomingMessage;request.url = "/inference?token=abc";request.method = method;request.headers = {70 unmodified lines};}describe("internalApiEndpointServerHook", () => {beforeEach(() => {vi.resetAllMocks();28 unmodified linesawait handler(request, response, vi.fn());expect(response.statusCode).toBe(405);expect(response.setHeader).toHaveBeenCalledWith("Allow", "POST");const payload = JSON.parse(response.end.mock.calls[0][0]);expect(payload.error).toBe("Method Not Allowed");});3 unmodified linesconst request = createRequest({}, "POST", "text/plain");await handler(request, response, vi.fn());expect(response.statusCode).toBe(415);const payload = JSON.parse(response.end.mock.calls[0][0]);expect(payload.error).toBe("Unsupported Media Type");});77 unmodified linesconst response = createResponse();await handler(createRequest(body), response, vi.fn());expect(response.statusCode).toBe(400);const payload = JSON.parse(response.end.mock.calls[0][0]);expect(payload.error).toContain(`Invalid request body: ${expectedPath}`);});1 unmodified lineconst handler = getRegisteredHandler();const response = createResponse();const chunk600k = "x".repeat(600 * 1024);const request = Readable.from([chunk600k, chunk600k]) as IncomingMessage;request.url = "/inference?token=abc";request.method = "POST";request.headers = {host: "localhost:3000","content-type": "application/json",};await handler(request, response, vi.fn());expect(response.statusCode).toBe(413);const payload = JSON.parse(response.end.mock.calls[0][0]);expect(payload.error).toBe("Request body too large");});it("responds 400 when body is not valid JSON", async () => {const handler = getRegisteredHandler();const response = createResponse();const request = Readable.from(["not json at all"]) as IncomingMessage;request.url = "/inference?token=abc";request.method = "POST";request.headers = {host: "localhost:3000","content-type": "application/json",};await handler(request, response, vi.fn());expect(response.statusCode).toBe(400);const payload = JSON.parse(response.end.mock.calls[0][0]);expect(payload.error).toBe("Invalid request body");});});2 unmodified linesit("responds 500 when API configuration is missing", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", undefined);vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", undefined);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);expect(response.statusCode).toBe(500);const payload = JSON.parse(response.end.mock.calls[0][0]);expect(payload.error).toBe("OpenAI API configuration is missing");});});3 unmodified linesvi.mocked(handleTokenVerification).mockResolvedValue({shouldContinue: false,});const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);expect(handleTokenVerification).toHaveBeenCalledWith("abc",expect.anything(),4 unmodified lines});describe("streaming path", () => {const setupStreaming = () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", "http://test-api");vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", "test-key");vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "test-model");vi.mocked(createOpenAICompatible).mockReturnValue({chatModel: vi.fn().mockReturnValue("mock-chat-model"),} as never);};beforeEach(setupStreaming);async function callWithFakeTimers(response = createResponse()) {vi.useFakeTimers();try {const pending = getRegisteredHandler()(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);await vi.runAllTimersAsync();await pending;} finally {vi.useRealTimers();}return response;}function requestedModels() {const provider = vi.mocked(createOpenAICompatible).mock.results[0]3 unmodified linesit("sends the configured reasoning effort upstream", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", " low ");vi.mocked(streamText).mockImplementation(() => streamOf([{ type: "finish" }]) as never,);await callWithFakeTimers();expect(vi.mocked(streamText).mock.calls[0][0].providerOptions).toEqual({openai: { reasoningEffort: "low" },2 unmodified linesit("leaves the reasoning effort to the upstream when unset", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", "");vi.mocked(streamText).mockImplementation(() => streamOf([{ type: "finish" }]) as never,);await callWithFakeTimers();expect(vi.mocked(streamText).mock.calls[0][0].providerOptions,4 unmodified linesvi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", " model-a , model-b ");vi.mocked(streamText).mockImplementationOnce(() => streamOf([]) as never).mockImplementationOnce(() =>streamOf([{ type: "text-delta", text: "Recovered" },{ type: "finish" },]) as never,);const response = await callWithFakeTimers();expect(requestedModels()).toEqual(["model-a", "model-b"]);expect(listOpenAiCompatibleModels).not.toHaveBeenCalled();expect(selectRandomModel).not.toHaveBeenCalled();const writes = response.write.mock.calls.map((c) => c[0]).join("");expect(writes).toContain("Recovered");});1 unmodified line// would end the request after two attempts instead of four.it("walks the configured list a second time before giving up", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "model-a,model-b,");vi.mocked(streamText).mockImplementation(() => streamOf([]) as never);const response = await callWithFakeTimers();expect(requestedModels()).toEqual(["model-a",9 unmodified linesit("retries a single configured model once", async () => {vi.mocked(streamText).mockImplementationOnce(() => streamOf([]) as never).mockImplementationOnce(() =>streamOf([{ type: "text-delta", text: "Second try" },{ type: "finish" },]) as never,);const response = await callWithFakeTimers();expect(requestedModels()).toEqual(["test-model", "test-model"]);const writes = response.write.mock.calls.map((c) => c[0]).join("");expect(writes).toContain("Second try");});it("emits SSE frames on successful stream", async () => {vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "text-delta", text: "Hello" },{ type: "finish" },]) as never,);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);expect(response.setHeader).toHaveBeenCalledWith("Content-Type","text/event-stream",6 unmodified lines"Cache-Control","no-cache",);const writeCalls = response.write.mock.calls.map((c) => c[0]);expect(writeCalls.some((s: string) => s.includes('"content":"Hello"')),).toBe(true);4 unmodified lines});it("passes on why the upstream stopped, so a cut answer is not reported as complete", async () => {vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "text-delta", text: "Cut" },{ type: "finish", finishReason: "length" },]) as never,);const response = createResponse();await getRegisteredHandler()(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);const writes = response.write.mock.calls.map((c) => c[0]).join("");expect(writes).toContain('"finish_reason":"length"');expect(writes).not.toContain('"finish_reason":"stop"');});it("spells the finish reason the way OpenAI does", async () => {vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "finish", finishReason: "content-filter" },]) as never,);const response = createResponse();await getRegisteredHandler()(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);const writes = response.write.mock.calls.map((c) => c[0]).join("");expect(writes).toContain('"finish_reason":"content_filter"');});6 unmodified linesasync (maxTokens, expected) => {vi.stubEnv("MODEL_DEFAULT_MAX_TOKENS", maxTokens);vi.spyOn(console, "error").mockImplementation(() => {});vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "text-delta", text: "Ok" },{ type: "finish" },]) as never,);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({messages: [{ role: "user", content: "hi" }],max_tokens: 9999,}),response,vi.fn(),);const callArgs = vi.mocked(streamText).mock.calls[0][0];expect(callArgs.maxOutputTokens).toBe(expected);},);it("passes max_tokens unchanged when under cap", async () => {vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "text-delta", text: "Ok" },{ type: "finish" },]) as never,);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({messages: [{ role: "user", content: "hi" }],max_tokens: 100,}),response,vi.fn(),);const callArgs = vi.mocked(streamText).mock.calls[0][0];expect(callArgs.maxOutputTokens).toBe(100);});it("passes undefined maxOutputTokens when max_tokens not provided", async () => {vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "text-delta", text: "Ok" },{ type: "finish" },]) as never,);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);const callArgs = vi.mocked(streamText).mock.calls[0][0];expect(callArgs.maxOutputTokens).toBeUndefined();});17 unmodified lines])("passes $param: 0 through instead of dropping it",async ({ reqKey, argKey }) => {vi.mocked(streamText).mockImplementation(() => streamOf([{ type: "finish" }]) as never,);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({messages: [{ role: "user", content: "hi" }],[reqKey]: 0,}),response,vi.fn(),);const callArgs = vi.mocked(streamText).mock.calls[0][0];expect(callArgs[argKey]).toBe(0);},);16 unmodified lines])("clamps $param to its upper bound (reqValue=$reqValue โ clampedTo=$clampedTo)",async ({ reqKey, reqValue, clampedTo, argKey }) => {vi.mocked(streamText).mockImplementation(() => streamOf([{ type: "finish" }]) as never,);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({messages: [{ role: "user", content: "hi" }],[reqKey]: reqValue,}),response,vi.fn(),);const callArgs = vi.mocked(streamText).mock.calls[0][0];expect(callArgs[argKey]).toBe(clampedTo);},);it("emits error SSE when stream ends without finish", async () => {vi.mocked(streamText).mockImplementation(() => streamOf([{ type: "text-delta", text: "Partial" }]) as never,);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);const writeCalls = response.write.mock.calls.map((c) => c[0]);expect(writeCalls.some((s: string) => s.includes("Stream ended unexpectedly")),).toBe(true);7 unmodified linesasync (timeout, timeoutMs) => {vi.stubEnv("MODEL_REQUEST_TIMEOUT_MS", timeout);vi.mocked(streamText).mockImplementation(({ abortSignal }: { abortSignal?: AbortSignal } = {}) => {// Yields one part, then yields an abort part when the signal fires โ// mirrors the AI SDK v7 pull handler behavior.return {stream: (async function* () {yield { type: "text-delta", text: "Half" } as never;await new Promise<void>((resolve) => {const check = () => {if (abortSignal?.aborted) {resolve();} else {abortSignal?.addEventListener("abort", () => resolve(), {once: true,});}};check();});yield { type: "abort" } as never;})(),} as never;},);const handler = getRegisteredHandler();const response = createResponse();vi.useFakeTimers();try {const pending = handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);// Not yet past the timeout โ signal should be clear.await vi.advanceTimersByTimeAsync(timeoutMs - 1);expect(5 unmodified lines// The abort is treated as an attempt failure: the stalled stream is// cut and the SSE error frame carries the message.const writes = response.write.mock.calls.map((c) => c[0] as string);expect(writes.some((s: string) => s.includes("Service unavailable")),).toBe(true);5 unmodified lines);it("retries the next model when the first model stalls before any content", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([{ id: "model-a" },{ id: "model-b" },]);vi.mocked(selectRandomModel).mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");vi.mocked(streamText).mockImplementationOnce(({ abortSignal }: { abortSignal?: AbortSignal } = {}) => {return {stream: (async function* () {await new Promise<void>((resolve) => {const check = () => {if (abortSignal?.aborted) {resolve();} else {abortSignal?.addEventListener("abort", () => resolve(), {once: true,});}};check();});yield { type: "abort" } as never;})(),} as never;},);vi.mocked(streamText).mockImplementationOnce(() =>streamOf([{ type: "text-delta", text: "Recovered" },{ type: "finish" },]) as never,);vi.useFakeTimers();try {const handler = getRegisteredHandler();const response = createResponse();const pending = handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);// Advance past the idle timeout; model-a stalls and aborts.await vi.runAllTimersAsync();await pending;expect(streamText).toHaveBeenCalledTimes(2);const writes = response.write.mock.calls.map((c) => c[0] as string);expect(writes.some((s: string) => s.includes("Recovered"))).toBe(true);expect(writes.some((s: string) => s.includes("stalled"))).toBe(false);} finally {vi.useRealTimers();}});it("responds 503 JSON when the stream ends before any content", async () => {vi.mocked(streamText).mockImplementation(() => streamOf([]) as never);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);expect(response.statusCode).toBe(503);const payload = JSON.parse(response.end.mock.calls[0][0]);expect(payload.lastError).toBe("Stream ended unexpectedly");expect(response.write).not.toHaveBeenCalled();});it("retries with another model when the stream ends before any content", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([{ id: "model-a" },{ id: "model-b" },]);vi.mocked(selectRandomModel).mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");let callCount = 0;vi.mocked(streamText).mockImplementation(() => {callCount += 1;return (callCount === 1? streamOf([]): streamOf([{ type: "text-delta", text: "Recovered" },{ type: "finish" },])) as never;});vi.useFakeTimers();try {const handler = getRegisteredHandler();const response = createResponse();const pending = handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);await vi.runAllTimersAsync();await pending;expect(streamText).toHaveBeenCalledTimes(2);const writes = response.write.mock.calls.map((c) => c[0]).join("");expect(writes).toContain("Recovered");expect(writes).not.toContain("Stream ended unexpectedly");} finally {vi.useRealTimers();}});it("returns early when response is no longer writable", async () => {vi.mocked(streamText).mockImplementation(() => streamOf([{ type: "text-delta", text: "Hello" }]) as never,);const handler = getRegisteredHandler();const response = createResponse();const mutable = response as {writableEnded: boolean;destroyed: boolean;};mutable.writableEnded = true;mutable.destroyed = true;await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);expect(response.setHeader).not.toHaveBeenCalledWith("Content-Type","text/event-stream",2 unmodified lines});it("surfaces an error part instead of reporting unexpected stream end", async () => {vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "text-delta", text: "Partial" },{ type: "error", error: new Error("upstream exploded") },]) as never,);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);const writes = response.write.mock.calls.map((c) => c[0]).join("");expect(writes).toContain("all models failed: upstream exploded");expect(writes).not.toContain("Stream ended unexpectedly");});it("retries with another model when the stream errors before any content", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([{ id: "model-a" },{ id: "model-b" },]);vi.mocked(selectRandomModel).mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");let callCount = 0;vi.mocked(streamText).mockImplementation(() => {callCount += 1;return (callCount === 1? streamOf([{ type: "error", error: new Error("upstream exploded") },]): streamOf([{ type: "text-delta", text: "Recovered" },{ type: "finish" },])) as never;});vi.useFakeTimers();try {const handler = getRegisteredHandler();const response = createResponse();const pending = handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);await vi.runAllTimersAsync();await pending;expect(streamText).toHaveBeenCalledTimes(2);const writes = response.write.mock.calls.map((c) => c[0]).join("");expect(writes).toContain("Recovered");expect(writes).not.toContain("all models failed");} finally {vi.useRealTimers();}});it("responds 503 JSON when the only model's stream fails before any content", async () => {vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "error", error: new Error("upstream down") },]) as never,);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);expect(response.statusCode).toBe(503);expect(response.setHeader).toHaveBeenCalledWith("Content-Type","application/json",);const payload = JSON.parse(response.end.mock.calls[0][0]);expect(payload).toEqual({error: "Service unavailable - all models failed",lastError: "upstream down",});expect(response.setHeader).not.toHaveBeenCalledWith("Content-Type","text/event-stream",4 unmodified lines});it("responds 503 JSON when the only model cannot start", async () => {vi.mocked(streamText).mockImplementation(() => {throw new Error("upstream down");});const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);expect(response.statusCode).toBe(503);expect(response.setHeader).toHaveBeenCalledWith("Content-Type","application/json",);const payload = JSON.parse(response.end.mock.calls[0][0]);expect(payload).toEqual({error: "Service unavailable - all models failed",lastError: "upstream down",});expect(response.write).not.toHaveBeenCalled();expect(vi.mocked(streamText)).toHaveBeenCalledTimes(2);});it("retries on model failure and succeeds on second attempt", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([{ id: "model-a" },{ id: "model-b" },]);vi.mocked(selectRandomModel).mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");let callCount = 0;vi.mocked(streamText).mockImplementation(() => {callCount += 1;if (callCount === 1) {throw new Error("upstream down");}return streamOf([{ type: "text-delta", text: "Ok" },{ type: "finish" },]) as never;});vi.useFakeTimers();try {const handler = getRegisteredHandler();const response = createResponse();const pending = handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);await vi.runAllTimersAsync();await pending;expect(streamText).toHaveBeenCalledTimes(2);const secondCallArgs = vi.mocked(selectRandomModel).mock.calls[1][1];expect(secondCallArgs).toBeInstanceOf(Set);expect((secondCallArgs as Set<string>).has("model-a")).toBe(true);const writeCalls = response.write.mock.calls.map((c) => c[0]);expect(writeCalls.some((s: string) => s.includes("[DONE]"))).toBe(true);} finally {vi.useRealTimers();}});it("does not retry after content was already sent to the client", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([{ id: "model-a" },{ id: "model-b" },]);vi.mocked(selectRandomModel).mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");let callCount = 0;vi.mocked(streamText).mockImplementation(() => {callCount += 1;return (callCount === 1? streamOf([{ type: "text-delta", text: "Half an answer" },{ type: "error", error: new Error("upstream exploded") },]): streamOf([{ type: "text-delta", text: "A different answer" },{ type: "finish" },])) as never;});const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);expect(streamText).toHaveBeenCalledTimes(1);const writes = response.write.mock.calls.map((c) => c[0]).join("");expect(writes).not.toContain("A different answer");expect(writes).toContain("all models failed");expect(writes).toContain("[DONE]");});it("re-lists the model pool when every model has been attempted", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValueOnce([{ id: "model-a" }]).mockResolvedValueOnce([{ id: "model-b" }]);vi.mocked(selectRandomModel).mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");let callCount = 0;vi.mocked(streamText).mockImplementation(() => {callCount += 1;return (callCount === 1? streamOf([{ type: "error", error: new Error("upstream down") }]): streamOf([{ type: "text-delta", text: "Recovered" },{ type: "finish" },])) as never;});vi.useFakeTimers();try {const handler = getRegisteredHandler();const response = createResponse();const pending = handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);await vi.runAllTimersAsync();await pending;expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);expect(streamText).toHaveBeenCalledTimes(2);const writes = response.write.mock.calls.map((c) => c[0]).join("");expect(writes).toContain("Recovered");expect(writes).not.toContain("all models failed");} finally {vi.useRealTimers();}});it("does not re-list when a model remains in the pool", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([{ id: "model-a" },{ id: "model-b" },]);vi.mocked(selectRandomModel).mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");let callCount = 0;vi.mocked(streamText).mockImplementation(() => {callCount += 1;return (callCount === 1? streamOf([{ type: "error", error: new Error("upstream down") }]): streamOf([{ type: "text-delta", text: "Recovered" },{ type: "finish" },])) as never;});vi.useFakeTimers();try {const handler = getRegisteredHandler();const response = createResponse();const pending = handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);await vi.runAllTimersAsync();await pending;expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(1);expect(streamText).toHaveBeenCalledTimes(2);} finally {vi.useRealTimers();}});it("re-lists only once even when both the original and refetched pools fail", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValueOnce([{ id: "model-a" }]).mockResolvedValueOnce([{ id: "model-b" }]);vi.mocked(selectRandomModel).mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "error", error: new Error("upstream down") },]) as never,);const before = getInferenceStats();vi.useFakeTimers();try {const handler = getRegisteredHandler();const response = createResponse();const pending = handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);await vi.runAllTimersAsync();await pending;// The pool was refreshed once; even though both models failed we do not// loop on a failing /models endpoint.expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);expect(vi.mocked(selectRandomModel).mock.calls[1][0]).toEqual([{ id: "model-b" },]);expect(response.statusCode).toBe(503);expect(getInferenceStats().modelsRefetched).toBe(before.modelsRefetched + 1,);} finally {vi.useRealTimers();}});2 unmodified linesvi.mocked(listOpenAiCompatibleModels).mockRejectedValue(new Error("network error"),);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);expect(response.statusCode).toBe(500);const payload = JSON.parse(response.end.mock.calls[0][0]);expect(payload.error).toBe("Failed to fetch available models");});1 unmodified linevi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([]);vi.mocked(selectRandomModel).mockReturnValue(null);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);expect(response.statusCode).toBe(500);const payload = JSON.parse(response.end.mock.calls[0][0]);expect(payload.error).toBe("No model available");});describe("error logging", () => {it("logs only the error message when a stream fails", async () => {vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "error", error: new Error("upstream exploded") },]) as never,);const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);const streamingCall = errorSpy.mock.calls.find((call) => call[0] === "Error during streaming:",);expect(streamingCall).toBeDefined();expect(streamingCall?.[1]).toBe("upstream exploded");expect(errorSpy.mock.calls.every((call) => !(call[1] instanceof Error)),).toBe(true);} finally {errorSpy.mockRestore();}});it("logs only the error message on unexpected endpoint failure", async () => {vi.mocked(streamText).mockImplementation(() => {throw new Error("upstream down");});const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {const handler = getRegisteredHandler();const response = createResponse();let thrown = false;response.setHeader.mockImplementation((name: string) => {2 unmodified linesthrow new Error("setHeader exploded");}});await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);const endpointCall = errorSpy.mock.calls.find((call) => call[0] === "Error in internal API endpoint:",);expect(endpointCall).toBeDefined();expect(endpointCall?.[1]).toBe("setHeader exploded");expect(errorSpy.mock.calls.every((call) => !(call[1] instanceof Error)),).toBe(true);expect(response.statusCode).toBe(500);} finally {errorSpy.mockRestore();1 unmodified line});it("logs only the error message when the model list fetch fails", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockRejectedValue(new Error("registry timeout"),);const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);const fetchCall = errorSpy.mock.calls.find((call) => call[0] === "Error fetching models:",);expect(fetchCall).toBeDefined();expect(fetchCall?.[1]).toBe("registry timeout");expect(errorSpy.mock.calls.every((call) => !(call[1] instanceof Error)),).toBe(true);expect(response.statusCode).toBe(500);} finally {errorSpy.mockRestore();2 unmodified lines});});describe("inference counters", () => {const setupStreaming = () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", "http://test-api");vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", "test-key");vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "test-model");vi.mocked(createOpenAICompatible).mockReturnValue({chatModel: vi.fn().mockReturnValue("mock-chat-model"),} as never);};async function callInference(response = createResponse()) {const handler = getRegisteredHandler();await handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),response,vi.fn(),);return response;}beforeEach(setupStreaming);// Every case in this block goes through the handler, so this covers all of// them rather than whichever one happened to run last.3 unmodified linesit("counts a finished answer under its model", async () => {const before = getInferenceStats(["test-model"]);vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "text-delta", text: "Hello" },{ type: "finish" },]) as never,);await callInference();const after = getInferenceStats(["test-model"]);expect(after.streamed).toBe(before.streamed + 1);9 unmodified linesit("counts a request the client walked away from", async () => {const before = getInferenceStats();vi.mocked(streamText).mockImplementation(() => streamOf([{ type: "text-delta", text: "Hello" }]) as never,);const response = createResponse();const mutable = response as {writableEnded: boolean;destroyed: boolean;};mutable.writableEnded = true;mutable.destroyed = true;await callInference(response);// The only outcome with no response to observe it by, which is the// reason it is worth counting at all.9 unmodified lineswritableEnded: boolean;destroyed: boolean;};vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "text-delta", text: "Half an answer" },{ type: "text-delta", text: "never read" },]) as never,);response.write.mockImplementation(() => {// Writable for the first part, gone before the second, which is the3 unmodified linesreturn true;});await callInference(response);const after = getInferenceStats(["test-model"]);expect(after.failed.abandoned).toBe(before.failed.abandoned + 1);6 unmodified linesit("counts an exhausted ladder as a failure before the first token", async () => {const before = getInferenceStats(["test-model"]);vi.mocked(streamText).mockImplementation(() => streamOf([]) as never);const response = await callInference();expect(response.statusCode).toBe(503);const after = getInferenceStats(["test-model"]);32 unmodified lines}const before = getInferenceStats().attemptFailures;vi.useFakeTimers();try {const pending = callInference();await vi.runAllTimersAsync();await pending;} finally {vi.useRealTimers();}const after = getInferenceStats().attemptFailures;expect(after.rateLimited).toBe(before.rateLimited + 1);5 unmodified linesit("counts a failure after content as a mid-stream failure", async () => {const before = getInferenceStats();vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "text-delta", text: "Half an answer" },{ type: "error", error: new Error("upstream died") },]) as never,);await callInference();expect(getInferenceStats().failed.failedMidStream).toBe(before.failed.failedMidStream + 1,2 unmodified linesit("counts a fallback to another model", async () => {const before = getInferenceStats(["model-a", "model-b"]);vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([{ id: "model-a" },{ id: "model-b" },]);vi.mocked(selectRandomModel).mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");let calls = 0;vi.mocked(streamText).mockImplementation(() => {calls += 1;return (calls === 1? streamOf([]): streamOf([{ type: "text-delta", text: "Recovered" },{ type: "finish" },])) as never;});vi.useFakeTimers();try {const handler = getRegisteredHandler();const pending = handler(createRequest({ messages: [{ role: "user", content: "hi" }] }),createResponse(),vi.fn(),);await vi.runAllTimersAsync();await pending;} finally {vi.useRealTimers();}const after = getInferenceStats(["model-a", "model-b"]);expect(after.modelFallbacks).toBe(before.modelFallbacks + 1);10 unmodified lines["badRequest",async () => {const handler = getRegisteredHandler();const request = Readable.from(["{invalid"]) as IncomingMessage;request.url = "/inference?token=abc";request.method = "POST";request.headers = {host: "localhost:3000","content-type": "application/json",};await handler(request, createResponse(), vi.fn());},],["notConfigured",async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", undefined);await callInference();},],["modelListUnavailable",async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockRejectedValue(new Error("registry timeout"),);const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {await callInference();} finally {errorSpy.mockRestore();}14 unmodified linesit("counts every request exactly once and classifies all of them", async () => {const before = getInferenceStats();vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "text-delta", text: "Hello" },{ type: "finish" },]) as never,);await callInference();await callInference();const stats = getInferenceStats();const total =6 unmodified lines});it("keeps no part of the conversation", async () => {vi.mocked(streamText).mockImplementation(() =>streamOf([{ type: "text-delta", text: "borogoves" },{ type: "finish" },]) as never,);const handler = getRegisteredHandler();await handler(createRequest({messages: [{ role: "user", content: "outgrabe mimsy-42" }],}),createResponse(),vi.fn(),);const serialized = JSON.stringify(getInferenceStats());expect(serialized).not.toContain("outgrabe");44 unmodified lines4546474849505152535455565758596070 unmodified lines13113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631728 unmodified lines3463473483493503513523 unmodified lines35635735835936036136277 unmodified lines4404414424434444454461 unmodified line4484494504514524534544554564574584594604614624634644654664672 unmodified lines4704714724734744754764774783 unmodified lines4824834844854864874884 unmodified lines4934944954964974984993 unmodified lines5035045055065075085095105112 unmodified lines5145155165175185195205215224 unmodified lines5275285295305315325335345355365375385395401 unmodified line5425435445455465475485495509 unmodified lines5605615625635645655665675685695705715725735745755765776 unmodified lines5845855865875885895904 unmodified lines5955965975985996006016026036046056066076086096106116126136146156166176186196206 unmodified lines62762862963063163263363463563663763863964064164264364464564664764864965065117 unmodified lines66967067167267367467567667767816 unmodified lines6956966976986997007017027037047057067077087097107117127137147 unmodified lines7227237247257267277287297307317327337347357365 unmodified lines7427437447457467477485 unmodified lines7547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078082 unmodified lines8118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468474 unmodified lines8528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899902 unmodified lines993994995996997998999100010011 unmodified line10031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110422 unmodified lines1045104610471048104910501051105210531054105510561 unmodified line105810591060106110621063106410651066106710681069107010711072107310742 unmodified lines10771078107910801081108210833 unmodified lines1087108810891090109110921093109410959 unmodified lines11051106110711081109111011111112111311149 unmodified lines112411251126112711281129113011311132113311343 unmodified lines11381139114011411142114311446 unmodified lines11511152115311541155115611571158115932 unmodified lines11921193119411951196119711985 unmodified lines120412051206120712081209121012111212121312141215121612172 unmodified lines122012211222122312241225122612271228122912301231123210 unmodified lines1243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127114 unmodified lines12861287128812891290129112921293129412956 unmodified lines130213031304130513061307130813091310131144 unmodified linesmethod = "POST",contentType = "application/json",): IncomingMessage {return createRawRequest([JSON.stringify(body)], method, contentType);}/** A request whose body arrives as these chunks, sent as they are. */function createRawRequest(chunks: string[],method = "POST",contentType = "application/json",): IncomingMessage {const request = Readable.from(chunks) as IncomingMessage;request.url = "/inference?token=abc";request.method = method;request.headers = {70 unmodified lines};}const helloBody = { messages: [{ role: "user", content: "hi" }] };/** Sends a request to the hook and returns the response with its pending run. */function startRequest(body: unknown = helloBody, response = createResponse()) {const pending = getRegisteredHandler()(createRequest(body),response,vi.fn(),);return { response, pending };}async function sendRequest(body: unknown = helloBody,response = createResponse(),) {const { pending } = startRequest(body, response);await pending;return response;}/** Runs the request with fake timers until it settles, so retries and stalls play out. */async function sendRequestThroughTimers(body: unknown = helloBody) {vi.useFakeTimers();try {const { response, pending } = startRequest(body);await vi.runAllTimersAsync();await pending;return response;} finally {vi.useRealTimers();}}/** A response the client already closed: nothing can be written to it. */function closedResponse() {return Object.assign(createResponse(), {writableEnded: true,destroyed: true,});}function endPayload(response: ReturnType<typeof createResponse>) {return JSON.parse(response.end.mock.calls[0][0]);}function writtenFrames(response: ReturnType<typeof createResponse>) {return response.write.mock.calls.map((c) => c[0] as string);}function writtenText(response: ReturnType<typeof createResponse>) {return response.write.mock.calls.map((c) => c[0]).join("");}/** A stream that answers `text` in one piece, then finishes. */function answerStream(text: string) {return streamOf([{ type: "text-delta", text }, { type: "finish" }]);}/*** A stream that yields `before`, then waits for the request's abort and yields* an abort part, as the AI SDK's pull handler does.*/function stallUntilAborted(abortSignal: AbortSignal | undefined,before: Array<{ type: string; text?: string }> = [],) {return {stream: (async function* () {for (const piece of before) yield piece as never;await new Promise<void>((resolve) => {if (abortSignal?.aborted) resolve();elseabortSignal?.addEventListener("abort", () => resolve(), {once: true,});});yield { type: "abort" } as never;})(),};}/** The first upstream call streams `first()`; every later call, `then()`. */function streamFirstThen(first: () => ReturnType<typeof streamOf>,then: () => ReturnType<typeof streamOf>,) {vi.mocked(streamText).mockImplementationOnce(() => first() as never).mockImplementation(() => then() as never);}/** Every upstream call streams a fresh `makeStream()`. */function streamEveryCall(makeStream: () => ReturnType<typeof streamOf>) {vi.mocked(streamText).mockImplementation(() => makeStream() as never);}/** The internal API is configured, and the provider hands back a chat model. */function configureStreamingApi() {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", "http://test-api");vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", "test-key");vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "test-model");vi.mocked(createOpenAICompatible).mockReturnValue({chatModel: vi.fn().mockReturnValue("mock-chat-model"),} as never);}/** No configured model: each attempt picks model-a, then model-b. */function useTwoRandomModels() {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([{ id: "model-a" },{ id: "model-b" },]);vi.mocked(selectRandomModel).mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");}/** Each listing returns one model (model-a, then model-b), so a retry re-lists. */function useSingleModelPoolThatRelists() {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValueOnce([{ id: "model-a" }]).mockResolvedValueOnce([{ id: "model-b" }]);vi.mocked(selectRandomModel).mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");}function failModelListing() {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockRejectedValue(new Error("registry timeout"),);}/** Sends a hello request with `extra` fields; returns what reached `streamText`. */async function upstreamArgsFor(extra: Record<string, unknown>) {await sendRequest({ ...helloBody, ...extra });return vi.mocked(streamText).mock.calls[0][0];}/** Sends through timers; expects exactly two upstream calls and "Recovered" in the output. Returns the written text. */async function sendExpectingSecondAttemptToRecover() {const response = await sendRequestThroughTimers();expect(streamText).toHaveBeenCalledTimes(2);const writes = writtenText(response);expect(writes).toContain("Recovered");return writes;}function expectAllModelsFailedJson(response: ReturnType<typeof createResponse>,lastError: string,) {expect(response.statusCode).toBe(503);expect(response.setHeader).toHaveBeenCalledWith("Content-Type","application/json",);expect(endPayload(response)).toEqual({error: "Service unavailable - all models failed",lastError,});}/** `label` was logged with the message only, and no Error object reached the log. */function expectOnlyMessageLogged(errorSpy: { mock: { calls: unknown[][] } },label: string,message: string,) {const call = errorSpy.mock.calls.find((logged) => logged[0] === label);expect(call).toBeDefined();expect(call?.[1]).toBe(message);expect(errorSpy.mock.calls.every((logged) => !(logged[1] instanceof Error)),).toBe(true);}describe("internalApiEndpointServerHook", () => {beforeEach(() => {vi.resetAllMocks();28 unmodified linesawait handler(request, response, vi.fn());expect(response.statusCode).toBe(405);expect(response.setHeader).toHaveBeenCalledWith("Allow", "POST");const payload = endPayload(response);expect(payload.error).toBe("Method Not Allowed");});3 unmodified linesconst request = createRequest({}, "POST", "text/plain");await handler(request, response, vi.fn());expect(response.statusCode).toBe(415);const payload = endPayload(response);expect(payload.error).toBe("Unsupported Media Type");});77 unmodified linesconst response = createResponse();await handler(createRequest(body), response, vi.fn());expect(response.statusCode).toBe(400);const payload = endPayload(response);expect(payload.error).toContain(`Invalid request body: ${expectedPath}`);});1 unmodified lineconst handler = getRegisteredHandler();const response = createResponse();const chunk600k = "x".repeat(600 * 1024);const request = createRawRequest([chunk600k, chunk600k]);await handler(request, response, vi.fn());expect(response.statusCode).toBe(413);const payload = endPayload(response);expect(payload.error).toBe("Request body too large");});it("responds 400 when body is not valid JSON", async () => {const handler = getRegisteredHandler();const response = createResponse();const request = createRawRequest(["not json at all"]);await handler(request, response, vi.fn());expect(response.statusCode).toBe(400);const payload = endPayload(response);expect(payload.error).toBe("Invalid request body");});});2 unmodified linesit("responds 500 when API configuration is missing", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", undefined);vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", undefined);const response = await sendRequest();expect(response.statusCode).toBe(500);const payload = endPayload(response);expect(payload.error).toBe("OpenAI API configuration is missing");});});3 unmodified linesvi.mocked(handleTokenVerification).mockResolvedValue({shouldContinue: false,});const response = await sendRequest();expect(handleTokenVerification).toHaveBeenCalledWith("abc",expect.anything(),4 unmodified lines});describe("streaming path", () => {beforeEach(configureStreamingApi);function requestedModels() {const provider = vi.mocked(createOpenAICompatible).mock.results[0]3 unmodified linesit("sends the configured reasoning effort upstream", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", " low ");streamEveryCall(() => streamOf([{ type: "finish" }]));await sendRequestThroughTimers();expect(vi.mocked(streamText).mock.calls[0][0].providerOptions).toEqual({openai: { reasoningEffort: "low" },2 unmodified linesit("leaves the reasoning effort to the upstream when unset", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", "");streamEveryCall(() => streamOf([{ type: "finish" }]));await sendRequestThroughTimers();expect(vi.mocked(streamText).mock.calls[0][0].providerOptions,4 unmodified linesvi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", " model-a , model-b ");vi.mocked(streamText).mockImplementationOnce(() => streamOf([]) as never).mockImplementationOnce(() => answerStream("Recovered") as never);const response = await sendRequestThroughTimers();expect(requestedModels()).toEqual(["model-a", "model-b"]);expect(listOpenAiCompatibleModels).not.toHaveBeenCalled();expect(selectRandomModel).not.toHaveBeenCalled();const writes = writtenText(response);expect(writes).toContain("Recovered");});1 unmodified line// would end the request after two attempts instead of four.it("walks the configured list a second time before giving up", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "model-a,model-b,");streamEveryCall(() => streamOf([]));const response = await sendRequestThroughTimers();expect(requestedModels()).toEqual(["model-a",9 unmodified linesit("retries a single configured model once", async () => {vi.mocked(streamText).mockImplementationOnce(() => streamOf([]) as never).mockImplementationOnce(() => answerStream("Second try") as never);const response = await sendRequestThroughTimers();expect(requestedModels()).toEqual(["test-model", "test-model"]);const writes = writtenText(response);expect(writes).toContain("Second try");});it("emits SSE frames on successful stream", async () => {streamEveryCall(() => answerStream("Hello"));const response = await sendRequest();expect(response.setHeader).toHaveBeenCalledWith("Content-Type","text/event-stream",6 unmodified lines"Cache-Control","no-cache",);const writeCalls = writtenFrames(response);expect(writeCalls.some((s: string) => s.includes('"content":"Hello"')),).toBe(true);4 unmodified lines});it("passes on why the upstream stopped, so a cut answer is not reported as complete", async () => {streamEveryCall(() =>streamOf([{ type: "text-delta", text: "Cut" },{ type: "finish", finishReason: "length" },]),);const response = await sendRequest();const writes = writtenText(response);expect(writes).toContain('"finish_reason":"length"');expect(writes).not.toContain('"finish_reason":"stop"');});it("spells the finish reason the way OpenAI does", async () => {streamEveryCall(() =>streamOf([{ type: "finish", finishReason: "content-filter" }]),);const response = await sendRequest();const writes = writtenText(response);expect(writes).toContain('"finish_reason":"content_filter"');});6 unmodified linesasync (maxTokens, expected) => {vi.stubEnv("MODEL_DEFAULT_MAX_TOKENS", maxTokens);vi.spyOn(console, "error").mockImplementation(() => {});streamEveryCall(() => answerStream("Ok"));const callArgs = await upstreamArgsFor({max_tokens: 9999,});expect(callArgs.maxOutputTokens).toBe(expected);},);it("passes max_tokens unchanged when under cap", async () => {streamEveryCall(() => answerStream("Ok"));const callArgs = await upstreamArgsFor({max_tokens: 100,});expect(callArgs.maxOutputTokens).toBe(100);});it("passes undefined maxOutputTokens when max_tokens not provided", async () => {streamEveryCall(() => answerStream("Ok"));await sendRequest();const callArgs = vi.mocked(streamText).mock.calls[0][0];expect(callArgs.maxOutputTokens).toBeUndefined();});17 unmodified lines])("passes $param: 0 through instead of dropping it",async ({ reqKey, argKey }) => {streamEveryCall(() => streamOf([{ type: "finish" }]));const callArgs = await upstreamArgsFor({[reqKey]: 0,});expect(callArgs[argKey]).toBe(0);},);16 unmodified lines])("clamps $param to its upper bound (reqValue=$reqValue โ clampedTo=$clampedTo)",async ({ reqKey, reqValue, clampedTo, argKey }) => {streamEveryCall(() => streamOf([{ type: "finish" }]));const callArgs = await upstreamArgsFor({[reqKey]: reqValue,});expect(callArgs[argKey]).toBe(clampedTo);},);it("emits error SSE when stream ends without finish", async () => {streamEveryCall(() =>streamOf([{ type: "text-delta", text: "Partial" }]),);const response = await sendRequest();const writeCalls = writtenFrames(response);expect(writeCalls.some((s: string) => s.includes("Stream ended unexpectedly")),).toBe(true);7 unmodified linesasync (timeout, timeoutMs) => {vi.stubEnv("MODEL_REQUEST_TIMEOUT_MS", timeout);vi.mocked(streamText).mockImplementation(({ abortSignal }: { abortSignal?: AbortSignal } = {}) =>stallUntilAborted(abortSignal, [{ type: "text-delta", text: "Half" },]) as never,);vi.useFakeTimers();try {const { response, pending } = startRequest();// Not yet past the timeout โ signal should be clear.await vi.advanceTimersByTimeAsync(timeoutMs - 1);expect(5 unmodified lines// The abort is treated as an attempt failure: the stalled stream is// cut and the SSE error frame carries the message.const writes = writtenFrames(response);expect(writes.some((s: string) => s.includes("Service unavailable")),).toBe(true);5 unmodified lines);it("retries the next model when the first model stalls before any content", async () => {useTwoRandomModels();const before = getInferenceStats().attemptFailures;vi.mocked(streamText).mockImplementationOnce(({ abortSignal }: { abortSignal?: AbortSignal } = {}) =>stallUntilAborted(abortSignal) as never,);vi.mocked(streamText).mockImplementationOnce(() => answerStream("Recovered") as never,);// Past the idle timeout, model-a stalls and aborts.const response = await sendRequestThroughTimers();const after = getInferenceStats().attemptFailures;expect(after.stalled).toBe(before.stalled + 1);expect(after.other).toBe(before.other);expect(streamText).toHaveBeenCalledTimes(2);const writes = writtenFrames(response);expect(writes.some((s: string) => s.includes("Recovered"))).toBe(true);expect(writes.some((s: string) => s.includes("stalled"))).toBe(false);});it("responds 503 JSON when the stream ends before any content", async () => {streamEveryCall(() => streamOf([]));const response = await sendRequest();expect(response.statusCode).toBe(503);const payload = endPayload(response);expect(payload.lastError).toBe("Stream ended unexpectedly");expect(response.write).not.toHaveBeenCalled();});it("retries with another model when the stream ends before any content", async () => {useTwoRandomModels();streamFirstThen(() => streamOf([]),() => answerStream("Recovered"),);const writes = await sendExpectingSecondAttemptToRecover();expect(writes).not.toContain("Stream ended unexpectedly");});it("returns early when response is no longer writable", async () => {streamEveryCall(() => streamOf([{ type: "text-delta", text: "Hello" }]));const response = closedResponse();await sendRequest(helloBody, response);expect(response.setHeader).not.toHaveBeenCalledWith("Content-Type","text/event-stream",2 unmodified lines});it("surfaces an error part instead of reporting unexpected stream end", async () => {streamEveryCall(() =>streamOf([{ type: "text-delta", text: "Partial" },{ type: "error", error: new Error("upstream exploded") },]),);const response = await sendRequest();const writes = writtenText(response);expect(writes).toContain("all models failed: upstream exploded");expect(writes).not.toContain("Stream ended unexpectedly");});it("retries with another model when the stream errors before any content", async () => {useTwoRandomModels();streamFirstThen(() =>streamOf([{ type: "error", error: new Error("upstream exploded") }]),() => answerStream("Recovered"),);const writes = await sendExpectingSecondAttemptToRecover();expect(writes).not.toContain("all models failed");});it("responds 503 JSON when the only model's stream fails before any content", async () => {streamEveryCall(() =>streamOf([{ type: "error", error: new Error("upstream down") }]),);const response = await sendRequest();expectAllModelsFailedJson(response, "upstream down");expect(response.setHeader).not.toHaveBeenCalledWith("Content-Type","text/event-stream",4 unmodified lines});it("responds 503 JSON when the only model cannot start", async () => {streamEveryCall(() => {throw new Error("upstream down");});const response = await sendRequest();expectAllModelsFailedJson(response, "upstream down");expect(response.write).not.toHaveBeenCalled();expect(vi.mocked(streamText)).toHaveBeenCalledTimes(2);});it("retries on model failure and succeeds on second attempt", async () => {useTwoRandomModels();streamFirstThen(() => {throw new Error("upstream down");},() => answerStream("Ok"),);const response = await sendRequestThroughTimers();expect(streamText).toHaveBeenCalledTimes(2);const secondCallArgs = vi.mocked(selectRandomModel).mock.calls[1][1];expect(secondCallArgs).toBeInstanceOf(Set);expect((secondCallArgs as Set<string>).has("model-a")).toBe(true);const writeCalls = writtenFrames(response);expect(writeCalls.some((s: string) => s.includes("[DONE]"))).toBe(true);});it("does not retry after content was already sent to the client", async () => {useTwoRandomModels();streamFirstThen(() =>streamOf([{ type: "text-delta", text: "Half an answer" },{ type: "error", error: new Error("upstream exploded") },]),() => answerStream("A different answer"),);const response = await sendRequest();expect(streamText).toHaveBeenCalledTimes(1);const writes = writtenText(response);expect(writes).not.toContain("A different answer");expect(writes).toContain("all models failed");expect(writes).toContain("[DONE]");});it("re-lists the model pool when every model has been attempted", async () => {useSingleModelPoolThatRelists();streamFirstThen(() => streamOf([{ type: "error", error: new Error("upstream down") }]),() => answerStream("Recovered"),);const writes = await sendExpectingSecondAttemptToRecover();expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);expect(writes).not.toContain("all models failed");});it("does not re-list when a model remains in the pool", async () => {useTwoRandomModels();streamFirstThen(() => streamOf([{ type: "error", error: new Error("upstream down") }]),() => answerStream("Recovered"),);await sendRequestThroughTimers();expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(1);expect(streamText).toHaveBeenCalledTimes(2);});it("re-lists only once even when both the original and refetched pools fail", async () => {useSingleModelPoolThatRelists();streamEveryCall(() =>streamOf([{ type: "error", error: new Error("upstream down") }]),);const before = getInferenceStats();const response = await sendRequestThroughTimers();// The pool was refreshed once; even though both models failed we do not// loop on a failing /models endpoint.expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);expect(vi.mocked(selectRandomModel).mock.calls[1][0]).toEqual([{ id: "model-b" },]);expect(response.statusCode).toBe(503);expect(getInferenceStats().modelsRefetched).toBe(before.modelsRefetched + 1,);});it("still answers 503 when the mid-retry re-list fails", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValueOnce([{ id: "model-a" }]).mockRejectedValueOnce(new Error("models endpoint down"));vi.mocked(selectRandomModel).mockReturnValueOnce("model-a");streamEveryCall(() =>streamOf([{ type: "error", error: new Error("upstream down") }]),);const before = getInferenceStats();const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});try {const response = await sendRequestThroughTimers();// The re-list failed, so the picker hands out nothing and the request// ends in the all-models-failed answer, not an internal error.expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);// The failed re-list left the old pool in place.expect(vi.mocked(selectRandomModel).mock.calls[1][0]).toEqual([{ id: "model-a" },]);expect(streamText).toHaveBeenCalledTimes(1);expect(response.statusCode).toBe(503);expect(getInferenceStats().failed.failedBeforeFirstToken).toBe(before.failed.failedBeforeFirstToken + 1,);expect(warnSpy).toHaveBeenCalledWith("Failed to refetch models:","models endpoint down",);} finally {warnSpy.mockRestore();}});2 unmodified linesvi.mocked(listOpenAiCompatibleModels).mockRejectedValue(new Error("network error"),);const response = await sendRequest();expect(response.statusCode).toBe(500);const payload = endPayload(response);expect(payload.error).toBe("Failed to fetch available models");});1 unmodified linevi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([]);vi.mocked(selectRandomModel).mockReturnValue(null);const response = await sendRequest();expect(response.statusCode).toBe(500);const payload = endPayload(response);expect(payload.error).toBe("No model available");});describe("error logging", () => {it("logs only the error message when a stream fails", async () => {streamEveryCall(() =>streamOf([{ type: "error", error: new Error("upstream exploded") }]),);const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {await sendRequest();expectOnlyMessageLogged(errorSpy,"Error during streaming:","upstream exploded",);} finally {errorSpy.mockRestore();}});it("logs only the error message on unexpected endpoint failure", async () => {streamEveryCall(() => {throw new Error("upstream down");});const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {const response = createResponse();let thrown = false;response.setHeader.mockImplementation((name: string) => {2 unmodified linesthrow new Error("setHeader exploded");}});await sendRequest(helloBody, response);expectOnlyMessageLogged(errorSpy,"Error in internal API endpoint:","setHeader exploded",);expect(response.statusCode).toBe(500);} finally {errorSpy.mockRestore();1 unmodified line});it("logs only the error message when the model list fetch fails", async () => {failModelListing();const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {const response = await sendRequest();expectOnlyMessageLogged(errorSpy,"Error fetching models:","registry timeout",);expect(response.statusCode).toBe(500);} finally {errorSpy.mockRestore();2 unmodified lines});});describe("inference counters", () => {beforeEach(configureStreamingApi);// Every case in this block goes through the handler, so this covers all of// them rather than whichever one happened to run last.3 unmodified linesit("counts a finished answer under its model", async () => {const before = getInferenceStats(["test-model"]);streamEveryCall(() => answerStream("Hello"));await sendRequest();const after = getInferenceStats(["test-model"]);expect(after.streamed).toBe(before.streamed + 1);9 unmodified linesit("counts a request the client walked away from", async () => {const before = getInferenceStats();streamEveryCall(() => streamOf([{ type: "text-delta", text: "Hello" }]));const response = closedResponse();await sendRequest(helloBody, response);// The only outcome with no response to observe it by, which is the// reason it is worth counting at all.9 unmodified lineswritableEnded: boolean;destroyed: boolean;};streamEveryCall(() =>streamOf([{ type: "text-delta", text: "Half an answer" },{ type: "text-delta", text: "never read" },]),);response.write.mockImplementation(() => {// Writable for the first part, gone before the second, which is the3 unmodified linesreturn true;});await sendRequest(helloBody, response);const after = getInferenceStats(["test-model"]);expect(after.failed.abandoned).toBe(before.failed.abandoned + 1);6 unmodified linesit("counts an exhausted ladder as a failure before the first token", async () => {const before = getInferenceStats(["test-model"]);streamEveryCall(() => streamOf([]));const response = await sendRequest();expect(response.statusCode).toBe(503);const after = getInferenceStats(["test-model"]);32 unmodified lines}const before = getInferenceStats().attemptFailures;await sendRequestThroughTimers();const after = getInferenceStats().attemptFailures;expect(after.rateLimited).toBe(before.rateLimited + 1);5 unmodified linesit("counts a failure after content as a mid-stream failure", async () => {const before = getInferenceStats();streamEveryCall(() =>streamOf([{ type: "text-delta", text: "Half an answer" },{ type: "error", error: new Error("upstream died") },]),);await sendRequest();expect(getInferenceStats().failed.failedMidStream).toBe(before.failed.failedMidStream + 1,2 unmodified linesit("counts a fallback to another model", async () => {const before = getInferenceStats(["model-a", "model-b"]);useTwoRandomModels();streamFirstThen(() => streamOf([]),() => answerStream("Recovered"),);await sendRequestThroughTimers();const after = getInferenceStats(["model-a", "model-b"]);expect(after.modelFallbacks).toBe(before.modelFallbacks + 1);10 unmodified lines["badRequest",async () => {await getRegisteredHandler()(createRawRequest(["{invalid"]),createResponse(),vi.fn(),);},],["notConfigured",async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", undefined);await sendRequest();},],["modelListUnavailable",async () => {failModelListing();const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {await sendRequest();} finally {errorSpy.mockRestore();}14 unmodified linesit("counts every request exactly once and classifies all of them", async () => {const before = getInferenceStats();streamEveryCall(() => answerStream("Hello"));await sendRequest();await sendRequest();const stats = getInferenceStats();const total =6 unmodified lines});it("keeps no part of the conversation", async () => {streamEveryCall(() => answerStream("borogoves"));await sendRequest({messages: [{ role: "user", content: "outgrabe mimsy-42" }],});const serialized = JSON.stringify(getInferenceStats());expect(serialized).not.toContain("outgrabe");
35 unmodified lines36373839404135 unmodified linesexpect(listOpenAiCompatibleModels).not.toHaveBeenCalled();});it("never hands out the same random model twice", async () => {// Always the first model left, so a missing exclusion repeats it every// time instead of only by chance.35 unmodified lines363738394041424344454647484950515235 unmodified linesexpect(listOpenAiCompatibleModels).not.toHaveBeenCalled();});// The throw is the contract the hook's 500 "Failed to fetch available// models" depends on; the refetch path below catches its own failure.it("throws when the initial listing fails", async () => {vi.mocked(listOpenAiCompatibleModels).mockRejectedValueOnce(new Error("models endpoint down"),);const picker = createModelPicker({ ...connection, models: [] });await expect(picker.first()).rejects.toThrow("models endpoint down");});it("never hands out the same random model twice", async () => {// Always the first model left, so a missing exclusion repeats it every// time instead of only by chance.
8 unmodified lines910111213147 unmodified lines22232425262728298 unmodified lines* configured models, it walks them in order of preference and then once* more, so a single configured model also gets one retry. Without them, it* picks at random from the API's `/models`, never the same model twice.*/export function createModelPicker({models,7 unmodified linesconst ladder = [...models, ...models];let position = 0;let availableModels: { id: string }[] = [];// Every model handed out counts as attempted: the hook runs each one it// gets, so marking here keeps the exclusion from depending on the caller.const attemptedModels = new Set<string>();let hasRefetched = false;8 unmodified lines910111213141516177 unmodified lines252627282930313233348 unmodified lines* configured models, it walks them in order of preference and then once* more, so a single configured model also gets one retry. Without them, it* picks at random from the API's `/models`, never the same model twice.* Create one per request, call `first()` once, then `next()` after each* failed attempt: it keeps its own position and pool, so the calls must* come in that order.*/export function createModelPicker({models,7 unmodified linesconst ladder = [...models, ...models];let position = 0;let availableModels: { id: string }[] = [];// Marked on hand-out, not when the attempt runs: this set is only read in// next(), after the previous attempt has finished, and every exit between// a hand-out and the next read ends the request, so it holds the same// models it would if marked at attempt time.const attemptedModels = new Set<string>();let hasRefetched = false;
87 unmodified lines88899091929342 unmodified lines1361371381391401411421431441454 unmodified lines1501511521531541551561571581591605 unmodified lines1661671681691701711721731741751761771781791801811821831841851861871887 unmodified lines19619719819920020120220320420520620720820923 unmodified lines23323423523623723823924024124224324424510 unmodified lines2562572582592602612622632642652 unmodified lines2682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093109 unmodified lines32032132232332432532632732832933033133233312 unmodified lines3463473483493503513523533543553563573583597 unmodified lines3673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034046 unmodified lines4114124134144154164174184194204214224234248 unmodified lines4334344354364374384394404414424434444454463 unmodified lines4504514524534544554564574584594604614624635 unmodified lines4694704714724734744754764774784794804814824834844854864874884894904914924934944954964974981 unmodified line5005015025035045055065075085095105115125135145155165175185194 unmodified lines5245255265275285295305314 unmodified lines5365375385395405415425435445455465475485495508 unmodified lines5595605615625635645655665675685695705715726 unmodified lines5795805815825835845855865875885895905915925935945955965975985996006016024 unmodified lines6076086096106116126136146156166176186196206216226236246256266276286296306316326336346354 unmodified lines64064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467587 unmodified linesreturn `/thumbnail?u=${encodeURIComponent(thumbnailUrl)}&token=abc`;}// Shaped like the IncomingMessage the pinned request resolves with: the// fields the hook reads, plus the async iteration readCappedStream drives.function fakeIncoming(42 unmodified lines});it("passes through requests that aren't under /thumbnail", async () => {const handler = getRegisteredHandler();const next = vi.fn();await handler(createRequest("/status"), createResponse(), next);expect(next).toHaveBeenCalled();expect(pinnedRequestMock).not.toHaveBeenCalled();4 unmodified lines"/thumbnailX?token=abc","/thumbnail/extra?token=abc",])("passes through %s, which is not the /thumbnail route", async (url) => {const handler = getRegisteredHandler();const next = vi.fn();const response = createResponse();await handler(createRequest(url), response, next);expect(next).toHaveBeenCalledTimes(1);expect(response.end).not.toHaveBeenCalled();5 unmodified linesvi.mocked(handleTokenVerification).mockResolvedValue({shouldContinue: false,});const handler = getRegisteredHandler();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),createResponse(),vi.fn(),);expect(pinnedRequestMock).not.toHaveBeenCalled();expect(recordThumbnailRequested).not.toHaveBeenCalled();});it("responds 400 when the thumbnail URL is missing", async () => {const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest("/thumbnail?token=abc"), response, vi.fn());expect(response.statusCode).toBe(400);expect(response.end).toHaveBeenCalledWith(7 unmodified linespinnedRequestMock.mockResolvedValue(imageResponse(new Uint8Array([1, 2, 3]), "IMAGE/JPEG; charset=binary"),);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(200);expect(response.setHeader).toHaveBeenCalledWith(23 unmodified linesit("verifies through the thumbnail's own rate-limit budget", async () => {pinnedRequestMock.mockResolvedValue(imageResponse());const { thumbnailRateLimiter } = await import("./verifyTokenAndRateLimit");const handler = getRegisteredHandler();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),createResponse(),vi.fn(),);// The whole separate-budget design rests on this wiring: delete the// options argument and the grid's 30 tile loads draw from the search10 unmodified linesconst url = publicThumbnailUrl();// A fresh response per call: a body can only be read once.pinnedRequestMock.mockImplementation(async () => imageResponse());const handler = getRegisteredHandler();await handler(createRequest(requestUrlFor(url)), createResponse(), vi.fn());await handler(createRequest(requestUrlFor(url)), createResponse(), vi.fn());expect(pinnedRequestMock).toHaveBeenCalledTimes(1);// Both requests are demand, so both count even though only one fetched.2 unmodified linesit("refuses a URL that resolves into a private address", async () => {lookupMock.mockResolvedValue([{ address: "192.168.1.5", family: 4 }]);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(403);expect(pinnedRequestMock).not.toHaveBeenCalled();expect(recordThumbnailBlocked).toHaveBeenCalledTimes(1);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);});it("refuses a URL with a non-HTTP scheme", async () => {const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor("file:///etc/passwd")),response,vi.fn(),);expect(response.statusCode).toBe(403);expect(pinnedRequestMock).not.toHaveBeenCalled();expect(recordThumbnailBlocked).toHaveBeenCalledTimes(1);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);});it("refuses a URL longer than the cap", async () => {const handler = getRegisteredHandler();const response = createResponse();const longUrl = `https://thumbs.example.com/${"a".repeat(2050)}`;await handler(createRequest(requestUrlFor(longUrl)), response, vi.fn());expect(response.statusCode).toBe(400);expect(pinnedRequestMock).not.toHaveBeenCalled();9 unmodified lines.mockResolvedValueOnce([{ address: "93.184.216.34", family: 4 }]).mockResolvedValue([{ address: "10.0.0.7", family: 4 }]);pinnedRequestMock.mockResolvedValue(imageResponse());const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(200);expect(pinnedRequestMock).toHaveBeenCalledTimes(1);12 unmodified lineslocation: "http://10.0.0.7/thumb.jpg",}),);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(403);// The redirect target was refused at validation: its socket was never7 unmodified linespinnedRequestMock.mockResolvedValue(fakeIncoming(new Uint8Array(), 404, {}),);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(502);expect(response.setHeader).toHaveBeenCalledWith("Cache-Control","no-store",);expect(response.end).toHaveBeenCalledWith(JSON.stringify({ error: "Thumbnail could not be fetched" }),);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);});it("logs why a fetch failed, never the thumbnail URL or its host", async () => {pinnedRequestMock.mockResolvedValue(fakeIncoming(new Uint8Array(), 403, {}),);const handler = getRegisteredHandler();const thumbnailUrl = publicThumbnailUrl();await handler(createRequest(requestUrlFor(thumbnailUrl)),createResponse(),vi.fn(),);const output = logLines.join("\n");expect(output).toContain("Thumbnail fetch failed: HTTP 403");6 unmodified lines"content-type": "text/html",}),);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(502);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);8 unmodified lines{ "content-type": "image/svg+xml" },),);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(502);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);3 unmodified linespinnedRequestMock.mockResolvedValueOnce(fakeIncoming(new Uint8Array(), 302, { location: "http://[" }),);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(502);expect(pinnedRequestMock).toHaveBeenCalledTimes(1);5 unmodified linespinnedRequestMock.mockResolvedValueOnce(fakeIncoming(new Uint8Array(), 404, {})).mockResolvedValueOnce(imageResponse());const handler = getRegisteredHandler();const first = createResponse();await handler(createRequest(requestUrlFor(url)), first, vi.fn());expect(first.statusCode).toBe(502);const second = createResponse();await handler(createRequest(requestUrlFor(url)), second, vi.fn());expect(second.statusCode).toBe(200);expect(pinnedRequestMock).toHaveBeenCalledTimes(2);});it("answers 502 when the upstream body is empty", async () => {pinnedRequestMock.mockResolvedValue(fakeIncoming(new Uint8Array(), 200, { "content-type": "image/jpeg" }),);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(502);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);1 unmodified lineit("bounds a hanging DNS lookup with the same deadline", async () => {// A resolver that never settles must not add its own timeout on top of// the documented one. Matches THUMBNAIL_TIMEOUT_MS.const thumbnailTimeoutMs = 3000;lookupMock.mockImplementation(() => new Promise(() => {}));vi.useFakeTimers();try {const handler = getRegisteredHandler();const response = createResponse();const handled = handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);await vi.advanceTimersByTimeAsync(thumbnailTimeoutMs);await handled;expect(response.statusCode).toBe(502);expect(pinnedRequestMock).not.toHaveBeenCalled();4 unmodified lines});it("answers 502 when the host never answers within the timeout", async () => {// Matches THUMBNAIL_TIMEOUT_MS in thumbnailEndpointServerHook.ts.const thumbnailTimeoutMs = 3000;vi.useFakeTimers();try {pinnedRequestMock.mockImplementation(4 unmodified lines);}),);const handler = getRegisteredHandler();const response = createResponse();const handled = handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);await vi.advanceTimersByTimeAsync(thumbnailTimeoutMs);await handled;expect(response.statusCode).toBe(502);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);8 unmodified lineslocation: "https://thumbs.example.com/loop.jpg",}),);const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(502);// One request per hop, four hops for three redirects.6 unmodified lines// as a damaged image.const bigBody = new Uint8Array(600_000).fill(7);pinnedRequestMock.mockResolvedValue(imageResponse(bigBody));const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(502);expect(response.setHeader).toHaveBeenCalledWith("Cache-Control","no-store",);expect(response.end).toHaveBeenCalledWith(JSON.stringify({ error: "Thumbnail could not be fetched" }),);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);expect(logLines.join("\n")).toContain("Thumbnail fetch failed: larger than 500000 bytes",);4 unmodified linespinnedRequestMock.mockResolvedValueOnce(imageResponse(new Uint8Array(600_000).fill(7))).mockResolvedValueOnce(imageResponse());const handler = getRegisteredHandler();const first = createResponse();await handler(createRequest(requestUrlFor(url)), first, vi.fn());expect(first.statusCode).toBe(502);const second = createResponse();await handler(createRequest(requestUrlFor(url)), second, vi.fn());expect(second.statusCode).toBe(200);expect(pinnedRequestMock).toHaveBeenCalledTimes(2);});it("serves a body of exactly the byte cap", async () => {const capSizedBody = new Uint8Array(500_000).fill(7);pinnedRequestMock.mockResolvedValue(imageResponse(capSizedBody));const handler = getRegisteredHandler();const response = createResponse();await handler(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);expect(response.statusCode).toBe(200);const body = response.end.mock.calls[0][0] as Buffer;4 unmodified linesit("evicts the least recently used entry, not the least recently loaded one", async () => {// A fresh response per call: a body can only be read once.pinnedRequestMock.mockImplementation(async () => imageResponse());const handler = getRegisteredHandler();// A clean slate, so the eviction side is exactly where this test puts it.resetThumbnailCache();const firstUrl = publicThumbnailUrl();const secondUrl = publicThumbnailUrl();const maxEntries = getThumbnailCacheLimits().entries;const load = (url: string) =>handler(createRequest(requestUrlFor(url)), createResponse(), vi.fn());const fetched = (url: string) =>pinnedRequestMock.mock.calls.filter((call) => String(call[0]) === url).length;await load(firstUrl);await load(secondUrl);// Re-reading firstUrl promotes it, so secondUrl is the eviction candidate.await load(firstUrl);for (let i = 0; i < maxEntries - 2; i += 1) {await load(publicThumbnailUrl());}// This insert pushes the cache past the cap: exactly one entry is evicted.await load(publicThumbnailUrl());// firstUrl (promoted by the re-read) survived and serves from the cache.// A cache without promote-on-hit would have evicted it, being the oldest// load.await load(firstUrl);expect(fetched(firstUrl)).toBe(1);await load(secondUrl);expect(fetched(secondUrl)).toBe(2);});});87 unmodified lines88899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916042 unmodified lines2032042052062072082094 unmodified lines2142152162172182192205 unmodified lines2262272282292302312322332342352362372382392407 unmodified lines24824925025125225325423 unmodified lines27827928028128228328428510 unmodified lines2962972982993003013023033042 unmodified lines3073083093103113123133143153163173183193203213223233243253263279 unmodified lines33733833934034134234312 unmodified lines3563573583593603613627 unmodified lines3703713723733743753763773783793803813823833843853863876 unmodified lines3943953963973983994008 unmodified lines4094104114124134144153 unmodified lines4194204214224234244255 unmodified lines4314324334344354364374384394404414424434444451 unmodified line4474484494504514524534544554564574 unmodified lines4624634644654664674 unmodified lines4724734744754764774788 unmodified lines4874884894904914924936 unmodified lines5005015025035045055065075084 unmodified lines5135145155165175185195205215225235245255264 unmodified lines53153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256387 unmodified linesreturn `/thumbnail?u=${encodeURIComponent(thumbnailUrl)}&token=abc`;}/*** Sends `path` through the hook; returns the response and the `next` it was* given. Registers a fresh hook per call; the cache is module state, so calls* still share it.*/async function requestPath(path: string) {const response = createResponse();const next = vi.fn();await getRegisteredHandler()(createRequest(path), response, next);return { response, next };}/*** Requests the thumbnail at `thumbnailUrl` through the hook; returns the* response. The default is a new URL each time, so it never hits the cache.*/async function requestThumbnail(thumbnailUrl = publicThumbnailUrl()) {return (await requestPath(requestUrlFor(thumbnailUrl))).response;}// Matches THUMBNAIL_TIMEOUT_MS in thumbnailEndpointServerHook.ts, which does// not export it.const THUMBNAIL_TIMEOUT_MS = 3000;/*** Requests a thumbnail and lets `ms` of fake time pass while the hook waits.* Needs `vi.useFakeTimers()`.*/async function requestThumbnailPast(ms: number) {const response = createResponse();const handled = getRegisteredHandler()(createRequest(requestUrlFor(publicThumbnailUrl())),response,vi.fn(),);await vi.advanceTimersByTimeAsync(ms);await handled;return response;}/** Refused at validation: no socket opened, counted as blocked and dropped. */function expectRefusedBeforeFetch(response: ReturnType<typeof createResponse>) {expect(response.statusCode).toBe(403);expect(pinnedRequestMock).not.toHaveBeenCalled();expect(recordThumbnailBlocked).toHaveBeenCalledTimes(1);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);}/** The generic 502, never cached by the browser, counted as dropped. */function expectCouldNotFetch(response: ReturnType<typeof createResponse>) {expect(response.statusCode).toBe(502);expect(response.setHeader).toHaveBeenCalledWith("Cache-Control", "no-store");expect(response.end).toHaveBeenCalledWith(JSON.stringify({ error: "Thumbnail could not be fetched" }),);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);}/** The first load of `url` fails; the second fetches again and succeeds. */async function expectFailureIsRetried(url: string) {const first = await requestThumbnail(url);expect(first.statusCode).toBe(502);const second = await requestThumbnail(url);expect(second.statusCode).toBe(200);expect(pinnedRequestMock).toHaveBeenCalledTimes(2);}// Shaped like the IncomingMessage the pinned request resolves with: the// fields the hook reads, plus the async iteration readCappedStream drives.function fakeIncoming(42 unmodified lines});it("passes through requests that aren't under /thumbnail", async () => {const { next } = await requestPath("/status");expect(next).toHaveBeenCalled();expect(pinnedRequestMock).not.toHaveBeenCalled();4 unmodified lines"/thumbnailX?token=abc","/thumbnail/extra?token=abc",])("passes through %s, which is not the /thumbnail route", async (url) => {const { response, next } = await requestPath(url);expect(next).toHaveBeenCalledTimes(1);expect(response.end).not.toHaveBeenCalled();5 unmodified linesvi.mocked(handleTokenVerification).mockResolvedValue({shouldContinue: false,});await requestThumbnail();expect(pinnedRequestMock).not.toHaveBeenCalled();expect(recordThumbnailRequested).not.toHaveBeenCalled();});it("responds 400 when the thumbnail URL is missing", async () => {const { response } = await requestPath("/thumbnail?token=abc");expect(response.statusCode).toBe(400);expect(response.end).toHaveBeenCalledWith(7 unmodified linespinnedRequestMock.mockResolvedValue(imageResponse(new Uint8Array([1, 2, 3]), "IMAGE/JPEG; charset=binary"),);const response = await requestThumbnail();expect(response.statusCode).toBe(200);expect(response.setHeader).toHaveBeenCalledWith(23 unmodified linesit("verifies through the thumbnail's own rate-limit budget", async () => {pinnedRequestMock.mockResolvedValue(imageResponse());const { thumbnailRateLimiter } = await import("./verifyTokenAndRateLimit");await requestThumbnail();// The whole separate-budget design rests on this wiring: delete the// options argument and the grid's 30 tile loads draw from the search10 unmodified linesconst url = publicThumbnailUrl();// A fresh response per call: a body can only be read once.pinnedRequestMock.mockImplementation(async () => imageResponse());await requestThumbnail(url);await requestThumbnail(url);expect(pinnedRequestMock).toHaveBeenCalledTimes(1);// Both requests are demand, so both count even though only one fetched.2 unmodified linesit("refuses a URL that resolves into a private address", async () => {lookupMock.mockResolvedValue([{ address: "192.168.1.5", family: 4 }]);const response = await requestThumbnail();expectRefusedBeforeFetch(response);});it("refuses a URL with a non-HTTP scheme", async () => {const response = await requestThumbnail("file:///etc/passwd");expectRefusedBeforeFetch(response);});it("refuses a URL longer than the cap", async () => {const response = await requestThumbnail(`https://thumbs.example.com/${"a".repeat(2050)}`,);expect(response.statusCode).toBe(400);expect(pinnedRequestMock).not.toHaveBeenCalled();9 unmodified lines.mockResolvedValueOnce([{ address: "93.184.216.34", family: 4 }]).mockResolvedValue([{ address: "10.0.0.7", family: 4 }]);pinnedRequestMock.mockResolvedValue(imageResponse());const response = await requestThumbnail();expect(response.statusCode).toBe(200);expect(pinnedRequestMock).toHaveBeenCalledTimes(1);12 unmodified lineslocation: "http://10.0.0.7/thumb.jpg",}),);const response = await requestThumbnail();expect(response.statusCode).toBe(403);// The redirect target was refused at validation: its socket was never7 unmodified linespinnedRequestMock.mockResolvedValue(fakeIncoming(new Uint8Array(), 404, {}),);const response = await requestThumbnail();expectCouldNotFetch(response);});it("logs why a fetch failed, never the thumbnail URL or its host", async () => {pinnedRequestMock.mockResolvedValue(fakeIncoming(new Uint8Array(), 403, {}),);const thumbnailUrl = publicThumbnailUrl();await requestThumbnail(thumbnailUrl);const output = logLines.join("\n");expect(output).toContain("Thumbnail fetch failed: HTTP 403");6 unmodified lines"content-type": "text/html",}),);const response = await requestThumbnail();expect(response.statusCode).toBe(502);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);8 unmodified lines{ "content-type": "image/svg+xml" },),);const response = await requestThumbnail();expect(response.statusCode).toBe(502);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);3 unmodified linespinnedRequestMock.mockResolvedValueOnce(fakeIncoming(new Uint8Array(), 302, { location: "http://[" }),);const response = await requestThumbnail();expect(response.statusCode).toBe(502);expect(pinnedRequestMock).toHaveBeenCalledTimes(1);5 unmodified linespinnedRequestMock.mockResolvedValueOnce(fakeIncoming(new Uint8Array(), 404, {})).mockResolvedValueOnce(imageResponse());await expectFailureIsRetried(url);});it("answers 502 when the upstream body is empty", async () => {pinnedRequestMock.mockResolvedValue(fakeIncoming(new Uint8Array(), 200, { "content-type": "image/jpeg" }),);const response = await requestThumbnail();expect(response.statusCode).toBe(502);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);1 unmodified lineit("bounds a hanging DNS lookup with the same deadline", async () => {// A resolver that never settles must not add its own timeout on top of// the documented one.lookupMock.mockImplementation(() => new Promise(() => {}));vi.useFakeTimers();try {const response = await requestThumbnailPast(THUMBNAIL_TIMEOUT_MS);expect(response.statusCode).toBe(502);expect(pinnedRequestMock).not.toHaveBeenCalled();4 unmodified lines});it("answers 502 when the host never answers within the timeout", async () => {vi.useFakeTimers();try {pinnedRequestMock.mockImplementation(4 unmodified lines);}),);const response = await requestThumbnailPast(THUMBNAIL_TIMEOUT_MS);expect(response.statusCode).toBe(502);expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);8 unmodified lineslocation: "https://thumbs.example.com/loop.jpg",}),);const response = await requestThumbnail();expect(response.statusCode).toBe(502);// One request per hop, four hops for three redirects.6 unmodified lines// as a damaged image.const bigBody = new Uint8Array(600_000).fill(7);pinnedRequestMock.mockResolvedValue(imageResponse(bigBody));const response = await requestThumbnail();expectCouldNotFetch(response);expect(logLines.join("\n")).toContain("Thumbnail fetch failed: larger than 500000 bytes",);4 unmodified linespinnedRequestMock.mockResolvedValueOnce(imageResponse(new Uint8Array(600_000).fill(7))).mockResolvedValueOnce(imageResponse());await expectFailureIsRetried(url);});it("serves a body of exactly the byte cap", async () => {const capSizedBody = new Uint8Array(500_000).fill(7);pinnedRequestMock.mockResolvedValue(imageResponse(capSizedBody));const response = await requestThumbnail();expect(response.statusCode).toBe(200);const body = response.end.mock.calls[0][0] as Buffer;4 unmodified linesit("evicts the least recently used entry, not the least recently loaded one", async () => {// A fresh response per call: a body can only be read once.pinnedRequestMock.mockImplementation(async () => imageResponse());// A clean slate, so the eviction side is exactly where this test puts it.resetThumbnailCache();const firstUrl = publicThumbnailUrl();const secondUrl = publicThumbnailUrl();const maxEntries = getThumbnailCacheLimits().entries;const fetched = (url: string) =>pinnedRequestMock.mock.calls.filter((call) => String(call[0]) === url).length;await requestThumbnail(firstUrl);await requestThumbnail(secondUrl);// Re-reading firstUrl promotes it, so secondUrl is the eviction candidate.await requestThumbnail(firstUrl);for (let i = 0; i < maxEntries - 2; i += 1) {await requestThumbnail(publicThumbnailUrl());}// This insert pushes the cache past the cap: exactly one entry is evicted.await requestThumbnail(publicThumbnailUrl());// firstUrl (promoted by the re-read) survived and serves from the cache.// A cache without promote-on-hit would have evicted it, being the oldest// load.await requestThumbnail(firstUrl);expect(fetched(firstUrl)).toBe(1);await requestThumbnail(secondUrl);expect(fetched(secondUrl)).toBe(2);});});
54 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371387 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861875 unmodified lines1931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292306 unmodified lines2372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243251 unmodified line3273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643655 unmodified lines37137237337437537637737837938038138238338438538613 unmodified lines40040140240340440540654 unmodified linesreturn `$argon2id$v=19$m=512,t=16,p=1$${salt}$${digest}`;}describe("validateAccessKeyServerHook", () => {it("should skip non-matching URLs", async () => {const { validateAccessKeyServerHook } = await import("./validateAccessKeyServerHook");const use = vi.fn();validateAccessKeyServerHook({middlewares: { use },} as never);const handler = use.mock.calls[0][0] as (req: { url: string; method: string },res: unknown,next: () => void,) => void;const next = vi.fn();handler({ url: "/other", method: "POST" }, {}, next);expect(next).toHaveBeenCalled();});it("should skip non-POST methods", async () => {const { validateAccessKeyServerHook } = await import("./validateAccessKeyServerHook");const use = vi.fn();validateAccessKeyServerHook({middlewares: { use },} as never);const handler = use.mock.calls[0][0] as (req: { url: string; method: string },res: unknown,next: () => void,) => void;const next = vi.fn();handler({ url: "/api/validate-access-key", method: "GET" }, {}, next);expect(next).toHaveBeenCalled();});it("should return valid: true for a matching access key", async () => {process.env.ACCESS_KEYS = "test-key";mockArgon2Verify.mockResolvedValue(true);const { validateAccessKeyServerHook } = await import("./validateAccessKeyServerHook");const use = vi.fn();validateAccessKeyServerHook({middlewares: { use },} as never);const handler = use.mock.calls[0][0] as (req: {url: string;method: string;on: (event: string, cb: (chunk: string) => void) => void;},res: {setHeader: ReturnType<typeof vi.fn>;end: ReturnType<typeof vi.fn>;},next: () => void,) => void;const res = makeMockResponse();const req = makeMockRequest("/api/validate-access-key","POST",JSON.stringify({ accessKeyHash: makeValidAccessKeyHash("valid") }),);await new Promise<void>((resolve) => {void handler(req as never, res as never, () => {});// The handler consumes a rate-limit point (async) before it registers its// end listener, so trigger it on a later macrotask.setImmediate(() => {for (const cb of req.endCallbacks) {cb();}setTimeout(resolve, 50);});});expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true }));expect(mockConsumeRateLimitPoint).toHaveBeenCalledTimes(1);7 unmodified linesreturn password === "other-key";},);const { validateAccessKeyServerHook } = await import("./validateAccessKeyServerHook");const use = vi.fn();validateAccessKeyServerHook({middlewares: { use },} as never);const handler = use.mock.calls[0][0] as (req: {url: string;method: string;on: (event: string, cb: (chunk: string) => void) => void;},res: {setHeader: ReturnType<typeof vi.fn>;end: ReturnType<typeof vi.fn>;},next: () => void,) => void;const res = makeMockResponse();const req = makeMockRequest("/api/validate-access-key","POST",JSON.stringify({ accessKeyHash: makeValidAccessKeyHash("valid") }),);await new Promise<void>((resolve) => {void handler(req as never, res as never, () => {});setImmediate(() => {for (const cb of req.endCallbacks) {cb();}setTimeout(resolve, 50);});});expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true }));const verifiedPasswords = mockArgon2Verify.mock.calls.map(5 unmodified linesit("responds 429 and skips the argon2 loop when the limiter refuses", async () => {process.env.ACCESS_KEYS = "test-key";mockConsumeRateLimitPoint.mockResolvedValue(false);const { validateAccessKeyServerHook } = await import("./validateAccessKeyServerHook");const use = vi.fn();validateAccessKeyServerHook({middlewares: { use },} as never);const handler = use.mock.calls[0][0] as (req: {url: string;method: string;on: (event: string, cb: (chunk: string) => void) => void;},res: {setHeader: ReturnType<typeof vi.fn>;end: ReturnType<typeof vi.fn>;statusCode: number;},next: () => void,) => void;const res = makeMockResponse();const req = makeMockRequest("/api/validate-access-key","POST",JSON.stringify({ accessKeyHash: makeValidAccessKeyHash("valid") }),);await new Promise<void>((resolve) => {handler(req as never, res as never, () => {});setTimeout(resolve, 50);});expect(res.statusCode).toBe(429);expect(res.end).toHaveBeenCalledWith(6 unmodified linesit("should return valid: false when no access keys match", async () => {process.env.ACCESS_KEYS = "test-key";mockArgon2Verify.mockResolvedValue(false);const { validateAccessKeyServerHook } = await import("./validateAccessKeyServerHook");const use = vi.fn();validateAccessKeyServerHook({middlewares: { use },} as never);const handler = use.mock.calls[0][0] as (req: {url: string;method: string;on: (event: string, cb: (chunk: string) => void) => void;},res: {setHeader: ReturnType<typeof vi.fn>;end: ReturnType<typeof vi.fn>;},next: () => void,) => void;const res = makeMockResponse();const req = makeMockRequest("/api/validate-access-key","POST",JSON.stringify({ accessKeyHash: makeValidAccessKeyHash("wrong") }),);await new Promise<void>((resolve) => {void handler(req as never, res as never, () => {});setImmediate(() => {for (const cb of req.endCallbacks) {cb();}setTimeout(resolve, 50);});});expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: false }));});it("refuses a hash whose parameter block differs from the client's before argon2Verify runs", async () => {process.env.ACCESS_KEYS = "test-key";const { validateAccessKeyServerHook } = await import("./validateAccessKeyServerHook");const use = vi.fn();validateAccessKeyServerHook({middlewares: { use },} as never);const handler = use.mock.calls[0][0] as (req: {url: string;method: string;on: (event: string, cb: (chunk: string) => void) => void;},res: {setHeader: ReturnType<typeof vi.fn>;end: ReturnType<typeof vi.fn>;statusCode: number;},next: () => void,) => void;const res = makeMockResponse();// A hash with inflated parameters: m=4194304 would force a multi-gigabyte// allocation if argon2Verify ever saw it.const malicious ="$argon2id$v=19$m=4194304,t=1000,p=1$xJaao6+z/VEA4+CU/+LAKg$JCE6vg7EHYLNv+EfNk1R6oJsEoDOsv2zNAXzQrrvI0E";const req = makeMockRequest("/api/validate-access-key","POST",JSON.stringify({ accessKeyHash: malicious }),);await new Promise<void>((resolve) => {void handler(req as never, res as never, () => {});setImmediate(() => {for (const cb of req.endCallbacks) {cb();}setTimeout(resolve, 50);});});expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: false }));expect(mockArgon2Verify).not.toHaveBeenCalled();1 unmodified lineit("should return 400 for invalid JSON body", async () => {process.env.ACCESS_KEYS = "test-key";const { validateAccessKeyServerHook } = await import("./validateAccessKeyServerHook");const use = vi.fn();validateAccessKeyServerHook({middlewares: { use },} as never);const handler = use.mock.calls[0][0] as (req: {url: string;method: string;on: (event: string, cb: (chunk: string) => void) => void;},res: {setHeader: ReturnType<typeof vi.fn>;end: ReturnType<typeof vi.fn>;statusCode: { value: number };},next: () => void,) => void;const res = makeMockResponse();const req = makeMockRequest("/api/validate-access-key", "POST", "not-json");await new Promise<void>((resolve) => {void handler(req as never, res as never, () => {});setImmediate(() => {for (const cb of req.endCallbacks) {cb();}setTimeout(resolve, 50);});});expect(res.statusCode).toBe(400);expect(res.end).toHaveBeenCalledWith(5 unmodified linesdescribe("request body cap", () => {it("answers 413 once and ignores the rest of the body", async () => {process.env.ACCESS_KEYS = "test-key";const { validateAccessKeyServerHook } = await import("./validateAccessKeyServerHook");const use = vi.fn();validateAccessKeyServerHook({ middlewares: { use } } as never);const handler = use.mock.calls[0][0] as (req: unknown,res: unknown,next: () => void,) => void;const destroy = vi.fn();const dataCallbacks: Array<(chunk: Buffer) => void> = [];13 unmodified linesconst res = { statusCode: 200, setHeader: vi.fn(), end: vi.fn() };await new Promise<void>((resolve) => {void handler(req, res, vi.fn());setImmediate(() => {// Two chunks, each within the cap on its own, over it together.for (const cb of dataCallbacks) cb(Buffer.alloc(3 * 1024, "x"));54 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191207 unmodified lines1281291301311321331345 unmodified lines1401411421431441451466 unmodified lines1531541551561571581591601611621631641651661671681691701 unmodified line1721731741751761771785 unmodified lines18418518618718818919013 unmodified lines20420520620720820921054 unmodified linesreturn `$argon2id$v=19$m=512,t=16,p=1$${salt}$${digest}`;}/** Imports the hook, registers it, and returns its middleware. */async function getRegisteredHandler() {const { validateAccessKeyServerHook } = await import("./validateAccessKeyServerHook");const use = vi.fn();validateAccessKeyServerHook({ middlewares: { use } } as never);return use.mock.calls[0][0] as (req: never,res: never,next: () => void,) => unknown;}/** Posts `body` to the endpoint, lets the request end, waits 50 ms, and returns the response. */async function postAccessKeyRequest(body: string) {const handler = await getRegisteredHandler();const res = makeMockResponse();const req = makeMockRequest("/api/validate-access-key", "POST", body);await new Promise<void>((resolve) => {void handler(req as never, res as never, () => {});// The handler consumes a rate-limit point (async) before it registers its// end listener, so trigger it on a later macrotask.setImmediate(() => {for (const cb of req.endCallbacks) {cb();}setTimeout(resolve, 50);});});return res;}function postAccessKeyHash(accessKeyHash: string) {return postAccessKeyRequest(JSON.stringify({ accessKeyHash }));}describe("validateAccessKeyServerHook", () => {it("should skip non-matching URLs", async () => {const handler = await getRegisteredHandler();const next = vi.fn();handler({ url: "/other", method: "POST" } as never, {} as never, next);expect(next).toHaveBeenCalled();});it("should skip non-POST methods", async () => {const handler = await getRegisteredHandler();const next = vi.fn();handler({ url: "/api/validate-access-key", method: "GET" } as never,{} as never,next,);expect(next).toHaveBeenCalled();});it("should return valid: true for a matching access key", async () => {process.env.ACCESS_KEYS = "test-key";mockArgon2Verify.mockResolvedValue(true);const res = await postAccessKeyHash(makeValidAccessKeyHash("valid"));expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true }));expect(mockConsumeRateLimitPoint).toHaveBeenCalledTimes(1);7 unmodified linesreturn password === "other-key";},);const res = await postAccessKeyHash(makeValidAccessKeyHash("valid"));expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true }));const verifiedPasswords = mockArgon2Verify.mock.calls.map(5 unmodified linesit("responds 429 and skips the argon2 loop when the limiter refuses", async () => {process.env.ACCESS_KEYS = "test-key";mockConsumeRateLimitPoint.mockResolvedValue(false);const res = await postAccessKeyHash(makeValidAccessKeyHash("valid"));expect(res.statusCode).toBe(429);expect(res.end).toHaveBeenCalledWith(6 unmodified linesit("should return valid: false when no access keys match", async () => {process.env.ACCESS_KEYS = "test-key";mockArgon2Verify.mockResolvedValue(false);const res = await postAccessKeyHash(makeValidAccessKeyHash("wrong"));expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: false }));});it("refuses a hash whose parameter block differs from the client's before argon2Verify runs", async () => {process.env.ACCESS_KEYS = "test-key";// A hash with inflated parameters: m=4194304 would force a multi-gigabyte// allocation if argon2Verify ever saw it.const malicious ="$argon2id$v=19$m=4194304,t=1000,p=1$xJaao6+z/VEA4+CU/+LAKg$JCE6vg7EHYLNv+EfNk1R6oJsEoDOsv2zNAXzQrrvI0E";const res = await postAccessKeyHash(malicious);expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: false }));expect(mockArgon2Verify).not.toHaveBeenCalled();1 unmodified lineit("should return 400 for invalid JSON body", async () => {process.env.ACCESS_KEYS = "test-key";const res = await postAccessKeyRequest("not-json");expect(res.statusCode).toBe(400);expect(res.end).toHaveBeenCalledWith(5 unmodified linesdescribe("request body cap", () => {it("answers 413 once and ignores the rest of the body", async () => {process.env.ACCESS_KEYS = "test-key";const handler = await getRegisteredHandler();const destroy = vi.fn();const dataCallbacks: Array<(chunk: Buffer) => void> = [];13 unmodified linesconst res = { statusCode: 200, setHeader: vi.fn(), end: vi.fn() };await new Promise<void>((resolve) => {void handler(req as never, res as never, vi.fn());setImmediate(() => {// Two chunks, each within the cap on its own, over it together.for (const cb of dataCallbacks) cb(Buffer.alloc(3 * 1024, "x"));
docs/search-history.md+2-2
docs/ui-components.md+2
package-lock.json+7-7
server/internalApiEndpointServerHook.test.ts+454-834
server/internalApiModelPicker.test.ts+11
server/internalApiModelPicker.ts+7-2
server/thumbnailEndpointServerHook.test.ts+107-219
server/validateAccessKeyServerHook.test.ts+53-249