Spaces:
Running
Running
Sync from felladrin/MiniSearch@3f9f9de
Browse filesFiles changed (32)
- .env.example+3
- changelog.md+11
- client/components/AiResponse/ChatHeader.test.tsxAdded+64
- client/components/AiResponse/ChatHeader.tsx+5-3
- client/components/AiResponse/ChatInterface.test.tsx+171
- client/components/AiResponse/ChatInterface.tsx+65-34
- client/components/AiResponse/MessageList.test.tsx+52-1
- client/components/AiResponse/MessageList.tsx+23-9
- client/hooks/useHistoryRestore.ts+5-3
- client/modules/pubSub.throttle.test.tsAdded+69
- client/modules/pubSub.ts+73-4
- client/modules/textGeneration.chatBudget.test.ts+1
- client/modules/textGeneration.degradation.test.ts+5
- client/modules/textGeneration.inference.test.ts+1
- client/modules/textGeneration.responsePersistence.test.tsAdded+111
- client/modules/textGeneration.test.ts+1
- client/modules/textGeneration.ts+10-4
- client/modules/textGenerationWithHorde.test.ts+88-3
- client/modules/textGenerationWithHorde.ts+27-2
- client/modules/textGenerationWithInternalApi.test.ts+126-2
- client/modules/textGenerationWithInternalApi.ts+117-71
- client/modules/textGenerationWithOpenAi.test.ts+4-2
- client/modules/textGenerationWithOpenAi.ts+25-29
- client/modules/textGenerationWithWllama.test.ts+1-1
- client/modules/textGenerationWithWllama.ts+3-2
- docs/ai-integration.md+1-1
- docs/api.md+5-1
- docs/configuration.md+9-6
- docs/failure-injection.md+2
- docs/glossary.md+1-1
- docs/overview.md+7-7
- docs/ui-components.md+7-6
18 unmodified lines19202122232418 unmodified lines# The model for the internal OpenAI compatible API.INTERNAL_OPENAI_COMPATIBLE_API_MODEL=""# The name of the internal OpenAI compatible API, displayed in the UI.INTERNAL_OPENAI_COMPATIBLE_API_NAME="Internal API"18 unmodified lines19202122232425262718 unmodified lines# The model for the internal OpenAI compatible API.INTERNAL_OPENAI_COMPATIBLE_API_MODEL=""# The reasoning effort for the internal OpenAI compatible API, sent as `reasoning_effort` (e.g. "none", "low", "medium", "high"). Leave blank to use the API's default.INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT=""# The name of the internal OpenAI compatible API, displayed in the UI.INTERNAL_OPENAI_COMPATIBLE_API_NAME="Internal API"
1 unmodified line234567891 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-25- Earlier chat turns no longer send their thinking back to the model. Stored answers keep their reasoning block, and every prompt built from the conversation was sending it again: wasted tokens, and older turns dropped from the context sooner because of it. The reasoning is now stripped where the prompt is built, for the continuation, the rolling summary and the follow-up question suggestions. The chat and the History still show it.- Fetches triggered by the settings are cancelled when superseded and give up after 10 seconds. Typing a base URL or a Horde key used to fire one request per character, and the slowest answer won: an old server's model list could replace the correct one, a cleared field could show the old user again, and an endpoint that never answers left the model dropdown stuck or delayed the start of an AI response indefinitely. Clearing the base URL now clears the model list too.- Follow-up question suggestions are now written from the question prompt alone. The prompt went out the way a chat answer does, behind the system prompt with the search results, which buried the instructions for the question under unrelated text; it now goes out on its own, like the related search query. A reply with no question in it also no longer leaves a blank entry in the list of earlier suggestions the next prompt asks the model not to repeat, which pushed a real one out of that list.1 unmodified line2345678910111213141516171819201 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-26- An AI Horde answer no longer fails because one of its two jobs did. With no model chosen, MiniSearch sends two jobs and uses whichever answers first, but a job that failed first, such as one whose worker crashed, ended the whole answer with "Generation failed" while the other job was about to finish. A failed job is now ignored as long as the other one is still running, and the answer fails only when both do. When both fail, a stop you pressed still ends it without a new attempt, and a job that could not run on the top models still sends the second round to any model.- Stop now ends an answer from the instance's own AI right away. The request was never cancelled: pressing Stop only took effect when the next piece of text arrived, so a stalled answer kept going until the server gave up, and even after Stop the connection stayed open, so the server kept generating and counted the answer as streamed instead of abandoned. The same happened when the answer ended with an error. The request is now cancelled on Stop, even while nothing is arriving, and whenever the answer does not finish.- A SearXNG that stops answering no longer holds a search until the client gives up. The request to SearXNG had no time limit, so a stalled instance kept a search waiting for up to 300 seconds, past the client's 30 second timeout, and the fallback providers were then skipped because the search's time had run out. The request, its retries and the waits between them are now canceled after 15 seconds when a fallback could still answer, leaving it the remaining 10, and after 25 seconds otherwise; each canceled request counts toward opening the SearXNG circuit. A failed SearXNG answer now also releases its connection right away, and a search whose every retry got a 500 says so in the log.- A failed regeneration no longer loses the answer. Regenerate removed the answer from the chat before asking for a new one, and when the model errored it was gone, with the regenerate button, and the follow-up suggestion was cleared too, so the question had to be typed again; the only trace was a line in the logs. The previous answer and the follow-up suggestion now come back, a red notification says the regeneration failed, and the answer can be regenerated again.## 2026-11-25- Admins can now set the reasoning effort of the instance's own AI. The new `INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT` variable is sent as `reasoning_effort` on every request to the internal OpenAI-compatible API, for every model in the list, so a reasoning model can be told to think less (or not at all) and answer faster. Left empty, nothing is sent and the API keeps its own default.- Follow-up questions are now shown when the main AI answer came back empty. The first follow-up question and its answer used to be hidden for good, "Copy conversation" left them out, and they could not be regenerated. A last answer that came back empty now shows "No response" with its Re-generate button, instead of showing nothing to retry from.- The AI answer is now saved to the history in full. Response updates are throttled to about 12 a second, and the save read the throttled channel right after the stream ended, before the write carrying the last tokens had run, so the stored answer could miss everything that arrived since the last publish — up to the whole answer, which with a reasoning model left a history row that restored as an unfinished thought. The save now takes the text the generation call returns, and the full answer is published before the generation state turns to completed, so the restored history row and the follow-up chat start from the complete answer. Restoring a saved answer publishes it the same way.- Earlier chat turns no longer send their thinking back to the model. Stored answers keep their reasoning block, and every prompt built from the conversation was sending it again: wasted tokens, and older turns dropped from the context sooner because of it. The reasoning is now stripped where the prompt is built, for the continuation, the rolling summary and the follow-up question suggestions. The chat and the History still show it.- Fetches triggered by the settings are cancelled when superseded and give up after 10 seconds. Typing a base URL or a Horde key used to fire one request per character, and the slowest answer won: an old server's model list could replace the correct one, a cleared field could show the old user again, and an endpoint that never answers left the model dropdown stuck or delayed the start of an AI response indefinitely. Clearing the base URL now clears the model list too.- Follow-up question suggestions are now written from the question prompt alone. The prompt went out the way a chat answer does, behind the system prompt with the search results, which buried the instructions for the question under unrelated text; it now goes out on its own, like the related search query. A reply with no question in it also no longer leaves a blank entry in the list of earlier suggestions the next prompt asks the model not to repeat, which pushed a real one out of that list.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import { MantineProvider } from "@mantine/core";import { render, screen } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import type { ChatMessage } from "@/modules/types";import ChatHeader from "./ChatHeader";
// Show the text the copy button would put on the clipboard.vi.mock("./CopyIconButton", () => ({ default: ({ value }: { value: string }) => ( <pre data-testid="copied-conversation">{value}</pre> ),}));
function renderChatHeader(messages: ChatMessage[], followUpStartIndex: number) { return render( <MantineProvider> <ChatHeader messages={messages} followUpStartIndex={followUpStartIndex} /> </MantineProvider>, );}
describe("ChatHeader", () => { it("copies the follow-ups that come after the main question and answer", () => { renderChatHeader( [ { role: "user", content: "Main question" }, { role: "assistant", content: "Main answer" }, { role: "user", content: "Q1" }, { role: "assistant", content: "A1" }, ], 2, );
expect(screen.getByTestId("copied-conversation").textContent).toBe( "1. USER\n\nQ1\n\n2. ASSISTANT\n\nA1", ); });
it("copies the first follow-up pair when there is no main question and answer", () => { renderChatHeader( [ { role: "user", content: "Q1" }, { role: "assistant", content: "A1" }, ], 0, );
expect(screen.getByTestId("copied-conversation").textContent).toBe( "1. USER\n\nQ1\n\n2. ASSISTANT\n\nA1", ); });
it("shows no copy button before the first follow-up", () => { renderChatHeader( [ { role: "user", content: "Main question" }, { role: "assistant", content: "Main answer" }, ], 2, );
expect(screen.queryByTestId("copied-conversation")).toBeNull(); });});3 unmodified lines4567891011121314154 unmodified lines202122232425263 unmodified linesinterface ChatHeaderProps {messages: ChatMessage[];}function ChatHeader({ messages }: ChatHeaderProps) {const getChatContent = () => {return messages.slice(2).map((msg, index) =>`${index + 1}. ${msg.role?.toUpperCase()}\n\n${msg.content}`,4 unmodified linesreturn (<Group justify="space-between"><Text fw={500}>Follow-up questions</Text>{messages.length > 2 && (<CopyIconButtonvalue={getChatContent()}tooltipLabel="Copy conversation"3 unmodified lines45678910111213141516174 unmodified lines222324252627283 unmodified linesinterface ChatHeaderProps {messages: ChatMessage[];/** Position of the first follow-up message: 2 after the main question and answer, 0 without them. */followUpStartIndex: number;}function ChatHeader({ messages, followUpStartIndex }: ChatHeaderProps) {const getChatContent = () => {return messages.slice(followUpStartIndex).map((msg, index) =>`${index + 1}. ${msg.role?.toUpperCase()}\n\n${msg.content}`,4 unmodified linesreturn (<Group justify="space-between"><Text fw={500}>Follow-up questions</Text>{messages.length > followUpStartIndex && (<CopyIconButtonvalue={getChatContent()}tooltipLabel="Copy conversation"
35 unmodified lines3637383940414243444546475 unmodified lines53545556575859606162635 unmodified lines69707172737445 unmodified lines120121122123124125612 unmodified lines73873974074174274335 unmodified linesvi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));vi.mock("./ChatHeader", () => ({ default: () => null }));let sendMessage: (textToSend?: string) => Promise<void>;let regenerateResponse: () => Promise<void>;let messageListMessages: ChatMessage[] = [];let messageListIsGenerating = false;vi.mock("./ChatInputArea", () => ({default: (props: { handleSend: (textToSend?: string) => Promise<void> }) => {5 unmodified linesvi.mock("./MessageList", () => ({default: (props: {messages: ChatMessage[];isGenerating: boolean;onRegenerate: () => Promise<void>;}) => {regenerateResponse = props.onRegenerate;messageListMessages = props.messages;messageListIsGenerating = props.isGenerating;return null;},5 unmodified lines);const { persistChatMessages } = await import("@/modules/chatHelpers");const { addLogEntry } = await import("@/modules/logEntries");/** A promise plus the handle to settle it, so a test can hold a call open. */function deferred<T>() {45 unmodified linesupdateSuppressNextFollowUp(false);messageListMessages = [];messageListIsGenerating = false;vi.mocked(generateChatResponse).mockResolvedValue("An answer.");vi.mocked(generateFollowUpQuestion).mockResolvedValue("A question?");});612 unmodified lines});});describe("ChatInterface previous follow-up questions", () => {it("does not record an empty follow-up question", async () => {vi.mocked(generateFollowUpQuestion)35 unmodified lines36373839404142434445464748495051525 unmodified lines585960616263646566676869705 unmodified lines7677787980818245 unmodified lines128129130131132133134612 unmodified lines74774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391435 unmodified linesvi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));vi.mock("@mantine/notifications", () => ({notifications: { show: vi.fn() },}));vi.mock("./ChatHeader", () => ({ default: () => null }));let sendMessage: (textToSend?: string) => Promise<void>;let regenerateResponse: () => Promise<void>;let messageListMessages: ChatMessage[] = [];let messageListIsGenerating = false;let messageListFollowUpStartIndex: number | undefined;vi.mock("./ChatInputArea", () => ({default: (props: { handleSend: (textToSend?: string) => Promise<void> }) => {5 unmodified linesvi.mock("./MessageList", () => ({default: (props: {messages: ChatMessage[];followUpStartIndex: number;isGenerating: boolean;onRegenerate: () => Promise<void>;}) => {regenerateResponse = props.onRegenerate;messageListMessages = props.messages;messageListFollowUpStartIndex = props.followUpStartIndex;messageListIsGenerating = props.isGenerating;return null;},5 unmodified lines);const { persistChatMessages } = await import("@/modules/chatHelpers");const { addLogEntry } = await import("@/modules/logEntries");const { notifications } = await import("@mantine/notifications");/** A promise plus the handle to settle it, so a test can hold a call open. */function deferred<T>() {45 unmodified linesupdateSuppressNextFollowUp(false);messageListMessages = [];messageListIsGenerating = false;messageListFollowUpStartIndex = undefined;vi.mocked(generateChatResponse).mockResolvedValue("An answer.");vi.mocked(generateFollowUpQuestion).mockResolvedValue("A question?");});612 unmodified lines});});describe("ChatInterface follow-up start", () => {const followUps: ChatMessage[] = [{ role: "user", content: "Q1" },{ role: "assistant", content: "A1" },];function renderWithoutMainAnswer() {return render(<MantineProvider><ChatInterfaceinitialQuery={initialQuery}initialResponse=""initialMessages={followUps}suppressInitialFollowUp/></MantineProvider>,);}it("starts the follow-ups after the main question and answer", () => {renderChatInterface();expect(messageListMessages).toEqual([{ role: "user", content: initialQuery },{ role: "assistant", content: initialResponse },]);expect(messageListFollowUpStartIndex).toBe(2);});it("starts the follow-ups at the top when the main answer is empty", () => {renderWithoutMainAnswer();expect(messageListMessages).toEqual(followUps);expect(messageListFollowUpStartIndex).toBe(0);});it("regenerates the first follow-up when the main answer is empty", async () => {renderWithoutMainAnswer();vi.mocked(generateChatResponse).mockResolvedValueOnce("A1 again");await act(async () => {await regenerateResponse();});expect(generateChatResponse).toHaveBeenCalledTimes(1);expect(vi.mocked(generateChatResponse).mock.calls[0][0]).toEqual([followUps[0],]);expect(messageListMessages.at(-1)).toEqual({role: "assistant",content: "A1 again",});});});describe("ChatInterface failed regeneration", () => {const nextQuestion = "And how do I use it?";async function sendThenFailRegenerate() {vi.mocked(generateChatResponse).mockResolvedValueOnce("An answer.").mockRejectedValueOnce(new Error("model crashed"));await act(async () => {await sendMessage(nextQuestion);});await act(async () => {await regenerateResponse();});}it("keeps the previous answer so it can be regenerated again", async () => {renderChatInterface();await sendThenFailRegenerate();expect(messageListMessages.at(-1)).toEqual({role: "assistant",content: "An answer.",});expect(messageListMessages).toHaveLength(4);expect(getChatGenerationState().isGeneratingResponse).toBe(false);vi.mocked(generateChatResponse).mockResolvedValueOnce("A second try.");await act(async () => {await regenerateResponse();});expect(generateChatResponse).toHaveBeenCalledTimes(3);expect(messageListMessages.at(-1)?.content).toBe("A second try.");});it("shows one red notification and still logs the error", async () => {renderChatInterface();await sendThenFailRegenerate();expect(notifications.show).toHaveBeenCalledTimes(1);expect(notifications.show).toHaveBeenCalledWith(expect.objectContaining({color: "red",message:"Couldn't re-generate the response. The previous answer has been kept.",}),);expect(addLogEntry).toHaveBeenCalledWith(expect.stringContaining("Error re-generating response"),);});it("brings back the follow-up question that was showing", async () => {renderChatInterface();await sendThenFailRegenerate();expect(getFollowUpQuestion()).toBe("A question?");});it("writes nothing and shows no notification after unmounting", async () => {const response = deferred<string>();vi.mocked(generateChatResponse).mockResolvedValueOnce("An answer.").mockReturnValueOnce(response.promise);const { unmount } = renderChatInterface();await act(async () => {await sendMessage(nextQuestion);});let regenerate: Promise<void> = Promise.resolve();await act(async () => {regenerate = regenerateResponse();});await act(async () => {unmount();});updateFollowUpQuestion("A question from the next chat?");await act(async () => {response.reject(new Error("model crashed"));await regenerate;});expect(notifications.show).not.toHaveBeenCalled();expect(getFollowUpQuestion()).toBe("A question from the next chat?");});it("shows no notification when the regeneration succeeds", async () => {vi.mocked(generateChatResponse).mockResolvedValueOnce("An answer.").mockResolvedValueOnce("A regenerated answer.");renderChatInterface();await act(async () => {await sendMessage(nextQuestion);});await act(async () => {await regenerateResponse();});expect(messageListMessages.at(-1)?.content).toBe("A regenerated answer.");expect(notifications.show).not.toHaveBeenCalled();});});describe("ChatInterface previous follow-up questions", () => {it("does not record an empty follow-up question", async () => {vi.mocked(generateFollowUpQuestion)
123414 unmodified lines19202122232413 unmodified lines38394041424344454647484950515253545556575859606162109 unmodified lines17217317417517617717817918018118218318418518618718818919019119219319419519676 unmodified lines27327427527627727827928028128228328428527 unmodified lines3133143153163173183 unmodified lines322323324325326327104 unmodified lines4324334344354364374382 unmodified lines441442443444445446import { Card, Stack } from "@mantine/core";import { usePubSub } from "create-pubsub/react";import {type KeyboardEvent,14 unmodified lineschatInputPubSub,followUpQuestionPubSub,getChatGenerationState,imageSearchResultsPubSub,queryPubSub,settingsPubSub,13 unmodified linessuppressInitialFollowUp?: boolean;}export default function ChatInterface({initialQuery,initialResponse,initialMessages,suppressInitialFollowUp,}: ChatInterfaceProps) {const initialMessagesArray =initialMessages &&initialMessages.length > 0 &&initialQuery &&initialResponse? [{ role: "user" as const, content: initialQuery },{ role: "assistant" as const, content: initialResponse },...initialMessages,]: initialMessages || [];const [messages, setMessages] = useState<ChatMessage[]>(initialMessagesArray);const [input, setInput] = usePubSub(chatInputPubSub);const [generationState, setGenerationState] = usePubSub(chatGenerationStatePubSub,109 unmodified linesprevInitialMessagesRef.current = initialMessages;const newInitialMessagesArray =initialMessages &&initialMessages.length > 0 &&initialQuery &&initialResponse? [{ role: "user" as const, content: initialQuery },{ role: "assistant" as const, content: initialResponse },...initialMessages,]: initialMessages || [];if (newInitialMessagesArray.length > 0) {setMessages(newInitialMessagesArray);} else if (initialQuery && initialResponse) {setMessages([{ role: "user", content: initialQuery },{ role: "assistant", content: initialResponse },]);}}, [initialQuery, initialResponse, initialMessages]);76 unmodified linesconst handleRegenerateResponse = useCallback(async () => {if (getChatGenerationState().isGeneratingResponse ||messages.length < 3 ||messages[messages.length - 1].role !== "assistant")return;const history = messages.slice(0, -1);const lastUser = history[history.length - 1];setMessages(history);setGenerationState({27 unmodified lines}} catch (error) {addLogEntry(`Error re-generating response: ${error}`);} finally {if (isMountedRef.current) {setGenerationState({3 unmodified lines}}}, [messages,regenerateFollowUpQuestion,settings,104 unmodified linesreturn (<Card withBorder shadow="sm" radius="md"><Card.Section withBorder inheritPadding py="xs"><ChatHeader messages={messages} /></Card.Section><Stack gap="md" pt="md"><MessageList2 unmodified lines? [...messages, { role: "assistant", content: streamedResponse }]: messages}onEditMessage={handleEditMessage}onRegenerate={handleRegenerateResponse}isGenerating={generationState.isGeneratingResponse}1234514 unmodified lines2021222324252613 unmodified lines404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384109 unmodified lines19419519619719819920020120220320420520620776 unmodified lines28428528628728828929029129229329429529629729829930030127 unmodified lines3293303313323333343353363373383393403413423433443 unmodified lines348349350351352353354104 unmodified lines4594604614624634644654664674682 unmodified lines471472473474475476477import { Card, Stack } from "@mantine/core";import { notifications } from "@mantine/notifications";import { usePubSub } from "create-pubsub/react";import {type KeyboardEvent,14 unmodified lineschatInputPubSub,followUpQuestionPubSub,getChatGenerationState,getFollowUpQuestion,imageSearchResultsPubSub,queryPubSub,settingsPubSub,13 unmodified linessuppressInitialFollowUp?: boolean;}/*** The messages the chat starts from, and where its follow-ups begin. The main* question and answer lead the list only when the answer has text: after an* empty main answer the follow-ups start at 0, so the first follow-up pair is* not mistaken for them.*/function buildInitialConversation(initialQuery: string | undefined,initialResponse: string | undefined,initialMessages: ChatMessage[] = [],): { messages: ChatMessage[]; followUpStartIndex: number } {if (initialQuery && initialResponse) {return {messages: [{ role: "user", content: initialQuery },{ role: "assistant", content: initialResponse },...initialMessages,],followUpStartIndex: 2,};}return { messages: initialMessages, followUpStartIndex: 0 };}export default function ChatInterface({initialQuery,initialResponse,initialMessages,suppressInitialFollowUp,}: ChatInterfaceProps) {const [initialConversation] = useState(() =>buildInitialConversation(initialQuery, initialResponse, initialMessages),);const [messages, setMessages] = useState<ChatMessage[]>(initialConversation.messages,);const [followUpStartIndex, setFollowUpStartIndex] = useState(initialConversation.followUpStartIndex,);const [input, setInput] = usePubSub(chatInputPubSub);const [generationState, setGenerationState] = usePubSub(chatGenerationStatePubSub,109 unmodified linesprevInitialMessagesRef.current = initialMessages;const conversation = buildInitialConversation(initialQuery,initialResponse,initialMessages,);if (conversation.messages.length > 0) {setMessages(conversation.messages);setFollowUpStartIndex(conversation.followUpStartIndex);}}, [initialQuery, initialResponse, initialMessages]);76 unmodified linesconst handleRegenerateResponse = useCallback(async () => {if (getChatGenerationState().isGeneratingResponse ||// There must be a follow-up question before the answer to regenerate.messages.length - 1 <= followUpStartIndex ||messages[messages.length - 1].role !== "assistant")return;const history = messages.slice(0, -1);const lastUser = history[history.length - 1];// Streaming needs the old answer off the list, so keep it and the// follow-up that was showing to put back if the regeneration fails.const previousAnswer = messages[messages.length - 1];const previousFollowUpQuestion = getFollowUpQuestion();setMessages(history);setGenerationState({27 unmodified lines}} catch (error) {addLogEntry(`Error re-generating response: ${error}`);if (isMountedRef.current) {setStreamedResponse("");setMessages((prev) => [...prev, previousAnswer]);setFollowUpQuestion(previousFollowUpQuestion);notifications.show({message:"Couldn't re-generate the response. The previous answer has been kept.",color: "red",});}} finally {if (isMountedRef.current) {setGenerationState({3 unmodified lines}}}, [followUpStartIndex,messages,regenerateFollowUpQuestion,settings,104 unmodified linesreturn (<Card withBorder shadow="sm" radius="md"><Card.Section withBorder inheritPadding py="xs"><ChatHeadermessages={messages}followUpStartIndex={followUpStartIndex}/></Card.Section><Stack gap="md" pt="md"><MessageList2 unmodified lines? [...messages, { role: "assistant", content: streamedResponse }]: messages}followUpStartIndex={followUpStartIndex}onEditMessage={handleEditMessage}onRegenerate={handleRegenerateResponse}isGenerating={generationState.isGeneratingResponse}
10 unmodified lines1112131415162 unmodified lines1920212223243 unmodified lines2829303132333460 unmodified lines959697989910010 unmodified linesfunction renderMessageList(props: {messages: ChatMessage[];onEditMessage?: (absoluteIndex: number) => void;onRegenerate?: () => void;isGenerating?: boolean;2 unmodified lines<MantineProvider><MessageListmessages={props.messages}onEditMessage={props.onEditMessage ?? vi.fn()}onRegenerate={props.onRegenerate ?? vi.fn()}isGenerating={props.isGenerating ?? false}3 unmodified lines}describe("MessageList", () => {it("renders nothing when there are 2 or fewer messages", () => {const messages: ChatMessage[] = [{ role: "user", content: "system instructions" },{ role: "assistant", content: "Ok!" },60 unmodified lines});});describe("unterminated reasoning", () => {const messages: ChatMessage[] = [{ role: "user", content: "system instructions" },10 unmodified lines111213141516172 unmodified lines202122232425263 unmodified lines3031323334353660 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015110 unmodified linesfunction renderMessageList(props: {messages: ChatMessage[];followUpStartIndex?: number;onEditMessage?: (absoluteIndex: number) => void;onRegenerate?: () => void;isGenerating?: boolean;2 unmodified lines<MantineProvider><MessageListmessages={props.messages}followUpStartIndex={props.followUpStartIndex ?? 2}onEditMessage={props.onEditMessage ?? vi.fn()}onRegenerate={props.onRegenerate ?? vi.fn()}isGenerating={props.isGenerating ?? false}3 unmodified lines}describe("MessageList", () => {it("renders nothing when there are no follow-up messages", () => {const messages: ChatMessage[] = [{ role: "user", content: "system instructions" },{ role: "assistant", content: "Ok!" },60 unmodified lines});});describe("no main question and answer", () => {// When the main answer came back empty, the follow-ups start at 0.const messages: ChatMessage[] = [{ role: "user", content: "Q1" },{ role: "assistant", content: "A1" },];it("renders the first follow-up pair", () => {renderMessageList({ messages, followUpStartIndex: 0 });expect(screen.getByText("Q1")).toBeInTheDocument();expect(screen.getByText("A1")).toBeInTheDocument();});it("edits the first follow-up question at position 0", () => {const onEditMessage = vi.fn();renderMessageList({ messages, followUpStartIndex: 0, onEditMessage });fireEvent.click(screen.getByLabelText("Edit message"));expect(onEditMessage).toHaveBeenCalledWith(0);});});describe("an empty last answer", () => {const messages: ChatMessage[] = [{ role: "user", content: "system instructions" },{ role: "assistant", content: "Ok!" },{ role: "user", content: "Q1" },{ role: "assistant", content: "" },];it("shows No response with a Re-generate button", () => {const onRegenerate = vi.fn();renderMessageList({ messages, onRegenerate });expect(screen.getByText("No response")).toBeInTheDocument();fireEvent.click(screen.getByLabelText("Re-generate response"));expect(onRegenerate).toHaveBeenCalledTimes(1);});it("shows no bubble for it while the answer is being generated", () => {renderMessageList({ messages, isGenerating: true });expect(screen.queryByText("No response")).toBeNull();expect(document.querySelectorAll(".mantine-Paper-root")).toHaveLength(1);});});describe("unterminated reasoning", () => {const messages: ChatMessage[] = [{ role: "user", content: "system instructions" },
12341 unmodified line6789101150 unmodified lines62636465666768697021 unmodified lines9293949596979899100101102103104105106107108109110111112113import { ActionIcon, Group, Paper, Stack, Tooltip } from "@mantine/core";import { IconPencil, IconRefresh } from "@tabler/icons-react";import { memo } from "react";import type { ChatMessage } from "@/modules/types";1 unmodified lineinterface MessageListProps {messages: ChatMessage[];onEditMessage: (absoluteIndex: number) => void;onRegenerate: () => void;isGenerating: boolean;50 unmodified linesp="sm"style={{ flex: 1, overflow: "auto" }}><FormattedMarkdown isGenerating={isGenerating && isLastAssistant}>{message.content}</FormattedMarkdown></Paper>{canRegenerate && (21 unmodified linesconst MessageList = memo(function MessageList({messages,onEditMessage,onRegenerate,isGenerating,}: MessageListProps) {if (messages.length <= 2) return null;return (<Stack gap="md">{messages.map((message, absoluteIndex) => {// The index is the message's position in `messages`, which is what// editing and regenerating act on. The first two messages are the// system prompt and its acknowledgement, and an empty message has// nothing to show, so neither renders, but both keep their position.if (absoluteIndex < 2 || message.content.length === 0) return null;const isLastAssistant =absoluteIndex === messages.length - 1 && message.role === "assistant";return (<Message// biome-ignore lint/suspicious/noArrayIndexKey: a message's position in the chat is its identity12341 unmodified line67891011121350 unmodified lines64656667686970717273747576777821 unmodified lines100101102103104105106107108109110111112113114115116117118119120121122123124125126127import { ActionIcon, Group, Paper, Stack, Text, Tooltip } from "@mantine/core";import { IconPencil, IconRefresh } from "@tabler/icons-react";import { memo } from "react";import type { ChatMessage } from "@/modules/types";1 unmodified lineinterface MessageListProps {messages: ChatMessage[];/** Position of the first follow-up message: 2 after the main question and answer, 0 without them. */followUpStartIndex: number;onEditMessage: (absoluteIndex: number) => void;onRegenerate: () => void;isGenerating: boolean;50 unmodified linesp="sm"style={{ flex: 1, overflow: "auto" }}>{message.content.length > 0 ? (<FormattedMarkdown isGenerating={isGenerating && isLastAssistant}>{message.content}</FormattedMarkdown>) : (<Text c="dimmed" fs="italic" size="sm">No response</Text>)}</Paper>{canRegenerate && (21 unmodified linesconst MessageList = memo(function MessageList({messages,followUpStartIndex,onEditMessage,onRegenerate,isGenerating,}: MessageListProps) {if (messages.length <= followUpStartIndex) return null;return (<Stack gap="md">{messages.map((message, absoluteIndex) => {// The index is the message's position in `messages`, which is what// editing and regenerating act on. Messages before the follow-ups are// shown above the chat, so they don't render here but keep their// position.if (absoluteIndex < followUpStartIndex) return null;const isLastAssistant =absoluteIndex === messages.length - 1 && message.role === "assistant";// An empty message has nothing to show, except a finished last answer:// it renders as "No response" so its Re-generate button has a row. A// trailing empty answer while generating is the stream placeholder.if (message.content.length === 0 && !(isLastAssistant && !isGenerating))return null;return (<Message// biome-ignore lint/suspicious/noArrayIndexKey: a message's position in the chat is its identity
19 unmodified lines2021222324252683 unmodified lines11011111211311411511611711811912019 unmodified linesupdateIsRestoringFromHistory,updateLlmTextSearchResults,updatePageContents,updateResponse,updateSuppressNextFollowUp,updateTextGenerationState,updateTextSearchResults,83 unmodified linesconst savedResponse = await getLatestLlmResponseForEntry(entry);if (savedResponse && savedResponse.trim().length > 0) {updateSuppressNextFollowUp(true);updateResponse(savedResponse);updateTextGenerationState("completed");} else {updateSuppressNextFollowUp(false);updateResponse("");updateTextGenerationState("idle");}19 unmodified lines2021222324252683 unmodified lines11011111211311411511611711811912012112219 unmodified linesupdateIsRestoringFromHistory,updateLlmTextSearchResults,updatePageContents,updateResponseImmediately,updateSuppressNextFollowUp,updateTextGenerationState,updateTextSearchResults,83 unmodified linesconst savedResponse = await getLatestLlmResponseForEntry(entry);if (savedResponse && savedResponse.trim().length > 0) {updateSuppressNextFollowUp(true);// The restore publishes the whole stored answer at once; a throttled// write could be overwritten by whatever was queued before it.updateResponseImmediately(savedResponse);updateTextGenerationState("completed");} else {updateSuppressNextFollowUp(false);updateResponseImmediately("");updateTextGenerationState("idle");}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const throttleInterval = 1000 / 12;
// Each test gets its own copy of the module, so the throttle window opened by// one test cannot decide whether the next test's first write is a leading one.async function loadResponseChannel() { vi.resetModules(); return await import("./pubSub");}
describe("response publishing", () => { beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });
it("publishes one leading and one trailing value per throttle window", async () => { const { responsePubSub, updateResponse } = await loadResponseChannel(); const published: string[] = []; const [, onResponseChange] = responsePubSub; const unsubscribe = onResponseChange((value) => { published.push(value); });
updateResponse("Hello"); updateResponse("Hello world"); updateResponse("Hello world!!!");
expect(published).toEqual(["Hello"]);
vi.advanceTimersByTime(throttleInterval);
expect(published).toEqual(["Hello", "Hello world!!!"]);
unsubscribe(); });
it("publishes the final value immediately and drops the queued trailing write", async () => { const { getResponse, responsePubSub, updateResponse, updateResponseImmediately, } = await loadResponseChannel(); const published: string[] = []; const [, onResponseChange] = responsePubSub; const unsubscribe = onResponseChange((value) => { published.push(value); });
updateResponse("Hello"); updateResponse("Hello world, but truncated");
updateResponseImmediately("Hello world, the complete answer");
expect(getResponse()).toBe("Hello world, the complete answer");
vi.advanceTimersByTime(throttleInterval * 3);
expect(getResponse()).toBe("Hello world, the complete answer"); expect(published).toEqual(["Hello", "Hello world, the complete answer"]);
unsubscribe(); });});12345127 unmodified lines1331341351361371381396 unmodified lines14614714814915015115295 unmodified lines248249250251252253254import { createPubSub } from "create-pubsub";import throttle from "throttleit";import { addLogEntry } from "./logEntries";import * as safeStorage from "./safeStorage";import {127 unmodified linesexport const responsePubSub = createPubSub("");export const updateResponse = throttle(responsePubSub[0], 1000 / 12);export const [, , getResponse] = responsePubSub;export const [updateSearchPromise, , getSearchPromise] = createPubSub<6 unmodified linesexport const [updateTextGenerationState, , getTextGenerationState] =textGenerationStatePubSub;const [, listenToTextGenerationStateChanges] = textGenerationStatePubSub;listenToTextGenerationStateChanges((textGenerationState) => {addLogEntry(`Text generation state changed to '${textGenerationState}'`);95 unmodified linesexport const followUpQuestionPubSub = createPubSub("");export const [updateFollowUpQuestion] = followUpQuestionPubSub;const conversationSummaryPubSub = createPubSub({conversationId: "",1234127 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062076 unmodified lines21421521621721821922095 unmodified lines316317318319320321322323import { createPubSub } from "create-pubsub";import { addLogEntry } from "./logEntries";import * as safeStorage from "./safeStorage";import {127 unmodified linesexport const responsePubSub = createPubSub("");const responseThrottleInterval = 1000 / 12;/*** Throttles a publisher to one leading write plus at most one trailing write* per interval, keeping the newest value. `publishNow` drops the trailing* write, so a caller that already holds the final value can publish it without* a queued stale write landing afterwards.*/function createThrottledPublisher<T>(publish: (value: T) => void,interval: number,) {let lastPublishTime = 0;let timeoutId: ReturnType<typeof setTimeout> | undefined;let pendingValue: T | undefined;let hasPendingValue = false;const cancelPending = () => {if (timeoutId !== undefined) clearTimeout(timeoutId);timeoutId = undefined;pendingValue = undefined;hasPendingValue = false;};const throttled = (value: T) => {const now = Date.now();const timeSinceLastPublish = now - lastPublishTime;cancelPending();if (timeSinceLastPublish >= interval) {lastPublishTime = now;publish(value);return;}pendingValue = value;hasPendingValue = true;timeoutId = setTimeout(() => {timeoutId = undefined;if (!hasPendingValue) return;const pending = pendingValue as T;pendingValue = undefined;hasPendingValue = false;lastPublishTime = Date.now();publish(pending);}, interval - timeSinceLastPublish);};throttled.publishNow = (value: T) => {cancelPending();lastPublishTime = Date.now();publish(value);};return throttled;}export const updateResponse = createThrottledPublisher(responsePubSub[0],responseThrottleInterval,);/*** Publishes the final response without waiting for the throttle window and* drops a trailing write still queued, so the UI and the chat mount read the* complete answer instead of the last value that happened to be published.*/export const updateResponseImmediately = updateResponse.publishNow;export const [, , getResponse] = responsePubSub;export const [updateSearchPromise, , getSearchPromise] = createPubSub<6 unmodified linesexport const [updateTextGenerationState, , getTextGenerationState] =textGenerationStatePubSub;export const [, listenToTextGenerationStateChanges] = textGenerationStatePubSub;listenToTextGenerationStateChanges((textGenerationState) => {addLogEntry(`Text generation state changed to '${textGenerationState}'`);95 unmodified linesexport const followUpQuestionPubSub = createPubSub("");export const [updateFollowUpQuestion, , getFollowUpQuestion] =followUpQuestionPubSub;const conversationSummaryPubSub = createPubSub({conversationId: "",
22 unmodified lines23242526272822 unmodified linesupdateImageSearchState: vi.fn(),updateLlmTextSearchResults: vi.fn(),updateResponse: vi.fn(),updateSearchPromise: vi.fn(),updateTextGenerationState: vi.fn(),updateTextSearchResults: vi.fn(),22 unmodified lines2324252627282922 unmodified linesupdateImageSearchState: vi.fn(),updateLlmTextSearchResults: vi.fn(),updateResponse: vi.fn(),updateResponseImmediately: vi.fn(),updateSearchPromise: vi.fn(),updateTextGenerationState: vi.fn(),updateTextSearchResults: vi.fn(),
41 unmodified lines4243444546478 unmodified lines56575859606141 unmodified linesgetSettings: () => harness.state.settings,getTextGenerationState: () => harness.state.textGenerationState,listenToSettingsChanges: vi.fn(() => vi.fn()),updateChatMessages: vi.fn(),updateConversationSummary: vi.fn(),updateImageSearchResults: vi.fn(),8 unmodified linesharness.state.response = value;harness.onResponseUpdate.current(value);},updateSearchPromise: (promise: Promise<unknown>) => {harness.state.searchPromise = promise;},41 unmodified lines424344454647488 unmodified lines5758596061626364656641 unmodified linesgetSettings: () => harness.state.settings,getTextGenerationState: () => harness.state.textGenerationState,listenToSettingsChanges: vi.fn(() => vi.fn()),listenToTextGenerationStateChanges: vi.fn(() => vi.fn()),updateChatMessages: vi.fn(),updateConversationSummary: vi.fn(),updateImageSearchResults: vi.fn(),8 unmodified linesharness.state.response = value;harness.onResponseUpdate.current(value);},updateResponseImmediately: (value: string) => {harness.state.response = value;harness.onResponseUpdate.current(value);},updateSearchPromise: (promise: Promise<unknown>) => {harness.state.searchPromise = promise;},
19 unmodified lines20212223242519 unmodified linesupdateImageSearchState: vi.fn(),updateLlmTextSearchResults: vi.fn(),updateResponse: vi.fn(),updateSearchPromise: vi.fn(),updateTextGenerationState: vi.fn(),updateTextSearchResults: vi.fn(),19 unmodified lines2021222324252619 unmodified linesupdateImageSearchState: vi.fn(),updateLlmTextSearchResults: vi.fn(),updateResponse: vi.fn(),updateResponseImmediately: vi.fn(),updateSearchPromise: vi.fn(),updateTextGenerationState: vi.fn(),updateTextSearchResults: vi.fn(),
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import { beforeEach, describe, expect, it, vi } from "vitest";
const harness = vi.hoisted(() => ({ saved: [] as Array<{ query: string; response: string; model: string }>, responseAtCompletion: { current: null as string | null },}));
vi.mock("./history", () => ({ getCurrentSearchRunId: vi.fn(() => "run-1"), saveLlmResponseForQuery: vi.fn( (query: string, response: string, model: string) => { harness.saved.push({ query, response, model }); return Promise.resolve(); }, ), updateSearchResults: vi.fn(() => Promise.resolve()),}));
vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));
vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));
vi.mock("./pageContent", () => ({ fetchPageContents: vi.fn(() => Promise.resolve({})),}));
vi.mock("./search", () => ({ searchText: vi.fn(() => Promise.resolve({ results: [["Sky", "A snippet", "https://example.com/sky"]], stale: false, }), ), searchImages: vi.fn(() => Promise.resolve({ results: [], stale: false })),}));
vi.mock("./searchTokenHash", () => ({ getSearchTokenHash: vi.fn(() => Promise.resolve("mock-token")),}));
import { getResponse, getSettings, queryPubSub, textGenerationStatePubSub, updateSettings,} from "./pubSub";import { searchAndRespond } from "./textGeneration";
const throttleInterval = 1000 / 12;
const mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);
function sseStream(frames: string[]) { const encoder = new TextEncoder(); return new Response( new ReadableStream({ start(controller) { for (const frame of frames) controller.enqueue(encoder.encode(frame)); controller.close(); }, }), { status: 200 }, );}
function contentFrame(content: string) { return `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n`;}
describe("response persistence", () => { beforeEach(() => { harness.saved.length = 0; harness.responseAtCompletion.current = null; mockFetch.mockReset(); queryPubSub[0]("why is the sky blue"); updateSettings({ ...getSettings(), inferenceType: "internal", enableAiResponse: true, enableTextSearch: true, enableImageSearch: false, enableNotificationOnAiComplete: false, enablePageContentFetch: false, }); });
it("saves the full answer when the last chunk lands inside the throttle window", async () => { mockFetch.mockResolvedValue( sseStream([contentFrame("Hello"), contentFrame(" world!!! done")]), );
const unsubscribe = textGenerationStatePubSub[1]((state) => { if (state === "completed") { harness.responseAtCompletion.current = getResponse(); } });
await searchAndRespond(); unsubscribe();
expect(harness.saved).toHaveLength(1); expect(harness.saved[0].response).toBe("Hello world!!! done"); expect(harness.responseAtCompletion.current).toBe("Hello world!!! done");
await new Promise((resolve) => setTimeout(resolve, throttleInterval * 3));
expect(getResponse()).toBe("Hello world!!! done"); });});21 unmodified lines22232425262721 unmodified linesgetResponse: vi.fn(),getQuery: vi.fn(),updateResponse: vi.fn(),updateSearchPromise: vi.fn(),updateTextSearchResults: vi.fn(),updateTextSearchState: vi.fn(),21 unmodified lines2223242526272821 unmodified linesgetResponse: vi.fn(),getQuery: vi.fn(),updateResponse: vi.fn(),updateResponseImmediately: vi.fn(),updateSearchPromise: vi.fn(),updateTextSearchResults: vi.fn(),updateTextSearchState: vi.fn(),
11 unmodified lines121314151617184 unmodified lines23242526272822 unmodified lines51525354555657222 unmodified lines2802812822832842852862872882892902912 unmodified lines29429529629729829911 unmodified linesimport {getConversationSummary,getQuery,getResponse,getSettings,getTextGenerationState,listenToSettingsChanges,4 unmodified linesupdateLlmTextSearchResults,updatePageContents,updateResponse,updateSearchPromise,updateSuppressNextFollowUp,updateTextGenerationState,22 unmodified linesconst SUMMARY_TOKEN_LIMIT = 800;type InferenceStrategy = {generateText: () => Promise<void>;generateChat: (messages: ChatMessage[],onUpdate: (partialResponse: string) => void,222 unmodified linesupdateTextGenerationState("loadingModel");}const strategy = await getCurrentInferenceStrategy();await strategy.generateText();try {await saveLlmResponseForQuery(getQuery(),getResponse(),getCurrentModelName(),);} catch (e) {2 unmodified lines);}updateTextGenerationState("completed");if (settings.enableNotificationOnAiComplete) {11 unmodified lines1213141516174 unmodified lines2223242526272822 unmodified lines51525354555657222 unmodified lines2802812822832842852862872882892902912 unmodified lines29429529629729829930030130230330430511 unmodified linesimport {getConversationSummary,getQuery,getSettings,getTextGenerationState,listenToSettingsChanges,4 unmodified linesupdateLlmTextSearchResults,updatePageContents,updateResponse,updateResponseImmediately,updateSearchPromise,updateSuppressNextFollowUp,updateTextGenerationState,22 unmodified linesconst SUMMARY_TOKEN_LIMIT = 800;type InferenceStrategy = {generateText: () => Promise<string>;generateChat: (messages: ChatMessage[],onUpdate: (partialResponse: string) => void,222 unmodified linesupdateTextGenerationState("loadingModel");}const strategy = await getCurrentInferenceStrategy();const finalResponse = await strategy.generateText();try {await saveLlmResponseForQuery(getQuery(),finalResponse,getCurrentModelName(),);} catch (e) {2 unmodified lines);}// The streaming writes are throttled, so the last chunk may still be// queued here. Publishing the returned text unthrottled before the state// flips to "completed" is what makes the mounted chat read the whole// answer.updateResponseImmediately(finalResponse);updateTextGenerationState("completed");if (settings.enableNotificationOnAiComplete) {
77 unmodified lines78798081828384280 unmodified lines36536636736836937037113 unmodified lines385386387388389390391147 unmodified lines53954054154254354477 unmodified lines}),);await generateTextWithHorde();expect(canStartResponding).toHaveBeenCalled();expect(vi.mocked(updateTextGenerationState).mock.calls).toEqual([280 unmodified linesworkers: Array<{ models: string[]; max_length: number }>;monthStats?: Record<string, number>;statsFails?: boolean;statusResponder: (pollIndex: number) => unknown;}) {let idCounter = 0;let pollCounter = 0;13 unmodified linesif (init?.method === "DELETE") {return jsonResponse({});}const reply = statusResponder(pollCounter++);return reply instanceof Response ? reply : jsonResponse(reply);},);147 unmodified linesexpect(generationRequestBodies()).toHaveLength(2);});it("reuses the cached ranking for the next generation", async () => {routeHordeFetch({workers: [{ models: ["m-a"], max_length: 1024 }],77 unmodified lines78798081828384280 unmodified lines36536636736836937037113 unmodified lines385386387388389390391147 unmodified lines53954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862977 unmodified lines}),);await expect(generateTextWithHorde()).resolves.toBe("Hello world");expect(canStartResponding).toHaveBeenCalled();expect(vi.mocked(updateTextGenerationState).mock.calls).toEqual([280 unmodified linesworkers: Array<{ models: string[]; max_length: number }>;monthStats?: Record<string, number>;statsFails?: boolean;statusResponder: (pollIndex: number, url: string) => unknown;}) {let idCounter = 0;let pollCounter = 0;13 unmodified linesif (init?.method === "DELETE") {return jsonResponse({});}const reply = statusResponder(pollCounter++, url);return reply instanceof Response ? reply : jsonResponse(reply);},);147 unmodified linesexpect(generationRequestBodies()).toHaveLength(2);});/** Answers each job's polls from its own script, by the job id in the URL. */function perJobResponder(scripts: Record<string, (jobPollIndex: number) => unknown>,) {const jobPolls: Record<string, number> = {};return (_pollIndex: number, url: string) => {const jobId = url.slice(url.lastIndexOf("/") + 1);const jobPollIndex = jobPolls[jobId] ?? 0;jobPolls[jobId] = jobPollIndex + 1;return scripts[jobId](jobPollIndex);};}const pendingResponse = { done: false, is_possible: true, generations: [] };it("serves the healthy job when its sibling faults first", async () => {routeHordeFetch({workers: [{ models: ["m-a"], max_length: 1024 }],monthStats: { "m-a": 10 },statusResponder: perJobResponder({"gen-1": () => ({ done: true, faulted: true }),"gen-2": (poll) => (poll === 0 ? pendingResponse : doneResponse),}),});const { generateTextWithHorde } = await import("./textGenerationWithHorde");await expect(generateTextWithHorde()).resolves.toBe("Top model answer");expect(updateResponse).toHaveBeenCalledWith("Top model answer");expect(generationRequestBodies()).toHaveLength(2);});it("still retries with any model when one job faults and the other cannot take the job", async () => {routeHordeFetch({workers: [{ models: ["m-a"], max_length: 1024 }],monthStats: { "m-a": 10 },statusResponder: perJobResponder({// The faulted job is first in submission order, so picking the// first error would hide the "not possible" that the retry needs."gen-1": () => ({ done: true, faulted: true }),"gen-2": () => ({ done: true, is_possible: false }),"gen-3": () => doneResponse,"gen-4": () => doneResponse,}),});const { generateTextWithHorde } = await import("./textGenerationWithHorde");await expect(generateTextWithHorde()).resolves.toBe("Top model answer");expect(generationRequestBodies()).toHaveLength(4);});it("reports an interrupt during the race and submits no retry", async () => {let interrupted = false;vi.mocked(getTextGenerationState).mockImplementation(() =>interrupted ? "interrupted" : "generating",);routeHordeFetch({workers: [{ models: ["m-a"], max_length: 1024 }],monthStats: { "m-a": 10 },statusResponder: perJobResponder({"gen-1": () => ({ done: true, is_possible: false }),"gen-2": (poll) => {// The user presses Stop while this job is still queued, after its// sibling has already reported it cannot take the job.if (poll >= 1) interrupted = true;return pendingResponse;},}),});const { generateTextWithHorde } = await import("./textGenerationWithHorde");await expect(generateTextWithHorde()).rejects.toThrow("Generation interrupted",);expect(generationRequestBodies()).toHaveLength(2);});it("reuses the cached ranking for the next generation", async () => {routeHordeFetch({workers: [{ models: ["m-a"], max_length: 1024 }],
492 unmodified lines4934944954964974984995 unmodified lines50550650750850951043 unmodified lines554555556557558559560492 unmodified lines// job is submitted shows the response card and its Stop button for the// whole queue wait, which is what makes an interrupt possible at all.updateTextGenerationState("generating");await executeHordeGeneration(messages, (text) => {updateResponse(text);});}5 unmodified linesreturn await executeHordeGeneration(messages, onUpdate);}async function raceGenerations(messages: ChatMessage[],models: string[] | undefined,43 unmodified lines).then((result: string) => ({ result, generationId: generation.id })),);const winner = await Promise.race(statusPromises);await Promise.all(generations492 unmodified lines4934944954964974984995 unmodified lines50550650750850951051151251351451551651751851952052152252352452552652752852943 unmodified lines573574575576577578579580581582583584585492 unmodified lines// job is submitted shows the response card and its Stop button for the// whole queue wait, which is what makes an interrupt possible at all.updateTextGenerationState("generating");return await executeHordeGeneration(messages, (text) => {updateResponse(text);});}5 unmodified linesreturn await executeHordeGeneration(messages, onUpdate);}/*** The error to report when every raced job failed. `AggregateError.errors` is* in submission order, not failure order, so the choice goes by priority: an* interrupt first, so a stop never turns into a retry, then "not possible",* the original object `executeHordeGeneration` retries on, then the first.*/function pickRaceFailure(errors: unknown[]): unknown {const withMessage = (message: string) =>errors.find((error) =>error instanceof ChatGenerationError && error.message === message,);return (withMessage("Generation interrupted") ??withMessage(GENERATION_NOT_POSSIBLE_MESSAGE) ??errors[0]);}async function raceGenerations(messages: ChatMessage[],models: string[] | undefined,43 unmodified lines).then((result: string) => ({ result, generationId: generation.id })),);// The first job to answer wins; a job that fails is ignored while another// is still running, so one crashed worker cannot sink a healthy sibling.const winner = await Promise.any(statusPromises).catch((error: unknown) => {throw error instanceof AggregateError? pickRaceFailure(error.errors): error;});await Promise.all(generations
1 unmodified line2345671 unmodified line91011121314151617181945 unmodified lines65666768697028 unmodified lines99100101102103104105151 unmodified lines2572582592601 unmodified lineimport {getQuery,getTextGenerationState,updateResponse,updateTextGenerationState,} from "./pubSub";1 unmodified lineChatGenerationError,canStartResponding,} from "./textGenerationUtilities";import type { ChatMessage } from "./types";vi.mock("./pubSub", () => ({getQuery: vi.fn().mockReturnValue("test query"),getTextGenerationState: vi.fn().mockReturnValue("idle"),updateResponse: vi.fn(),updateTextGenerationState: vi.fn(),}));45 unmodified linesreturn new Response(body, { status });}async function generateChatFromChunks(chunks: Array<string | Uint8Array>) {const { generateChatWithInternalApi } = await import("./textGenerationWithInternalApi"28 unmodified lines),);await generateTextWithInternalApi();expect(canStartResponding).toHaveBeenCalled();expect(updateTextGenerationState).toHaveBeenCalledWith(151 unmodified linesexpect(onUpdate).toHaveBeenCalledWith("Partial");});});});1 unmodified line23456781 unmodified line10111213141516171819202145 unmodified lines67686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211328 unmodified lines142143144145146147148151 unmodified lines3003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833841 unmodified lineimport {getQuery,getTextGenerationState,listenToTextGenerationStateChanges,updateResponse,updateTextGenerationState,} from "./pubSub";1 unmodified lineChatGenerationError,canStartResponding,} from "./textGenerationUtilities";import type { ChatMessage, TextGenerationState } from "./types";vi.mock("./pubSub", () => ({getQuery: vi.fn().mockReturnValue("test query"),getTextGenerationState: vi.fn().mockReturnValue("idle"),listenToTextGenerationStateChanges: vi.fn(() => vi.fn()),updateResponse: vi.fn(),updateTextGenerationState: vi.fn(),}));45 unmodified linesreturn new Response(body, { status });}/*** A response whose stream sends `chunks` and then stays open, as a stalled* upstream does, with a spy on the stream's cancel.*/function openStreamResponse(chunks: string[]) {const cancel = vi.fn();const encoder = new TextEncoder();const body = new ReadableStream({start(controller) {for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));},cancel,});return { response: new Response(body), cancel };}/** A closed stream, with a spy on its cancel. */function closedStreamResponse(chunks: string[]) {const cancel = vi.fn();const encoder = new TextEncoder();const body = new ReadableStream({start(controller) {for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));controller.close();},cancel,});return { response: new Response(body), cancel };}/** The state listener the module registered last. */function lastStateListener() {const call = vi.mocked(listenToTextGenerationStateChanges).mock.calls.at(-1);if (!call) throw new Error("no state listener was registered");return call[0] as (state: TextGenerationState) => void;}function fetchSignal(): AbortSignal {return mockFetch.mock.calls[0][1].signal;}async function generateChatFromChunks(chunks: Array<string | Uint8Array>) {const { generateChatWithInternalApi } = await import("./textGenerationWithInternalApi"28 unmodified lines),);await expect(generateTextWithInternalApi()).resolves.toBe("Hello");expect(canStartResponding).toHaveBeenCalled();expect(updateTextGenerationState).toHaveBeenCalledWith(151 unmodified linesexpect(onUpdate).toHaveBeenCalledWith("Partial");});});describe("cancelling the stream", () => {it("cancels the request when generation is interrupted mid-stream", async () => {const { generateTextWithInternalApi } = await import("./textGenerationWithInternalApi");const stream = openStreamResponse(['data: {"choices":[{"delta":{"content":"partial"}}]}\n',]);mockFetch.mockResolvedValueOnce(stream.response);vi.mocked(getTextGenerationState).mockReturnValue("interrupted");await expect(generateTextWithInternalApi()).rejects.toThrow("Generation interrupted",);expect(fetchSignal().aborted).toBe(true);expect(stream.cancel).toHaveBeenCalled();});it("cancels the request when the stream sends an error frame", async () => {const { generateChatWithInternalApi } = await import("./textGenerationWithInternalApi");const stream = openStreamResponse(['data: {"error":"boom"}\n']);mockFetch.mockResolvedValueOnce(stream.response);const error = await generateChatWithInternalApi([{ role: "user", content: "Hi" }],vi.fn(),).catch((caught: unknown) => caught);expect(error).toBeInstanceOf(ChatGenerationError);expect((error as Error).message).toBe("boom");expect(fetchSignal().aborted).toBe(true);expect(stream.cancel).toHaveBeenCalled();});it("stops a silent stream as soon as generation is interrupted", async () => {const { generateChatWithInternalApi } = await import("./textGenerationWithInternalApi");const stream = openStreamResponse([]);mockFetch.mockResolvedValueOnce(stream.response);const chat = generateChatWithInternalApi([{ role: "user", content: "Hi" }],vi.fn(),);const outcome = expect(chat).rejects.toThrow("Chat generation interrupted",);await vi.waitFor(() => expect(mockFetch).toHaveBeenCalled());// No chunk ever arrives, so only the state change can end the wait.lastStateListener()("interrupted");await outcome;expect(fetchSignal().aborted).toBe(true);expect(stream.cancel).toHaveBeenCalled();});it("leaves a finished request alone and stops listening", async () => {const { generateChatWithInternalApi } = await import("./textGenerationWithInternalApi");const stream = closedStreamResponse(sseChunks(['{"choices":[{"delta":{"content":"Hello"}}]}']),);mockFetch.mockResolvedValueOnce(stream.response);await expect(generateChatWithInternalApi([{ role: "user", content: "Hi" }], vi.fn()),).resolves.toBe("Hello");expect(fetchSignal().aborted).toBe(false);expect(stream.cancel).not.toHaveBeenCalled();const stopListening = vi.mocked(listenToTextGenerationStateChanges).mock.results[0].value;expect(stopListening).toHaveBeenCalledTimes(1);});});});
1234520 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123import {getTextGenerationState,updateResponse,updateTextGenerationState,} from "./pubSub";20 unmodified linesawait getFormattedSearchResults(true),);const streamedMessage = await processStreamResponse(messages, (message) => {if (getTextGenerationState() === "interrupted") {throw new ChatGenerationError("Generation interrupted");}if (getTextGenerationState() !== "generating") {updateTextGenerationState("generating");}updateResponse(message);});updateResponse(streamedMessage);}export async function generateChatWithInternalApi(messages: ChatMessage[],onUpdate: (partialResponse: string) => void,) {return processStreamResponse(messages, (message) => {onUpdate(message);if (getTextGenerationState() === "interrupted") {throw new ChatGenerationError("Chat generation interrupted");}});}async function processStreamResponse(messages: ChatMessage[],onChunk: (message: string) => void,): Promise<string> {const inferenceUrl = new URL("/inference", self.location.origin);const token = await getSearchTokenHash();inferenceUrl.searchParams.set("token", token);const response = await fetch(inferenceUrl.toString(), {method: "POST",headers: {"Content-Type": "application/json",},body: JSON.stringify({...getDefaultChatCompletionCreateParamsStreaming(messages),messages,}),});if (!response.ok || !response.body) {throw new Error(`HTTP error! status: ${response.status}`);}const reader = response.body.getReader();const decoder = new TextDecoder("utf-8");let streamedMessage = "";let bufferedText = "";const processLine = (line: string) => {const data = line.replace(/^data: /, "").trim();if (data === "" || data === "[DONE]") return;let parsedLine: InternalApiStreamPayload;try {parsedLine = JSON.parse(data) as InternalApiStreamPayload;} catch {return;}if (typeof parsedLine?.error === "string") {throw new ChatGenerationError(parsedLine.error);}const deltaContent = parsedLine?.choices?.[0]?.delta?.content;if (typeof deltaContent === "string" && deltaContent !== "") {streamedMessage += deltaContent;onChunk(streamedMessage);}};while (true) {const { done, value } = await reader.read();if (done) break;bufferedText += decoder.decode(value, { stream: true });const lines = bufferedText.split("\n");bufferedText = lines.pop() ?? "";for (const line of lines) {processLine(line);}}bufferedText += decoder.decode();processLine(bufferedText);return streamedMessage;}12345620 unmodified lines27282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169import {getTextGenerationState,listenToTextGenerationStateChanges,updateResponse,updateTextGenerationState,} from "./pubSub";20 unmodified linesawait getFormattedSearchResults(true),);const streamedMessage = await processStreamResponse(messages,(message) => {if (getTextGenerationState() === "interrupted") {throw new ChatGenerationError("Generation interrupted");}if (getTextGenerationState() !== "generating") {updateTextGenerationState("generating");}updateResponse(message);},"Generation interrupted",);updateResponse(streamedMessage);return streamedMessage;}export async function generateChatWithInternalApi(messages: ChatMessage[],onUpdate: (partialResponse: string) => void,) {return processStreamResponse(messages,(message) => {onUpdate(message);if (getTextGenerationState() === "interrupted") {throw new ChatGenerationError("Chat generation interrupted");}},"Chat generation interrupted",);}/*** Streams one answer from the server's `/inference` endpoint. The request is* cancelled whenever the answer does not finish: on Stop, which aborts it at* once even while the stream is silent, and on any error thrown while reading.* Cancelling closes the connection, which is how the server learns that the* reader is gone and stops streaming the run.*/async function processStreamResponse(messages: ChatMessage[],onChunk: (message: string) => void,interruptedMessage: string,): Promise<string> {const controller = new AbortController();const { signal } = controller;const stopListening = listenToTextGenerationStateChanges((state) => {if (state === "interrupted") {controller.abort(new ChatGenerationError(interruptedMessage));}});let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;// The browser also errors the body when its fetch is aborted, but only a// cancel ends a read that is already waiting on a silent stream everywhere.const cancelReader = () => {reader?.cancel(signal.reason).catch(() => {});};signal.addEventListener("abort", cancelReader, { once: true });let completed = false;try {const inferenceUrl = new URL("/inference", self.location.origin);const token = await getSearchTokenHash();inferenceUrl.searchParams.set("token", token);const response = await fetch(inferenceUrl.toString(), {method: "POST",headers: {"Content-Type": "application/json",},body: JSON.stringify({...getDefaultChatCompletionCreateParamsStreaming(messages),messages,}),signal,});if (!response.ok || !response.body) {throw new Error(`HTTP error! status: ${response.status}`);}reader = response.body.getReader();const decoder = new TextDecoder("utf-8");let streamedMessage = "";let bufferedText = "";const processLine = (line: string) => {const data = line.replace(/^data: /, "").trim();if (data === "" || data === "[DONE]") return;let parsedLine: InternalApiStreamPayload;try {parsedLine = JSON.parse(data) as InternalApiStreamPayload;} catch {return;}if (typeof parsedLine?.error === "string") {throw new ChatGenerationError(parsedLine.error);}const deltaContent = parsedLine?.choices?.[0]?.delta?.content;if (typeof deltaContent === "string" && deltaContent !== "") {streamedMessage += deltaContent;onChunk(streamedMessage);}};while (true) {const { done, value } = await reader.read();// A cancelled read resolves as done, so the abort is checked first.signal.throwIfAborted();if (done) break;bufferedText += decoder.decode(value, { stream: true });const lines = bufferedText.split("\n");bufferedText = lines.pop() ?? "";for (const line of lines) {processLine(line);}}bufferedText += decoder.decode();processLine(bufferedText);completed = true;return streamedMessage;} finally {stopListening();// Any way out but a finished stream cancels the request.if (!completed) controller.abort();signal.removeEventListener("abort", cancelReader);}}
96 unmodified lines97989910010110210315 unmodified lines11912012112212312412596 unmodified linessseResponse([{ choices: [{ delta: { content: "Hello" } }] }]),);await generateTextWithOpenAi();expect(canStartResponding).toHaveBeenCalled();expect(updateTextGenerationState).toHaveBeenCalledWith(15 unmodified lines]),);await generateTextWithOpenAi();expect(updateResponse).toHaveBeenLastCalledWith("<think>Thinking...</think>\n\nHello",96 unmodified lines97989910010110210315 unmodified lines11912012112212312412512612796 unmodified linessseResponse([{ choices: [{ delta: { content: "Hello" } }] }]),);await expect(generateTextWithOpenAi()).resolves.toBe("Hello");expect(canStartResponding).toHaveBeenCalled();expect(updateTextGenerationState).toHaveBeenCalledWith(15 unmodified lines]),);await expect(generateTextWithOpenAi()).resolves.toBe("<think>Thinking...</think>\n\nHello",);expect(updateResponse).toHaveBeenLastCalledWith("<think>Thinking...</think>\n\nHello",
35 unmodified lines363738394041119 unmodified lines1611621631641651661672 unmodified lines1701711721731741751763 unmodified lines1801811821831841851861871881891901911921931941951961971984 unmodified lines20320420520620720820921021121221321421521621721821922022122222322422535 unmodified linesreasoningContent?: string;}async function createOpenAiStream({messages,onUpdate,119 unmodified linesreturn tryNextModel();}export async function generateTextWithOpenAi() {await canStartResponding();updateTextGenerationState("preparingToGenerate");2 unmodified lines);const settings = getSettings();await createOpenAiStream({messages,onUpdate: (text, reasoningContent) => {if (3 unmodified linesupdateTextGenerationState("generating");}if (reasoningContent && reasoningContent.length > 0) {if (text && text.length > 0) {updateResponse(`${settings.reasoningStartMarker}${reasoningContent}${settings.reasoningEndMarker}\n\n${text}`,);} else {updateResponse(`${settings.reasoningStartMarker}${reasoningContent}`);}} else {updateResponse(text);}},});}export async function generateChatWithOpenAi(4 unmodified linesconst result = await createOpenAiStream({messages,onUpdate: (text, reasoningContent) => {if (reasoningContent && reasoningContent.length > 0) {if (text && text.length > 0) {onUpdate(`${settings.reasoningStartMarker}${reasoningContent}${settings.reasoningEndMarker}\n\n${text}`,);} else {onUpdate(`${settings.reasoningStartMarker}${reasoningContent}`);}} else {onUpdate(text);}},});if (result.reasoningContent && result.reasoningContent.length > 0) {return `${settings.reasoningStartMarker}${result.reasoningContent}${settings.reasoningEndMarker}\n\n${result.text}`;}return result.text;}35 unmodified lines363738394041424344454647484950515253545556575859119 unmodified lines1791801811821831841852 unmodified lines1881891901911921931943 unmodified lines1981992002012022032042052062072084 unmodified lines21321421521621721821922022135 unmodified linesreasoningContent?: string;}/*** The text the response channel carries for a streamed answer: the reasoning* block wrapped in its markers, followed by the answer once it arrives.*/function composeResponseText(text: string,reasoningContent: string | undefined,settings: { reasoningStartMarker: string; reasoningEndMarker: string },) {if (!reasoningContent) return text;const reasoning = `${settings.reasoningStartMarker}${reasoningContent}`;if (!text) return reasoning;return `${reasoning}${settings.reasoningEndMarker}\n\n${text}`;}async function createOpenAiStream({messages,onUpdate,119 unmodified linesreturn tryNextModel();}export async function generateTextWithOpenAi(): Promise<string> {await canStartResponding();updateTextGenerationState("preparingToGenerate");2 unmodified lines);const settings = getSettings();const result = await createOpenAiStream({messages,onUpdate: (text, reasoningContent) => {if (3 unmodified linesupdateTextGenerationState("generating");}updateResponse(composeResponseText(text, reasoningContent, settings));},});return composeResponseText(result.text, result.reasoningContent, settings);}export async function generateChatWithOpenAi(4 unmodified linesconst result = await createOpenAiStream({messages,onUpdate: (text, reasoningContent) => {onUpdate(composeResponseText(text, reasoningContent, settings));},});return composeResponseText(result.text, result.reasoningContent, settings);}
117 unmodified lines118119120121122123124117 unmodified lines{ loaded: 175 * megabyte, total: 250 * megabyte },]);await generateTextWithWllama();expect(updateModelLoadingProgress).toHaveBeenCalledTimes(2);expect(updateModelLoadingProgress).toHaveBeenLastCalledWith(70);117 unmodified lines118119120121122123124117 unmodified lines{ loaded: 175 * megabyte, total: 250 * megabyte },]);await expect(generateTextWithWllama()).resolves.toBe("Hello");expect(updateModelLoadingProgress).toHaveBeenCalledTimes(2);expect(updateModelLoadingProgress).toHaveBeenLastCalledWith(70);
28 unmodified lines29303132333435369 unmodified lines46474849505128 unmodified linestotal: number;}) => void;export async function generateTextWithWllama(): Promise<void> {if (!getSettings().enableAiResponse) return;try {const response = await generateWithWllama({9 unmodified linesshouldCheckCanRespond: true,});updateResponse(response);} catch (error) {addLogEntry(`Text generation failed: ${28 unmodified lines29303132333435369 unmodified lines4647484950515228 unmodified linestotal: number;}) => void;export async function generateTextWithWllama(): Promise<string> {if (!getSettings().enableAiResponse) return "";try {const response = await generateWithWllama({9 unmodified linesshouldCheckCanRespond: true,});updateResponse(response);return response;} catch (error) {addLogEntry(`Text generation failed: ${
143 unmodified lines144145146147148149150143 unmodified lines{inferenceType: 'horde',hordeApiKey: '0000000000', // Default anonymous key; set your own for priorityhordeModel: '' // Optional; empty asks for the five most requested models this month and races two requests, using the first response}```143 unmodified lines144145146147148149150143 unmodified lines{inferenceType: 'horde',hordeApiKey: '0000000000', // Default anonymous key; set your own for priorityhordeModel: '' // Optional; empty asks for the five most requested models this month and races two requests, using the first one that answers; one that fails is ignored while the other is still running}```
193 unmodified lines194195196197198199200193 unmodified linesskipped when less than two seconds of the search's own 25-second deadlineremain, since an answer that late cannot reach the client before its 30-secondtimeout, and that skip answers the `502` above and counts as a fallback thatfailed. If at least one provider answers with nothing usable and none returnsresults, this endpoint responds `200` with `[]`, so the client shows the"No results found" alert rather than the "Text search unavailable" one; onlywhen every provider tried fails, or none could be tried at all, does the193 unmodified lines194195196197198199200201202203204193 unmodified linesskipped when less than two seconds of the search's own 25-second deadlineremain, since an answer that late cannot reach the client before its 30-secondtimeout, and that skip answers the `502` above and counts as a fallback thatfailed. So that a stalled SearXNG cannot use up that deadline, the SearXNGrequest, its retries and their backoff are canceled after 15 seconds when thefallback could follow, which leaves it the last 10, and after the full 25seconds otherwise; a canceled request counts as a SearXNG failure toward thecircuit breaker. If at least one provider answers with nothing usable and none returnsresults, this endpoint responds `200` with `[]`, so the client shows the"No results found" alert rather than the "Text search unavailable" one; onlywhen every provider tried fails, or none could be tried at all, does the
50 unmodified lines5152535455565758596061626 unmodified lines69707172737450 unmodified linesFor self-hosted OpenAI-compatible APIs:| Variable | Default | Description || ----------------------------------------- | -------------- | ------------------------------------------------------------------ || `INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL` | `''` | Base URL of your API (e.g., `https://api.internal.company.com/v1`) || `INTERNAL_OPENAI_COMPATIBLE_API_KEY` | `''` | API key for authentication || `INTERNAL_OPENAI_COMPATIBLE_API_MODEL` | `''` | Model ID, or a comma-separated list (random model if empty) || `INTERNAL_OPENAI_COMPATIBLE_API_NAME` | `Internal API` | Display name shown in UI |**Example:**6 unmodified lines`INTERNAL_OPENAI_COMPATIBLE_API_MODEL` takes several models, separated by commas, in order of preference (`"llama-3.1-8b,qwen-3-8b"`). When a model fails before sending the first token, the server moves to the next one, and after the last one it starts the list over once, up to 5 attempts in all. So a single model gets one retry. Left empty, each request picks a random model from the API's `/models` list, which includes every model the API serves.### Default Behavior| Variable | Default | Description |50 unmodified lines515253545556575859606162636 unmodified lines707172737475767750 unmodified linesFor self-hosted OpenAI-compatible APIs:| Variable | Default | Description || ------------------------------------------------- | -------------- | ------------------------------------------------------------------ || `INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL` | `''` | Base URL of your API (e.g., `https://api.internal.company.com/v1`) || `INTERNAL_OPENAI_COMPATIBLE_API_KEY` | `''` | API key for authentication || `INTERNAL_OPENAI_COMPATIBLE_API_MODEL` | `''` | Model ID, or a comma-separated list (random model if empty) || `INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT` | `''` | Sent as `reasoning_effort` on every request (API default if empty) || `INTERNAL_OPENAI_COMPATIBLE_API_NAME` | `Internal API` | Display name shown in UI |**Example:**6 unmodified lines`INTERNAL_OPENAI_COMPATIBLE_API_MODEL` takes several models, separated by commas, in order of preference (`"llama-3.1-8b,qwen-3-8b"`). When a model fails before sending the first token, the server moves to the next one, and after the last one it starts the list over once, up to 5 attempts in all. So a single model gets one retry. Left empty, each request picks a random model from the API's `/models` list, which includes every model the API serves.`INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT` sets the `reasoning_effort` field of every request to the API, for every model in the list. The value is passed through as written, because providers accept different values (`none`, `minimal`, `low`, `medium`, `high`, `xhigh`); one the API rejects fails the request, and the error shows in the server log. Left empty, the field is not sent and the API applies its own default.### Default Behavior| Variable | Default | Description |
53 unmodified lines54555657585926 unmodified lines86878889909153 unmodified lines| Search returns nothing to the endpoint | HTTP 200 with `[]`, not an error | `server/searchEndpointServerHook.test.ts` › graceful degradation || Text search returns nothing to the client | Keyword-only query retried as a fallback | `client/modules/textGeneration.degradation.test.ts` || Keyword fallback also returns nothing | Text search state stays `completed` with the no-results alert | `client/modules/textGeneration.degradation.test.ts` || SearXNG is down on the client | Text search state becomes `failed`, keyword fallback does not fire | `client/modules/textGeneration.degradation.test.ts` || Client search fails after a previous search populated the LLM channel | The grounding channel is cleared, so the AI can't ground on the previous query's results; when image search is on and it answers, the channel is repopulated with the (image)-tagged titles and URLs instead | `client/modules/textGeneration.degradation.test.ts` || Text search fails and the image search answers | The answer waits for the image results and grounds on their (image)-tagged titles and URLs, and the failed-state alert says so | `client/modules/textGeneration.degradation.test.ts` › search degradation |26 unmodified lines| `ChatInterface` unmounts while a follow-up question is in flight | Both generation flags are cleared and the orphaned completion writes nothing into the next mount | `client/components/AiResponse/ChatInterface.test.tsx` › leaves both generation flags off after unmounting mid-generation || A follow-up question generation rejects after a newer one started | The failed call blanks nothing, so the newer question still lands and the flag stays on until it does | `client/components/AiResponse/ChatInterface.test.tsx` › blanks nothing when an orphaned call rejects after a newer one started || `ChatInterface` unmounts while a regenerate is still awaiting its response | The orphaned regenerate leaves the next mount's response flag alone | `client/components/AiResponse/ChatInterface.test.tsx` › leaves the next mount's response flag alone when an orphaned regenerate settles || `ChatInterface` unmounts while a send is still awaiting its response | The orphaned send asks for no follow-up question and leaves the next mount's response flag alone | `client/components/AiResponse/ChatInterface.test.tsx` › starts no follow-up question for a send that settles after unmount, leaves the next mount's response flag alone when an orphaned send settles || The dictation model cannot load in the browser, or its download fails | While the on-device model is preferred, the local engine is abandoned for the browser's `SpeechRecognition` before the microphone opens, and the button hides when that is missing too | `client/modules/speechToText.test.ts` › falls back to the browser recognizer without opening the microphone when the model fails to load || The browser recognizer fails while the on-device model is off | The session fails outright; there is no reverse fallback, so the disabled model is never downloaded behind the user's back | `client/modules/speechToText.test.ts` › does not fall back to the wasm engine when the recognizer fails |53 unmodified lines5455565758596026 unmodified lines8788899091929353 unmodified lines| Search returns nothing to the endpoint | HTTP 200 with `[]`, not an error | `server/searchEndpointServerHook.test.ts` › graceful degradation || Text search returns nothing to the client | Keyword-only query retried as a fallback | `client/modules/textGeneration.degradation.test.ts` || Keyword fallback also returns nothing | Text search state stays `completed` with the no-results alert | `client/modules/textGeneration.degradation.test.ts` || Stop on an internal-API answer, also while the stream is silent, or an error frame | The request is aborted and its stream cancelled, so the server stops streaming and counts the run abandoned | `client/modules/textGenerationWithInternalApi.test.ts` › cancelling the stream || SearXNG is down on the client | Text search state becomes `failed`, keyword fallback does not fire | `client/modules/textGeneration.degradation.test.ts` || Client search fails after a previous search populated the LLM channel | The grounding channel is cleared, so the AI can't ground on the previous query's results; when image search is on and it answers, the channel is repopulated with the (image)-tagged titles and URLs instead | `client/modules/textGeneration.degradation.test.ts` || Text search fails and the image search answers | The answer waits for the image results and grounds on their (image)-tagged titles and URLs, and the failed-state alert says so | `client/modules/textGeneration.degradation.test.ts` › search degradation |26 unmodified lines| `ChatInterface` unmounts while a follow-up question is in flight | Both generation flags are cleared and the orphaned completion writes nothing into the next mount | `client/components/AiResponse/ChatInterface.test.tsx` › leaves both generation flags off after unmounting mid-generation || A follow-up question generation rejects after a newer one started | The failed call blanks nothing, so the newer question still lands and the flag stays on until it does | `client/components/AiResponse/ChatInterface.test.tsx` › blanks nothing when an orphaned call rejects after a newer one started || `ChatInterface` unmounts while a regenerate is still awaiting its response | The orphaned regenerate leaves the next mount's response flag alone | `client/components/AiResponse/ChatInterface.test.tsx` › leaves the next mount's response flag alone when an orphaned regenerate settles || A regenerate fails (model error, interrupted inference) | The previous answer and follow-up question come back with a red notification, the error is logged, and the answer can be regenerated again | `client/components/AiResponse/ChatInterface.test.tsx` › keeps the previous answer so it can be regenerated again || `ChatInterface` unmounts while a send is still awaiting its response | The orphaned send asks for no follow-up question and leaves the next mount's response flag alone | `client/components/AiResponse/ChatInterface.test.tsx` › starts no follow-up question for a send that settles after unmount, leaves the next mount's response flag alone when an orphaned send settles || The dictation model cannot load in the browser, or its download fails | While the on-device model is preferred, the local engine is abandoned for the browser's `SpeechRecognition` before the microphone opens, and the button hides when that is missing too | `client/modules/speechToText.test.ts` › falls back to the browser recognizer without opening the microphone when the model fails to load || The browser recognizer fails while the on-device model is off | The session fails outright; there is no reverse fallback, so the disabled model is never downloaded behind the user's back | `client/modules/speechToText.test.ts` › does not fall back to the wasm engine when the recognizer fails |
29 unmodified lines3031323334353629 unmodified lines- **Data Flow**: Components subscribe to "channels" (e.g., `queryPubSub`, `responsePubSub`)- **Tuple Pattern**: Each channel is a 3-element tuple: `[update, subscribe, get]`- **Persistence**: Some channels use `createLocalStoragePubSub` to automatically sync state with `localStorage`- **Throttling**: UI-heavy updates like AI response streaming are throttled to ~12 updates/sec using `throttleit`### Reranker29 unmodified lines3031323334353629 unmodified lines- **Data Flow**: Components subscribe to "channels" (e.g., `queryPubSub`, `responsePubSub`)- **Tuple Pattern**: Each channel is a 3-element tuple: `[update, subscribe, get]`- **Persistence**: Some channels use `createLocalStoragePubSub` to automatically sync state with `localStorage`- **Throttling**: UI-heavy updates like AI response streaming are throttled to ~12 updates/sec; the response channel keeps one trailing write and exposes an unthrottled final publish### Reranker
106 unmodified lines10710810911011111211359 unmodified lines173174175176177178179180181182183184185186106 unmodified lines2. State machine transitions: `idle` -> `awaitingModelDownloadAllowance` -> `loadingModel` -> `awaitingSearchResults` -> `preparingToGenerate` -> `generating` -> `completed`/`failed`/`interrupted` (see Text Generation States below; `awaitingModelDownloadAllowance` and `loadingModel` only occur on the browser/Wllama path, while every backend transitions through `awaitingSearchResults` and then `preparingToGenerate`)3. Search results are formatted and injected into system prompt via `{{searchResults}}` placeholder. With `enablePageContentFetch` on, the pages behind the top results are read through `/page-content` first and their excerpts are appended to each result (see `docs/page-content.md`)4. LLM generates response with streaming tokens5. Response updates throttled to ~12 updates/sec via `throttleit` to prevent React render overload6. Response saved to history database via `saveLlmResponseForQuery`The `textGeneration` module orchestrates the entire search-to-response flow, managing search requests, LLM context preparation, and response streaming. Search results are optionally reranked in-process via ONNX Runtime before being passed to the LLM for response generation.59 unmodified lines### Response ThrottlingStreaming LLM output produces token-by-token state changes that would overwhelm React's rendering pipeline. Two channels apply throttling via `throttleit`:| Channel | Throttle Interval | Purpose || ------------------------ | ----------------- | ------------------------------------ || `responsePubSub` | ~83ms (12/sec) | AI response text streaming || `reasoningContentPubSub` | ~83ms (12/sec) | Reasoning/thinking content streaming |Callers write tokens directly to `updateResponse` or `updateReasoningContent` without awareness of internal throttling.### Side Effects106 unmodified lines10710810911011111211359 unmodified lines173174175176177178179180181182183184185186106 unmodified lines2. State machine transitions: `idle` -> `awaitingModelDownloadAllowance` -> `loadingModel` -> `awaitingSearchResults` -> `preparingToGenerate` -> `generating` -> `completed`/`failed`/`interrupted` (see Text Generation States below; `awaitingModelDownloadAllowance` and `loadingModel` only occur on the browser/Wllama path, while every backend transitions through `awaitingSearchResults` and then `preparingToGenerate`)3. Search results are formatted and injected into system prompt via `{{searchResults}}` placeholder. With `enablePageContentFetch` on, the pages behind the top results are read through `/page-content` first and their excerpts are appended to each result (see `docs/page-content.md`)4. LLM generates response with streaming tokens5. Response updates throttled to ~12 updates/sec to prevent React render overload; the final answer is published unthrottled before the state turns to `completed` (see Response Throttling)6. Response saved to history database via `saveLlmResponseForQuery`The `textGeneration` module orchestrates the entire search-to-response flow, managing search requests, LLM context preparation, and response streaming. Search results are optionally reranked in-process via ONNX Runtime before being passed to the LLM for response generation.59 unmodified lines### Response ThrottlingStreaming LLM output produces token-by-token state changes that would overwhelm React's rendering pipeline. Two channels cap updates at ~12/sec (83ms):| Channel | Throttle Interval | Purpose || ----------------------------------- | ----------------- | -------------------------------------------- || `responsePubSub` (`updateResponse`) | ~83ms (12/sec) | AI response text streaming || `ChatInterface` streamed response | ~83ms (12/sec) | Chat panel re-render while an answer streams |`updateResponse` keeps at most one trailing write for the newest value; `updateResponseImmediately` drops that write and publishes the final answer at once. Callers write tokens directly to these exports without awareness of internal throttling.### Side Effects
43 unmodified lines444546474849505152535455565743 unmodified lines### Throttling High-Frequency UpdatesStreaming LLM output produces token-by-token state changes that would overwhelm React's rendering pipeline. Two channels apply `throttle` from `throttleit` to cap subscriber notification rate to ~12 updates/sec (83.3ms interval):| Export | Raw Updater | Throttle Interval || ------------------------ | --------------------------- | ----------------- || `updateResponse` | `responsePubSub[0]` | 1000 / 12 ms || `updateReasoningContent` | `reasoningContentPubSub[0]` | 1000 / 12 ms |Callers write streaming token output directly to these exports without awareness of internal throttling.### Side Effects43 unmodified lines44454647484950515253545556575843 unmodified lines### Throttling High-Frequency UpdatesStreaming LLM output produces token-by-token state changes that would overwhelm React's rendering pipeline. Two channels cap subscriber notification rate to ~12 updates/sec (83ms interval):| Export | Raw Updater | Throttle || ---------------------------------------- | ------------------- | ----------------------------------- || `updateResponse` | `responsePubSub[0]` | 1000 / 12 ms, plus a trailing write || `updateResponseImmediately` | `responsePubSub[0]` | none — drops the trailing write || `updateStreamedResponse` (ChatInterface) | local React state | `throttleit`, 1000 / 12 ms |Callers write streaming token output directly to these exports without awareness of internal throttling; the generation flow publishes the final answer through `updateResponseImmediately`, so the last chunk is never lost.### Side Effects
.env.example+3
changelog.md+11
client/components/AiResponse/ChatHeader.test.tsxAdded+64
client/components/AiResponse/ChatHeader.tsx+5-3
client/components/AiResponse/ChatInterface.test.tsx+171
client/components/AiResponse/ChatInterface.tsx+65-34
client/components/AiResponse/MessageList.test.tsx+52-1
client/components/AiResponse/MessageList.tsx+23-9
client/hooks/useHistoryRestore.ts+5-3
client/modules/pubSub.throttle.test.tsAdded+69
client/modules/pubSub.ts+73-4
client/modules/textGeneration.chatBudget.test.ts+1
client/modules/textGeneration.degradation.test.ts+5
client/modules/textGeneration.inference.test.ts+1
client/modules/textGeneration.responsePersistence.test.tsAdded+111
client/modules/textGeneration.test.ts+1
client/modules/textGeneration.ts+10-4
client/modules/textGenerationWithHorde.test.ts+88-3
client/modules/textGenerationWithHorde.ts+27-2
client/modules/textGenerationWithInternalApi.test.ts+126-2
client/modules/textGenerationWithInternalApi.ts+117-71
client/modules/textGenerationWithOpenAi.test.ts+4-2
client/modules/textGenerationWithOpenAi.ts+25-29
client/modules/textGenerationWithWllama.test.ts+1-1
client/modules/textGenerationWithWllama.ts+3-2
docs/ai-integration.md+1-1
docs/api.md+5-1
docs/configuration.md+9-6
docs/failure-injection.md+2
docs/glossary.md+1-1
docs/overview.md+7-7
docs/ui-components.md+7-6