Spaces:
Running
Running
Sync from felladrin/MiniSearch@9686d62
Browse filesFiles changed (40)
- .source-commit+1-1
- agents.md+2-1
- changelog.md+9
- client/components/AiResponse/AiResponseContent.test.tsx+162-10
- client/components/AiResponse/AiResponseContent.tsx+95-2
- client/components/AiResponse/CopyIconButton.tsx+5-1
- client/components/Pages/Main/Menu/SearchSettingsForm.tsx+12
- client/components/Pages/Main/Menu/SettingsForms.test.tsx+33
- client/components/Search/Results/Textual/TextSearchResults.test.tsx+77
- client/components/Search/Results/Textual/TextSearchResults.tsx+26-2
- client/components/Search/Results/Textual/UnitConversionCard.tsxAdded+23
- client/hooks/useHistoryRestore.ts+7
- client/modules/answerExport.test.tsAdded+278
- client/modules/answerExport.tsAdded+141
- client/modules/chatHelpers.test.ts+32-4
- client/modules/chatHelpers.ts+15-2
- client/modules/generationRate.test.tsAdded+104
- client/modules/generationRate.tsAdded+82
- client/modules/history.test.ts+54
- client/modules/history.ts+2-1
- client/modules/imageResultKey.test.tsAdded+27
- client/modules/imageResultKey.ts+4-6
- client/modules/pubSub.test.ts+10
- client/modules/pubSub.ts+31
- client/modules/search.test.ts+215
- client/modules/search.ts+128-13
- client/modules/settings.ts+13-2
- client/modules/stringFormatters.test.ts+25
- client/modules/stringFormatters.ts+9-2
- client/modules/textGeneration.degradation.test.ts+31
- client/modules/textGeneration.test.ts+1
- client/modules/textGeneration.ts+28-1
- client/modules/textGenerationTestUtils.ts+3
- client/modules/textGenerationWithHorde.test.ts+21
- client/modules/textGenerationWithOpenAi.test.ts+91
- client/modules/textGenerationWithOpenAi.ts+34-1
- client/modules/textGenerationWithWllama.test.ts+87
- client/modules/textGenerationWithWllama.ts+17
- docs/api.md+45-10
- docs/configuration.md+2-1
1ebacf2619686d62
131 unmodified lines1321331341351361371384 unmodified lines143144145146147148131 unmodified lines- `client/modules/querySuggestions.ts` - Search suggestion UI, stored in IndexedDB- `client/modules/relatedSearchQuery.ts` - Generates related search queries- `client/modules/searchResultSelection.ts` - Picks the results the answer reads, by score when they carry one- `client/modules/imageResultKey.ts` - Identifies an image result by its full-size source, then its thumbnail, since one page can hold several images- `client/modules/searchAttempts.ts` - The newest search attempt per search run, so a late result can tell it was replaced by a retry that kept the run id- `client/modules/followUpQuestions.ts` - Generates follow-up questions via `followUpQuestionPubSub`- `client/modules/accessKey.ts` - Validates and stores access keys using argon2id hashing and localStorage4 unmodified lines- `client/modules/pageExcerptWorker.ts` - Tokenizes page bodies off the main thread at the search-to-generation handoff- `client/modules/pageExcerptWorkerProtocol.ts` - Message types shared by both sides of the excerpt worker- `client/modules/systemPrompt.ts` - System prompt templates- `client/modules/logEntries.ts` - Application logging with unique IDs- `client/modules/appInfo.ts` - Application metadata and version info- `client/modules/textToSpeech.ts` - Reads answers aloud: engine selection, fallback, and the playback queue131 unmodified lines1321331341351361371384 unmodified lines143144145146147148149131 unmodified lines- `client/modules/querySuggestions.ts` - Search suggestion UI, stored in IndexedDB- `client/modules/relatedSearchQuery.ts` - Generates related search queries- `client/modules/searchResultSelection.ts` - Picks the results the answer reads, by score when they carry one- `client/modules/imageResultKey.ts` - Identifies an image result tuple through `shared/imageIdentity.ts`: its full-size source, then its thumbnail, then its page, since one page can hold several images. The server's dedupe and the history merge use the same function- `client/modules/searchAttempts.ts` - The newest search attempt per search run, so a late result can tell it was replaced by a retry that kept the run id- `client/modules/followUpQuestions.ts` - Generates follow-up questions via `followUpQuestionPubSub`- `client/modules/accessKey.ts` - Validates and stores access keys using argon2id hashing and localStorage4 unmodified lines- `client/modules/pageExcerptWorker.ts` - Tokenizes page bodies off the main thread at the search-to-generation handoff- `client/modules/pageExcerptWorkerProtocol.ts` - Message types shared by both sides of the excerpt worker- `client/modules/systemPrompt.ts` - System prompt templates- `client/modules/answerExport.ts` - Builds the Markdown export of an answer, with a file name taken from the query- `client/modules/logEntries.ts` - Application logging with unique IDs- `client/modules/appInfo.ts` - Application metadata and version info- `client/modules/textToSpeech.ts` - Reads answers aloud: engine selection, fallback, and the playback queue
1 unmodified line234567891 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-28- An in-browser model that is already downloaded now loads without asking Hugging Face first. Every load used to request the model's file list from the Hugging Face API before it looked at the browser's cache, twice per answer, so an API outage, a rate limit or a blocked `huggingface.co` stopped answers for a model that was already on the device. Models now load straight from their file URL, which is also the address the cache stores them under.- A follow-up question saved after its search was deleted from History is no longer stored. It used to be written anyway with no search pointing to it, leaving orphaned chat rows in the browser's storage.- Searches can be limited to the past day, week, month or year. The time filter sits next to the Search button and in the search settings, both bound to one setting that survives a reload, and SearXNG gets its `time_range` for it. Anytime is the default and sends nothing, so an unfiltered search reaches SearXNG exactly as it did before. The AI prompt keeps using the query as typed, so only the results are shaped by the period. When SearXNG is down and a fallback provider answers instead, that provider takes only a query and a count and cannot filter by time, so the results now say "Time filter not applied to these results" instead of looking filtered; `/search/text` announces it with an `X-Search-Time-Range-Applied: false` response header, and a search served from the browser's cache keeps saying it.1 unmodified line234567891011121314151617181 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-29- Future timestamps now show their locale date instead of being reported as just now.- History date groups now use calendar-day boundaries, so entries stay in the correct bucket across daylight-saving transitions.## 2026-11-28- A unit conversion now shows as an instant answer, with no model in the loop. SearXNG already works one out for a query like `5 m to ft` (it answers `16.4041994751 ft`); MiniSearch was throwing that answer away. It now shows in a small "Unit conversion" card above the results, and it shows even when the search found no web results at all: the converter reads the query itself and needs no search engine, so a conversion still answers on an instance whose engines are blocked, rate-limited or down, as long as the request reaches SearXNG (it does not while the search circuit is open, which is most of the time on the Hugging Face Space). When the engines are the ones that failed and a fallback search is configured, the fallback still supplies the web results. Only the converter's own answers are shown. An engine's are not: the currency engine read `5 m to ft` as `5.0 LSL = 97.4461855875 HUF`. The value is kept with the cached results, so a search served from the cache shows it too.- Answers now say how fast they came. A finished answer carries a muted line with its generation speed, for example `42 tokens/s`, and only when the speed is known exactly. The browser model reports its own decode speed, so loading the model, which it does again for every answer, stays out of it. An OpenAI-compatible API shows a speed when its backend reports how many tokens it wrote, and MiniSearch now asks it to. The instance's own AI and AI Horde show none, because neither reports a token count. Nothing shows while an answer is still coming.- The answer can now be exported as Markdown. The answer card gains "Copy as Markdown" and "Download .md" next to "Copy response". What they give you is the answer exactly as it was written, then a "Sources" section numbering the results the answer was grounded on, then one line saying what was searched and when. An answer already cites each fact with a link of its own, so the export adds no `[1]` markers and rewrites nothing in the answer. The file holds the query, the answer, the source titles and URLs and the date, and nothing else: no model name, no instance address, no settings. The downloaded file is named after the query, in a name every file system accepts.- Searches can now be limited to a language, from Search Language in the search settings. It defaults to Browser language, which sends the browser's own locale (or just its language when SearXNG can't take the full locale, so `es-419` sends `es`). Detect from the query keeps the old behavior, Any language sends no preference, and the list offers the common locales by name. MiniSearch used to send SearXNG a `lang` parameter it never reads, so SearXNG always used its own default. The answer still follows the language of the question. When a fallback provider answers, the note above the results now says which filters it could not apply.- An in-browser model that is already downloaded now loads without asking Hugging Face first. Every load used to request the model's file list from the Hugging Face API before it looked at the browser's cache, twice per answer, so an API outage, a rate limit or a blocked `huggingface.co` stopped answers for a model that was already on the device. Models now load straight from their file URL, which is also the address the cache stores them under.- A follow-up question saved after its search was deleted from History is no longer stored. It used to be written anyway with no search pointing to it, leaving orphaned chat rows in the browser's storage.- Searches can be limited to the past day, week, month or year. The time filter sits next to the Search button and in the search settings, both bound to one setting that survives a reload, and SearXNG gets its `time_range` for it. Anytime is the default and sends nothing, so an unfiltered search reaches SearXNG exactly as it did before. The AI prompt keeps using the query as typed, so only the results are shaped by the period. When SearXNG is down and a fallback provider answers instead, that provider takes only a query and a count and cannot filter by time, so the results now say "Time filter not applied to these results" instead of looking filtered; `/search/text` announces it with an `X-Search-Time-Range-Applied: false` response header, and a search served from the browser's cache keeps saying it.
1234567891011121320 unmodified lines3435363738394041424344454647484950515266 unmodified lines119120121122import { MantineProvider } from "@mantine/core";import { render, screen } from "@testing-library/react";import { usePubSub } from "create-pubsub/react";import { beforeEach, describe, expect, it, vi } from "vitest";import AiResponseContent from "./AiResponseContent";vi.mock("create-pubsub/react", () => ({usePubSub: vi.fn(),}));vi.mock("@/modules/textGeneration", () => ({interruptSearch: vi.fn(),searchAndRespond: vi.fn(),20 unmodified lines),}));function renderContent(textGenerationState: string) {vi.mocked(usePubSub).mockReturnValueOnce([{ enableAiResponseScrolling: false }, vi.fn()]).mockReturnValueOnce(["idle", vi.fn()]);return render(<MantineProvider><AiResponseContenttextGenerationState={textGenerationState}response="Hello world"/></MantineProvider>,);}describe("AiResponseContent", () => {66 unmodified linesscreen.getByRole("button", { name: "Regenerate response" }),).toBeInTheDocument();});});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495020 unmodified lines717273747576777879808182838485868788899091929394959697989910010110210310410510666 unmodified lines173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274import { MantineProvider } from "@mantine/core";import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { usePubSub } from "create-pubsub/react";import { beforeEach, describe, expect, it, vi } from "vitest";import {buildAnswerFileName,buildAnswerMarkdown,downloadAnswerMarkdown,} from "@/modules/answerExport";import AiResponseContent from "./AiResponseContent";vi.mock("create-pubsub/react", () => ({usePubSub: vi.fn(),}));const liveSources = vi.hoisted(() => ({current: [["Mercury - Wikipedia", "snippet", "https://en.wikipedia.org"]] as [string,string,string,][],}));vi.mock("@/modules/pubSub", async (importOriginal) => ({...(await importOriginal<typeof import("@/modules/pubSub")>()),getQuery: vi.fn(() => "mercury"),getLlmTextSearchResults: vi.fn(() => liveSources.current),}));vi.mock("@/modules/answerExport", () => ({buildAnswerMarkdown: vi.fn(() => "exported markdown"),buildAnswerFileName: vi.fn(() => "mercury.md"),downloadAnswerMarkdown: vi.fn(),}));// Show the text each copy button would put on the clipboard.vi.mock("./CopyIconButton", () => ({default: ({value,tooltipLabel,}: {value: string;tooltipLabel?: string;}) => <button type="button" aria-label={tooltipLabel} data-value={value} />,}));vi.mock("@/modules/textGeneration", () => ({interruptSearch: vi.fn(),searchAndRespond: vi.fn(),20 unmodified lines),}));const settings = {enableAiResponseScrolling: false,reasoningStartMarker: "<think>",reasoningEndMarker: "</think>",};function renderContent(textGenerationState: string,response = "Hello world",generationRate?: string,) {// Each render reads the settings, the speech state, then the speed.let call = 0;vi.mocked(usePubSub).mockImplementation(() => {const slot = call++ % 3;if (slot === 0) return [settings, vi.fn()];if (slot === 1) return ["idle", vi.fn()];return [generationRate, vi.fn()];});const ui = (state: string) => (<MantineProvider><AiResponseContent textGenerationState={state} response={response} /></MantineProvider>);const result = render(ui(textGenerationState));return {...result,rerenderWith: (state: string) => result.rerender(ui(state)),};}describe("AiResponseContent", () => {66 unmodified linesscreen.getByRole("button", { name: "Regenerate response" }),).toBeInTheDocument();});it("keeps copying the raw response and adds the export next to it", () => {renderContent("completed");expect(buildAnswerMarkdown).toHaveBeenCalledWith(expect.objectContaining({ answer: "Hello world" }),);expect(screen.getByRole("button", { name: "Copy response" }),).toHaveAttribute("data-value", "Hello world");expect(screen.getByRole("button", { name: "Copy as Markdown" }),).toHaveAttribute("data-value", "exported markdown");});it("downloads the built markdown under a name from the query", async () => {renderContent("completed");await userEvent.click(screen.getByRole("button", { name: "Download as Markdown" }),);expect(downloadAnswerMarkdown).toHaveBeenCalledWith("exported markdown","mercury.md",);expect(buildAnswerFileName).toHaveBeenCalledWith("mercury");});it("exports the answer without its reasoning", () => {renderContent("completed", "<think>Let me check.</think>Mercury is small.");expect(buildAnswerMarkdown).toHaveBeenLastCalledWith(expect.objectContaining({ answer: "Mercury is small." }),);});it("keeps the sources the answer finished with after a follow-up replaces them", () => {const { rerenderWith } = renderContent("completed");liveSources.current = [["Follow-up result", "snippet", "https://other.org"],];rerenderWith("completed");expect(buildAnswerMarkdown).toHaveBeenLastCalledWith(expect.objectContaining({sources: [["Mercury - Wikipedia", "snippet", "https://en.wikipedia.org"],],}),);liveSources.current = [["Mercury - Wikipedia", "snippet", "https://en.wikipedia.org"],];});it("strips the prompt's image tag from a source title", () => {liveSources.current = [["(image) A diagram", "", "https://example.com/d"]];renderContent("completed");expect(buildAnswerMarkdown).toHaveBeenLastCalledWith(expect.objectContaining({sources: [["A diagram", "", "https://example.com/d"]],}),);liveSources.current = [["Mercury - Wikipedia", "snippet", "https://en.wikipedia.org"],];});it("offers the export only once the answer is complete", () => {renderContent("generating");expect(screen.queryByRole("button", { name: "Copy as Markdown" }),).not.toBeInTheDocument();expect(screen.queryByRole("button", { name: "Download as Markdown" }),).not.toBeInTheDocument();});it("shows the generation speed once it is known", () => {renderContent("completed", "Hello world", "42 tokens/s");expect(screen.getByText("42 tokens/s")).toBeInTheDocument();});it("shows no generation speed while the answer is still generating", () => {renderContent("generating", "Hello world", "42 tokens/s");expect(screen.queryByText("42 tokens/s")).not.toBeInTheDocument();});it("shows no generation speed when none is known", () => {renderContent("completed");expect(screen.queryByText(/tokens\/s/)).not.toBeInTheDocument();});});
11 unmodified lines121314151617181920212223242526276 unmodified lines3435363738394041100 unmodified lines1421431441451461475 unmodified lines15315415515615715811 unmodified linesimport {IconArrowsMaximize,IconArrowsMinimize,IconHandStop,IconInfoCircle,IconRefresh,IconVolume2,} from "@tabler/icons-react";import { usePubSub } from "create-pubsub/react";import { type ReactNode, useMemo } from "react";import { settingsPubSub, textToSpeechStatePubSub } from "@/modules/pubSub";import { interruptSearch, searchAndRespond } from "@/modules/textGeneration";import { speak } from "@/modules/textToSpeech";import CopyIconButton from "./CopyIconButton";import FormattedMarkdown from "./FormattedMarkdown";6 unmodified lines}) {const [settings, setSettings] = usePubSub(settingsPubSub);const [textToSpeechState] = usePubSub(textToSpeechStatePubSub);const isSpeaking = textToSpeechState === "speaking";const isGenerating = textGenerationState === "generating";const ConditionalScrollArea = useMemo(() =>100 unmodified lines</Tooltip>)}<CopyIconButton value={response} tooltipLabel="Copy response" /></Group></Group></Card.Section>5 unmodified lines</FormattedMarkdown></Box></ConditionalScrollArea>{textGenerationState === "failed" && (<Alertvariant="light"11 unmodified lines12131415161718192021222324252627282930313233343536373839404142436 unmodified lines5051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101100 unmodified lines2022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342355 unmodified lines24124224324424524624724824925025111 unmodified linesimport {IconArrowsMaximize,IconArrowsMinimize,IconDownload,IconHandStop,IconInfoCircle,IconMarkdown,IconRefresh,IconVolume2,} from "@tabler/icons-react";import { usePubSub } from "create-pubsub/react";import { type ReactNode, useEffect, useMemo, useState } from "react";import {buildAnswerFileName,buildAnswerMarkdown,downloadAnswerMarkdown,} from "@/modules/answerExport";import {generationRatePubSub,getLlmTextSearchResults,getQuery,settingsPubSub,textToSpeechStatePubSub,} from "@/modules/pubSub";import { splitReasoning } from "@/modules/reasoning";import { interruptSearch, searchAndRespond } from "@/modules/textGeneration";import { imageResultTag } from "@/modules/textGenerationUtilities";import { speak } from "@/modules/textToSpeech";import type { TextSearchResults } from "@/modules/types";import CopyIconButton from "./CopyIconButton";import FormattedMarkdown from "./FormattedMarkdown";6 unmodified lines}) {const [settings, setSettings] = usePubSub(settingsPubSub);const [textToSpeechState] = usePubSub(textToSpeechStatePubSub);const [generationRate] = usePubSub(generationRatePubSub);const isSpeaking = textToSpeechState === "speaking";const isGenerating = textGenerationState === "generating";const isCompleted = textGenerationState === "completed";const query = getQuery();// Taken when the answer finishes: a follow-up replaces the live list with// its own results, and this card still shows the first answer. The image// tag is the prompt's own marker, not part of a title.const [answerSources, setAnswerSources] = useState<TextSearchResults>([]);useEffect(() => {if (!isCompleted || !response) return;setAnswerSources(getLlmTextSearchResults().map(([title, snippet, url]) => [title.startsWith(imageResultTag)? title.slice(imageResultTag.length): title,snippet,url,]),);}, [isCompleted, response]);const exportMarkdown = useMemo(() =>isCompleted? buildAnswerMarkdown({// The answer only: the reasoning block stays out of the file, as// it stays folded on the card.answer: splitReasoning(response,settings.reasoningStartMarker,settings.reasoningEndMarker,).answer,sources: answerSources,query,exportedAt: new Date(),}): "",[isCompleted,response,answerSources,query,settings.reasoningStartMarker,settings.reasoningEndMarker,],);const ConditionalScrollArea = useMemo(() =>100 unmodified lines</Tooltip>)}<CopyIconButton value={response} tooltipLabel="Copy response" />{isCompleted && (<><CopyIconButtonvalue={exportMarkdown}tooltipLabel="Copy as Markdown"icon={<IconMarkdown size={16} />}/><Tooltiplabel="Download as Markdown"withArrowposition="right"><ActionIconaria-label="Download as Markdown"onClick={() =>downloadAnswerMarkdown(exportMarkdown,buildAnswerFileName(query),)}variant="subtle"color="gray"><IconDownload size={16} /></ActionIcon></Tooltip></>)}</Group></Group></Card.Section>5 unmodified lines</FormattedMarkdown></Box></ConditionalScrollArea>{generationRate && textGenerationState !== "generating" && (<Text size="xs" c="dimmed" px="lg" pb="sm">{generationRate}</Text>)}{textGenerationState === "failed" && (<Alertvariant="light"
12345678910111213149 unmodified lines24252627282930import { ActionIcon, CopyButton, Tooltip } from "@mantine/core";import { IconCheck, IconCopy } from "@tabler/icons-react";interface CopyIconButtonProps {value: string;tooltipLabel?: string;}export default function CopyIconButton({value,tooltipLabel = "Copy",}: CopyIconButtonProps) {return (<CopyButton value={value} timeout={2000}>9 unmodified linesvariant="subtle"onClick={copy}>{copied ? <IconCheck size={16} /> : <IconCopy size={16} />}</ActionIcon></Tooltip>)}1234567891011121314151617189 unmodified lines28293031323334import { ActionIcon, CopyButton, Tooltip } from "@mantine/core";import { IconCheck, IconCopy } from "@tabler/icons-react";import type { ReactNode } from "react";interface CopyIconButtonProps {value: string;tooltipLabel?: string;/** Shown instead of the copy icon, so two copy buttons side by side differ. */icon?: ReactNode;}export default function CopyIconButton({value,tooltipLabel = "Copy",icon = <IconCopy size={16} />,}: CopyIconButtonProps) {return (<CopyButton value={value} timeout={2000}>9 unmodified linesvariant="subtle"onClick={copy}>{copied ? <IconCheck size={16} /> : icon}</ActionIcon></Tooltip>)}
1234567891029 unmodified lines404142434445import { Select, Slider, Stack, Switch, Text } from "@mantine/core";import { searchTimeRangeOptions } from "@shared/searchTimeRange";import { useSettingsForm } from "@/hooks/useSettingsForm";const SETTINGS_KEYS = ["searchResultsLimit","searchTimeRange","enableTextSearch","enableImageSearch",] as const;29 unmodified linesallowDeselect={false}/><Switch{...form.getInputProps("enableTextSearch", {type: "checkbox",12345678910111229 unmodified lines42434445464748495051525354555657import { Select, Slider, Stack, Switch, Text } from "@mantine/core";import { searchLanguageOptions } from "@shared/searchLanguage";import { searchTimeRangeOptions } from "@shared/searchTimeRange";import { useSettingsForm } from "@/hooks/useSettingsForm";const SETTINGS_KEYS = ["searchResultsLimit","searchTimeRange","searchLanguage","enableTextSearch","enableImageSearch",] as const;29 unmodified linesallowDeselect={false}/><Select{...form.getInputProps("searchLanguage")}label="Search Language"// The answer is not what this changes: it keeps following the question.description="Which language the results come back in. Browser language sends your browser's own locale, Detect from the query lets the search engine guess, and Any language asks for no preference. The answer still follows the language of the question."data={searchLanguageOptions}searchableallowDeselect={false}/><Switch{...form.getInputProps("enableTextSearch", {type: "checkbox",
29 unmodified lines30313233343549 unmodified lines8586878829 unmodified linesfireEvent.click(within(listbox).getByText(label));}describe("the menu's settings forms", () => {beforeEach(() => {updateSettings(defaultSettings);49 unmodified linesexpect(getSettings()).toMatchObject({ searchTimeRange: "week" });});});29 unmodified lines303132333435363738394041424344454647484950515249 unmodified lines10210310410510610710810911011111211311411511611711811912012129 unmodified linesfireEvent.click(within(listbox).getByText(label));}/*** Types `search` into the language select to filter it, then picks the option* with this label. The typing is the point: the list is long enough that a* reader has to search it.*/function pickLanguage(search: string, label: string) {const select = screen.getByRole("combobox", { name: /search language/i });fireEvent.mouseDown(select);fireEvent.click(select);fireEvent.change(select, { target: { value: search } });const listbox = document.getElementById(select.getAttribute("aria-controls") ?? "",);if (!listbox) throw new Error("The select did not render a listbox");fireEvent.click(within(listbox).getByText(label));}describe("the menu's settings forms", () => {beforeEach(() => {updateSettings(defaultSettings);49 unmodified linesexpect(getSettings()).toMatchObject({ searchTimeRange: "week" });});it("writes the language chosen in the search section", () => {render(<MantineProvider><SearchSettingsForm /></MantineProvider>,);expect(screen.getByRole("combobox", { name: /search language/i }),).toHaveValue("Browser language");pickLanguage("portug", "Portuguรชs (Brasil)");expect(getSettings()).toMatchObject({ searchLanguage: "pt-BR" });});});
1 unmodified line23456789101112 unmodified lines24252627282930313233343516 unmodified lines52535455565721 unmodified lines798081821 unmodified lineimport { act, render, screen } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {textSearchResultsPubSub,textSearchStalePubSub,textSearchStatePubSub,textSearchTimeFilterPubSub,} from "@/modules/pubSub";import type { TextSearchResults as TextSearchResultList } from "@/modules/types";import TextSearchResults from "./TextSearchResults";12 unmodified linesconst [setTextSearchResults] = textSearchResultsPubSub;const [setTextSearchStale] = textSearchStalePubSub;const [setTextSearchTimeFilterNotApplied] = textSearchTimeFilterPubSub;const results: TextSearchResultList = [["A result", "Its snippet", "https://example.com"],];const NOTE = "Time filter not applied to these results";function renderTextSearchResults() {return render(16 unmodified linessetTextSearchResults([]);setTextSearchStale(false);setTextSearchTimeFilterNotApplied(false);});});21 unmodified linesexpect(screen.queryByText(NOTE)).not.toBeInTheDocument();});});1 unmodified line234567891011121312 unmodified lines26272829303132333435363738394041424316 unmodified lines606162636465666721 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591 unmodified lineimport { act, render, screen } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {textSearchLanguagePubSub,textSearchResultsPubSub,textSearchStalePubSub,textSearchStatePubSub,textSearchTimeFilterPubSub,textSearchUnitConversionPubSub,} from "@/modules/pubSub";import type { TextSearchResults as TextSearchResultList } from "@/modules/types";import TextSearchResults from "./TextSearchResults";12 unmodified linesconst [setTextSearchResults] = textSearchResultsPubSub;const [setTextSearchStale] = textSearchStalePubSub;const [setTextSearchTimeFilterNotApplied] = textSearchTimeFilterPubSub;const [setTextSearchLanguageNotApplied] = textSearchLanguagePubSub;const [setTextSearchUnitConversion] = textSearchUnitConversionPubSub;const results: TextSearchResultList = [["A result", "Its snippet", "https://example.com"],];const NOTE = "Time filter not applied to these results";const LANGUAGE_NOTE = "Language not applied to these results";const BOTH_NOTE = "Time filter and language not applied to these results";const CONVERSION = "16.4041994751 ft";const NO_RESULTS = "No results found";function renderTextSearchResults() {return render(16 unmodified linessetTextSearchResults([]);setTextSearchStale(false);setTextSearchTimeFilterNotApplied(false);setTextSearchLanguageNotApplied(false);setTextSearchUnitConversion(null);});});21 unmodified linesexpect(screen.queryByText(NOTE)).not.toBeInTheDocument();});it("says when the results carry no language although one was asked for", () => {act(() => setTextSearchLanguageNotApplied(true));renderTextSearchResults();expect(screen.getByText(LANGUAGE_NOTE)).toBeInTheDocument();expect(screen.queryByText(NOTE)).not.toBeInTheDocument();});it("names both filters when neither was applied", () => {act(() => {setTextSearchTimeFilterNotApplied(true);setTextSearchLanguageNotApplied(true);});renderTextSearchResults();expect(screen.getByText(BOTH_NOTE)).toBeInTheDocument();// One note for both, not two notes for the same outage.expect(screen.queryByText(NOTE)).not.toBeInTheDocument();expect(screen.queryByText(LANGUAGE_NOTE)).not.toBeInTheDocument();});it("shows the conversion the search came back with above the results", () => {act(() => setTextSearchUnitConversion(CONVERSION));renderTextSearchResults();expect(screen.getByText("Unit conversion")).toBeInTheDocument();expect(screen.getByText(CONVERSION)).toBeInTheDocument();expect(screen.getByLabelText("Text results")).toBeInTheDocument();});it("shows the conversion on its own when the search found no results", () => {act(() => {setTextSearchResults([]);setTextSearchUnitConversion(CONVERSION);});renderTextSearchResults();expect(screen.getByText(CONVERSION)).toBeInTheDocument();// The conversion is the answer, so the empty-results alert contradicts it.expect(screen.queryByText(NO_RESULTS)).not.toBeInTheDocument();});it("shows no card when the search carried no conversion", () => {renderTextSearchResults();expect(screen.queryByText("Unit conversion")).not.toBeInTheDocument();expect(screen.getByLabelText("Text results")).toBeInTheDocument();});it("shows no card and the empty-results alert with neither a conversion nor results", () => {act(() => setTextSearchResults([]));renderTextSearchResults();expect(screen.queryByText("Unit conversion")).not.toBeInTheDocument();expect(screen.getByText(NO_RESULTS)).toBeInTheDocument();});it("renders a conversion as text, never as markup", () => {act(() => setTextSearchUnitConversion('<img src=x onerror="alert(1)">'));renderTextSearchResults();expect(screen.getByText('<img src=x onerror="alert(1)">'),).toBeInTheDocument();expect(document.querySelector("img")).toBeNull();});});
4 unmodified lines56789101112131415161718192021222324252 unmodified lines28293031323310 unmodified lines444546474849505152535455565758594 unmodified linesimageSearchResultsPubSub,imageSearchStatePubSub,settingsPubSub,textSearchResultsPubSub,textSearchStalePubSub,textSearchStatePubSub,textSearchTimeFilterPubSub,} from "@/modules/pubSub";import { searchAndRespond } from "@/modules/textGeneration";import SearchResultsList from "./SearchResultsList";import TextResultsLoadingState from "./TextResultsLoadingState";export default function TextSearchResults() {const [searchState] = usePubSub(textSearchStatePubSub);const [results] = usePubSub(textSearchResultsPubSub);const [stale] = usePubSub(textSearchStalePubSub);const [timeFilterNotApplied] = usePubSub(textSearchTimeFilterPubSub);const [imageState] = usePubSub(imageSearchStatePubSub);const [imageResults] = usePubSub(imageSearchResultsPubSub);const [settings] = usePubSub(settingsPubSub);2 unmodified linesreturn <TextResultsLoadingState />;}if (searchState === "completed") {if (results.length > 0) {return (10 unmodified linesresults are from an earlier search and may be out of date.</Alert>)}{timeFilterNotApplied && (<Text size="xs" c="dimmed" mb="sm">Time filter not applied to these results</Text>)}<SearchResultsList searchResults={results} /></>);}return (<Alertvariant="light"4 unmodified lines567891011121314151617181920212223242526272829302 unmodified lines333435363738394041424344454647484910 unmodified lines6061626364656667686970717273747576777879808182834 unmodified linesimageSearchResultsPubSub,imageSearchStatePubSub,settingsPubSub,textSearchLanguagePubSub,textSearchResultsPubSub,textSearchStalePubSub,textSearchStatePubSub,textSearchTimeFilterPubSub,textSearchUnitConversionPubSub,} from "@/modules/pubSub";import { searchAndRespond } from "@/modules/textGeneration";import SearchResultsList from "./SearchResultsList";import TextResultsLoadingState from "./TextResultsLoadingState";import UnitConversionCard from "./UnitConversionCard";export default function TextSearchResults() {const [searchState] = usePubSub(textSearchStatePubSub);const [results] = usePubSub(textSearchResultsPubSub);const [stale] = usePubSub(textSearchStalePubSub);const [timeFilterNotApplied] = usePubSub(textSearchTimeFilterPubSub);const [languageNotApplied] = usePubSub(textSearchLanguagePubSub);const [unitConversion] = usePubSub(textSearchUnitConversionPubSub);const [imageState] = usePubSub(imageSearchStatePubSub);const [imageResults] = usePubSub(imageSearchResultsPubSub);const [settings] = usePubSub(settingsPubSub);2 unmodified linesreturn <TextResultsLoadingState />;}// One note naming whichever filters the results are missing, so a search that// came back wide says so instead of passing for the narrow one that was// asked for.const unappliedNote = [timeFilterNotApplied && "time filter",languageNotApplied && "language",].filter(Boolean).join(" and ").replace(/^./, (first) => first.toUpperCase());if (searchState === "completed") {if (results.length > 0) {return (10 unmodified linesresults are from an earlier search and may be out of date.</Alert>)}{unappliedNote && (<Text size="xs" c="dimmed" mb="sm">{unappliedNote} not applied to these results</Text>)}{unitConversion && <UnitConversionCard value={unitConversion} />}<SearchResultsList searchResults={results} /></>);}// The unit converter needs no engine, so its answer can be all a search// brought back. Saying "no results found" under it would take back what// the card just said.if (unitConversion) {return <UnitConversionCard value={unitConversion} />;}return (<Alertvariant="light"
1234567891011121314151617181920212223import { Group, Paper, Text } from "@mantine/core";import { IconArrowsExchange } from "@tabler/icons-react";
/** * The value SearXNG's own unit converter plugin worked out for the query, shown * above the results it came with. The value is text from upstream and is * rendered as text, so nothing it carries can be read as markup. */export default function UnitConversionCard({ value }: { value: string }) { return ( <Paper withBorder radius="sm" p="sm" mb="sm"> <Group gap="sm"> <IconArrowsExchange size={18} aria-hidden /> <div> <Text size="xs" c="dimmed" fw={600}> Unit conversion </Text> <Text size="sm">{value}</Text> </div> </Group> </Paper> );}19 unmodified lines2021222324252 unmodified lines2829303132333435363751 unmodified lines89909192939444 unmodified lines13914014114214314419 unmodified linesupdateChatMessages,updateChatSession,updateFollowUpQuestion,updateImageSearchResults,updateImageSearchState,updateIsRestoringFromHistory,2 unmodified linesupdateResponseImmediately,updateSuppressNextFollowUp,updateTextGenerationState,updateTextSearchResults,updateTextSearchStale,updateTextSearchState,updateTextSearchTimeFilterNotApplied,} from "../modules/pubSub";import { cancelSearchAnswer } from "../modules/textGeneration";import type { ImageSearchResults, TextSearchResults } from "../modules/types";51 unmodified lines// The stored results carry no record of the filter they were found// with, so the note belongs to the search that is being replaced.updateTextSearchTimeFilterNotApplied(false);const results = hasTextResults(entry)? getResultsFromEntry(entry): null;44 unmodified lines}const savedResponse = await getLatestLlmResponseForEntry(entry);if (savedResponse && savedResponse.trim().length > 0) {updateSuppressNextFollowUp(true);// The restore publishes the whole stored answer at once; a throttled19 unmodified lines202122232425262 unmodified lines29303132333435363738394051 unmodified lines929394959697989944 unmodified lines14414514614714814915015119 unmodified linesupdateChatMessages,updateChatSession,updateFollowUpQuestion,updateGenerationRate,updateImageSearchResults,updateImageSearchState,updateIsRestoringFromHistory,2 unmodified linesupdateResponseImmediately,updateSuppressNextFollowUp,updateTextGenerationState,updateTextSearchLanguageNotApplied,updateTextSearchResults,updateTextSearchStale,updateTextSearchState,updateTextSearchTimeFilterNotApplied,updateTextSearchUnitConversion,} from "../modules/pubSub";import { cancelSearchAnswer } from "../modules/textGeneration";import type { ImageSearchResults, TextSearchResults } from "../modules/types";51 unmodified lines// The stored results carry no record of the filter they were found// with, so the note belongs to the search that is being replaced.updateTextSearchTimeFilterNotApplied(false);updateTextSearchLanguageNotApplied(false);updateTextSearchUnitConversion(null);const results = hasTextResults(entry)? getResultsFromEntry(entry): null;44 unmodified lines}const savedResponse = await getLatestLlmResponseForEntry(entry);// A stored answer was never timed here, so it shows no speed line.updateGenerationRate(undefined);if (savedResponse && savedResponse.trim().length > 0) {updateSuppressNextFollowUp(true);// The restore publishes the whole stored answer at once; a throttled
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278import { describe, expect, it, vi } from "vitest";import { buildAnswerFileName, buildAnswerMarkdown, downloadAnswerMarkdown,} from "./answerExport";import type { TextSearchResults } from "./types";
const exportedAt = new Date(2026, 10, 28);
const sources: TextSearchResults = [ [ "Mercury - Wikipedia", "Mercury is the smallest planet in the Solar System.", "https://en.wikipedia.org/wiki/Mercury", ], [ "NASA - Mercury", "Mercury orbits the Sun in 88 days.", "https://www.nasa.gov/mercury", ],];
describe("buildAnswerMarkdown", () => { it("writes the answer, the numbered sources and the footer", () => { const markdown = buildAnswerMarkdown({ answer: "Mercury is the smallest planet. It orbits the Sun in 88 days.", sources, query: "mercury planet", exportedAt, });
expect(markdown).toBe( [ "Mercury is the smallest planet. It orbits the Sun in 88 days.", "", "## Sources", "", "1. [Mercury - Wikipedia](https://en.wikipedia.org/wiki/Mercury)", "2. [NASA - Mercury](https://www.nasa.gov/mercury)", "", 'Searched for "mercury planet" with MiniSearch, exported on 2026-11-28', "", ].join("\n"), ); });
it("numbers the sources without adding markers to the answer", () => { const answer = "Mercury is the smallest planet [usgs.gov](https://www.usgs.gov/).\n\n[USGS][1].";
const markdown = buildAnswerMarkdown({ answer, sources, query: "mercury", exportedAt, });
expect(markdown.startsWith(`${answer}\n\n## Sources`)).toBe(true); expect(markdown).toContain("[usgs.gov](https://www.usgs.gov/)"); expect(markdown).toContain("[USGS][1]"); expect(markdown).not.toMatch(/^\[\d+\]/m); });
it("leaves out the Sources section when the answer has no sources", () => { const markdown = buildAnswerMarkdown({ answer: "Mercury is the smallest planet.", sources: [], query: "mercury", exportedAt, });
expect(markdown).toBe( 'Mercury is the smallest planet.\n\nSearched for "mercury" with MiniSearch, exported on 2026-11-28\n', ); });
it("keeps the export valid when the answer is empty", () => { const markdown = buildAnswerMarkdown({ answer: " \n\n ", sources: [sources[0]], query: "mercury", exportedAt, });
expect(markdown).toBe( [ "## Sources", "", "1. [Mercury - Wikipedia](https://en.wikipedia.org/wiki/Mercury)", "", 'Searched for "mercury" with MiniSearch, exported on 2026-11-28', "", ].join("\n"), ); expect(markdown).not.toMatch(/^#+\s*$/m); });
it("keeps the export valid when the answer and the sources are both empty", () => { expect( buildAnswerMarkdown({ answer: "", sources: [], query: "", exportedAt }), ).toBe("Searched with MiniSearch, exported on 2026-11-28\n"); });
it("skips a source with no URL and keeps the numbering in order", () => { const markdown = buildAnswerMarkdown({ answer: "Answer.", sources: [sources[0], ["No URL", "A snippet.", " "], sources[1]], query: "mercury", exportedAt, });
expect(markdown).toContain( [ "1. [Mercury - Wikipedia](https://en.wikipedia.org/wiki/Mercury)", "2. [NASA - Mercury](https://www.nasa.gov/mercury)", ].join("\n"), ); });
it("escapes brackets in a source title and falls back to the URL", () => { const markdown = buildAnswerMarkdown({ answer: "Answer.", sources: [ ["Grid [F] plan", "A snippet.", "https://example.com/grid"], [" ", "A snippet.", "https://example.com/untitled"], ], query: "grid", exportedAt, });
expect(markdown).toContain( "1. [Grid \\[F\\] plan](https://example.com/grid)", ); expect(markdown).toContain( "2. [https://example.com/untitled](https://example.com/untitled)", ); });
it("keeps markup in a source title and in the query as plain text", () => { const markdown = buildAnswerMarkdown({ answer: "Answer.", sources: [ [ "<img src=x onerror=alert(1)> *bold* `code` a_b & c | d ~e~", "A snippet.", "https://example.com/page", ], ], query: "<b>bees</b>", exportedAt, });
expect(markdown).toContain( "1. [\\<img src=x onerror=alert(1)\\> \\*bold\\* \\`code\\` a\\_b \\& c \\| d \\~e\\~](https://example.com/page)", ); expect(markdown).toContain('Searched for "\\<b\\>bees\\</b\\>"'); });
it("percent-encodes URL characters that would end the link, and drops non-web links", () => { const markdown = buildAnswerMarkdown({ answer: "Answer.", sources: [ ["Spaces", "A snippet.", "https://example.com/a b(c)<d>"], ["Script", "A snippet.", "javascript:alert(1)"], ["Plain", "A snippet.", "https://example.com/plain"], ], query: "links", exportedAt, });
expect(markdown).toContain( "1. [Spaces](https://example.com/a%20b%28c%29%3Cd%3E)", ); expect(markdown).not.toContain("javascript:"); expect(markdown).toContain("2. [Plain](https://example.com/plain)"); });
it("keeps a query that spans lines on one footer line", () => { const markdown = buildAnswerMarkdown({ answer: "Answer.", sources: [], query: "mercury\n probe", exportedAt, });
expect(markdown).toContain('Searched for "mercury probe" with MiniSearch'); });});
describe("buildAnswerFileName", () => { it("keeps the words of the query", () => { expect(buildAnswerFileName("mercury planet")).toBe("mercury planet.md"); expect(buildAnswerFileName("computaรงรฃo quรขntica")).toBe( "computaรงรฃo quรขntica.md", ); });
it("keeps combining marks, in either normal form, inside words", () => { expect(buildAnswerFileName("เคนเคฟเคจเฅเคฆเฅ เคญเคพเคทเคพ")).toBe("เคนเคฟเคจเฅเคฆเฅ เคญเคพเคทเคพ.md"); expect(buildAnswerFileName("computac\u0327a\u0303o")).toBe("computaรงรฃo.md"); });
it("never splits a character when it bounds the length", () => { // A CJK ideograph outside the Basic Multilingual Plane: one letter, two // UTF-16 units. const name = buildAnswerFileName("๐ ".repeat(70)); expect(name).toBe(`${"๐ ".repeat(60)}.md`); });
it("replaces path separators and characters Windows refuses", () => { expect(buildAnswerFileName('a/b\\c:d*e?f"g<h>i|j')).toBe( "a-b-c-d-e-f-g-h-i-j.md", ); expect(buildAnswerFileName("../etc/passwd")).toBe("etc-passwd.md"); expect(buildAnswerFileName('mercury: the "planet"')).toBe( "mercury-the-planet.md", ); });
it("refuses a name Windows reserves for a device", () => { expect(buildAnswerFileName("con")).toBe("_con.md"); expect(buildAnswerFileName("con.txt")).toBe("_con.txt.md"); expect(buildAnswerFileName("com1")).toBe("_com1.md"); });
it("bounds the length of a very long query", () => { expect(buildAnswerFileName(`${"a".repeat(59)} bb`)).toBe( `${"a".repeat(59)}.md`, ); expect(buildAnswerFileName("x".repeat(500)).length).toBe(63); });
it("falls back to a plain name when the query gives nothing", () => { expect(buildAnswerFileName("")).toBe("answer.md"); expect(buildAnswerFileName(" ")).toBe("answer.md"); expect(buildAnswerFileName("???")).toBe("answer.md"); expect(buildAnswerFileName("...")).toBe("answer.md"); });});
describe("downloadAnswerMarkdown", () => { it("saves the markdown and releases the object URL", async () => { let link: HTMLAnchorElement | undefined; let blob: Blob | undefined; const createObjectURL = vi.fn((value: Blob) => { blob = value; return "blob:answer"; }); const revokeObjectURL = vi.fn();
vi.stubGlobal("URL", { createObjectURL, revokeObjectURL }); vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function ( this: HTMLAnchorElement, ) { link = this; });
vi.useFakeTimers(); try { downloadAnswerMarkdown("Answer.", "mercury.md"); // Not released during the click, only a moment later. expect(revokeObjectURL).not.toHaveBeenCalled(); vi.advanceTimersByTime(1000); } finally { vi.useRealTimers(); vi.spyOn(HTMLAnchorElement.prototype, "click").mockRestore(); vi.unstubAllGlobals(); }
expect(blob?.type).toBe("text/markdown"); expect(await blob?.text()).toBe("Answer."); expect(link?.download).toBe("mercury.md"); expect(link?.href).toBe("blob:answer"); expect(revokeObjectURL).toHaveBeenCalledWith("blob:answer"); expect(document.querySelector("a")).toBeNull(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import type { TextSearchResults } from "./types";
interface AnswerExportParts { /** The answer's Markdown, as it was written. */ answer: string; /** The results the answer was grounded on, in the order they were read. */ sources: TextSearchResults; /** What was typed in the search field. */ query: string; /** When the file is exported. */ exportedAt: Date;}
const maxFileNameBaseLength = 60;const windowsReservedFileNames = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;// Marks are allowed so scripts that write vowels as combining marks (Devanagari,// Thai) keep whole words instead of getting a dash inside each one.const unsupportedFileNameCharacters = /[^\p{L}\p{M}\p{N} ._-]/gu;
/** * Renders an answer as a standalone Markdown document: the answer, then the * results it was grounded on, then one line saying what was searched and when. * * An answer cites its sources with inline Markdown links, so the source list * only lists what was read: no `[1]` marker is added to the answer, and the * answer's own text and links are never rewritten. Nothing but the query, the * answer, the source titles and URLs and the date goes into the file. */export function buildAnswerMarkdown({ answer, sources, query, exportedAt,}: AnswerExportParts): string { const sections: string[] = []; const body = answer.trim(); if (body) { sections.push(body); }
const items: string[] = []; for (const [title, , url] of sources) { const link = buildMarkdownLink(title, url); if (link) { items.push(`${items.length + 1}. ${link}`); } } if (items.length) { sections.push(`## Sources\n\n${items.join("\n")}`); }
// The export date, not the search date: an answer restored from history is // exported long after its search ran. const searchedFor = escapeInlineMarkdown(singleLine(query)); sections.push( `Searched${searchedFor ? ` for "${searchedFor}"` : ""} with MiniSearch, exported on ${formatDate(exportedAt)}`, );
return `${sections.join("\n\n")}\n`;}
/** A file name that survives every file system, bounded in length, ending in `.md`. */export function buildAnswerFileName(query: string): string { const cleaned = singleLine(query.normalize("NFC")) .replace(unsupportedFileNameCharacters, "-") .replace(/\s*-\s*/g, "-") .replace(/-{2,}/g, "-") .replace(/^[-.]+|[-.]+$/g, ""); // Counted in code points, so the cut never splits a surrogate pair. const base = Array.from(cleaned) .slice(0, maxFileNameBaseLength) .join("") .replace(/[-. ]+$/g, ""); // Windows reserves a device name whatever follows its first dot, so // `con.txt.md` fails as surely as `con.md`. const stem = windowsReservedFileNames.test(base.split(".")[0] ?? "") ? `_${base}` : base;
return `${stem || "answer"}.md`;}
/** Saves text as a file through an object URL, which is released afterwards. */export function downloadAnswerMarkdown( markdown: string, fileName: string,): void { const url = URL.createObjectURL( new Blob([markdown], { type: "text/markdown" }), ); const link = document.createElement("a"); link.href = url; link.download = fileName; document.body.append(link); link.click(); link.remove(); // Released a moment later rather than at once: some browsers, Safari among // them, have failed downloads whose URL was revoked right after the click. setTimeout(() => URL.revokeObjectURL(url), 1000);}
function buildMarkdownLink(title: string, url: string): string { const destination = url.trim(); // Only web links: a source URL comes from a third-party page. if (!/^https?:\/\//i.test(destination)) { return ""; }
const text = escapeInlineMarkdown(singleLine(title)) || escapeInlineMarkdown(destination); // Percent-encoded rather than wrapped in `<โฆ>`, so the URL keeps every // character and nothing in it can end the link early. const encodedDestination = destination.replace( /[\s()<>\\`]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`, );
return `[${text}](${encodedDestination})`;}
/** * Escapes what Markdown reads inside a line: emphasis, code spans, links, * images, raw HTML, entities, strikethrough and table pipes. A source title * comes from a third-party page, so a `<img onerror>` in it must stay text. */function escapeInlineMarkdown(text: string): string { return text.replace(/[\\`*_[\]<>!&~|]/g, "\\$&");}
function singleLine(text: string): string { return text.replace(/\s+/g, " ").trim();}
function formatDate(date: Date): string { const month = String(date.getMonth() + 1).padStart(2, "0"); const day = String(date.getDate()).padStart(2, "0");
return `${date.getFullYear()}-${month}-${day}`;}14 unmodified lines1516171819202122232427 unmodified lines5253545556575859606138 unmodified lines100101102103104105302 unmodified lines4084094104114124134142 unmodified lines41741841942042142242342415 unmodified lines4404414424434444454465 unmodified lines45245345445545645714 unmodified linesvi.mock("./pubSub", () => ({getImageSearchResults: vi.fn(() => []),getPageContents: vi.fn(() => ({})),getTextSearchTimeFilterNotApplied: vi.fn(() => false),updateImageSearchResults: vi.fn(),updateLlmTextSearchResults: vi.fn(),updatePageContents: vi.fn(),updateTextSearchResults: vi.fn(),updateTextSearchStale: vi.fn(),updateTextSearchTimeFilterNotApplied: vi.fn(),27 unmodified linesimport {getImageSearchResults,getPageContents,getTextSearchTimeFilterNotApplied,updateImageSearchResults,updateLlmTextSearchResults,updatePageContents,updateTextSearchResults,updateTextSearchStale,updateTextSearchTimeFilterNotApplied,38 unmodified lines},);it("deduplicates by URL and appends fresh results", async () => {const existing: TextSearchResults = [["Existing", "snippet", "https://existing.com"],302 unmodified linesawait runFollowUpSearch([{ role: "user", content: "what about next month" }],"what about next month",makeSettings(),[],[],);2 unmodified lines}const anchoredQuery = "new series on disney plus next month December 2026";expect(mockSearchText).toHaveBeenCalledWith(anchoredQuery, 10, "any");expect(mockSearchImages).toHaveBeenCalledWith(anchoredQuery, 10, "any");});it("replaces the year the model wrote with the one the question means", async () => {15 unmodified lines{ role: "user", content: "who won it last year" },],"who won it last year",makeSettings(),[],[],);5 unmodified lines"who won world series 2025",10,"any",);});14 unmodified lines15161718192021222324252627 unmodified lines54555657585960616263646538 unmodified lines104105106107108109110111112113114115116117118119120121122302 unmodified lines4254264274284294304312 unmodified lines43443543643743843944044144244344444544644744844945045115 unmodified lines4674684694704714724735 unmodified lines47948048148248348448514 unmodified linesvi.mock("./pubSub", () => ({getImageSearchResults: vi.fn(() => []),getPageContents: vi.fn(() => ({})),getTextSearchLanguageNotApplied: vi.fn(() => false),getTextSearchTimeFilterNotApplied: vi.fn(() => false),updateImageSearchResults: vi.fn(),updateLlmTextSearchResults: vi.fn(),updatePageContents: vi.fn(),updateTextSearchLanguageNotApplied: vi.fn(),updateTextSearchResults: vi.fn(),updateTextSearchStale: vi.fn(),updateTextSearchTimeFilterNotApplied: vi.fn(),27 unmodified linesimport {getImageSearchResults,getPageContents,getTextSearchLanguageNotApplied,getTextSearchTimeFilterNotApplied,updateImageSearchResults,updateLlmTextSearchResults,updatePageContents,updateTextSearchLanguageNotApplied,updateTextSearchResults,updateTextSearchStale,updateTextSearchTimeFilterNotApplied,38 unmodified lines},);it("keeps the language note on when a follow-up applied the language", async () => {vi.mocked(getTextSearchLanguageNotApplied).mockReturnValueOnce(true);mockSearchText.mockResolvedValueOnce({results: [["New", "snippet", "https://new.com"]],stale: false,languageNotApplied: false,});await refreshTextSearchResults("query", 10, [], undefined, "any", "pt-BR");expect(updateTextSearchLanguageNotApplied).toHaveBeenCalledWith(true);});it("deduplicates by URL and appends fresh results", async () => {const existing: TextSearchResults = [["Existing", "snippet", "https://existing.com"],302 unmodified linesawait runFollowUpSearch([{ role: "user", content: "what about next month" }],"what about next month",makeSettings({ searchLanguage: "pt-BR" }),[],[],);2 unmodified lines}const anchoredQuery = "new series on disney plus next month December 2026";expect(mockSearchText).toHaveBeenCalledWith(anchoredQuery,10,"any","pt-BR",);expect(mockSearchImages).toHaveBeenCalledWith(anchoredQuery,10,"any","pt-BR",);});it("replaces the year the model wrote with the one the question means", async () => {15 unmodified lines{ role: "user", content: "who won it last year" },],"who won it last year",makeSettings({ searchLanguage: "pt-BR" }),[],[],);5 unmodified lines"who won world series 2025",10,"any","pt-BR",);});
12349 unmodified lines1415161718192021222336 unmodified lines6061626364659 unmodified lines757677787980815 unmodified lines8788899091929394959633 unmodified lines1301311321331341356 unmodified lines142143144145146147125 unmodified lines27327427527627727821 unmodified lines300301302303304305import { normalizeFollowUpDates } from "@shared/relativeDates";import type { SearchTimeRange } from "@shared/searchTimeRange";import {getCurrentSearchRunId,9 unmodified linesimport {getImageSearchResults,getPageContents,getTextSearchTimeFilterNotApplied,updateImageSearchResults,updateLlmTextSearchResults,updatePageContents,updateTextSearchResults,updateTextSearchStale,updateTextSearchTimeFilterNotApplied,36 unmodified linesexistingResults: TextSearchResults,searchRunId = getCurrentSearchRunId(),timeRange?: SearchTimeRange,): Promise<TextSearchResults> {const invocation = ++textRefreshInvocation;latestTextRefreshByRunId.set(searchRunId, invocation);9 unmodified linesresults: freshResults,stale,timeFilterNotApplied,} = await searchText(searchQuery, resultsLimit, timeRange);if (freshResults.length === 0) return [];5 unmodified linesif (isCurrent()) {updateTextSearchStale(stale);// A follow-up adds its results below the ones on screen, so it can add// the note but never take it away from results that are still there.updateTextSearchTimeFilterNotApplied(getTextSearchTimeFilterNotApplied() || Boolean(timeFilterNotApplied),);updateLlmTextSearchResults(llmResults);}33 unmodified linesexistingResults: ImageSearchResults,searchRunId = getCurrentSearchRunId(),timeRange?: SearchTimeRange,): Promise<void> {// No newest-refresh check, unlike text: image refreshes merge into the list// on screen and into history, so an older one landing after a newer one6 unmodified linessearchQuery,resultsLimit,timeRange,);if (imageResults.length === 0) return;125 unmodified linesexistingTextResults,searchRunId,settings.searchTimeRange,);if (21 unmodified linesexistingImageResults,searchRunId,settings.searchTimeRange,).catch((error) => {addLogEntry(`Error in follow-up image search: ${error}`);});123459 unmodified lines15161718192021222324252636 unmodified lines636465666768699 unmodified lines79808182838485865 unmodified lines929394959697989910010110210310410533 unmodified lines1391401411421431441456 unmodified lines152153154155156157158125 unmodified lines28428528628728828929021 unmodified lines312313314315316317318import { normalizeFollowUpDates } from "@shared/relativeDates";import type { SearchLanguage } from "@shared/searchLanguage";import type { SearchTimeRange } from "@shared/searchTimeRange";import {getCurrentSearchRunId,9 unmodified linesimport {getImageSearchResults,getPageContents,getTextSearchLanguageNotApplied,getTextSearchTimeFilterNotApplied,updateImageSearchResults,updateLlmTextSearchResults,updatePageContents,updateTextSearchLanguageNotApplied,updateTextSearchResults,updateTextSearchStale,updateTextSearchTimeFilterNotApplied,36 unmodified linesexistingResults: TextSearchResults,searchRunId = getCurrentSearchRunId(),timeRange?: SearchTimeRange,language?: SearchLanguage,): Promise<TextSearchResults> {const invocation = ++textRefreshInvocation;latestTextRefreshByRunId.set(searchRunId, invocation);9 unmodified linesresults: freshResults,stale,timeFilterNotApplied,languageNotApplied,} = await searchText(searchQuery, resultsLimit, timeRange, language);if (freshResults.length === 0) return [];5 unmodified linesif (isCurrent()) {updateTextSearchStale(stale);// A follow-up adds its results below the ones on screen, so it can add// a "not applied" note but never take one away from results that are// still there.updateTextSearchTimeFilterNotApplied(getTextSearchTimeFilterNotApplied() || Boolean(timeFilterNotApplied),);updateTextSearchLanguageNotApplied(getTextSearchLanguageNotApplied() || Boolean(languageNotApplied),);updateLlmTextSearchResults(llmResults);}33 unmodified linesexistingResults: ImageSearchResults,searchRunId = getCurrentSearchRunId(),timeRange?: SearchTimeRange,language?: SearchLanguage,): Promise<void> {// No newest-refresh check, unlike text: image refreshes merge into the list// on screen and into history, so an older one landing after a newer one6 unmodified linessearchQuery,resultsLimit,timeRange,language,);if (imageResults.length === 0) return;125 unmodified linesexistingTextResults,searchRunId,settings.searchTimeRange,settings.searchLanguage,);if (21 unmodified linesexistingImageResults,searchRunId,settings.searchTimeRange,settings.searchLanguage,).catch((error) => {addLogEntry(`Error in follow-up image search: ${error}`);});
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import { describe, expect, it } from "vitest";import { GenerationRateMeter } from "./generationRate";
/** * A meter on a clock the test moves by hand, so a rate never depends on how * long the test machine took between two statements. */function meterOnClock() { let now = 0; const meter = new GenerationRateMeter(() => now); return { meter, /** Records text arriving at each of `times`, in milliseconds. */ deltasAt: (...times: number[]) => { for (const time of times) { now = time; meter.onDelta(); } }, };}
describe("GenerationRateMeter", () => { it("shows the rate the engine measured itself", () => { const { meter } = meterOnClock(); meter.setMeasuredRate(23.766792915058094);
expect(meter.rate()).toBe("23.8 tokens/s"); });
it("prefers the engine's measured rate to a reported count", () => { const { meter, deltasAt } = meterOnClock(); deltasAt(0, 1000); meter.setTokenCount(500); meter.setMeasuredRate(12);
expect(meter.rate()).toBe("12 tokens/s"); });
it("leaves the first token out of a reported count, since it came before the clock", () => { const { meter, deltasAt } = meterOnClock(); deltasAt(1000, 6000); meter.setTokenCount(42);
// 41 tokens over the 5 seconds between the first text and the last. expect(meter.rate()).toBe("8.2 tokens/s"); });
it("keeps a whole number whole", () => { const { meter, deltasAt } = meterOnClock(); deltasAt(0, 2000); meter.setTokenCount(17);
expect(meter.rate()).toBe("8 tokens/s"); });
it("shows nothing for text that arrived in one short burst", () => { const { meter, deltasAt } = meterOnClock(); deltasAt(0, 249); meter.setTokenCount(300);
expect(meter.rate()).toBeUndefined(); });
it("shows nothing when the backend reports no count", () => { const { meter, deltasAt } = meterOnClock(); deltasAt(0, 5000);
expect(meter.rate()).toBeUndefined(); });
it("shows nothing for an answer of one token", () => { const { meter, deltasAt } = meterOnClock(); deltasAt(0, 5000); meter.setTokenCount(1);
expect(meter.rate()).toBeUndefined(); });
it("shows nothing when no text arrived", () => { const { meter } = meterOnClock(); meter.setTokenCount(42);
expect(meter.rate()).toBeUndefined(); });
it("shows nothing when the clock went backwards", () => { const { meter, deltasAt } = meterOnClock(); deltasAt(5000, 1000); meter.setTokenCount(42);
expect(meter.rate()).toBeUndefined(); });
it.each([Number.NaN, Number.POSITIVE_INFINITY, 0, -3])( "shows nothing for a measured rate of %s", (rate) => { const { meter } = meterOnClock(); meter.setMeasuredRate(rate);
expect(meter.rate()).toBeUndefined(); }, );});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182/** * How fast one answer streamed in, for the muted line under it. * * A rate only comes out when it is exact, from one of two sources: * * - The engine measured it: wllama's last chunk carries llama.cpp's own * `timings.predicted_per_second`, the decode speed with model load and the * prompt left out. The browser model reloads itself on every answer, so * anything timed from the request would read far slower than the model is. * - The backend reported how many tokens it wrote. The clock then runs from * the first streamed text to the last, and the first token is left out of * the count because it was generated before the clock started. * * Nothing is ever guessed from characters or from chunk counts, because an * estimate shown as an exact rate is worse than no rate. */export class GenerationRateMeter { private readonly now: () => number; private firstDeltaTime: number | undefined; private lastDeltaTime: number | undefined; private reportedTokens: number | undefined; private measuredRate: number | undefined;
/** `now` is injectable so a test can place the deltas on a timeline. */ constructor(now: () => number = () => performance.now()) { this.now = now; }
/** Records that text arrived, which moves the clock but counts no token. */ onDelta(): void { const time = this.now(); this.firstDeltaTime ??= time; this.lastDeltaTime = time; }
/** The completion token count the backend reported, when it reports one. */ setTokenCount(count: number | undefined): void { this.reportedTokens = count; }
/** A rate the engine measured itself, in tokens per second. */ setMeasuredRate(tokensPerSecond: number | undefined): void { this.measuredRate = tokensPerSecond; }
/** The speed for the answer card, or nothing when it is not known exactly. */ rate(): string | undefined { return formatRate(this.measuredRate ?? this.rateFromReportedCount()); }
private rateFromReportedCount(): number | undefined { const tokens = this.reportedTokens; if ( tokens === undefined || this.firstDeltaTime === undefined || this.lastDeltaTime === undefined ) { return undefined; } const elapsedMs = this.lastDeltaTime - this.firstDeltaTime; // Text that arrives in one burst behind a buffering proxy would claim // thousands of tokens per second, so a span this short says nothing. if (elapsedMs < MIN_MEASURED_SPAN_MS) return undefined; return ((tokens - 1) * 1000) / elapsedMs; }}
const MIN_MEASURED_SPAN_MS = 250;
function formatRate(tokensPerSecond: number | undefined): string | undefined { if ( tokensPerSecond === undefined || !Number.isFinite(tokensPerSecond) || tokensPerSecond <= 0 ) { return undefined; } // One decimal, so a browser model at 3.4 tokens/s does not read as 3, // and a whole number keeps no ".0" behind it. const rounded = Math.round(tokensPerSecond * 10) / 10; return rounded > 0 ? `${rounded} tokens/s` : undefined;}508 unmodified lines509510511512513514508 unmodified lines]);});it("writes nothing when no search has the run id", async () => {const { mergeSearchImageResults, getRecentSearches } = await import("./history"508 unmodified lines509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568508 unmodified lines]);});it("stores an image once by its source, whatever thumbnail it came with", async () => {const {addSearchToHistory,mergeSearchImageResults,getRecentSearches,getCurrentSearchRunId,} = await import("./history");const report = (host: string) => ({title: "photo",url: `https://${host}.example.com/post`,thumbnail: `https://${host}.example.com/thumbnail.jpg`,sourceUrl: "https://cdn.example.com/photo.jpg",});await addSearchToHistory("photo", {type: "image",items: [report("one")],});await mergeSearchImageResults(getCurrentSearchRunId(), {type: "image",items: [report("two")],});const [entry] = await getRecentSearches();expect(entry.imageResults?.items).toEqual([report("two")]);});it("tells apart two stored images that have neither a source nor a thumbnail", async () => {const {addSearchToHistory,mergeSearchImageResults,getRecentSearches,getCurrentSearchRunId,} = await import("./history");const bare = (host: string) => ({title: host,url: `https://${host}.example.com/page`,thumbnail: "",});await addSearchToHistory("bare", {type: "image",items: [bare("one")],});await mergeSearchImageResults(getCurrentSearchRunId(), {type: "image",items: [bare("two")],});// Their page is all that tells them apart, so neither replaces the other.const [entry] = await getRecentSearches();expect(entry.imageResults?.items).toEqual([bare("two"), bare("one")]);});it("writes nothing when no search has the run id", async () => {const { mergeSearchImageResults, getRecentSearches } = await import("./history"
123351 unmodified lines355356357358359360361import Dexie, { type Table, type Transaction } from "dexie";import { addLogEntry } from "./logEntries";import { getSettings } from "./pubSub";351 unmodified lines}function storedImageKey(item: ImageResults["items"][number]): string {return item.sourceUrl || item.thumbnail;}/**1234351 unmodified lines356357358359360361362import { getImageIdentity } from "@shared/imageIdentity";import Dexie, { type Table, type Transaction } from "dexie";import { addLogEntry } from "./logEntries";import { getSettings } from "./pubSub";351 unmodified lines}function storedImageKey(item: ImageResults["items"][number]): string {return getImageIdentity(item.sourceUrl, item.thumbnail, item.url);}/**
123456789101112131415161718192021222324252627import { describe, expect, it } from "vitest";import { imageResultKey } from "./imageResultKey";
describe("imageResultKey", () => { const page = "https://example.com/gallery";
it("identifies an image by its full-size source", () => { expect( imageResultKey([ "Photo", page, "https://cdn.example.com/photo-thumb.jpg", "https://cdn.example.com/photo.jpg", ]), ).toBe("https://cdn.example.com/photo.jpg"); });
it("falls back to the thumbnail when the image has no source", () => { expect( imageResultKey(["Photo", page, "https://cdn.example.com/thumb.jpg", ""]), ).toBe("https://cdn.example.com/thumb.jpg"); });
it("falls back to the page when the image has neither", () => { expect(imageResultKey(["Photo", page, "", ""])).toBe(page); });});1234567891011121314import type { ImageSearchResult } from "./types";/*** Identifies an image result by its full-size source, falling back to the* thumbnail. The page URL is not enough: one gallery page holds many images.*/export function imageResultKey([,,thumbnailUrl,sourceUrl,]: ImageSearchResult): string {return sourceUrl || thumbnailUrl;}123456789101112import { getImageIdentity } from "@shared/imageIdentity";import type { ImageSearchResult } from "./types";/** The identity of an image result tuple, as `getImageIdentity` defines it. */export function imageResultKey([,url,thumbnailUrl,sourceUrl,]: ImageSearchResult): string {return getImageIdentity(sourceUrl, thumbnailUrl, url);}
142 unmodified lines143144145146147148142 unmodified linesexpect(getSettings().historyRetentionDays).toBeGreaterThan(0);});it("turns an unknown stored time range into Anytime", async () => {const { defaultSettings } = await import("./settings");localStorage.setItem(142 unmodified lines143144145146147148149150151152153154155156157158142 unmodified linesexpect(getSettings().historyRetentionDays).toBeGreaterThan(0);});it("turns an unknown stored search language into the browser's", async () => {const { defaultSettings } = await import("./settings");localStorage.setItem("settings",JSON.stringify({ ...defaultSettings, searchLanguage: "klingon" }),);const { getSettings } = await import("./pubSub");expect(getSettings().searchLanguage).toBe("browser");});it("turns an unknown stored time range into Anytime", async () => {const { defaultSettings } = await import("./settings");localStorage.setItem(
203 unmodified lines20420520620720820997 unmodified lines307308309310311312203 unmodified linesexport const [, , getResponse] = responsePubSub;export const [updateSearchPromise, , getSearchPromise] = createPubSub<Promise<SearchResults>>(Promise.resolve({ textResults: [], imageResults: [] }));97 unmodified linesgetTextSearchTimeFilterNotApplied,] = textSearchTimeFilterPubSub;const pageContentsPubSub = createPubSub<PageContents>({});export const [updatePageContents, , getPageContents] = pageContentsPubSub;203 unmodified lines20420520620720820921021121221321421521621721821997 unmodified lines317318319320321322323324325326327328329330331332333334335336337338339340341342343203 unmodified linesexport const [, , getResponse] = responsePubSub;/*** The generation speed of the answer on screen, already worded for the card* (for example `42 tokens/s`). Nothing is published while an answer is still* generating, and a backend that reports no exact token count publishes* nothing, so a rate only ever appears once it is known for that answer.*/export const generationRatePubSub = createPubSub<string | undefined>(undefined);export const [updateGenerationRate] = generationRatePubSub;export const [updateSearchPromise, , getSearchPromise] = createPubSub<Promise<SearchResults>>(Promise.resolve({ textResults: [], imageResults: [] }));97 unmodified linesgetTextSearchTimeFilterNotApplied,] = textSearchTimeFilterPubSub;/*** Whether the text results on screen came back in no particular language* although one was asked for, which is the same fallback having answered.*/export const textSearchLanguagePubSub = createPubSub<boolean>(false);export const [updateTextSearchLanguageNotApplied,,getTextSearchLanguageNotApplied,] = textSearchLanguagePubSub;/*** The unit conversion SearXNG's own plugin worked out for the search on screen,* as plain text, or null when it worked out none. It needs no search engine, so* it can be the only thing a search brings back.*/export const textSearchUnitConversionPubSub = createPubSub<string | null>(null);export const [updateTextSearchUnitConversion] = textSearchUnitConversionPubSub;const pageContentsPubSub = createPubSub<PageContents>({});export const [updatePageContents, , getPageContents] = pageContentsPubSub;
140 unmodified lines14114214314414514682 unmodified lines229230231232233234382 unmodified lines617618619620621622156 unmodified lines779780781782783784140 unmodified lines);});it("should return a deterministic hex string of fixed length", async () => {const hash =await searchModule.searchServiceInstance.hashQuery("any query");82 unmodified linesexpect(calledUrl).not.toContain("time_range");});it("should throw on non-OK response", async () => {mockFetch.mockResolvedValue({ok: false,382 unmodified linesexpect(mockFetch).toHaveBeenCalledTimes(1);});it("should refetch when TTL expires", async () => {const mockResults: string[][] = [["Title", "Snippet", "https://example.com"],156 unmodified lines});});describe("URL Construction", () => {it("should include the search token hash in the request URL", async () => {mockFetchResponse([]);140 unmodified lines14114214314414514614714814915015115215315415515615715815916016116216316416582 unmodified lines248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312382 unmodified lines695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727156 unmodified lines884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999140 unmodified lines);});it("should include the language in the hash so different languages produce different keys", async () => {const { hashQuery } = searchModule.searchServiceInstance;const hashes = await Promise.all(["pt-BR", "en-US", "de", "all"].map((language) =>hashQuery("test query", 10, undefined, language),),);expect(new Set(hashes).size).toBe(4);});it("should keep the key of a search that sends no language the one it was before the setting existed", async () => {const { hashQuery } = searchModule.searchServiceInstance;// No language adds nothing to the hashed input, so the entries cached// before the setting existed are still the ones such a search reads.expect(await hashQuery("test query", 10, undefined, undefined)).toBe(await hashQuery("test query", 10),);});it("should return a deterministic hex string of fixed length", async () => {const hash =await searchModule.searchServiceInstance.hashQuery("any query");82 unmodified linesexpect(calledUrl).not.toContain("time_range");});it("should send a chosen locale as the language parameter", async () => {mockFetchResponse([]);await searchModule.searchServiceInstance.performSearch<string[][]>("text","test",10,undefined,"pt-BR",);expect(mockFetch.mock.calls[0][0] as string).toContain("language=pt-BR");});it("should send all for Any language", async () => {mockFetchResponse([]);await searchModule.searchServiceInstance.performSearch<string[][]>("text","test",10,undefined,"all",);expect(mockFetch.mock.calls[0][0] as string).toContain("language=all");});it("should send the browser's own locale for Browser language", async () => {const browserLanguage = vi.spyOn(Navigator.prototype, "language", "get").mockReturnValue("pt-BR");mockFetchResponse([]);await searchModule.searchText("browser locale query",10,undefined,"browser",);// Resolved at search time, so the server gets a locale it can act on// rather than the guess it would have had to make from the query.expect(mockFetch.mock.calls[0][0] as string).toContain("language=pt-BR");browserLanguage.mockRestore();});it("should send no language when the search has none", async () => {mockFetchResponse([]);await searchModule.searchServiceInstance.performSearch<string[][]>("text","test",10,);expect(mockFetch.mock.calls[0][0] as string).not.toContain("language=");});it("should throw on non-OK response", async () => {mockFetch.mockResolvedValue({ok: false,382 unmodified linesexpect(mockFetch).toHaveBeenCalledTimes(1);});it("should treat different languages as separate cache entries", async () => {const mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockSearchResponse(mockResults);await searchModule.searchText("same query", 5, undefined, "pt-BR");await searchModule.searchText("same query", 5, undefined, "en-US");expect(mockFetch).toHaveBeenCalledTimes(2);});it("should read a search with no language from the entry cached before the setting existed", async () => {const mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockSearchResponse(mockResults);await searchModule.searchText("no language query", 5);await searchModule.searchText("no language query",5,undefined,undefined,);expect(mockFetch).toHaveBeenCalledTimes(1);});it("should refetch when TTL expires", async () => {const mockResults: string[][] = [["Title", "Snippet", "https://example.com"],156 unmodified lines});});describe("Language Not Applied", () => {const mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];const notApplied = { "X-Search-Language-Applied": "false" };it("should report the note when the server says the language was not applied", async () => {mockSearchResponse(mockResults, notApplied);const outcome = await searchModule.searchText("fallback query",5,undefined,"pt-BR",);expect(outcome).toEqual({results: mockResults,stale: false,timeFilterNotApplied: false,languageNotApplied: true,});});it("should keep the note when those results come back from the cache", async () => {mockSearchResponse(mockResults, notApplied);await searchModule.searchText("cached fallback query",5,undefined,"pt-BR",);const cached = await searchModule.searchText("cached fallback query",5,undefined,"pt-BR",);expect(mockFetch).toHaveBeenCalledTimes(1);expect(cached.languageNotApplied).toBe(true);});it("should not report the note when the server applied the language", async () => {mockSearchResponse(mockResults);const outcome = await searchModule.searchText("filtered query",5,undefined,"pt-BR",);expect(outcome.languageNotApplied).toBeUndefined();});});describe("Unit Conversion", () => {const mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];// Exactly what the server puts in the header: the answer, percent-encoded.const withConversion = { "X-Search-Unit-Conversion": "16.4041994751%20ft" };it("should read the conversion off the response header", async () => {mockSearchResponse(mockResults, withConversion);const outcome = await searchModule.searchText("5 m to ft", 5);expect(outcome).toEqual({results: mockResults,stale: false,timeFilterNotApplied: false,unitConversion: "16.4041994751 ft",});});it("should keep the conversion when those results come back from the cache", async () => {mockSearchResponse(mockResults, withConversion);await searchModule.searchText("cached conversion query", 5);const cached = await searchModule.searchText("cached conversion query",5,);expect(mockFetch).toHaveBeenCalledTimes(1);expect(cached.unitConversion).toBe("16.4041994751 ft");});it("should drop a header that does not decode and keep the results", async () => {// A lone percent sign is not a valid encoding.mockSearchResponse(mockResults, { "X-Search-Unit-Conversion": "100%" });const outcome = await searchModule.searchText("5 m to ft", 5);expect(outcome.results).toEqual(mockResults);expect(outcome.unitConversion).toBeUndefined();});it("should report no conversion when the header is absent", async () => {mockSearchResponse(mockResults);const outcome = await searchModule.searchText("plain query", 5);expect(outcome.unitConversion).toBeUndefined();});});describe("URL Construction", () => {it("should include the search token hash in the request URL", async () => {mockFetchResponse([]);
1234567117 unmodified lines1251261271281291301311321331341351362 unmodified lines1391401411421431445 unmodified lines1501511521531541551561571581591601611621631641651661679 unmodified lines1771781791801811821 unmodified line18418518618718818919019119219319419519619719819920020120220320410 unmodified lines2152162172182192204 unmodified lines2252262272282292302311 unmodified line23323423523623723823924024124224324424524624724844 unmodified lines29329429529629729829930030130230310 unmodified lines314315316317318319106 unmodified lines4264274284294304314 unmodified lines4364374384394404417 unmodified lines4494504514524534548 unmodified lines4634644654664674684 unmodified lines4734744754764774782 unmodified lines48148248348448548624 unmodified lines5115125135145155165175185195205215225235245255265275284 unmodified lines53353453553653753812 unmodified lines5515525535545555565577 unmodified lines5655665675685695705714 unmodified lines5765775785795805811 unmodified line58358458558658758858959059159259359420 unmodified lines615616617618619620621622623624625626import {SEARCH_TIME_RANGE_APPLIED_HEADER,type SearchTimeRange,} from "@shared/searchTimeRange";import Dexie, { type Table } from "dexie";import { sha256 } from "hash-wasm";import { invalidateConfig } from "./config";117 unmodified linesquery: string,limit?: number,timeRange?: SearchTimeRange,) => Promise<string>;performSearch: (endpoint: "text" | "images",query: string,limit?: number,timeRange?: SearchTimeRange,) => Promise<SearchFetch<T>>;}2 unmodified linesresults: T;/** The server answered from a source that could not apply the time range. */timeFilterNotApplied: boolean;}interface CachedSearchOutcome<T> {5 unmodified lines* existed reads back as "applied" instead of failing to say anything.*/timeFilterNotApplied?: boolean;}async function executeCachedSearch<T extends SearchResults>(query: string,limit: number | undefined,timeRange: SearchTimeRange | undefined,context: SearchExecutionConfig,operations: SearchOperations<T>,): Promise<CachedSearchOutcome<T>> {await db.cleanExpiredCache(context.storeName);const key = await operations.hashQuery(query, limit, timeRange);const cachedData = await db.getCachedResult<T>(context.storeName, key);if (cachedData?.fresh) {9 unmodified linesresults: cachedData.results,stale: false,timeFilterNotApplied: cachedData.timeFilterNotApplied,};}1 unmodified linecacheMetrics.incrementTotalOperations();try {const { results, timeFilterNotApplied } = await operations.performSearch(context.endpoint,query,limit,timeRange,);await db.cacheResult(context.storeName, key, results, timeFilterNotApplied);logAndMaybeResetMetrics();addLogEntry(`${context.logLabel}: Fetched ${results.length} results from the API`,);return { results, stale: false, timeFilterNotApplied };} catch (error) {if (cachedData &&10 unmodified linesresults: cachedData.results,stale: true,timeFilterNotApplied: cachedData.timeFilterNotApplied,};}throw error;4 unmodified linesconst UNAUTHORIZED_STATUS = 401;type SearchAttempt<T> =| { ok: true; results: T; timeFilterNotApplied: boolean }| { ok: false; status: number };async function buildSearchUrl(1 unmodified linequery: string,limit: number | undefined,timeRange: SearchTimeRange | undefined,): Promise<URL> {const searchUrl = new URL(`/search/${endpoint}`, self.location.origin);searchUrl.searchParams.set("q", query);searchUrl.searchParams.set("token", await getSearchTokenHash());if (limit) searchUrl.searchParams.set("limit", limit.toString());// Anytime sends no parameter at all, so an unfiltered search asks the server// for exactly what it asked before the filter existed.if (timeRange && timeRange !== "any") {searchUrl.searchParams.set("time_range", timeRange);}return searchUrl;}44 unmodified linesreturn { ok: false, status: response.status };}return {ok: true,results: (await response.json()) as T,timeFilterNotApplied:response.headers.get(SEARCH_TIME_RANGE_APPLIED_HEADER) === "false",};} catch (error) {throw labelSearchFailure(error, controller.signal);10 unmodified lines* time filter was not applied. Absent on every entry written before it.*/timeFilterNotApplied?: boolean;}interface TextSearchCache extends SearchCacheEntry {106 unmodified linesfresh: boolean;timestamp: number;timeFilterNotApplied?: boolean;} | null> {if (!cacheConfig.enabled) return null;4 unmodified linesresults: T;timestamp: number;timeFilterNotApplied?: boolean;},string>;7 unmodified linesfresh,timestamp: cachedItem.timestamp,timeFilterNotApplied: cachedItem.timeFilterNotApplied,};} catch (error) {addLogEntry(8 unmodified lineskey: string,results: T,timeFilterNotApplied?: boolean,): Promise<void> {if (!cacheConfig.enabled) return;4 unmodified linesresults: T;timestamp: number;timeFilterNotApplied?: boolean;},string>;2 unmodified linesresults,timestamp: Date.now(),timeFilterNotApplied,});const cacheWrites = this._cacheWriteCount;24 unmodified linesconst searchService = {/*** The limit and the time range are part of the key, so neither a different* limit nor a different period can read another one's results. Anytime adds* nothing, so an unfiltered search keeps reading the entries cached before* the filter existed.*/async hashQuery(query: string,limit?: number,timeRange?: SearchTimeRange,): Promise<string> {let input = limit !== undefined ? `${query}::limit=${limit}` : query;if (timeRange && timeRange !== "any") input += `::time_range=${timeRange}`;const hash = await sha256(input);// 16 hex chars are enough for a cache key.return hash.slice(0, 16);4 unmodified linesquery: string,limit?: number,timeRange?: SearchTimeRange,): Promise<SearchFetch<T>> {if (!["text", "images"].includes(endpoint)) {throw new Error(12 unmodified lines}let attempt = await attemptSearch<T>(await buildSearchUrl(endpoint, query, limit, timeRange),);// Every server process mints its own search token, so a restart leaves7 unmodified lines);invalidateConfig();attempt = await attemptSearch<T>(await buildSearchUrl(endpoint, query, limit, timeRange),);}4 unmodified linesreturn {results: attempt.results,timeFilterNotApplied: attempt.timeFilterNotApplied,};},1 unmodified linequery: string,limit?: number,timeRange?: SearchTimeRange,): Promise<CachedSearchOutcome<TextSearchResults>> {try {return await executeCachedSearch<TextSearchResults>(query,limit,timeRange,{storeName: "textSearchHistory",endpoint: "text",20 unmodified linesquery: string,limit?: number,timeRange?: SearchTimeRange,): Promise<CachedSearchOutcome<ImageSearchResults>> {try {return await executeCachedSearch<ImageSearchResults>(query,limit,timeRange,{storeName: "imageSearchHistory",endpoint: "images",12345678910111213141516117 unmodified lines1341351361371381391401411421431441451461472 unmodified lines1501511521531541551561571581591601611621631641651661675 unmodified lines1731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072089 unmodified lines2182192202212222232242251 unmodified line22722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526610 unmodified lines2772782792802812822832844 unmodified lines2892902912922932942952962972982993003011 unmodified line30330430530630730830931031131231331431531631731831932032144 unmodified lines36636736836937037137237337437537637737837938038138238338438538638738838939039139210 unmodified lines403404405406407408409410411412106 unmodified lines5195205215225235245255264 unmodified lines5315325335345355365375387 unmodified lines5465475485495505515525538 unmodified lines5625635645655665675685694 unmodified lines5745755765775785795805812 unmodified lines58458558658758858959059124 unmodified lines6166176186196206216226236246256266276286296306316326336346356364 unmodified lines64164264364464564664712 unmodified lines6606616626636646656667 unmodified lines6746756766776786796804 unmodified lines6856866876886896906916921 unmodified line69469569669769869970070170270370470570670720 unmodified lines728729730731732733734735736737738739740741import {resolveSearchLanguage,SEARCH_LANGUAGE_APPLIED_HEADER,type SearchLanguage,} from "@shared/searchLanguage";import {SEARCH_TIME_RANGE_APPLIED_HEADER,type SearchTimeRange,} from "@shared/searchTimeRange";import {decodeUnitConversion,SEARCH_UNIT_CONVERSION_HEADER,} from "@shared/unitConversion";import Dexie, { type Table } from "dexie";import { sha256 } from "hash-wasm";import { invalidateConfig } from "./config";117 unmodified linesquery: string,limit?: number,timeRange?: SearchTimeRange,language?: string,) => Promise<string>;performSearch: (endpoint: "text" | "images",query: string,limit?: number,timeRange?: SearchTimeRange,language?: string,) => Promise<SearchFetch<T>>;}2 unmodified linesresults: T;/** The server answered from a source that could not apply the time range. */timeFilterNotApplied: boolean;/*** The server answered from a source that could not apply the language. Left* out rather than set false, so a search that applied one reads back as it* did before the setting existed, in the cache and in the outcome alike.*/languageNotApplied?: boolean;/*** The unit conversion SearXNG's own plugin computed for the query, kept out* of the result array by the header it arrives in. Left out when it answered* nothing, the same way the two notes above are.*/unitConversion?: string;}interface CachedSearchOutcome<T> {5 unmodified lines* existed reads back as "applied" instead of failing to say anything.*/timeFilterNotApplied?: boolean;/*** The same, for a search that asked for a language, and left out the same way* when the language was applied.*/languageNotApplied?: boolean;/** The unit conversion that came with these results, if there was one. */unitConversion?: string;}async function executeCachedSearch<T extends SearchResults>(query: string,limit: number | undefined,timeRange: SearchTimeRange | undefined,language: SearchLanguage | undefined,context: SearchExecutionConfig,operations: SearchOperations<T>,): Promise<CachedSearchOutcome<T>> {await db.cleanExpiredCache(context.storeName);// Resolved here, at search time, so the cache key and the request agree on// the locale actually asked for, and "Browser language" keeps following the// browser when its locale changes.const requestLanguage = resolveSearchLanguage(language, navigator.language);const key = await operations.hashQuery(query,limit,timeRange,requestLanguage,);const cachedData = await db.getCachedResult<T>(context.storeName, key);if (cachedData?.fresh) {9 unmodified linesresults: cachedData.results,stale: false,timeFilterNotApplied: cachedData.timeFilterNotApplied,languageNotApplied: cachedData.languageNotApplied,unitConversion: cachedData.unitConversion,};}1 unmodified linecacheMetrics.incrementTotalOperations();try {const {results,timeFilterNotApplied,languageNotApplied,unitConversion,} = await operations.performSearch(context.endpoint,query,limit,timeRange,requestLanguage,);await db.cacheResult(context.storeName,key,results,timeFilterNotApplied,languageNotApplied,unitConversion,);logAndMaybeResetMetrics();addLogEntry(`${context.logLabel}: Fetched ${results.length} results from the API`,);return {results,stale: false,timeFilterNotApplied,languageNotApplied,unitConversion,};} catch (error) {if (cachedData &&10 unmodified linesresults: cachedData.results,stale: true,timeFilterNotApplied: cachedData.timeFilterNotApplied,languageNotApplied: cachedData.languageNotApplied,unitConversion: cachedData.unitConversion,};}throw error;4 unmodified linesconst UNAUTHORIZED_STATUS = 401;type SearchAttempt<T> =| {ok: true;results: T;timeFilterNotApplied: boolean;languageNotApplied?: boolean;unitConversion?: string;}| { ok: false; status: number };async function buildSearchUrl(1 unmodified linequery: string,limit: number | undefined,timeRange: SearchTimeRange | undefined,language: string | undefined,): Promise<URL> {const searchUrl = new URL(`/search/${endpoint}`, self.location.origin);searchUrl.searchParams.set("q", query);searchUrl.searchParams.set("token", await getSearchTokenHash());if (limit) searchUrl.searchParams.set("limit", limit.toString());// Anytime sends no parameter at all, so an unfiltered search asks the server// for exactly what it asked before the filter existed. A search with no// language does the same, which keeps SearXNG on its own default.if (timeRange && timeRange !== "any") {searchUrl.searchParams.set("time_range", timeRange);}if (language) searchUrl.searchParams.set("language", language);return searchUrl;}44 unmodified linesreturn { ok: false, status: response.status };}const results = (await response.json()) as T;// Read after the body: a response that dies mid-body is the failure it// died on, not a missing header. A header that does not decode only loses// the card, never the results the search found.const unitConversionHeader = response.headers.get(SEARCH_UNIT_CONVERSION_HEADER,);return {ok: true,results,timeFilterNotApplied:response.headers.get(SEARCH_TIME_RANGE_APPLIED_HEADER) === "false",languageNotApplied:response.headers.get(SEARCH_LANGUAGE_APPLIED_HEADER) === "false"? true: undefined,unitConversion: unitConversionHeader? decodeUnitConversion(unitConversionHeader): undefined,};} catch (error) {throw labelSearchFailure(error, controller.signal);10 unmodified lines* time filter was not applied. Absent on every entry written before it.*/timeFilterNotApplied?: boolean;/** The same, for a search that asked for a language. */languageNotApplied?: boolean;/** The same, for the unit conversion that came with these results. */unitConversion?: string;}interface TextSearchCache extends SearchCacheEntry {106 unmodified linesfresh: boolean;timestamp: number;timeFilterNotApplied?: boolean;languageNotApplied?: boolean;unitConversion?: string;} | null> {if (!cacheConfig.enabled) return null;4 unmodified linesresults: T;timestamp: number;timeFilterNotApplied?: boolean;languageNotApplied?: boolean;unitConversion?: string;},string>;7 unmodified linesfresh,timestamp: cachedItem.timestamp,timeFilterNotApplied: cachedItem.timeFilterNotApplied,languageNotApplied: cachedItem.languageNotApplied,unitConversion: cachedItem.unitConversion,};} catch (error) {addLogEntry(8 unmodified lineskey: string,results: T,timeFilterNotApplied?: boolean,languageNotApplied?: boolean,unitConversion?: string,): Promise<void> {if (!cacheConfig.enabled) return;4 unmodified linesresults: T;timestamp: number;timeFilterNotApplied?: boolean;languageNotApplied?: boolean;unitConversion?: string;},string>;2 unmodified linesresults,timestamp: Date.now(),timeFilterNotApplied,languageNotApplied,unitConversion,});const cacheWrites = this._cacheWriteCount;24 unmodified linesconst searchService = {/*** The limit, the time range and the language are part of the key, so neither* a different limit nor a different period nor a different language can read* another one's results. A search with no language and an Anytime search add* nothing, so they keep reading the entries cached before those settings* existed.*/async hashQuery(query: string,limit?: number,timeRange?: SearchTimeRange,language?: string,): Promise<string> {let input = limit !== undefined ? `${query}::limit=${limit}` : query;if (timeRange && timeRange !== "any") input += `::time_range=${timeRange}`;if (language) input += `::language=${language}`;const hash = await sha256(input);// 16 hex chars are enough for a cache key.return hash.slice(0, 16);4 unmodified linesquery: string,limit?: number,timeRange?: SearchTimeRange,language?: string,): Promise<SearchFetch<T>> {if (!["text", "images"].includes(endpoint)) {throw new Error(12 unmodified lines}let attempt = await attemptSearch<T>(await buildSearchUrl(endpoint, query, limit, timeRange, language),);// Every server process mints its own search token, so a restart leaves7 unmodified lines);invalidateConfig();attempt = await attemptSearch<T>(await buildSearchUrl(endpoint, query, limit, timeRange, language),);}4 unmodified linesreturn {results: attempt.results,timeFilterNotApplied: attempt.timeFilterNotApplied,languageNotApplied: attempt.languageNotApplied,unitConversion: attempt.unitConversion,};},1 unmodified linequery: string,limit?: number,timeRange?: SearchTimeRange,language?: SearchLanguage,): Promise<CachedSearchOutcome<TextSearchResults>> {try {return await executeCachedSearch<TextSearchResults>(query,limit,timeRange,language,{storeName: "textSearchHistory",endpoint: "text",20 unmodified linesquery: string,limit?: number,timeRange?: SearchTimeRange,language?: SearchLanguage,): Promise<CachedSearchOutcome<ImageSearchResults>> {try {return await executeCachedSearch<ImageSearchResults>(query,limit,timeRange,language,{storeName: "imageSearchHistory",endpoint: "images",
1 unmodified line23456762 unmodified lines70717273747529 unmodified lines10510610710810911011111216 unmodified lines1291301311321331341 unmodified lineCITATION_EXAMPLE,DEFAULT_SYSTEM_PROMPT,} from "@shared/defaultSystemPrompt";import {type SearchTimeRange,searchTimeRangeOptions,62 unmodified linescpuThreads: getDefaultCpuThreads(),searchResultsLimit: 15,searchTimeRange: "any" as SearchTimeRange,systemPrompt: DEFAULT_SYSTEM_PROMPT,inferenceType: DEFAULT_INFERENCE_TYPE,openAiApiBaseUrl: "",29 unmodified lines* emits `""`, which `??` does not catch and `> 0` reads as false, so it would* otherwise reach consumers as a `max_tokens` of `""` or a retention that* silently stops cleanup. Keys whose default is not a number are left alone,* except the time range: an unknown one (hand-edited, or renamed in a later* version) would make the server refuse every search, so it becomes Anytime.*/export function coerceNumericSettings(settings: typeof defaultSettings,16 unmodified lines) {coerced.searchTimeRange = defaultSettings.searchTimeRange;}return coerced as typeof defaultSettings;}1 unmodified line23456789101162 unmodified lines7475767778798029 unmodified lines11011111211311411511611711816 unmodified lines1351361371381391401411421431441451 unmodified lineCITATION_EXAMPLE,DEFAULT_SYSTEM_PROMPT,} from "@shared/defaultSystemPrompt";import {type SearchLanguage,searchLanguageOptions,} from "@shared/searchLanguage";import {type SearchTimeRange,searchTimeRangeOptions,62 unmodified linescpuThreads: getDefaultCpuThreads(),searchResultsLimit: 15,searchTimeRange: "any" as SearchTimeRange,searchLanguage: "browser" as SearchLanguage,systemPrompt: DEFAULT_SYSTEM_PROMPT,inferenceType: DEFAULT_INFERENCE_TYPE,openAiApiBaseUrl: "",29 unmodified lines* emits `""`, which `??` does not catch and `> 0` reads as false, so it would* otherwise reach consumers as a `max_tokens` of `""` or a retention that* silently stops cleanup. Keys whose default is not a number are left alone,* except the time range and the search language: an unknown one (hand-edited,* or renamed in a later version) would make the server refuse every search,* so it goes back to its default.*/export function coerceNumericSettings(settings: typeof defaultSettings,16 unmodified lines) {coerced.searchTimeRange = defaultSettings.searchTimeRange;}if (!searchLanguageOptions.some(({ value }) => value === coerced.searchLanguage)) {coerced.searchLanguage = defaultSettings.searchLanguage;}return coerced as typeof defaultSettings;}
99 unmodified lines10010110210310410595 unmodified lines20120220320420599 unmodified linesnew Date(sevenDaysAgo).toLocaleDateString(),);});});describe("searchWithFuzzy", () => {95 unmodified linesconst groups = groupSearchResultsByDate(items);expect(groups.Today).toHaveLength(2);});});});99 unmodified lines10010110210310410510610710810911011111295 unmodified lines20820921021121221321421521621721821922022122222322422522622722822923099 unmodified linesnew Date(sevenDaysAgo).toLocaleDateString(),);});it("shows a future timestamp as its locale date", () => {const tomorrow = Date.now() + 24 * 60 * 60 * 1000;expect(formatRelativeTime(tomorrow)).toBe(new Date(tomorrow).toLocaleDateString(),);});});describe("searchWithFuzzy", () => {95 unmodified linesconst groups = groupSearchResultsByDate(items);expect(groups.Today).toHaveLength(2);});it("uses calendar days across a daylight-saving transition", () => {const originalTimeZone = process.env.TZ;try {process.env.TZ = "America/New_York";vi.setSystemTime(new Date(2024, 2, 11, 12, 0, 0));const twoDaysAgo = new Date(2024, 2, 9, 23, 30, 0).getTime();const groups = groupSearchResultsByDate([{ item: { id: 1 }, timestamp: twoDaysAgo },]);expect(groups["This Week"]).toHaveLength(1);expect(groups.Yesterday).toBeUndefined();} finally {if (originalTimeZone === undefined) delete process.env.TZ;else process.env.TZ = originalTimeZone;}});});});
15 unmodified lines16171819202157 unmodified lines798081828384858615 unmodified linesexport function formatRelativeTime(timestamp: number): string {const now = Date.now();const diff = now - timestamp;const minutes = Math.floor(diff / 60000);const hours = Math.floor(diff / 3600000);const days = Math.floor(diff / 86400000);57 unmodified linesconst groups: Record<string, Array<{ item: T; timestamp: number }>> = {};const now = new Date();const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);for (const result of items) {const date = new Date(result.timestamp);15 unmodified lines161718192021222324252657 unmodified lines8485868788899091929315 unmodified linesexport function formatRelativeTime(timestamp: number): string {const now = Date.now();const diff = now - timestamp;if (diff < 0) {return new Date(timestamp).toLocaleDateString();}const minutes = Math.floor(diff / 60000);const hours = Math.floor(diff / 3600000);const days = Math.floor(diff / 86400000);57 unmodified linesconst groups: Record<string, Array<{ item: T; timestamp: number }>> = {};const now = new Date();const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());const yesterday = new Date(today);yesterday.setDate(yesterday.getDate() - 1);const weekAgo = new Date(today);weekAgo.setDate(weekAgo.getDate() - 7);for (const result of items) {const date = new Date(result.timestamp);
33 unmodified lines34353637383917 unmodified lines57585960616232 unmodified lines959697989910064 unmodified lines16516616716816917097 unmodified lines268269270271272273222 unmodified lines49649749849950050133 unmodified lines};});import {contentFrame,historyMock,17 unmodified lineslistenToTextGenerationStateChanges: vi.fn(() => vi.fn()),updateChatMessages: vi.fn(),updateConversationSummary: vi.fn(),updateImageSearchResults: vi.fn((results: unknown[]) => {harness.state.imageSearchResults = results;}),32 unmodified linesharness.state.staleFlag = value;}),updateTextSearchTimeFilterNotApplied: vi.fn(),getTextSearchStale: () => harness.state.staleFlag,}));64 unmodified linesupdateImageSearchResults,updateImageSearchState,updateTextSearchStale,} from "./pubSub";import { searchImages, searchText } from "./search";import { interruptSearch, searchAndRespond } from "./textGeneration";97 unmodified linesexpect(harness.state.textSearchState).toBe("completed");});it("grounds the answer on the best-scored results while the list keeps the pinned one first", async () => {const scoredResults: TextSearchResults = [["Pinned", "A snippet", "https://pinned.example", 12],222 unmodified linesexpect(harness.state.suppressNextFollowUp).toBe(false);});});describe("search supersession ownership", () => {33 unmodified lines3435363738394017 unmodified lines5859606162636432 unmodified lines97989910010110210310464 unmodified lines16917017117217317417597 unmodified lines273274275276277278279280281282283284285286287288289290291292293294295296297222 unmodified lines52052152252352452552652752852953053153233 unmodified lines};});import { updateGenerationRate } from "./pubSub";import {contentFrame,historyMock,17 unmodified lineslistenToTextGenerationStateChanges: vi.fn(() => vi.fn()),updateChatMessages: vi.fn(),updateConversationSummary: vi.fn(),updateGenerationRate: vi.fn(),updateImageSearchResults: vi.fn((results: unknown[]) => {harness.state.imageSearchResults = results;}),32 unmodified linesharness.state.staleFlag = value;}),updateTextSearchTimeFilterNotApplied: vi.fn(),updateTextSearchLanguageNotApplied: vi.fn(),updateTextSearchUnitConversion: vi.fn(),getTextSearchStale: () => harness.state.staleFlag,}));64 unmodified linesupdateImageSearchResults,updateImageSearchState,updateTextSearchStale,updateTextSearchUnitConversion,} from "./pubSub";import { searchImages, searchText } from "./search";import { interruptSearch, searchAndRespond } from "./textGeneration";97 unmodified linesexpect(harness.state.textSearchState).toBe("completed");});it("keeps a unit conversion instead of retrying with keywords when no web results came back", async () => {harness.state.query = "5 m to ft";vi.mocked(searchText).mockResolvedValue({results: [],stale: false,unitConversion: "16.4041994751 ft",});await searchAndRespond();await harness.state.searchPromise;// The keyword query would drop "to" as a stopword and lose the conversion.expect(searchText).toHaveBeenCalledTimes(1);expect(vi.mocked(updateTextSearchUnitConversion)).toHaveBeenLastCalledWith("16.4041994751 ft",);expect(harness.state.textSearchState).toBe("completed");});it("grounds the answer on the best-scored results while the list keeps the pinned one first", async () => {const scoredResults: TextSearchResults = [["Pinned", "A snippet", "https://pinned.example", 12],222 unmodified linesexpect(harness.state.suppressNextFollowUp).toBe(false);});it("clears the speed line so a new search never shows the old answer's", async () => {await searchAndRespond();await harness.state.searchPromise;expect(updateGenerationRate).toHaveBeenCalledWith(undefined);});});describe("search supersession ownership", () => {
16 unmodified lines17181920212216 unmodified linesmockGetConversationSummary(...args),listenToSettingsChanges: vi.fn(() => vi.fn()),updateConversationSummary: vi.fn(),updateTextGenerationState: vi.fn(),getTextGenerationState: vi.fn(),getResponse: vi.fn(),16 unmodified lines1718192021222316 unmodified linesmockGetConversationSummary(...args),listenToSettingsChanges: vi.fn(() => vi.fn()),updateConversationSummary: vi.fn(),updateGenerationRate: vi.fn(),updateTextGenerationState: vi.fn(),getTextGenerationState: vi.fn(),getResponse: vi.fn(),
19 unmodified lines2021222324253 unmodified lines29303132333435363738316 unmodified lines3553563573583593603 unmodified lines364365366367368369382 unmodified lines7527537547557567577587597607617627637647657667677687697705 unmodified lines7767777787797807817827837847857 unmodified lines79379479579679779822 unmodified lines82182282382482582649 unmodified lines87687787887988088119 unmodified lineslistenToSettingsChanges,updateChatMessages,updateConversationSummary,updateImageSearchResults,updateImageSearchState,updateLlmTextSearchResults,3 unmodified linesupdateSearchPromise,updateSuppressNextFollowUp,updateTextGenerationState,updateTextSearchResults,updateTextSearchStale,updateTextSearchState,updateTextSearchTimeFilterNotApplied,} from "./pubSub";import { searchImages, searchText } from "./search";import { getLatestSearchAttempt, recordSearchAttempt } from "./searchAttempts";316 unmodified linesdocument.title = getQuery();updateResponse("");clearConversationSummary();3 unmodified linesupdateTextSearchTimeFilterNotApplied(false);updateLlmTextSearchResults([]);updateImageSearchResults([]);382 unmodified linesresults: textResults,stale,timeFilterNotApplied,} = searchQuery? await searchText(searchQuery,getSettings().searchResultsLimit,getSettings().searchTimeRange,): {results: [] as TextSearchResults,stale: false,timeFilterNotApplied: false,};if (textResults.length === 0) {const keywordQuery = normalizeRelativeDates((await getKeywords(query, 10)).join(" "),asOf,5 unmodified lineskeywordQuery,getSettings().searchResultsLimit,getSettings().searchTimeRange,);textResults = keywordOutcome.results;stale = keywordOutcome.stale;timeFilterNotApplied = keywordOutcome.timeFilterNotApplied;}}7 unmodified linesif (isCurrent()) {updateTextSearchStale(stale);updateTextSearchTimeFilterNotApplied(Boolean(timeFilterNotApplied));updateTextSearchState("completed");updateTextSearchResults(textResults);updateLlmTextSearchResults(resultsForLlm);22 unmodified linesif (isCurrent()) {updateTextSearchStale(false);updateTextSearchTimeFilterNotApplied(false);updateTextSearchState("failed");}textSearchFailed = true;49 unmodified linessearchQuery,getSettings().searchResultsLimit,getSettings().searchTimeRange,);results.imageResults = imageResults;19 unmodified lines202122232425263 unmodified lines303132333435363738394041316 unmodified lines3583593603613623633643653663 unmodified lines370371372373374375376377378379382 unmodified lines7627637647657667677687697707717727737747757767777787797807817827837847857867877887895 unmodified lines7957967977987998008018028038048058068077 unmodified lines81581681781881982082182222 unmodified lines84584684784884985085185249 unmodified lines90290390490590690790819 unmodified lineslistenToSettingsChanges,updateChatMessages,updateConversationSummary,updateGenerationRate,updateImageSearchResults,updateImageSearchState,updateLlmTextSearchResults,3 unmodified linesupdateSearchPromise,updateSuppressNextFollowUp,updateTextGenerationState,updateTextSearchLanguageNotApplied,updateTextSearchResults,updateTextSearchStale,updateTextSearchState,updateTextSearchTimeFilterNotApplied,updateTextSearchUnitConversion,} from "./pubSub";import { searchImages, searchText } from "./search";import { getLatestSearchAttempt, recordSearchAttempt } from "./searchAttempts";316 unmodified linesdocument.title = getQuery();updateResponse("");// The speed belongs to the answer it was measured on, so the previous one's// goes here instead of sitting under the new answer until it finishes.updateGenerationRate(undefined);clearConversationSummary();3 unmodified linesupdateTextSearchTimeFilterNotApplied(false);updateTextSearchLanguageNotApplied(false);updateTextSearchUnitConversion(null);updateLlmTextSearchResults([]);updateImageSearchResults([]);382 unmodified linesresults: textResults,stale,timeFilterNotApplied,languageNotApplied,unitConversion,} = searchQuery? await searchText(searchQuery,getSettings().searchResultsLimit,getSettings().searchTimeRange,getSettings().searchLanguage,): {results: [] as TextSearchResults,stale: false,timeFilterNotApplied: false,languageNotApplied: false,unitConversion: undefined,};// A conversion-only answer has no web results by design. The keyword// query drops "to" and "in" as stopwords, so it would lose the// conversion and could fail the search on an instance with blocked// engines.if (textResults.length === 0 && !unitConversion) {const keywordQuery = normalizeRelativeDates((await getKeywords(query, 10)).join(" "),asOf,5 unmodified lineskeywordQuery,getSettings().searchResultsLimit,getSettings().searchTimeRange,getSettings().searchLanguage,);textResults = keywordOutcome.results;stale = keywordOutcome.stale;timeFilterNotApplied = keywordOutcome.timeFilterNotApplied;languageNotApplied = keywordOutcome.languageNotApplied;unitConversion = keywordOutcome.unitConversion;}}7 unmodified linesif (isCurrent()) {updateTextSearchStale(stale);updateTextSearchTimeFilterNotApplied(Boolean(timeFilterNotApplied));updateTextSearchLanguageNotApplied(Boolean(languageNotApplied));updateTextSearchUnitConversion(unitConversion ?? null);updateTextSearchState("completed");updateTextSearchResults(textResults);updateLlmTextSearchResults(resultsForLlm);22 unmodified linesif (isCurrent()) {updateTextSearchStale(false);updateTextSearchTimeFilterNotApplied(false);updateTextSearchLanguageNotApplied(false);updateTextSearchUnitConversion(null);updateTextSearchState("failed");}textSearchFailed = true;49 unmodified linessearchQuery,getSettings().searchResultsLimit,getSettings().searchTimeRange,getSettings().searchLanguage,);results.imageResults = imageResults;
104 unmodified lines1051061071081091103 unmodified lines114115116117118119120121122104 unmodified lineslistenToSettingsChanges: vi.fn(() => vi.fn()),updateChatMessages: vi.fn(),updateConversationSummary: vi.fn(),updateImageSearchResults: vi.fn(),updateImageSearchState: vi.fn(),updateLlmTextSearchResults: vi.fn(),3 unmodified linesupdateSearchPromise: vi.fn(),updateSuppressNextFollowUp: vi.fn(),updateTextGenerationState: vi.fn(),updateTextSearchResults: vi.fn(),updateTextSearchStale: vi.fn(),updateTextSearchState: vi.fn(),updateTextSearchTimeFilterNotApplied: vi.fn(),};}104 unmodified lines1051061071081091101113 unmodified lines115116117118119120121122123124125104 unmodified lineslistenToSettingsChanges: vi.fn(() => vi.fn()),updateChatMessages: vi.fn(),updateConversationSummary: vi.fn(),updateGenerationRate: vi.fn(),updateImageSearchResults: vi.fn(),updateImageSearchState: vi.fn(),updateLlmTextSearchResults: vi.fn(),3 unmodified linesupdateSearchPromise: vi.fn(),updateSuppressNextFollowUp: vi.fn(),updateTextGenerationState: vi.fn(),updateTextSearchLanguageNotApplied: vi.fn(),updateTextSearchResults: vi.fn(),updateTextSearchStale: vi.fn(),updateTextSearchState: vi.fn(),updateTextSearchTimeFilterNotApplied: vi.fn(),updateTextSearchUnitConversion: vi.fn(),};}
1 unmodified line2345678 unmodified lines16171819202193 unmodified lines1151161171181191201 unmodified lineimport { addLogEntry } from "./logEntries";import {getSettings,updateResponse,updateTextGenerationState,} from "./pubSub";8 unmodified linesvi.mock("./pubSub", () => ({getSettings: vi.fn(),updateResponse: vi.fn(),updateTextGenerationState: vi.fn(),}));93 unmodified linesexpect(JSON.parse(startInit.body).models).toEqual(["chosen-model"]);});it("throws ChatGenerationError when the generation is faulted", async () => {const generateTextWithHorde = await loadHordeGenerator();1 unmodified line23456788 unmodified lines1718192021222393 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411 unmodified lineimport { addLogEntry } from "./logEntries";import {getSettings,updateGenerationRate,updateResponse,updateTextGenerationState,} from "./pubSub";8 unmodified linesvi.mock("./pubSub", () => ({getSettings: vi.fn(),updateGenerationRate: vi.fn(),updateResponse: vi.fn(),updateTextGenerationState: vi.fn(),}));93 unmodified linesexpect(JSON.parse(startInit.body).models).toEqual(["chosen-model"]);});it("publishes no speed, since the horde sends the whole text at once", async () => {const generateTextWithHorde = await loadHordeGenerator();mockFetch.mockResolvedValueOnce(jsonResponse({ id: "gen-rate" }));mockFetch.mockResolvedValueOnce(jsonResponse({done: true,is_possible: true,generations: [{ text: "All at once" }],}),);await generateTextWithHorde();// One poll carries the whole answer, so there is no rate to measure.expect(updateResponse).toHaveBeenCalledWith("All at once");expect(updateGenerationRate).not.toHaveBeenCalled();});it("throws ChatGenerationError when the generation is faulted", async () => {const generateTextWithHorde = await loadHordeGenerator();
6 unmodified lines7891011127 unmodified lines20212223242594 unmodified lines1201211221231241256 unmodified linesimport {getSettings,getTextGenerationState,updateResponse,updateTextGenerationState,} from "@/modules/pubSub";7 unmodified linesvi.mock("@/modules/pubSub", () => ({getSettings: vi.fn(),getTextGenerationState: vi.fn().mockReturnValue("idle"),updateResponse: vi.fn(),updateTextGenerationState: vi.fn(),}));94 unmodified lines});describe("generateTextWithOpenAi", () => {it("streams a text response and updates state", async () => {const { generateTextWithOpenAi } = await import("./textGenerationWithOpenAi"6 unmodified lines789101112137 unmodified lines2122232425262794 unmodified lines1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152166 unmodified linesimport {getSettings,getTextGenerationState,updateGenerationRate,updateResponse,updateTextGenerationState,} from "@/modules/pubSub";7 unmodified linesvi.mock("@/modules/pubSub", () => ({getSettings: vi.fn(),getTextGenerationState: vi.fn().mockReturnValue("idle"),updateGenerationRate: vi.fn(),updateResponse: vi.fn(),updateTextGenerationState: vi.fn(),}));94 unmodified lines});describe("generateTextWithOpenAi", () => {/*** Answers "Hello" over a held-open stream whose two deltas arrive 5 seconds* apart, so the answer's own span is known, and ends it after `lastChunk`.*/async function streamTimedDeltas(lastChunk: unknown) {let now = 0;const nowSpy = vi.spyOn(performance, "now").mockImplementation(() => now);const streams: ReturnType<typeof heldOpenSseResponse>[] = [];mockFetch.mockImplementation((_url: string, init?: RequestInit) => {const stream = heldOpenSseResponse(init);streams.push(stream);return Promise.resolve(stream.response);});try {const { generateTextWithOpenAi } = await import("./textGenerationWithOpenAi");const answer = generateTextWithOpenAi();await vi.waitFor(() => expect(streams).toHaveLength(1));now = 1000;streams[0].send({ choices: [{ delta: { content: "Hel" } }] });await vi.waitFor(() =>expect(updateResponse).toHaveBeenCalledWith("Hel"),);now = 6000;streams[0].send({ choices: [{ delta: { content: "lo" } }] });await vi.waitFor(() =>expect(updateResponse).toHaveBeenCalledWith("Hello"),);if (lastChunk) streams[0].send(lastChunk);streams[0].close();await expect(answer).resolves.toBe("Hello");} finally {nowSpy.mockRestore();}}it("publishes the speed from the completion count the backend reports", async () => {await streamTimedDeltas({choices: [{ delta: {}, finish_reason: "stop" }],usage: { prompt_tokens: 10, completion_tokens: 42, total_tokens: 52 },});// 41 of the 42 completion tokens (the first came before the clock)// across the 5 seconds between the first delta and the last, not across// the whole request.expect(updateGenerationRate).toHaveBeenCalledWith("8.2 tokens/s");});it("counts only the text tokens when the server kept its reasoning to itself", async () => {await streamTimedDeltas({choices: [{ delta: {}, finish_reason: "stop" }],usage: {prompt_tokens: 10,completion_tokens: 2042,total_tokens: 2052,completion_tokens_details: { reasoning_tokens: 2000 },},});// 2,000 reasoning tokens never streamed, so their time never reached// the clock: only the 42 text tokens count.expect(updateGenerationRate).toHaveBeenCalledWith("8.2 tokens/s");});it("asks the server for the token usage of the stream", async () => {const { generateTextWithOpenAi } = await import("./textGenerationWithOpenAi");mockFetch.mockResolvedValueOnce(sseResponse([{ choices: [{ delta: { content: "Hello" } }] }]),);await generateTextWithOpenAi();const body = JSON.parse(String(mockFetch.mock.calls[0]?.[1]?.body));expect(body.stream_options).toEqual({ include_usage: true });});it("publishes no speed when the backend reports no usage", async () => {await streamTimedDeltas(undefined);// A delta is not a token, so nothing here counts them exactly.expect(updateGenerationRate).toHaveBeenCalledWith(undefined);});it("streams a text response and updates state", async () => {const { generateTextWithOpenAi } = await import("./textGenerationWithOpenAi"
3 unmodified lines45678910111214 unmodified lines272829303132333435363718 unmodified lines565758596061626364656649 unmodified lines11611711811912012112212312412512612712812913026 unmodified lines15715815916016116216322 unmodified lines1861871881891901911921931947 unmodified lines2022032042052062073 unmodified linesselectRandomModel,} from "@shared/openaiModels";import { streamText } from "ai";import { addLogEntry } from "@/modules/logEntries";import {getSettings,updateResponse,updateTextGenerationState,} from "@/modules/pubSub";14 unmodified linesmessages: ChatMessage[];onUpdate: (text: string, reasoningContent?: string) => void;signal?: AbortSignal;}interface StreamResult {text: string;reasoningContent?: string;}/**18 unmodified linesmessages,onUpdate,signal,}: StreamOptions): Promise<StreamResult> {const settings = getSettings();const openaiProvider = createOpenAICompatible({name: settings.openAiApiBaseUrl,baseURL: settings.openAiApiBaseUrl,apiKey: settings.openAiApiKey,});49 unmodified lineslet text = "";let reasoning = "";let streamError: unknown;for await (const part of result.stream) {if (part.type === "reasoning-delta") {reasoning += part.text;onUpdate(text, reasoning);} else if (part.type === "text-delta") {text += part.text;onUpdate(text, reasoning);} else if (part.type === "error") {streamError = part.error;}26 unmodified lines}}return { text, reasoningContent: reasoning };} catch (error) {if (signal?.aborted ||22 unmodified lineslet generating = false;const result = await createOpenAiStream({messages,signal,onUpdate: (text, reasoningContent) => {if (!generating &&7 unmodified lines},});return composeResponseText(result.text, result.reasoningContent, settings);}3 unmodified lines456789101112131414 unmodified lines2930313233343536373839404142434445464718 unmodified lines6667686970717273747576777879808149 unmodified lines13113213313413513613713813914014114214314414514614714814915015115215315415515615726 unmodified lines18418518618718818919022 unmodified lines2132142152162172182192202212222232247 unmodified lines2322332342352362372382392403 unmodified linesselectRandomModel,} from "@shared/openaiModels";import { streamText } from "ai";import { GenerationRateMeter } from "@/modules/generationRate";import { addLogEntry } from "@/modules/logEntries";import {getSettings,updateGenerationRate,updateResponse,updateTextGenerationState,} from "@/modules/pubSub";14 unmodified linesmessages: ChatMessage[];onUpdate: (text: string, reasoningContent?: string) => void;signal?: AbortSignal;/** Times the main answer for the speed line; a chat reply passes none. */rateMeter?: GenerationRateMeter;}interface StreamResult {text: string;reasoningContent?: string;/*** The completion tokens the backend reported, which is the only exact count* this path has: a streamed delta is not always one token. Only some* OpenAI-compatible backends report usage, and then only at the end.*/outputTokens?: number;}/**18 unmodified linesmessages,onUpdate,signal,rateMeter,}: StreamOptions): Promise<StreamResult> {const settings = getSettings();const openaiProvider = createOpenAICompatible({name: settings.openAiApiBaseUrl,baseURL: settings.openAiApiBaseUrl,// Asks the server for the token usage at the end of the stream// (`stream_options.include_usage`), the only exact count it gives; the// provider leaves it off unless asked.includeUsage: true,apiKey: settings.openAiApiKey,});49 unmodified lineslet text = "";let reasoning = "";let outputTokens: number | undefined;let streamError: unknown;for await (const part of result.stream) {if (part.type === "reasoning-delta") {reasoning += part.text;rateMeter?.onDelta();onUpdate(text, reasoning);} else if (part.type === "text-delta") {text += part.text;rateMeter?.onDelta();onUpdate(text, reasoning);} else if (part.type === "finish") {// The completion count includes reasoning tokens. When the server// kept its reasoning to itself, their time never reached the clock,// so only the text tokens are counted against it.outputTokens =reasoning.length > 0? part.totalUsage.outputTokens: (part.totalUsage.outputTokenDetails?.textTokens ??part.totalUsage.outputTokens);} else if (part.type === "error") {streamError = part.error;}26 unmodified lines}}return { text, reasoningContent: reasoning, outputTokens };} catch (error) {if (signal?.aborted ||22 unmodified lineslet generating = false;const rateMeter = new GenerationRateMeter();const result = await createOpenAiStream({messages,signal,rateMeter,onUpdate: (text, reasoningContent) => {if (!generating &&7 unmodified lines},});rateMeter.setTokenCount(result.outputTokens);updateGenerationRate(rateMeter.rate());return composeResponseText(result.text, result.reasoningContent, settings);}
2 unmodified lines34567817 unmodified lines262728293031296 unmodified lines3283293303313323332 unmodified linesimport { addLogEntry } from "./logEntries";import {getSettings,updateModelLoadingProgress,updateModelSizeInMegabytes,updateSettings,17 unmodified linesreasoningEndMarker: "</think>",}),getTextGenerationState: vi.fn().mockReturnValue("generating"),updateModelLoadingProgress: vi.fn(),updateModelSizeInMegabytes: vi.fn(),updateResponse: vi.fn(),296 unmodified lines});});describe("composeStreamedText", () => {it("returns the answer unchanged when the model does not think", () => {expect(composeStreamedText("", "The answer.")).toBe("The answer.");2 unmodified lines345678917 unmodified lines27282930313233296 unmodified lines3303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194202 unmodified linesimport { addLogEntry } from "./logEntries";import {getSettings,updateGenerationRate,updateModelLoadingProgress,updateModelSizeInMegabytes,updateSettings,17 unmodified linesreasoningEndMarker: "</think>",}),getTextGenerationState: vi.fn().mockReturnValue("generating"),updateGenerationRate: vi.fn(),updateModelLoadingProgress: vi.fn(),updateModelSizeInMegabytes: vi.fn(),updateResponse: vi.fn(),296 unmodified lines});});describe("generation speed", () => {beforeEach(() => {vi.clearAllMocks();});/*** Streams `chunks`, each one arriving at its own moment on a clock the test* owns, and answers with the speed the run published.*/async function streamOnClock(chunks: {delta: Record<string, string>;at: number;timings?: { predicted_per_second: number };}[],signal?: AbortSignal,onChunk?: () => void,) {let now = 0;const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);vi.mocked(initializeWllama).mockImplementation(async () =>({createChatCompletion: vi.fn().mockResolvedValue((async function* () {for (const { delta, at, timings } of chunks) {now = at;yield { choices: [{ delta }], timings };onChunk?.();}})(),),exit: vi.fn().mockResolvedValue(undefined),// biome-ignore lint/suspicious/noExplicitAny: minimal Wllama stub}) as any,);try {await generateTextWithWllama(signal);return vi.mocked(updateGenerationRate).mock.calls.at(-1)?.[0];} finally {nowSpy.mockRestore();}}it("publishes llama.cpp's own decode speed from the last chunk", async () => {const rate = await streamOnClock([{ delta: { content: "The" }, at: 0 },{ delta: { reasoning_content: "hmm" }, at: 1000 },{ delta: { content: "answer" }, at: 2000 },// The last chunk carries no text, only the timings.{ delta: {}, at: 4000, timings: { predicted_per_second: 23.77 } },]);expect(rate).toBe("23.8 tokens/s");});it("publishes nothing when the engine reports no timings", async () => {const rate = await streamOnClock([{ delta: { content: "The" }, at: 0 },{ delta: { content: "answer" }, at: 2000 },]);// A chunk is not always one token, so counting chunks would be a guess.expect(rate).toBeUndefined();});it("publishes nothing when the answer is interrupted", async () => {const controller = new AbortController();await expect(streamOnClock([{ delta: { content: "an" }, at: 0 },{ delta: { content: "swer" }, at: 1000 },],controller.signal,() => controller.abort(),),).rejects.toThrow("Chat generation interrupted");expect(updateGenerationRate).not.toHaveBeenCalled();});});describe("composeStreamedText", () => {it("returns the answer unchanged when the model does not think", () => {expect(composeStreamedText("", "The answer.")).toBe("The answer.");
1234567825 unmodified lines3435363738395 unmodified lines45464748495051525354555627 unmodified lines84858687888923 unmodified lines11311411511611711867 unmodified lines186187188189190191import type { Wllama } from "@wllama/wllama";import { FALLBACK_CONFIG, getConfig } from "./config";import { addLogEntry } from "./logEntries";import {getSettings,updateModelLoadingProgress,updateModelSizeInMegabytes,updateResponse,25 unmodified linesif (!getSettings().enableAiResponse) return "";try {const response = await generateWithWllama({messages: async () => {const modelConfig = await getSelectedWllamaModel();5 unmodified lines},onUpdate: updateResponse,shouldCheckCanRespond: true,signal,});// An abort while the session exits still returns the whole answer.if (signal?.aborted)throw new ChatGenerationError("Generation interrupted");updateResponse(response);return response;} catch (error) {addLogEntry(27 unmodified linesonUpdate: (text: string) => void;shouldCheckCanRespond?: boolean;signal?: AbortSignal;}/**23 unmodified linesmessages: messagesOrBuilder,onUpdate,shouldCheckCanRespond = false,signal,}: WllamaConfig): Promise<string> {let loadingPercentage = 0;67 unmodified linesconst reasoningDelta =(chunk.choices[0]?.delta as { reasoning_content?: string } | undefined)?.reasoning_content ?? "";if (!delta && !reasoningDelta) continue;if (shouldCheckCanRespond && !generating) {1234567891025 unmodified lines363738394041425 unmodified lines484950515253545556575859606127 unmodified lines899091929394959697989923 unmodified lines12312412512612712812967 unmodified lines197198199200201202203204205206207208import type { Wllama } from "@wllama/wllama";import { FALLBACK_CONFIG, getConfig } from "./config";import { GenerationRateMeter } from "./generationRate";import { addLogEntry } from "./logEntries";import {getSettings,updateGenerationRate,updateModelLoadingProgress,updateModelSizeInMegabytes,updateResponse,25 unmodified linesif (!getSettings().enableAiResponse) return "";try {const rateMeter = new GenerationRateMeter();const response = await generateWithWllama({messages: async () => {const modelConfig = await getSelectedWllamaModel();5 unmodified lines},onUpdate: updateResponse,shouldCheckCanRespond: true,rateMeter,signal,});// An abort while the session exits still returns the whole answer.if (signal?.aborted)throw new ChatGenerationError("Generation interrupted");updateResponse(response);updateGenerationRate(rateMeter.rate());return response;} catch (error) {addLogEntry(27 unmodified linesonUpdate: (text: string) => void;shouldCheckCanRespond?: boolean;signal?: AbortSignal;/*** Times the answer for the speed line. Only the main answer carries one:* a chat reply shows no rate, and it shares this generation code.*/rateMeter?: GenerationRateMeter;}/**23 unmodified linesmessages: messagesOrBuilder,onUpdate,shouldCheckCanRespond = false,rateMeter,signal,}: WllamaConfig): Promise<string> {let loadingPercentage = 0;67 unmodified linesconst reasoningDelta =(chunk.choices[0]?.delta as { reasoning_content?: string } | undefined)?.reasoning_content ?? "";// The last chunk carries llama.cpp's own decode speed, with no text, so// it is read before the skip below. A chunk is not always one token, so// nothing is counted here.rateMeter?.setMeasuredRate(chunk.timings?.predicted_per_second ?? undefined,);if (!delta && !reasoningDelta) continue;if (shouldCheckCanRespond && !generating) {
136 unmodified lines13713813914014114237 unmodified lines1801811821831841856 unmodified lines1921931941951961971981992002012021 unmodified line204205206207208209210211212213214215216217218136 unmodified lines| `token` | yes | Search token hash || `limit` | no | How many of SearXNG's results to consider, default and maximum 30; a value that is not a positive integer falls back to the default. SearXNG is not sent this number: it caps a single SearXNG response after duplicate URLs are dropped, and the score filter below can return fewer || `time_range` | no | Only results published within this period: `day`, `week`, `month` or `year`. Absent means any time, and the request to SearXNG then carries no `time_range` at all |Responds with a JSON array of tuples, in the order the client renders them:37 unmodified lines| `400` | `{"error":"Missing query parameter"}` | `q` missing or blank || `400` | `{"error":"Query parameter must not exceed 2000 characters"}` | `q` too long || `400` | `{"error":"Invalid time_range parameter"}` | `time_range` is not `day`, `week`, `month` or `year` || `502` | `{"error":"Search service unavailable"}` | SearXNG failed and the text-search fallback was off or failed too, so an outage is distinguishable from a search with no matches || `500` | `{"error":"Internal server error"}` | Anything else |6 unmodified linesdeadline when that is shorter, and each attempt gets the remaining budgetdivided by the number of providers still untried and not paused. A providerpaused after a `429` is skipped without a request. The cascade runs only after SearXNG hasfailed: never while SearXNG answers, and never on an image search. It isskipped 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 the1 unmodified lineresults, 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 thesearch fall through to the same `502`.Those providers take a query and a count, so none of them can apply a`time_range`. When one answers a search that asked for one, the responsecarries `X-Search-Time-Range-Applied: false` and the body is unchanged: theheader is the only signal, so a client that ignores it still parses theresults. The header is absent on every other response, including a search thatasked for no time range, and the client says "Time filter not applied to theseresults" above the results it got that way.### `GET /search/images`136 unmodified lines13713813914014114214337 unmodified lines1811821831841851861876 unmodified lines1941951961971981992002012022032042051 unmodified line207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253136 unmodified lines| `token` | yes | Search token hash || `limit` | no | How many of SearXNG's results to consider, default and maximum 30; a value that is not a positive integer falls back to the default. SearXNG is not sent this number: it caps a single SearXNG response after duplicate URLs are dropped, and the score filter below can return fewer || `time_range` | no | Only results published within this period: `day`, `week`, `month` or `year`. Absent means any time, and the request to SearXNG then carries no `time_range` at all || `language` | no | Which language the results come back in: a locale with an optional region (`pt`, `pt-BR`, `en-US`), `all` for no preference, or `auto`. Absent means the request to SearXNG carries no `language` at all, leaving SearXNG on its own default |Responds with a JSON array of tuples, in the order the client renders them:37 unmodified lines| `400` | `{"error":"Missing query parameter"}` | `q` missing or blank || `400` | `{"error":"Query parameter must not exceed 2000 characters"}` | `q` too long || `400` | `{"error":"Invalid time_range parameter"}` | `time_range` is not `day`, `week`, `month` or `year` || `400` | `{"error":"Invalid language parameter"}` | `language` is not a locale SearXNG takes: `^[a-z]{2,3}(-[a-zA-Z]{2})?$`, or `all`, or `auto` || `502` | `{"error":"Search service unavailable"}` | SearXNG failed and the text-search fallback was off or failed too, so an outage is distinguishable from a search with no matches || `500` | `{"error":"Internal server error"}` | Anything else |6 unmodified linesdeadline when that is shorter, and each attempt gets the remaining budgetdivided by the number of providers still untried and not paused. A providerpaused after a `429` is skipped without a request. The cascade runs only after SearXNG hasfailed, and never on an image search. The one case where SearXNG answered is aunit conversion that only the plugin could answer, described below. It isskipped 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 (or, for that conversion, a`200` with no results) and counts as a fallback that failed. 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 the1 unmodified lineresults, 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 thesearch fall through to the same `502`, except for a unit conversion the pluginanswered, which stays a `200` with `[]` and its header.Those providers take a query and a count, so none of them can apply a`time_range` or a `language`. When one answers a search that asked for either,the response carries `X-Search-Time-Range-Applied: false` and`X-Search-Language-Applied: false` for whichever was lost, and the body isunchanged: the headers are the only signal, so a client that ignores them stillparses the results. A header is absent on every other response, including asearch that asked for no time range and no language, and the client nameswhichever was lost above the results it got that way: "Time filter not appliedto these results", "Language not applied to these results", or "Time filter andlanguage not applied to these results".A text search can also carry a unit conversion, in`X-Search-Unit-Conversion`. SearXNG runs a `unit_converter` plugin over thequery itself, which answers a query shaped `<number> <unit> to|in|as <unit>`(`5 m to ft` gives `16.4041994751 ft`), and the plugin needs no search engine.Only its answers are sent, and only its own: the same `answers` field carriesanswers from search engines, and those misread such queries (the currencyengine read `5 m to ft` as `5.0 LSL = 97.4461855875 HUF`). The body is an arrayof results and has no room for the value, so the header is the only place itgoes, percent-encoded with `encodeURIComponent` because a header value cannotcarry every character the answer can; read it back with `decodeURIComponent`. Itis absent whenever the plugin answered nothing, which is every search that isnot a conversion.Because the plugin answered, such a search is served rather than failed evenwhen its engines returned nothing or reported themselves unresponsive: the`502` above is not the answer to a query that was answered, and the body is then`[]`. When the engines were the ones that failed and the fallback above isswitched on, the fallback is asked for web results as it would be for any otherfailed search, and the header stays. If the fallback fails, the answer is stillthe `200` with `[]` and the header, not the `502`. The client shows the value above theresults in a "Unit conversion" card, and keeps it with the cached results, so asearch served from the cache shows it too.The conversion needs the request to reach SearXNG. While the text circuitbreaker is open, which is most of the time on a Hugging Face Space where everyweb engine is blocked, the request never gets there and carries no conversion.An image search never carries one.### `GET /search/images`
146 unmodified lines147148149150151152326 unmodified lines479480481482483484485146 unmodified lines| `enableTextSearch` | boolean | `true` | Include text results in searches || `searchResultsLimit` | number | `15` | Maximum search results to fetch || `searchTimeRange` | string | `any` | Only return results published within this period: `any`, `day`, `week`, `month` or `year` || `systemPrompt` | string | (template) | Custom system prompt template for AI || `enterToSubmit` | boolean | `true` | Press Enter to submit query (vs Shift+Enter for new line) || `enableAiResponseScrolling` | boolean | `true` | Auto-scroll AI response as it generates |326 unmodified linesMiniSearch logs internal events to an in-app log panel (see the Logs section of the menu), backed by `logEntriesPubSub` in `client/modules/logEntries.ts`. There is no separate browser-console debug flag to enable.**Diagnosing empty search results:** the client distinguishes a search that returned no results (a no-results alert, state stays `completed`) from one that failed outright on an outage (a distinct failed state, with a retry on text searches). An empty response that names unresponsive engines is retried within the same budget as a 500 and counts as the second if it is still empty when the retries are spent, since a rate-limited, suspended or CAPTCHA-challenged engine is reported that way and not with a status code. The actual reason is printed to the server's console (via `server/webSearchService.ts`, always-on `debug` logging), either the SearXNG engines that failed (timeouts, suspensions, rate limits, from SearXNG's `unresponsive_engines` field) or a note that all returned results were discarded during processing (missing title, snippet, or media source). Check the server logs (`docker compose logs`) when troubleshooting failed searches.Check effective configuration:146 unmodified lines147148149150151152153326 unmodified lines480481482483484485486146 unmodified lines| `enableTextSearch` | boolean | `true` | Include text results in searches || `searchResultsLimit` | number | `15` | Maximum search results to fetch || `searchTimeRange` | string | `any` | Only return results published within this period: `any`, `day`, `week`, `month` or `year` || `searchLanguage` | string | `browser` | Results language: `browser`, `auto` (from the query), `all` (no preference), or a locale like `pt-BR` || `systemPrompt` | string | (template) | Custom system prompt template for AI || `enterToSubmit` | boolean | `true` | Press Enter to submit query (vs Shift+Enter for new line) || `enableAiResponseScrolling` | boolean | `true` | Auto-scroll AI response as it generates |326 unmodified linesMiniSearch logs internal events to an in-app log panel (see the Logs section of the menu), backed by `logEntriesPubSub` in `client/modules/logEntries.ts`. There is no separate browser-console debug flag to enable.**Diagnosing empty search results:** the client distinguishes a search that returned no results (a no-results alert, state stays `completed`) from one that failed outright on an outage (a distinct failed state, with a retry on text searches). An empty response that names unresponsive engines is retried within the same budget as a 500 and counts as the second if it is still empty when the retries are spent, since a rate-limited, suspended or CAPTCHA-challenged engine is reported that way and not with a status code. A conversion query the unit converter plugin answered is the exception: it is served on the first attempt, with no retries and no failure counted. The actual reason is printed to the server's console (via `server/webSearchService.ts`, always-on `debug` logging), either the SearXNG engines that failed (timeouts, suspensions, rate limits, from SearXNG's `unresponsive_engines` field) or a note that all returned results were discarded during processing (missing title, snippet, or media source). Check the server logs (`docker compose logs`) when troubleshooting failed searches.Check effective configuration:
.source-commit+1-1
agents.md+2-1
changelog.md+9
client/components/AiResponse/AiResponseContent.test.tsx+162-10
client/components/AiResponse/AiResponseContent.tsx+95-2
client/components/AiResponse/CopyIconButton.tsx+5-1
client/components/Pages/Main/Menu/SearchSettingsForm.tsx+12
client/components/Pages/Main/Menu/SettingsForms.test.tsx+33
client/components/Search/Results/Textual/TextSearchResults.test.tsx+77
client/components/Search/Results/Textual/TextSearchResults.tsx+26-2
client/components/Search/Results/Textual/UnitConversionCard.tsxAdded+23
client/hooks/useHistoryRestore.ts+7
client/modules/answerExport.test.tsAdded+278
client/modules/answerExport.tsAdded+141
client/modules/chatHelpers.test.ts+32-4
client/modules/chatHelpers.ts+15-2
client/modules/generationRate.test.tsAdded+104
client/modules/generationRate.tsAdded+82
client/modules/history.test.ts+54
client/modules/history.ts+2-1
client/modules/imageResultKey.test.tsAdded+27
client/modules/imageResultKey.ts+4-6
client/modules/pubSub.test.ts+10
client/modules/pubSub.ts+31
client/modules/search.test.ts+215
client/modules/search.ts+128-13
client/modules/settings.ts+13-2
client/modules/stringFormatters.test.ts+25
client/modules/stringFormatters.ts+9-2
client/modules/textGeneration.degradation.test.ts+31
client/modules/textGeneration.test.ts+1
client/modules/textGeneration.ts+28-1
client/modules/textGenerationTestUtils.ts+3
client/modules/textGenerationWithHorde.test.ts+21
client/modules/textGenerationWithOpenAi.test.ts+91
client/modules/textGenerationWithOpenAi.ts+34-1
client/modules/textGenerationWithWllama.test.ts+87
client/modules/textGenerationWithWllama.ts+17
docs/api.md+45-10
docs/configuration.md+2-1