Spaces:
Running
Running
Sync from felladrin/MiniSearch@49c5d20
Browse filesFiles changed (6)
1 unmodified line2345671 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-12- The follow-up question field and its Send button now look like one control: the field has square right corners and shares a single border with the button. The microphone button no longer turns into a solid gray block while an answer is being generated, and its hover and recording fills stay inside the field's border, in the follow-up field and in the search field.1 unmodified line2345678910111 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-17- With the AI Horde engine and no model selected, the request no longer lands on a random model: it now goes to the five text models with online workers that have the most requests this month, so answers come from the models the community actually uses. The ranking refreshes every 5 minutes. If it cannot be fetched, or none of those models can take the job, the request falls back to any available model, as before.## 2026-11-12- The follow-up question field and its Send button now look like one control: the field has square right corners and shares a single border with the button. The microphone button no longer turns into a solid gray block while an answer is being generated, and its hover and recording fills stay inside the field's border, in the follow-up field and in the search field.
32 unmodified lines3334353637383932 unmodified linesform.values.hordeApiKey !== aiHordeDefaultApiKey && (<Selectlabel="Model"description="Optional. When not selected, AI Horde will automatically choose an available model."placeholder="Auto-selected"data={hordeModels}{...form.getInputProps("hordeModel")}32 unmodified lines3334353637383932 unmodified linesform.values.hordeApiKey !== aiHordeDefaultApiKey && (<Selectlabel="Model"description="Optional. When not selected, the request goes to the five most requested models this month, and the first answer wins."placeholder="Auto-selected"data={hordeModels}{...form.getInputProps("hordeModel")}
55 unmodified lines565758596061129 unmodified lines19119219319419519655 unmodified linesdescribe("textGenerationWithHorde", () => {beforeEach(() => {vi.clearAllMocks();mockSettings({ hordeModel: "chosen-model" });vi.mocked(getTextGenerationState).mockReturnValue("idle");});129 unmodified lines});});describe("fetchHordeModels", () => {it("returns the models reported by the AI Horde API", async () => {const { fetchHordeModels } = await import("./textGenerationWithHorde");55 unmodified lines5657585960616263129 unmodified lines19319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141255 unmodified linesdescribe("textGenerationWithHorde", () => {beforeEach(() => {vi.clearAllMocks();// The module caches the model ranking; each test starts from a clean slate.vi.resetModules();mockSettings({ hordeModel: "chosen-model" });vi.mocked(getTextGenerationState).mockReturnValue("idle");});129 unmodified lines});});describe("automatic model selection when no model is pinned", () => {const doneResponse = {done: true,is_possible: true,generations: [{ text: "Top model answer", model: "m-f" }],};function routeHordeFetch({workerModels,monthStats,statsFails = false,statusResponder,}: {workerModels: Array<{ name: string; count: number }>;monthStats?: Record<string, number>;statsFails?: boolean;statusResponder: (pollIndex: number) => unknown;}) {let idCounter = 0;let pollCounter = 0;mockFetch.mockImplementation(async (url: string, init?: { method?: string; body?: string }) => {if (url.includes("/status/models")) {return jsonResponse(workerModels.map((model) => ({performance: 1,queued: 0,jobs: 0,eta: 0,type: "text",...model,})),);}if (url.includes("/stats/text/models")) {return statsFails? jsonResponse({}, 500): jsonResponse({ day: {}, month: monthStats ?? {}, total: {} });}if (url.includes("/generate/text/async")) {return jsonResponse({ id: `gen-${++idCounter}` });}if (init?.method === "DELETE") {return jsonResponse({});}return jsonResponse(statusResponder(pollCounter++));},);}function generationRequestBodies() {return mockFetch.mock.calls.filter(([url]) => String(url).includes("/generate/text/async")).map(([, init]) => JSON.parse((init as { body: string }).body));}beforeEach(() => {mockSettings({ hordeModel: "" });});it("asks for the models with workers ranked by requests this month", async () => {routeHordeFetch({workerModels: [{ name: "m-a", count: 1 },{ name: "m-b", count: 2 },{ name: "m-c", count: 1 },{ name: "m-d", count: 1 },{ name: "m-e", count: 1 },{ name: "m-f", count: 1 },{ name: "m-offline", count: 0 },],monthStats: {"m-a": 400,"m-b": 500,"m-c": 600,"m-d": 700,"m-e": 800,"m-f": 900,"m-offline": 9999,},statusResponder: () => doneResponse,});const { generateTextWithHorde } = await import("./textGenerationWithHorde");await generateTextWithHorde();const bodies = generationRequestBodies();expect(bodies).toHaveLength(2);for (const body of bodies) {expect(body.models).toEqual(["m-f", "m-e", "m-d", "m-c", "m-b"]);}});it("falls back to any available model when the statistics fetch fails", async () => {routeHordeFetch({workerModels: [{ name: "m-a", count: 1 }],statsFails: true,statusResponder: () => doneResponse,});const { generateTextWithHorde } = await import("./textGenerationWithHorde");await generateTextWithHorde();const bodies = generationRequestBodies();expect(bodies).toHaveLength(2);for (const body of bodies) {expect(body.models).toBeUndefined();}expect(addLogEntry).toHaveBeenCalledWith(expect.stringContaining("falling back to any available model"),);});it("retries with any available model when the top models cannot take the job", async () => {routeHordeFetch({workerModels: [{ name: "m-a", count: 1 }],monthStats: { "m-a": 10 },statusResponder: (pollIndex) =>pollIndex < 2 ? { done: true, is_possible: false } : doneResponse,});const { generateTextWithHorde } = await import("./textGenerationWithHorde");await generateTextWithHorde();expect(updateResponse).toHaveBeenCalledWith("Top model answer");const bodies = generationRequestBodies();expect(bodies).toHaveLength(4);expect(bodies.slice(0, 2).map((body) => body.models)).toEqual([["m-a"],["m-a"],]);expect(bodies.slice(2).map((body) => body.models)).toEqual([undefined,undefined,]);expect(addLogEntry).toHaveBeenCalledWith(expect.stringContaining("retrying with any available model"),);});it("does not retry when the generation faults", async () => {routeHordeFetch({workerModels: [{ name: "m-a", count: 1 }],monthStats: { "m-a": 10 },statusResponder: () => ({ done: true, faulted: true }),});const { generateTextWithHorde } = await import("./textGenerationWithHorde");await expect(generateTextWithHorde()).rejects.toThrow("Generation failed",);expect(generationRequestBodies()).toHaveLength(2);});it("reuses the cached ranking for the next generation", async () => {routeHordeFetch({workerModels: [{ name: "m-a", count: 1 }],monthStats: { "m-a": 10 },statusResponder: () => doneResponse,});const { generateTextWithHorde } = await import("./textGenerationWithHorde");await generateTextWithHorde();await generateTextWithHorde();const rankingFetches = mockFetch.mock.calls.filter(([url]) =>String(url).includes("/status/models") ||String(url).includes("/stats/text/models"),);expect(rankingFetches).toHaveLength(2);expect(generationRequestBodies().map((body) => body.models)).toEqual([["m-a"],["m-a"],["m-a"],["m-a"],]);});it("refetches the ranking after the cache expires", async () => {routeHordeFetch({workerModels: [{ name: "m-a", count: 1 }],monthStats: { "m-a": 10 },statusResponder: () => doneResponse,});const nowSpy = vi.spyOn(Date, "now").mockReturnValue(0);const { generateTextWithHorde } = await import("./textGenerationWithHorde");await generateTextWithHorde();nowSpy.mockReturnValue(5 * 60 * 1000 + 1);await generateTextWithHorde();nowSpy.mockRestore();const rankingFetches = mockFetch.mock.calls.filter(([url]) =>String(url).includes("/status/models") ||String(url).includes("/stats/text/models"),);expect(rankingFetches).toHaveLength(4);});});describe("fetchHordeModels", () => {it("returns the models reported by the AI Horde API", async () => {const { fetchHordeModels } = await import("./textGenerationWithHorde");
37 unmodified lines38394041424319 unmodified lines6364656667686970717273747520 unmodified lines9697989910010110272 unmodified lines17517617717817918018118218343 unmodified lines2272282292302312322332342352362378 unmodified lines24624724824925025133 unmodified lines28528628728828929029129229329429529629729829930030130230330430530630730865 unmodified lines37437537637737837937 unmodified linescount: number;}interface HordeUserInfo {username: string;kudos: number;19 unmodified lines/** Anonymous AI Horde API key; the lowest-priority tier when the horde is busy. */export const aiHordeDefaultApiKey = "0000000000";function getEffectiveHordeApiKey(settings: ReturnType<typeof getSettings> = getSettings(),) {return settings.hordeApiKey || aiHordeDefaultApiKey;}async function startGeneration(messages: ChatMessage[], signal?: AbortSignal) {const settings = getSettings();const aiHordeApiKey = getEffectiveHordeApiKey(settings);const aiHordeMaxResponseLengthInTokens =20 unmodified linesstop_sequence: [userMarker, assistantMarker],validated_backends: false,},models: settings.hordeModel ? [settings.hordeModel] : undefined,}),});72 unmodified lines}if (!status.is_possible) {throw new ChatGenerationError("Generation not possible with the selected model",);}const generatedText = status.generations?.[0].text;43 unmodified lines}}export async function fetchHordeModels(): Promise<HordeModelInfo[]> {const response = await fetch(buildHordeUrl("/status/models?type=text&model_state=all"),{method: "GET",headers: {[HTTP_HEADERS.CLIENT_AGENT]: aiHordeClientAgent,[HTTP_HEADERS.ACCEPT]: "application/json",8 unmodified linesreturn response.json();}export async function fetchHordeUserInfo(apiKey: string,): Promise<HordeUserInfo> {33 unmodified linesreturn await executeHordeGeneration(messages, onUpdate);}async function executeHordeGeneration(messages: ChatMessage[],onUpdate: (text: string) => void,): Promise<string> {const settings = getSettings();if (settings.hordeModel) {const generation = await startGeneration(messages);return await handleGenerationStatus(generation.id, onUpdate);}const controllers: AbortController[] = [new AbortController(),new AbortController(),];try {const startPromises = controllers.map(async (ctrl) => {const generation = await startGeneration(messages, ctrl.signal);return { id: generation.id, ctrl };});65 unmodified lines}}function formatPrompt(messages: ChatMessage[]): string {return `${messages.map((msg) => `**${msg.role?.toUpperCase()}**:\n${msg.content}`)37 unmodified lines3839404142434445464719 unmodified lines676869707172737475767778798081828384858687888990919293949520 unmodified lines11611711811912012112272 unmodified lines19519619719819920020143 unmodified lines2452462472482492502512522532542552562572588 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933 unmodified lines36336436536636736836937037137237337437537637737837938065 unmodified lines44644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950037 unmodified linescount: number;}interface HordeModelStatsResponse {month?: Record<string, number>;}interface HordeUserInfo {username: string;kudos: number;19 unmodified lines/** Anonymous AI Horde API key; the lowest-priority tier when the horde is busy. */export const aiHordeDefaultApiKey = "0000000000";// How many of the most-requested models an unpinned request asks the horde for.const TOP_HORDE_MODEL_COUNT = 5;// The monthly-request statistics response is large, so the ranking is reused for a while.const TOP_HORDE_MODEL_CACHE_MS = 5 * 60 * 1000;// A hung ranking endpoint must not stall the generation; it falls back instead.const HORDE_RANKING_FETCH_TIMEOUT_MS = 10 * 1000;const GENERATION_NOT_POSSIBLE_MESSAGE ="Generation not possible with the selected model";function getEffectiveHordeApiKey(settings: ReturnType<typeof getSettings> = getSettings(),) {return settings.hordeApiKey || aiHordeDefaultApiKey;}async function startGeneration(messages: ChatMessage[],signal?: AbortSignal,models?: string[],) {const settings = getSettings();const aiHordeApiKey = getEffectiveHordeApiKey(settings);const aiHordeMaxResponseLengthInTokens =20 unmodified linesstop_sequence: [userMarker, assistantMarker],validated_backends: false,},models,}),});72 unmodified lines}if (!status.is_possible) {throw new ChatGenerationError(GENERATION_NOT_POSSIBLE_MESSAGE);}const generatedText = status.generations?.[0].text;43 unmodified lines}}export async function fetchHordeModels(signal?: AbortSignal,): Promise<HordeModelInfo[]> {const response = await fetch(buildHordeUrl("/status/models?type=text&model_state=all"),{method: "GET",signal,headers: {[HTTP_HEADERS.CLIENT_AGENT]: aiHordeClientAgent,[HTTP_HEADERS.ACCEPT]: "application/json",8 unmodified linesreturn response.json();}async function fetchHordeModelMonthlyRequests(signal?: AbortSignal,): Promise<Record<string, number>> {const response = await fetch(buildHordeUrl("/stats/text/models"), {method: "GET",signal,headers: {[HTTP_HEADERS.CLIENT_AGENT]: aiHordeClientAgent,[HTTP_HEADERS.ACCEPT]: "application/json",},});if (!response.ok) {throw new Error("Failed to fetch AI Horde model request statistics");}const data = (await response.json()) as HordeModelStatsResponse;if (!data.month) {throw new Error("AI Horde model request statistics are missing the monthly counter",);}return data.month;}let topHordeModelsCache: { modelNames: string[]; expiresAt: number } | null =null;// The text models with online workers, ranked by requests this month: the// community's own vote on which models are worth using. Cached because the// statistics response is large and the ranking shifts slowly.async function getTopHordeModels(): Promise<string[]> {if (topHordeModelsCache && Date.now() < topHordeModelsCache.expiresAt) {return topHordeModelsCache.modelNames;}const signal = AbortSignal.timeout(HORDE_RANKING_FETCH_TIMEOUT_MS);const [models, monthlyRequests] = await Promise.all([fetchHordeModels(signal),fetchHordeModelMonthlyRequests(signal),]);const modelNames = models.filter((model) => model.count > 0).sort((a, b) => (monthlyRequests[b.name] ?? 0) - (monthlyRequests[a.name] ?? 0),).slice(0, TOP_HORDE_MODEL_COUNT).map((model) => model.name);topHordeModelsCache = {modelNames,expiresAt: Date.now() + TOP_HORDE_MODEL_CACHE_MS,};return modelNames;}export async function fetchHordeUserInfo(apiKey: string,): Promise<HordeUserInfo> {33 unmodified linesreturn await executeHordeGeneration(messages, onUpdate);}async function raceGenerations(messages: ChatMessage[],models: string[] | undefined,onUpdate: (text: string) => void,): Promise<string> {const controllers: AbortController[] = [new AbortController(),new AbortController(),];try {const startPromises = controllers.map(async (ctrl) => {const generation = await startGeneration(messages, ctrl.signal, models);return { id: generation.id, ctrl };});65 unmodified lines}}async function executeHordeGeneration(messages: ChatMessage[],onUpdate: (text: string) => void,): Promise<string> {const settings = getSettings();if (settings.hordeModel) {const generation = await startGeneration(messages, undefined, [settings.hordeModel,]);return await handleGenerationStatus(generation.id, onUpdate);}let topModels: string[] = [];try {topModels = await getTopHordeModels();} catch (error) {addLogEntry(`Failed to rank AI Horde models by requests this month, falling back to any available model: ${error}`,);}// The ranking fetch widened the window between the user pressing stop and// the jobs being submitted; close it before submitting.if (getTextGenerationState() === "interrupted") {throw new ChatGenerationError("Generation interrupted");}try {return await raceGenerations(messages,topModels.length > 0 ? topModels : undefined,onUpdate,);} catch (error) {if (topModels.length > 0 &&error instanceof ChatGenerationError &&error.message === GENERATION_NOT_POSSIBLE_MESSAGE) {addLogEntry("None of the top AI Horde models could take the generation, retrying with any available model",);return await raceGenerations(messages, undefined, onUpdate);}throw error;}}function formatPrompt(messages: ChatMessage[]): string {return `${messages.map((msg) => `**${msg.role?.toUpperCase()}**:\n${msg.content}`)
121 unmodified lines1221231241251261271281291301311328 unmodified lines141142143144145146147121 unmodified lines**How It Works:**1. Request sent to AI Horde API2. Distributed to volunteer workers3. Multiple workers may process in parallel4. First response wins (race condition handling)5. Results streamed back**Features:**8 unmodified lines{inferenceType: 'horde',hordeApiKey: '0000000000', // Default anonymous key; set your own for priorityhordeModel: '' // Optional; empty races two random workers and uses the first response}```121 unmodified lines1221231241251261271281291301311321338 unmodified lines142143144145146147148121 unmodified lines**How It Works:**1. With no model selected, the five text models with online workers that have the most requests this month are picked (cached for 5 minutes)2. Request sent to AI Horde API3. Distributed to volunteer workers4. Multiple workers may process in parallel5. First response wins (race condition handling)6. Results streamed back**Features:**8 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| `allowAiModelDownload` | boolean | `false` | Allow automatic AI model downloads || `wllamaModelId` | string | WebGPU or CPU default, see above. | Default Wllama model ID, chosen by whether the browser has WebGPU || `hordeApiKey` | string | `'0000000000'` | AI Horde API key (default is anonymous) || `hordeModel` | string | `''` | Specific AI Horde model to request || `openAiApiBaseUrl` | string | `''` | Base URL for the OpenAI-compatible API || `openAiApiKey` | string | `''` | API key for the OpenAI-compatible API || `openAiApiModel` | string | `''` | Model identifier for the OpenAI-compatible API |143 unmodified lines144145146147148149150143 unmodified lines| `allowAiModelDownload` | boolean | `false` | Allow automatic AI model downloads || `wllamaModelId` | string | WebGPU or CPU default, see above. | Default Wllama model ID, chosen by whether the browser has WebGPU || `hordeApiKey` | string | `'0000000000'` | AI Horde API key (default is anonymous) || `hordeModel` | string | `''` | Specific AI Horde model to request; empty asks for the five most requested models this month || `openAiApiBaseUrl` | string | `''` | Base URL for the OpenAI-compatible API || `openAiApiKey` | string | `''` | API key for the OpenAI-compatible API || `openAiApiModel` | string | `''` | Model identifier for the OpenAI-compatible API |
changelog.md+4
client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx+1-1
client/modules/textGenerationWithHorde.test.ts+216
client/modules/textGenerationWithHorde.ts+136-15
docs/ai-integration.md+7-6
docs/configuration.md+1-1