Spaces:
Running
Running
Sync from felladrin/MiniSearch@165e4b2 (part 2)
Browse filesFiles changed (8)
9 unmodified lines10111213131415161 unmodified line18192021212223249 unmodified lines
1. `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`).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 History
When `enableHistory` is off, `isHistoryEnabled()` makes every history write (`addSearchToHistory`, `updateSearchResults`, `saveLlmResponseForQuery`, `saveChatMessageForQuery`, the follow-up question chat entries) and the `useSearchHistory` reads return without touching IndexedDB. Skipping `historyDatabase.open()` at startup is not enough on its own: Dexie opens a database that was never opened on its first query, so the setting, not the open state, decides.When `enableHistory` is off, `isHistoryEnabled()` makes every history write (`addSearchToHistory`, `updateSearchResults`, `saveLlmResponseForQuery`, `replaceChatConversation`) and the `useSearchHistory` reads return without touching IndexedDB. Skipping `historyDatabase.open()` at startup is not enough on its own: Dexie opens a database that was never opened on its first query, so the setting, not the open state, decides.
## Cleanup Guarantees
377 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 history95 unmodified lines96979899100101991001011021031042734 unmodified lines283928402841284228432844284228432844284528462847284728482849285095 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==", "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.179", "resolved": "https://registry.npmjs.org/ai/-/ai-7.0.179.tgz", "integrity": "sha512-WT2ad3qEQPLne/5RDE/utNMSKYUuNpnGkI46AO/6Lv+IbEJ3kRwbatLX3HNfk25Y7N8LpdqOcSnMLcdw11VyIQ==", "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.152", "@ai-sdk/gateway": "4.0.154", "@ai-sdk/provider": "4.0.39", "@ai-sdk/provider-utils": "5.0.83" },44 unmodified lines454647484950515253545556485758596070 unmodified lines13113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631728 unmodified lines3463473481593493503513523 unmodified lines35635735816935936036136277 unmodified lines4404414422534434444454461 unmodified line4484494502612622632642652662674514524532704544554564574584594602772782792802812822834614624632864644654664672 unmodified lines4704714722952962972982993003014734743034754764774783 unmodified lines4824834843133143153163173183194854864874884 unmodified lines4934944953303313323333343353363373383393403413423433443453463473483493503513523533543554964974984993 unmodified lines5035045053653663675065073695085095105112 unmodified lines5145155163783793805175183825195205215224 unmodified lines5275285293933943953963973983995305314015325335345355364065375385395401 unmodified line5425435444145455464165475485495509 unmodified lines5605615624324334344354364374385635644405655665674435685695705715724484494504514524534544554564574584594604615735745755765776 unmodified lines5845855864745875885895904 unmodified lines5955965974854864874884894905985996006016024914924934944954964976036046055006066076086096106115065075085095105115125135145155165176126136146156165206176186196206 unmodified lines62762862953353453553653753853954054154254354454554654754854955063063163263363463563663763855655755855956056156256356456556656756856957057157257363964064164264364464564657857958058158258358458558658758858959059164764864965065117 unmodified lines66967067161561661761861962062162262362462562662762867267367467567667767816 unmodified lines6956966976516526536546556566576586596606616626636646986997007017027037047057066706717077087096736746756766776786796807107117127137147 unmodified lines7227237246946956966976986997007017027037047057067077087097107117127137147157257267277287297307187197317327227237247257267337347357365 unmodified lines7427437447387457467477485 unmodified lines7547557567507517527537547557567577577587597607607617627637647657667677687697707717727737747757767777787617627637647817827837847857657667677887897907917927937947957967977987998008018028038048058068077687697707717727737747757767777787797807818118128138148158168178187827837848207857867877887897908268278288298308318328338348358368378388398408418428438448458467917928488498508518528538548558568578587937947957967978608618628638648658667987998008018028708718728738748758768778788798808818828838848858038048058068078082 unmodified lines8118128138948958968978988998148158168178189009019029039049059068199088208218228238248258269149159169179189199209219229239249259269279289299309319329339349359368278289389399409419429439449459469479488298308318328338349509519529539549559568358368378388399609619629639649659669679689699709719729739749759768408418429789799809819828438448458468474 unmodified lines852853854993855856857996997998999100010011002100310041005100610071008100910101011101285885986086186286386410188658661020102110221023102410251026102710281029103010318678688691033103410351036103710388708718728731040104110421043104410451046104710481049105010511052105310541055105610578748758768778788798808811058105910608828838841064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610878858861089109010911092109310948878888898908918928938948958968978981098899900901902903904905110511061107110811091110111111121113111411151116111711181119112011211122112311249069071126112711281129113011311132113311341135113690890991091191211381139114011411142114311441145913914915916917918114911501151115211531154115511561157115811591160116111621163116411651166116711681169919920117111721173117411751176117711781179118011819219229239249251183118411851186118792692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695711941195119611979589599601199120012011202120396196296396496512079669671209121012111212121312141215121612179689691219122097097197297397412239759769779781226122797998098198298398498598612309879889899902 unmodified lines99399499512391240124112421243124412459969971247998999100010011 unmodified line1003100410051255125612571258125912601261100610071263100810091010101110121013126912701271127212731014101510161017101810191020127912801281128212831284128512861287102110221023102410251026128912901291129212931027102810291030103110321300103310341035103610371038103913071040104110422 unmodified lines1045104610471316131713181319104810491050105110521053132113221323132413251326132713281054105510561 unmodified line105810591060133613371338133910611062106310641065134413451346134713481349106610671068106910701071135113521353135413551356135713581072107310742 unmodified lines1077107810791367136813691370137113721373137413751376137713781379138013811382138313841385138610801081108210833 unmodified lines108710881089139613971398139914001401140210901091140410921093109410959 unmodified lines1105110611071420142114221423142414251426142714281429110811091110143111111112111311149 unmodified lines112411251126144714481449145014511452112711281129113011311132113311343 unmodified lines113811391140146211411142114311446 unmodified lines1151115211531475115411551477115611571158115932 unmodified lines1192119311941516151715181519152015211522152311951196119711985 unmodified lines1204120512061535153615371538153915401207120812091210121112121213154312141215121612172 unmodified lines122012211222155215531554155515561557155815591560156115621563156415651566156715681569157015711223122412251226122712281573157415751576157715781579158015811582158315841585122912301231123210 unmodified lines1243124412451602160316041605160616071608160916101246124712481249125012511252125312541255125616171257125812591260126112621623162416251626126312641265126612671631126812691270127114 unmodified lines12861287128816521653165416551656165716581289129016601661129112921293129412956 unmodified lines130213031304167416751676167716781679168016811682168316841685130513061307130816861687168813091310131144 unmodified lines method = "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([JSON.stringify(body)]) as 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(); else abortSignal?.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 lines await 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]); const payload = endPayload(response); expect(payload.error).toBe("Method Not Allowed"); });
3 unmodified lines const 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]); const payload = endPayload(response); expect(payload.error).toBe("Unsupported Media Type"); });
77 unmodified lines const response = createResponse(); await handler(createRequest(body), response, vi.fn()); expect(response.statusCode).toBe(400); const payload = JSON.parse(response.end.mock.calls[0][0]); const payload = endPayload(response); expect(payload.error).toContain(`Invalid request body: ${expectedPath}`); });
1 unmodified line const 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", }; const request = createRawRequest([chunk600k, chunk600k]); await handler(request, response, vi.fn()); expect(response.statusCode).toBe(413); const payload = JSON.parse(response.end.mock.calls[0][0]); 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 = 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", }; const request = createRawRequest(["not json at all"]); await handler(request, response, vi.fn()); expect(response.statusCode).toBe(400); const payload = JSON.parse(response.end.mock.calls[0][0]); const payload = endPayload(response); expect(payload.error).toBe("Invalid request body"); }); });2 unmodified lines it("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(), ); const response = await sendRequest(); expect(response.statusCode).toBe(500); const payload = JSON.parse(response.end.mock.calls[0][0]); const payload = endPayload(response); expect(payload.error).toBe("OpenAI API configuration is missing"); }); });3 unmodified lines vi.mocked(handleTokenVerification).mockResolvedValue({ shouldContinue: false, }); const handler = getRegisteredHandler(); const response = createResponse(); await handler( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), ); const response = await sendRequest(); 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; } beforeEach(configureStreamingApi);
function requestedModels() { const provider = vi.mocked(createOpenAICompatible).mock.results[0]3 unmodified lines
it("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, ); streamEveryCall(() => streamOf([{ type: "finish" }]));
await callWithFakeTimers(); await sendRequestThroughTimers();
expect(vi.mocked(streamText).mock.calls[0][0].providerOptions).toEqual({ openai: { reasoningEffort: "low" },2 unmodified lines
it("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, ); streamEveryCall(() => streamOf([{ type: "finish" }]));
await callWithFakeTimers(); await sendRequestThroughTimers();
expect( vi.mocked(streamText).mock.calls[0][0].providerOptions,4 unmodified lines vi.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, ); .mockImplementationOnce(() => answerStream("Recovered") as never);
const response = await callWithFakeTimers(); const response = await sendRequestThroughTimers();
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(""); 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,"); vi.mocked(streamText).mockImplementation(() => streamOf([]) as never); streamEveryCall(() => streamOf([]));
const response = await callWithFakeTimers(); const response = await sendRequestThroughTimers();
expect(requestedModels()).toEqual([ "model-a",9 unmodified lines it("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, ); .mockImplementationOnce(() => answerStream("Second try") as never);
const response = await callWithFakeTimers(); const response = await sendRequestThroughTimers();
expect(requestedModels()).toEqual(["test-model", "test-model"]); const writes = response.write.mock.calls.map((c) => c[0]).join(""); const writes = writtenText(response); 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(), ); 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 = response.write.mock.calls.map((c) => c[0]); 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 () => { vi.mocked(streamText).mockImplementation( () => streamOf([ { type: "text-delta", text: "Cut" }, { type: "finish", finishReason: "length" }, ]) as never, streamEveryCall(() => streamOf([ { type: "text-delta", text: "Cut" }, { type: "finish", finishReason: "length" }, ]), ); const response = createResponse();
await getRegisteredHandler()( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), ); const response = await sendRequest();
const writes = response.write.mock.calls.map((c) => c[0]).join(""); 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 () => { 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(), streamEveryCall(() => streamOf([{ type: "finish", finishReason: "content-filter" }]), ); const response = await sendRequest();
const writes = response.write.mock.calls.map((c) => c[0]).join(""); const writes = writtenText(response); expect(writes).toContain('"finish_reason":"content_filter"'); });
6 unmodified lines async (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]; streamEveryCall(() => answerStream("Ok")); const callArgs = await upstreamArgsFor({ max_tokens: 9999, }); 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]; 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 () => { 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(), ); 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 }) => { 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]; 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 }) => { 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]; 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 () => { vi.mocked(streamText).mockImplementation( () => streamOf([{ type: "text-delta", text: "Partial" }]) as never, streamEveryCall(() => streamOf([{ type: "text-delta", text: "Partial" }]), ); 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]); const response = await sendRequest(); const writeCalls = writtenFrames(response); expect( writeCalls.some((s: string) => s.includes("Stream ended unexpectedly")), ).toBe(true);7 unmodified lines async (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; }, ({ abortSignal }: { abortSignal?: AbortSignal } = {}) => stallUntilAborted(abortSignal, [ { type: "text-delta", text: "Half" }, ]) as never, );
const handler = getRegisteredHandler(); const response = createResponse(); vi.useFakeTimers(); try { const pending = handler( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), ); 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 = response.write.mock.calls.map((c) => c[0] as string); 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 () => { 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"); useTwoRandomModels(); const before = getInferenceStats().attemptFailures;
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; }, ({ abortSignal }: { abortSignal?: AbortSignal } = {}) => stallUntilAborted(abortSignal) as never, ); vi.mocked(streamText).mockImplementationOnce( () => streamOf([ { type: "text-delta", text: "Recovered" }, { type: "finish" }, ]) as never, () => answerStream("Recovered") 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(); } // 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 () => { vi.mocked(streamText).mockImplementation(() => streamOf([]) as never); const handler = getRegisteredHandler(); const response = createResponse(); await handler( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), ); streamEveryCall(() => streamOf([])); const response = await sendRequest(); expect(response.statusCode).toBe(503); const payload = JSON.parse(response.end.mock.calls[0][0]); 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 () => { 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; }); useTwoRandomModels();
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; streamFirstThen( () => streamOf([]), () => answerStream("Recovered"), );
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(); } const writes = await sendExpectingSecondAttemptToRecover(); expect(writes).not.toContain("Stream ended unexpectedly"); });
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(), ); 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 () => { vi.mocked(streamText).mockImplementation( () => streamOf([ { type: "text-delta", text: "Partial" }, { type: "error", error: new Error("upstream exploded") }, ]) as never, streamEveryCall(() => streamOf([ { type: "text-delta", text: "Partial" }, { type: "error", error: new Error("upstream exploded") }, ]), ); 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(""); 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 () => { 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; }); useTwoRandomModels();
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; streamFirstThen( () => streamOf([{ type: "error", error: new Error("upstream exploded") }]), () => answerStream("Recovered"), );
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(); } 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 () => { 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", streamEveryCall(() => streamOf([{ type: "error", error: new Error("upstream down") }]), ); const payload = JSON.parse(response.end.mock.calls[0][0]); expect(payload).toEqual({ error: "Service unavailable - all models failed", lastError: "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 () => { vi.mocked(streamText).mockImplementation(() => { streamEveryCall(() => { 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", }); 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 () => { vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined); useTwoRandomModels();
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) { streamFirstThen( () => { throw new Error("upstream down"); } return streamOf([ { type: "text-delta", text: "Ok" }, { type: "finish" }, ]) as never; }); }, () => answerStream("Ok"), );
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); 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); } 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; }); useTwoRandomModels();
const handler = getRegisteredHandler(); const response = createResponse(); await handler( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), 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 = response.write.mock.calls.map((c) => c[0]).join(""); 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 () => { 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; }); useSingleModelPoolThatRelists();
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; streamFirstThen( () => streamOf([{ type: "error", error: new Error("upstream down") }]), () => answerStream("Recovered"), );
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(); } 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 () => { 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; }); useTwoRandomModels();
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; streamFirstThen( () => streamOf([{ type: "error", error: new Error("upstream down") }]), () => answerStream("Recovered"), );
expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(1); expect(streamText).toHaveBeenCalledTimes(2); } finally { vi.useRealTimers(); } 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" }]) .mockResolvedValueOnce([{ id: "model-b" }]); vi.mocked(selectRandomModel) .mockReturnValueOnce("model-a") .mockReturnValueOnce("model-b"); .mockRejectedValueOnce(new Error("models endpoint down")); vi.mocked(selectRandomModel).mockReturnValueOnce("model-a");
vi.mocked(streamText).mockImplementation( () => streamOf([ { type: "error", error: new Error("upstream down") }, ]) as never, streamEveryCall(() => streamOf([{ type: "error", error: new Error("upstream down") }]), );
const before = getInferenceStats(); vi.useFakeTimers(); const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); try { const handler = getRegisteredHandler(); const response = createResponse(); const pending = handler( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), ); await vi.runAllTimersAsync(); await pending; const response = await sendRequestThroughTimers();
// The pool was refreshed once; even though both models failed we do not // loop on a failing /models endpoint. // 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-b" }, { id: "model-a" }, ]); expect(streamText).toHaveBeenCalledTimes(1); expect(response.statusCode).toBe(503); expect(getInferenceStats().modelsRefetched).toBe( before.modelsRefetched + 1, expect(getInferenceStats().failed.failedBeforeFirstToken).toBe( before.failed.failedBeforeFirstToken + 1, ); expect(warnSpy).toHaveBeenCalledWith( "Failed to refetch models:", "models endpoint down", ); } finally { vi.useRealTimers(); warnSpy.mockRestore(); } });
2 unmodified lines vi.mocked(listOpenAiCompatibleModels).mockRejectedValue( new Error("network error"), ); const handler = getRegisteredHandler(); const response = createResponse(); await handler( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), ); const response = await sendRequest(); expect(response.statusCode).toBe(500); const payload = JSON.parse(response.end.mock.calls[0][0]); const payload = endPayload(response); expect(payload.error).toBe("Failed to fetch available models"); });
1 unmodified line vi.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(), ); const response = await sendRequest(); expect(response.statusCode).toBe(500); const payload = JSON.parse(response.end.mock.calls[0][0]); 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 () => { vi.mocked(streamText).mockImplementation( () => streamOf([ { type: "error", error: new Error("upstream exploded") }, ]) as never, streamEveryCall(() => streamOf([{ type: "error", error: new Error("upstream exploded") }]), ); 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:", await sendRequest(); expectOnlyMessageLogged( errorSpy, "Error during streaming:", "upstream exploded", ); 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(() => { streamEveryCall(() => { 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 lines throw new Error("setHeader exploded"); } }); await handler( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), await sendRequest(helloBody, response); expectOnlyMessageLogged( errorSpy, "Error in internal API endpoint:", "setHeader exploded", ); 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"), ); failModelListing(); 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 response = await sendRequest(); expectOnlyMessageLogged( errorSpy, "Error fetching models:", "registry timeout", ); 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); 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 lines
it("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, ); streamEveryCall(() => answerStream("Hello"));
await callInference(); await sendRequest();
const after = getInferenceStats(["test-model"]); expect(after.streamed).toBe(before.streamed + 1);9 unmodified lines
it("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; streamEveryCall(() => streamOf([{ type: "text-delta", text: "Hello" }])); const response = closedResponse();
await callInference(response); 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 lines writableEnded: boolean; destroyed: boolean; }; vi.mocked(streamText).mockImplementation( () => streamOf([ { type: "text-delta", text: "Half an answer" }, { type: "text-delta", text: "never read" }, ]) as never, 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 lines return true; });
await callInference(response); await sendRequest(helloBody, response);
const after = getInferenceStats(["test-model"]); expect(after.failed.abandoned).toBe(before.failed.abandoned + 1);6 unmodified lines
it("counts an exhausted ladder as a failure before the first token", async () => { const before = getInferenceStats(["test-model"]); vi.mocked(streamText).mockImplementation(() => streamOf([]) as never); streamEveryCall(() => streamOf([]));
const response = await callInference(); const response = await sendRequest();
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(); } await sendRequestThroughTimers();
const after = getInferenceStats().attemptFailures; expect(after.rateLimited).toBe(before.rateLimited + 1);5 unmodified lines
it("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, streamEveryCall(() => streamOf([ { type: "text-delta", text: "Half an answer" }, { type: "error", error: new Error("upstream died") }, ]), );
await callInference(); await sendRequest();
expect(getInferenceStats().failed.failedMidStream).toBe( before.failed.failedMidStream + 1,2 unmodified lines
it("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; }); useTwoRandomModels(); streamFirstThen( () => streamOf([]), () => answerStream("Recovered"), );
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(); } await sendRequestThroughTimers();
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()); await getRegisteredHandler()( createRawRequest(["{invalid"]), createResponse(), vi.fn(), ); }, ], [ "notConfigured", async () => { vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", undefined); await callInference(); await sendRequest(); }, ], [ "modelListUnavailable", async () => { vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined); vi.mocked(listOpenAiCompatibleModels).mockRejectedValue( new Error("registry timeout"), ); failModelListing(); const errorSpy = vi .spyOn(console, "error") .mockImplementation(() => {}); try { await callInference(); await sendRequest(); } finally { errorSpy.mockRestore(); }14 unmodified lines
it("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, ); streamEveryCall(() => answerStream("Hello"));
await callInference(); await callInference(); await sendRequest(); await sendRequest();
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" }], }), streamEveryCall(() => answerStream("borogoves")); await sendRequest({ messages: [{ role: "user", content: "outgrabe mimsy-42" }], }); createResponse(), vi.fn(), );
const serialized = JSON.stringify(getInferenceStats()); expect(serialized).not.toContain("outgrabe");35 unmodified lines363738394041424344454647484950515235 unmodified lines expect(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 lines910111213141516177 unmodified lines2526272526282930313233348 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 lines const 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. // 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 lines88899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916042 unmodified lines2032042051391401411422062072082094 unmodified lines2142152161531541551561572172182192205 unmodified lines2262272281692291711721731741752302312322332342352361821831841852372382392407 unmodified lines24824925019920020120220320420520625125225325423 unmodified lines27827928023628123823924024124228228328428510 unmodified lines2962972982592992612623003013023033042 unmodified lines3073083092712722732742752762772783103112802812822833123133143152872882892902912922932943163172962972982993183193203213033043053063073223233243253263279 unmodified lines33733833932332432532632732832933034034134234312 unmodified lines3563573583493503513523533543553563593603613627 unmodified lines3703713723703713723733743753763773733743793803813823833843853863873753763773783793803813943823833973983994004013843853863876 unmodified lines3943953964144154164174184194204213973983994008 unmodified lines4094104114364374384394404414424434124134144153 unmodified lines4194204214534544554564574584594604224234244255 unmodified lines4314324334724734744754764344784794804814354364374384394404414884894904914924934944954424434444451 unmodified line4474484495035044504514524535085095105115125135145155164544554564574 unmodified lines4624634645275284654664674 unmodified lines4724734745395405415425435445455465474754764774788 unmodified lines4874884895625635645655665675685694904914924936 unmodified lines5005015025825835845855865875885895035045915925935945955965975985995055065075084 unmodified lines5135145156106116126136145166166176186195175185195205215226256266276286296306316325235245255264 unmodified lines53153253364353453553653753864965053954054154265565654354454554665954754854966255055155266555355455555655767055855967256056156256387 unmodified lines return `/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 handler = getRegisteredHandler(); const next = vi.fn();
await handler(createRequest("/status"), createResponse(), next); 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 handler = getRegisteredHandler(); const next = vi.fn(); const response = createResponse();
await handler(createRequest(url), response, next); const { response, next } = await requestPath(url);
expect(next).toHaveBeenCalledTimes(1); expect(response.end).not.toHaveBeenCalled();5 unmodified lines vi.mocked(handleTokenVerification).mockResolvedValue({ shouldContinue: false, }); const handler = getRegisteredHandler();
await handler( createRequest(requestUrlFor(publicThumbnailUrl())), createResponse(), vi.fn(), ); await requestThumbnail();
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()); const { response } = await requestPath("/thumbnail?token=abc");
expect(response.statusCode).toBe(400); expect(response.end).toHaveBeenCalledWith(7 unmodified lines pinnedRequestMock.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(), ); const response = await requestThumbnail();
expect(response.statusCode).toBe(200); expect(response.setHeader).toHaveBeenCalledWith(23 unmodified lines it("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(), ); 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 lines const 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()); await requestThumbnail(url); await requestThumbnail(url);
expect(pinnedRequestMock).toHaveBeenCalledTimes(1); // Both requests are demand, so both count even though only one fetched.2 unmodified lines
it("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(), ); const response = await requestThumbnail();
expect(response.statusCode).toBe(403); expect(pinnedRequestMock).not.toHaveBeenCalled(); expect(recordThumbnailBlocked).toHaveBeenCalledTimes(1); expect(recordThumbnailDropped).toHaveBeenCalledTimes(1); expectRefusedBeforeFetch(response); });
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(), ); const response = await requestThumbnail("file:///etc/passwd");
expect(response.statusCode).toBe(403); expect(pinnedRequestMock).not.toHaveBeenCalled(); expect(recordThumbnailBlocked).toHaveBeenCalledTimes(1); expect(recordThumbnailDropped).toHaveBeenCalledTimes(1); expectRefusedBeforeFetch(response); });
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()); 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 handler = getRegisteredHandler(); const response = createResponse();
await handler( createRequest(requestUrlFor(publicThumbnailUrl())), response, vi.fn(), ); const response = await requestThumbnail();
expect(response.statusCode).toBe(200); expect(pinnedRequestMock).toHaveBeenCalledTimes(1);12 unmodified lines location: "http://10.0.0.7/thumb.jpg", }), ); const handler = getRegisteredHandler(); const response = createResponse();
await handler( createRequest(requestUrlFor(publicThumbnailUrl())), response, vi.fn(), ); const response = await requestThumbnail();
expect(response.statusCode).toBe(403); // The redirect target was refused at validation: its socket was never7 unmodified lines pinnedRequestMock.mockResolvedValue( fakeIncoming(new Uint8Array(), 404, {}), ); const handler = getRegisteredHandler(); const response = createResponse();
await handler( createRequest(requestUrlFor(publicThumbnailUrl())), response, vi.fn(), ); const response = await requestThumbnail();
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); expectCouldNotFetch(response); });
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(), ); await requestThumbnail(thumbnailUrl);
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(), ); const response = await requestThumbnail();
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(), ); const response = await requestThumbnail();
expect(response.statusCode).toBe(502); expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);3 unmodified lines pinnedRequestMock.mockResolvedValueOnce( fakeIncoming(new Uint8Array(), 302, { location: "http://[" }), ); const handler = getRegisteredHandler(); const response = createResponse();
await handler( createRequest(requestUrlFor(publicThumbnailUrl())), response, vi.fn(), ); const response = await requestThumbnail();
expect(response.statusCode).toBe(502); expect(pinnedRequestMock).toHaveBeenCalledTimes(1);5 unmodified lines pinnedRequestMock .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); await expectFailureIsRetried(url); });
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(), ); const response = await requestThumbnail();
expect(response.statusCode).toBe(502); expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);1 unmodified line
it("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; // the documented one. 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; 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 () => { // 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; const response = await requestThumbnailPast(THUMBNAIL_TIMEOUT_MS);
expect(response.statusCode).toBe(502); expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);8 unmodified lines location: "https://thumbs.example.com/loop.jpg", }), ); const handler = getRegisteredHandler(); const response = createResponse();
await handler( createRequest(requestUrlFor(publicThumbnailUrl())), response, vi.fn(), ); 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 handler = getRegisteredHandler(); const response = createResponse();
await handler( createRequest(requestUrlFor(publicThumbnailUrl())), response, vi.fn(), ); const response = await requestThumbnail();
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); expectCouldNotFetch(response); expect(logLines.join("\n")).toContain( "Thumbnail fetch failed: larger than 500000 bytes", );4 unmodified lines pinnedRequestMock .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); 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 handler = getRegisteredHandler(); const response = createResponse();
await handler( createRequest(requestUrlFor(publicThumbnailUrl())), response, vi.fn(), ); const response = await requestThumbnail();
expect(response.statusCode).toBe(200); const body = response.end.mock.calls[0][0] as Buffer;4 unmodified lines it("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); await requestThumbnail(firstUrl); await requestThumbnail(secondUrl);
// Re-reading firstUrl promotes it, so secondUrl is the eviction candidate. await load(firstUrl); await requestThumbnail(firstUrl);
for (let i = 0; i < maxEntries - 2; i += 1) { await load(publicThumbnailUrl()); await requestThumbnail(publicThumbnailUrl()); } // This insert pushes the cache past the cap: exactly one entry is evicted. await load(publicThumbnailUrl()); 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 load(firstUrl); await requestThumbnail(firstUrl); expect(fetched(firstUrl)).toBe(1); await load(secondUrl); await requestThumbnail(secondUrl); expect(fetched(secondUrl)).toBe(2); });});54 unmodified lines555657585960616263646566676869707172737475767778798081828384858687888990919293949596606162636465666768697071979873991001011021037879808182838485868788891041059110610710810911011111211311411511698991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351171181191207 unmodified lines1281291301491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841311321331345 unmodified lines1401411421961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262271431441451466 unmodified lines1531541552402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742751561571581591601611622822832842852862872882892902912922932942952962972982993003013023031631641651663083093103113123133143153163173183193203213221671681691701 unmodified line1721731743303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613621751761771785 unmodified lines18418518637437537637737837938038138238318718818919013 unmodified lines20420520640320720820921054 unmodified lines return `$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 { 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 handler = await getRegisteredHandler(); const next = vi.fn(); handler({ url: "/other", method: "POST" }, {}, next); handler({ url: "/other", method: "POST" } as never, {} as never, 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 handler = await getRegisteredHandler(); const next = vi.fn(); handler({ url: "/api/validate-access-key", method: "GET" }, {}, next); 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 { 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); }); }); const res = await postAccessKeyHash(makeValidAccessKeyHash("valid"));
expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true })); expect(mockConsumeRateLimitPoint).toHaveBeenCalledTimes(1);7 unmodified lines return 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); }); }); const res = await postAccessKeyHash(makeValidAccessKeyHash("valid"));
expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true })); const verifiedPasswords = mockArgon2Verify.mock.calls.map(5 unmodified lines it("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); }); const res = await postAccessKeyHash(makeValidAccessKeyHash("valid"));
expect(res.statusCode).toBe(429); expect(res.end).toHaveBeenCalledWith(6 unmodified lines it("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); }); }); 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"; 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); }); }); const res = await postAccessKeyHash(malicious);
expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: false })); expect(mockArgon2Verify).not.toHaveBeenCalled();1 unmodified line
it("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); }); }); 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 { 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 handler = await getRegisteredHandler();
const destroy = vi.fn(); const dataCallbacks: Array<(chunk: Buffer) => void> = [];13 unmodified lines const res = { statusCode: 200, setHeader: vi.fn(), end: vi.fn() };
await new Promise<void>((resolve) => { void handler(req, res, vi.fn()); 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