Spaces:
Running
Running
Sync from felladrin/MiniSearch@ebacf26
Browse filesFiles changed (32)
- .source-commit+1-1
- agents.md+1
- changelog.md+8
- client/components/Pages/Main/Menu/SearchSettingsForm.tsx+11-1
- client/components/Pages/Main/Menu/SettingsForms.test.tsx+29-1
- client/components/Search/Form/SearchForm.test.tsx+19
- client/components/Search/Form/SearchForm.tsx+29-3
- client/components/Search/Results/Graphical/ImageResultsList.test.tsx+26
- client/components/Search/Results/Graphical/ImageResultsList.tsx+19-15
- client/components/Search/Results/Textual/TextSearchResults.test.tsxAdded+82
- client/components/Search/Results/Textual/TextSearchResults.tsx+8-1
- client/hooks/useHistoryRestore.test.ts+26
- client/hooks/useHistoryRestore.ts+17-1
- client/modules/chatHelpers.test.ts+87-16
- client/modules/chatHelpers.ts+25-8
- client/modules/history.test.ts+105
- client/modules/history.ts+54-17
- client/modules/imageResultKey.tsAdded+14
- client/modules/pubSub.test.ts+10
- client/modules/pubSub.ts+12
- client/modules/search.test.ts+180-21
- client/modules/search.ts+105-21
- client/modules/settings.ts+15-1
- client/modules/speechToText.ts-1
- client/modules/textGeneration.degradation.test.ts+18
- client/modules/textGeneration.ts+28-5
- client/modules/textGenerationTestUtils.ts+1
- client/modules/textGenerationWithWllama.ts-1
- client/modules/wllama.initialize.test.ts+15-5
- client/modules/wllama.ts+16-9
- docs/api.md+15-5
- docs/configuration.md+1
11cdd715febacf26131 unmodified lines132133134135136137138131 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 localStorage1 unmodified line2345678910111213141516171 unmodified line
Notable 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.
## 2026-11-27
- An answer that finishes after you delete its search from History is no longer saved. It used to be stored anyway, with no search to point to, so it stayed in the browser's storage where you could neither see nor remove it. It still shows in the open tab until you leave the search.- Image search now shows every image the search finds on a page, not just the first. Images were told apart by the page they were found on, so several different images from one gallery page came back as one result, and the carousel showed one photo where there were several. Images are now told apart by their full-size image, or their thumbnail when there is none, when results are deduplicated and reranked, when a follow-up's images are merged in, and when images are saved to history. The same image reported twice is still shown once.- The in-browser AI model list now marks the models that are already downloaded. A model whose files are all in the browser's cache shows "โข Downloaded" after its name, so a model that starts answering at once no longer looks the same as one that first downloads hundreds of megabytes. A model whose download stopped halfway is not marked, and the list is checked again each time it opens, so a download that finishes during the visit shows up without a reload.- Starting a new search from the results page now ends dictation, releases the microphone and discards any pending transcript. You can start dictating again right away.- Image search failing no longer takes text search down with it. Text and image searches shared one circuit breaker, so five image searches in a row lost to failing image engines opened it and refused every text search for up to a minute, although SearXNG was still serving text results. Each search type now has its own circuit. `/status` adds `searches.circuitStateByType` and `searches.circuitOpensByType`, while `circuitState` keeps reporting the worse of the two circuits and `circuitOpens` their sum, so existing monitors keep working. An open image circuit alone now makes `webSearchServiceStatus` `degraded` rather than `unhealthy`.11234567891021 unmodified lines3233343536373839404142434445import { Slider, Stack, Switch, Text } from "@mantine/core";import { 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;21 unmodified lines /> </Stack>
<Select {...form.getInputProps("searchTimeRange")} label="Time Range" description="Only show results published within this period. Anytime applies no time filter." data={searchTimeRangeOptions} allowDeselect={false} />
<Switch {...form.getInputProps("enableTextSearch", { type: "checkbox",12234512 unmodified lines18192021222324252627282930313233343533 unmodified lines6970717273747576777879808182838485868788import { MantineProvider } from "@mantine/core";import { act, fireEvent, render, screen } from "@testing-library/react";import { act, fireEvent, render, screen, within } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";import { settingsPubSub } from "@/modules/pubSub";import { defaultSettings } from "@/modules/settings";12 unmodified lines fireEvent.click(screen.getByRole("switch", { name }));}
/** Opens the time-range select and picks the option with this label. */function pickTimeRange(label: string) { const select = screen.getByRole("combobox", { name: /time range/i }); fireEvent.mouseDown(select); fireEvent.click(select); 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);33 unmodified lines wllamaModelId: "another-model", }); });
it("writes the time range chosen in the search section", () => { render( <MantineProvider> <SearchSettingsForm /> </MantineProvider>, );
expect(screen.getByRole("combobox", { name: /time range/i })).toHaveValue( "Anytime", );
pickTimeRange("Past week");
expect(getSettings()).toMatchObject({ searchTimeRange: "week" }); });});117 unmodified lines118119120121122123124125126127128129130131132133134135136137138139140141142117 unmodified lines await waitForPlaceholder(); });
it("offers the five time ranges in the button row", async () => { // Mantine scrolls the selected option into view, which jsdom does not have. Element.prototype.scrollIntoView = vi.fn(); const user = userEvent.setup(); renderSearchForm("hello", vi.fn()); await screen.findByRole("textbox");
const timeRange = screen.getByRole("combobox", { name: /time range/i }); expect(timeRange).toHaveValue("Anytime");
await user.click(timeRange);
expect( screen .getAllByRole("option", { hidden: true }) .map((option) => option.textContent), ).toEqual(["Anytime", "Past day", "Past week", "Past month", "Past year"]); });
describe("the suggestion for an emptied field", () => { it("is taken once when the last character is deleted", async () => { const user = userEvent.setup();11234567 unmodified lines7374757576777879180 unmodified lines2602612622632642652662672682692702712722732742752762772782792802812823 unmodified lines286287288271289290291292293294295296297298299300import { Button, Group, Stack, Textarea } from "@mantine/core";import { Button, Group, Select, Stack, Textarea } from "@mantine/core";import { searchTimeRangeOptions } from "@shared/searchTimeRange";import { usePubSub } from "create-pubsub/react";import { type ChangeEvent,67 unmodified lines const [dictationSessionKey, setDictationSessionKey] = useState(0);
const [, navigate] = useLocation(); const [pubSubSettings] = usePubSub(settingsPubSub); const [pubSubSettings, setPubSubSettings] = usePubSub(settingsPubSub); const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub); const { addToHistory } = useSearchHistory(); const { restoreSearch } = useHistoryRestore((newQuery) => {180 unmodified lines </div> <Group gap="xs"> <HistoryButton onSearchSelect={restoreSearch} /> <Select // Compact by design: the row sits under the query field, and the // period it sets is spelled out in the search settings too. size="xs" w={104} aria-label="Time range" data={searchTimeRangeOptions} value={pubSubSettings.searchTimeRange} allowDeselect={false} onChange={(timeRange) => { if (!timeRange) return; setPubSubSettings({ ...pubSubSettings, searchTimeRange: timeRange, }); }} /> {state.textAreaValue.length >= 1 && ( <Button size="xs"3 unmodified lines Clear </Button> )} <Button type="submit" size="xs" variant="default" flex={1}> {/* Wraps to its own line on a narrow screen instead of shrinking below its label, now that the time-range select shares the row. */} <Button type="submit" size="xs" variant="default" flex={1} miw="fit-content" > Search </Button> {additionalButtons}99 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013199 unmodified lines ); });
it("shows every image from the same page with its own thumbnail", async () => { const galleryImages: ImageSearchResult[] = ["first", "second"].map( (name) => [ `Gallery ${name}`, "https://example.com/gallery", `https://example.com/${name}-thumb.gif`, `https://example.com/${name}.gif`, ], ); render( <MantineProvider> <ImageResultsList imageResults={galleryImages} /> </MantineProvider>, );
await waitFor(() => expect( screen.getAllByRole("img").map((img) => img.getAttribute("src")), ).toEqual( ["first", "second"].map((name) => thumbnailSrcFor(`https://example.com/${name}-thumb.gif`), ), ), ); });
it("shows the host name for a result without a thumbnail", async () => { render( <MantineProvider>18 unmodified lines1920212223242551 unmodified lines77787980818283848 unmodified lines9394959396979895991009710110210310417 unmodified lines1221231241211221251261271281251261291301311321332 unmodified lines1361371381351391401411421 unmodified line14414514614314714814915031 unmodified lines1821831841811851861871887 unmodified lines1961971981951992002012025 unmodified lines20820921020721121221321421121221321521621721821922018 unmodified linesimport classes from "./ImageResultsList.module.css";import "yet-another-react-lightbox/styles.css";import "yet-another-react-lightbox/plugins/captions.css";import { imageResultKey } from "@/modules/imageResultKey";import { addLogEntry } from "@/modules/logEntries";import { getHostname } from "@/modules/stringFormatters";import { getThumbnailSrc } from "@/modules/thumbnailUrls";51 unmodified lines const [failedThumbnails, setFailedThumbnails] = useState< Record<string, boolean> >({}); // Thumbnails are tracked per image, not per page: one page can hold several. const imageKeys = imageResults.map(imageResultKey);
useEffect(() => { setState((prev) => ({ ...prev, canStartTransition: true }));8 unmodified lines
void (async () => { const entries = await Promise.all( imageResults.map(async ([, url, thumbnailUrl]) => { imageResults.map(async (result) => { const key = imageResultKey(result); try { return [url, await getThumbnailSrc(thumbnailUrl)] as const; return [key, await getThumbnailSrc(result[2])] as const; } catch { return [url, null] as const; return [key, null] as const; } }), );17 unmodified lines })); };
const markThumbnailFailed = (url: string) => { setFailedThumbnails((prev) => ({ ...prev, [url]: true })); const markThumbnailFailed = (key: string) => { setFailedThumbnails((prev) => ({ ...prev, [key]: true })); };
const renderTile = (title: string, url: string) => { const tileSrc = failedThumbnails[url] ? null : thumbnailSrcs[url]; const renderTile = (title: string, url: string, key: string) => { const tileSrc = failedThumbnails[key] ? null : thumbnailSrcs[key];
if (tileSrc) { return (2 unmodified lines src={tileSrc} loading="lazy" style={imageStyle} onError={() => markThumbnailFailed(url)} onError={() => markThumbnailFailed(key)} /> ); }1 unmodified line // `null` means the result has no thumbnail, or the load failed: the host // name is the most that can be shown. `undefined` means the src is still // being resolved, so the tile keeps a skeleton in the meantime. if (thumbnailSrcs[url] === undefined) { if (thumbnailSrcs[key] === undefined) { return ( <Box style={tileBoxStyle}> <Skeleton style={{ height: "100%", width: "100%" }} />31 unmodified lines > {imageResults.map(([title, url], index) => ( <Transition key={url} key={imageKeys[index]} mounted={state.canStartTransition} transition="fade" timingFunction="ease"7 unmodified lines className={classes.thumbnailButton} onClick={() => handleImageClick(index)} > {renderTile(title, url)} {renderTile(title, url, imageKeys[index])} </UnstyledButton> </Carousel.Slide> )}5 unmodified lines close={() => setState((prev) => ({ ...prev, isLightboxOpen: false }))} plugins={[Captions]} index={state.lightboxIndex} slides={imageResults.map(([title, url, , sourceUrl]) => ({ slides={imageResults.map(([title, url, , sourceUrl], index) => ({ // The grid's thumbnail when it loaded; when it did not, the same // host-name placeholder the tile shows. src: thumbnailSrcs[url] && !failedThumbnails[url] ? thumbnailSrcs[url] : hostNamePlaceholder(getHostname(url)), (!failedThumbnails[imageKeys[index]] && thumbnailSrcs[imageKeys[index]]) || hostNamePlaceholder(getHostname(url)), alt: title, description: ( <Stack align="center" gap="md">12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import { MantineProvider } from "@mantine/core";import { 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";
vi.mock("./SearchResultsList", () => ({ default: ({ searchResults }: { searchResults: string[][] }) => ( <ul aria-label="Text results"> {searchResults.map(([title]) => ( <li key={title}>{title}</li> ))} </ul> ),}));
const [setTextSearchState] = textSearchStatePubSub;const [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( <MantineProvider> <TextSearchResults /> </MantineProvider>, );}
beforeEach(() => { act(() => { setTextSearchState("completed"); setTextSearchResults(results); });});
afterEach(() => { act(() => { setTextSearchState("idle"); setTextSearchResults([]); setTextSearchStale(false); setTextSearchTimeFilterNotApplied(false); });});
describe("TextSearchResults", () => { it("says when the results carry no time filter although one was asked for", () => { act(() => setTextSearchTimeFilterNotApplied(true)); renderTextSearchResults();
expect(screen.getByText(NOTE)).toBeInTheDocument(); expect(screen.getByLabelText("Text results")).toBeInTheDocument(); });
it("says nothing when the time filter was applied", () => { renderTextSearchResults();
expect(screen.queryByText(NOTE)).not.toBeInTheDocument(); });
it("says nothing when there are no results to put the note over", () => { act(() => { setTextSearchResults([]); setTextSearchTimeFilterNotApplied(true); }); renderTextSearchResults();
expect(screen.queryByText(NOTE)).not.toBeInTheDocument(); });});112343 unmodified lines8910111213144 unmodified lines1920212223242518 unmodified lines4445464748495051525354import { Alert, Button, Group } from "@mantine/core";import { Alert, Button, Group, Text } from "@mantine/core";import { IconInfoCircle, IconRefresh } from "@tabler/icons-react";import { usePubSub } from "create-pubsub/react";import {3 unmodified lines textSearchResultsPubSub, textSearchStalePubSub, textSearchStatePubSub, textSearchTimeFilterPubSub,} from "@/modules/pubSub";import { searchAndRespond } from "@/modules/textGeneration";
4 unmodified lines 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);18 unmodified lines results 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} /> </> );205 unmodified lines206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237205 unmodified lines expect(imageSearchStatePubSub[2]()).toBe("completed"); });
it("restores one picture saved twice from two pages as one image", async () => { const picture = { title: "Same picture", thumbnail: "https://cdn.example.com/thumbnail.png", sourceUrl: "https://cdn.example.com/picture.png", }; await restoreEntry({ imageResults: { type: "image", items: [ { ...picture, url: "https://first.example.com/gallery" }, { ...picture, url: "https://second.example.com/gallery" }, ], }, });
expect(imageSearchResultsPubSub[2]()).toEqual([ [ "Same picture", "https://first.example.com/gallery", "https://cdn.example.com/thumbnail.png", "https://cdn.example.com/picture.png", ], ]); });
it("leaves suppressNextFollowUp false when the restored entry has no saved response", async () => { await restoreEntry({ textResults });
10 unmodified lines1112131415161713 unmodified lines3132333435363748 unmodified lines86878889909192939421 unmodified lines11611711811912012112211412312412512612712812913013113213310 unmodified lines hasTextResults, setCurrentSearchRunId,} from "../modules/history";import { imageResultKey } from "../modules/imageResultKey";import { postMessageToParentWindow } from "../modules/parentWindow";import { getChatGenerationState,13 unmodified lines updateTextSearchResults, updateTextSearchStale, updateTextSearchState, updateTextSearchTimeFilterNotApplied,} from "../modules/pubSub";import { cancelSearchAnswer } from "../modules/textGeneration";import type { ImageSearchResults, TextSearchResults } from "../modules/types";48 unmodified lines // Replacing the chat also replaces the source material it can use. updatePageContents({}); updateTextSearchStale(false); // 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;21 unmodified lines it.thumbnail, it.sourceUrl || "", ]); // History saved before images were told apart by their own source // was deduplicated by page, so it can hold one picture twice (found // on two pages). The list keys tiles by image, so keep the first. const seen = new Set<string>(); updateImageSearchResults(imageTuples); updateImageSearchResults( imageTuples.filter((tuple) => { const key = imageResultKey(tuple); if (seen.has(key)) return false; seen.add(key); return true; }), ); updateImageSearchState("completed"); } else { updateImageSearchResults([]);14 unmodified lines1516171819202122232425262724 unmodified lines5253545556575859606162636415 unmodified lines808182838485868788899091929394959697989910010110210310410567 unmodified lines1731741751521761771781791801811821831841851861871881891901911921931941951961971981992002011542022032042052062072082091571582102112122132142152162172182191 unmodified line2212222231661672242252262272282292302312322332342351732362372381762392402412429 unmodified lines2522532541922552562572582592601982612622632641 unmodified line2662672682062692702712722102112732742752762772782792802812822 unmodified lines28528628722028828929029127 unmodified lines31932032132232332432591 unmodified lines41741841935135242042142242342426 unmodified lines451452453454455456457103 unmodified lines56156256356456556656714 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(),}));vi.mock("./pageContent", () => ({ fetchPageContents: vi.fn(() => Promise.resolve({})),24 unmodified linesimport { getImageSearchResults, getPageContents, getTextSearchTimeFilterNotApplied, updateImageSearchResults, updateLlmTextSearchResults, updatePageContents, updateTextSearchResults, updateTextSearchStale, updateTextSearchTimeFilterNotApplied,} from "./pubSub";import { generateRelatedSearchQuery } from "./relatedSearchQuery";import { searchImages, searchText } from "./search";15 unmodified linesconst mockGenerateRelatedSearchQuery = vi.mocked(generateRelatedSearchQuery);
describe("refreshTextSearchResults", () => { it.each([ { shown: true, followUp: false, note: true }, { shown: false, followUp: true, note: true }, { shown: false, followUp: false, note: false }, ])( "shows the time-filter note: $note (results on screen without the filter: $shown, follow-up without it: $followUp)", async ({ shown, followUp, note }) => { vi.mocked(getTextSearchTimeFilterNotApplied).mockReturnValueOnce(shown); mockSearchText.mockResolvedValueOnce({ results: [["New", "snippet", "https://new.com"]], stale: false, timeFilterNotApplied: followUp, });
await refreshTextSearchResults("query", 10, [], undefined, "week");
expect(updateTextSearchTimeFilterNotApplied).toHaveBeenCalledWith(note); }, );
it("deduplicates by URL and appends fresh results", async () => { const existing: TextSearchResults = [ ["Existing", "snippet", "https://existing.com"],67 unmodified lines});
describe("refreshImageSearchResults", () => { it("deduplicates by URL and prepends fresh results", async () => { it("keeps a fresh image from the same page as one on screen", async () => { const existing: ImageSearchResults = [ [ "First", "https://gallery.com", "https://gallery.com/first-thumb.jpg", "https://gallery.com/first.jpg", ], ]; const fresh: ImageSearchResults = [ [ "Second", "https://gallery.com", "https://gallery.com/second-thumb.jpg", "https://gallery.com/second.jpg", ], ]; mockSearchImages.mockResolvedValueOnce({ results: fresh, stale: false });
await refreshImageSearchResults("query", 10, existing);
expect(mockUpdateImage).toHaveBeenCalledWith([...fresh, ...existing]); });
it("drops a fresh copy of an image on screen and prepends the rest", async () => { const existing: ImageSearchResults = [ ["Existing", "https://existing.com", "thumb", "source"], [ "Existing", "https://existing.com", "thumb", "https://existing.com/full.jpg", ], ]; const fresh: ImageSearchResults = [ ["New", "https://new.com", "thumb", "source"], ["Duplicate", "https://existing.com", "thumb", "source"], ["New", "https://new.com", "thumb", "https://new.com/full.jpg"], [ "Duplicate", "https://existing.com", "thumb", "https://existing.com/full.jpg", ], ];
mockSearchImages.mockResolvedValueOnce({ results: fresh, stale: false });1 unmodified line await refreshImageSearchResults("query", 10, existing);
expect(mockUpdateImage).toHaveBeenCalledWith([ ["New", "https://new.com", "thumb", "source"], ["Existing", "https://existing.com", "thumb", "source"], ["New", "https://new.com", "thumb", "https://new.com/full.jpg"], [ "Existing", "https://existing.com", "thumb", "https://existing.com/full.jpg", ], ]); });
it("keeps the first search's images that landed after the follow-up started", async () => { const firstImages: ImageSearchResults = [ ["First", "https://first.com", "thumb", "source"], ["First", "https://first.com", "thumb", "https://first.com/full.jpg"], ]; const fresh: ImageSearchResults = [ ["New", "https://new.com", "thumb", "source"], ["New", "https://new.com", "thumb", "https://new.com/full.jpg"], ]; mockSearchImages.mockResolvedValueOnce({ results: fresh, stale: false }); // The follow-up was handed an empty list; the first images arrived since.9 unmodified lines title: "New", url: "https://new.com", thumbnail: "thumb", sourceUrl: "source", sourceUrl: "https://new.com/full.jpg", }, { title: "First", url: "https://first.com", thumbnail: "thumb", sourceUrl: "source", sourceUrl: "https://first.com/full.jpg", }, ], });1 unmodified line
it("shows an image found by both searches once", async () => { const firstImages: ImageSearchResults = [ ["First", "https://first.com", "thumb", "source"], ["First", "https://first.com", "thumb", "https://first.com/full.jpg"], ]; mockSearchImages.mockResolvedValueOnce({ results: [ ["New", "https://new.com", "thumb", "source"], ["First again", "https://first.com", "thumb", "source"], ["New", "https://new.com", "thumb", "https://new.com/full.jpg"], [ "First again", "https://first.com", "thumb", "https://first.com/full.jpg", ], ], stale: false, });2 unmodified lines await refreshImageSearchResults("query", 10, []);
expect(mockUpdateImage).toHaveBeenCalledWith([ ["New", "https://new.com", "thumb", "source"], ["New", "https://new.com", "thumb", "https://new.com/full.jpg"], ...firstImages, ]); });27 unmodified lines enableImageSearch: true, enablePageContentFetch: true, searchResultsLimit: 10, searchTimeRange: "any", ...overrides, }) as unknown as Parameters<typeof runFollowUpSearch>[2];
91 unmodified lines }
const anchoredQuery = "new series on disney plus next month December 2026"; expect(mockSearchText).toHaveBeenCalledWith(anchoredQuery, 10); expect(mockSearchImages).toHaveBeenCalledWith(anchoredQuery, 10); 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 () => {26 unmodified lines expect(mockSearchText).toHaveBeenCalledWith( "who won world series 2025", 10, "any", ); });
103 unmodified lines enableImageSearch: true, enablePageContentFetch: true, searchResultsLimit: 10, searchTimeRange: "any", ...overrides, }) as unknown as Parameters<typeof runFollowUpSearch>[2];
123452 unmodified lines89101112131415161718192021222324252632 unmodified lines596061626364655 unmodified lines7172736970717274757677787980814 unmodified lines868788899091929394959632 unmodified lines1291301311321331341355 unmodified lines1411421431441451461471 unmodified line149150151139152153154142155156157158144159160146161162163164107 unmodified lines27227327427527627727820 unmodified lines299300301302303304305import { normalizeFollowUpDates } from "@shared/relativeDates";import type { SearchTimeRange } from "@shared/searchTimeRange";import { getCurrentSearchRunId, type ImageResults,2 unmodified lines type TextResults, updateSearchResults,} from "./history";import { imageResultKey } from "./imageResultKey";import { addLogEntry } from "./logEntries";import { fetchPageContents } from "./pageContent";import { getImageSearchResults, getPageContents, getTextSearchTimeFilterNotApplied, updateImageSearchResults, updateLlmTextSearchResults, updatePageContents, updateTextSearchResults, updateTextSearchStale, updateTextSearchTimeFilterNotApplied,} from "./pubSub";import { searchImages, searchText } from "./search";import { getLatestSearchAttempt } from "./searchAttempts";32 unmodified lines resultsLimit: number, existingResults: TextSearchResults, searchRunId = getCurrentSearchRunId(), timeRange?: SearchTimeRange,): Promise<TextSearchResults> { const invocation = ++textRefreshInvocation; latestTextRefreshByRunId.set(searchRunId, invocation);5 unmodified lines const isRunCurrent = () => latestTextRefreshByRunId.get(searchRunId) === invocation && isSameAttempt();
const { results: freshResults, stale } = await searchText( searchQuery, resultsLimit, ); const { results: freshResults, stale, timeFilterNotApplied, } = await searchText(searchQuery, resultsLimit, timeRange);
if (freshResults.length === 0) return [];
4 unmodified lines
if (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); }
32 unmodified lines resultsLimit: number, existingResults: 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 one5 unmodified lines const { results: imageResults } = await searchImages( searchQuery, resultsLimit, timeRange, );
if (imageResults.length === 0) return;1 unmodified line // The first search's images can land after this refresh started, so it adds // to the list on screen now as well as the one it was handed then. const shown = isCurrent() ? getImageSearchResults() : []; const shownUrls = new Set(shown.map(([, url]) => url)); const shownKeys = new Set(shown.map(imageResultKey)); const baseResults: ImageSearchResults = [ ...shown, ...existingResults.filter(([, url]) => !shownUrls.has(url)), ...existingResults.filter( (result) => !shownKeys.has(imageResultKey(result)), ), ]; const existingUrls = new Set(baseResults.map(([, url]) => url)); const existingKeys = new Set(baseResults.map(imageResultKey)); const uniqueFreshResults = imageResults.filter( ([, url]) => !existingUrls.has(url), (result) => !existingKeys.has(imageResultKey(result)), );
if (uniqueFreshResults.length > 0) {107 unmodified lines settings.searchResultsLimit, existingTextResults, searchRunId, settings.searchTimeRange, );
if (20 unmodified lines settings.searchResultsLimit, existingImageResults, searchRunId, settings.searchTimeRange, ).catch((error) => { addLogEntry(`Error in follow-up image search: ${error}`); });478 unmodified lines47948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351489 unmodified lines60460560660760860961061161261361461561651 unmodified lines668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706468 unmodified lines11751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212478 unmodified lines ]); });
it("keeps different images from the same page", async () => { const { addSearchToHistory, mergeSearchImageResults, getRecentSearches, getCurrentSearchRunId, } = await import("./history"); const galleryImage = (name: string) => ({ title: name, url: "https://example.com/gallery", thumbnail: `https://example.com/${name}-thumb.gif`, sourceUrl: `https://example.com/${name}.gif`, }); await addSearchToHistory("gallery", { type: "image", items: [galleryImage("first")], });
await mergeSearchImageResults(getCurrentSearchRunId(), { type: "image", items: [galleryImage("second")], });
const [entry] = await getRecentSearches(); expect(entry.imageResults?.items).toEqual([ galleryImage("second"), galleryImage("first"), ]); });
it("writes nothing when no search has the run id", async () => { const { mergeSearchImageResults, getRecentSearches } = await import( "./history"89 unmodified lines { role: "assistant" as const, content: answer }, ];
beforeEach(async () => { await historyDatabase.searches.bulkAdd([ { searchRunId: "run-a", query: "query-a", timestamp: 1 }, { searchRunId: "run-b", query: "query-b", timestamp: 2 }, ]); });
it("stores the messages in the order given", async () => { const { replaceChatConversation, getChatMessagesForQuery } = await import( "./history"51 unmodified lines const messages = await getChatMessagesForQuery("nonexistent-run-id"); expect(messages).toEqual([]); });
it("stores nothing when the owning search was deleted", async () => { const { addSearchToHistory, getCurrentSearchRunId, getRecentSearches, replaceChatConversation, } = await import("./history"); const runId = getCurrentSearchRunId(); await addSearchToHistory("deleted search", oneTextResult()); const [entry] = await getRecentSearches(); await historyDatabase.deleteSearchesWithChildren([entry]);
await replaceChatConversation(runId, pair("Q1", "A1"));
expect(await historyDatabase.chatHistory.count()).toBe(0); });
it("saves a follow-up for a legacy search without searchRunId under its query", async () => { const { replaceChatConversation, getChatMessagesForQuery } = await import( "./history" ); await historyDatabase.searches.add({ query: "legacy-query", timestamp: 3, });
await replaceChatConversation("legacy-query", pair("Q1", "A1"));
expect(await getChatMessagesForQuery("legacy-query")).toEqual( pair("Q1", "A1"), ); }); });
describe("cleanup after add", () => {468 unmodified lines expect(indexNames).not.toContain("pinned"); });});
describe("saveLlmResponseForQuery - deleted search", () => { beforeEach(async () => { const { historyDatabase, resetSearchRunId } = await import("./history"); resetSearchRunId(); await Promise.all([ historyDatabase.searches.clear(), historyDatabase.llmResponses.clear(), historyDatabase.chatHistory.clear(), ]); });
it("should not save an answer whose search was deleted while it streamed", async () => { const { addSearchToHistory, getCurrentSearchRunId, saveLlmResponseForQuery, getLatestLlmResponseForEntry, getRecentSearches, historyDatabase, } = await import("./history"); const runId = getCurrentSearchRunId(); await addSearchToHistory("deleted while streaming", oneTextResult()); const [entry] = await getRecentSearches(); await historyDatabase.deleteSearchesWithChildren([entry]); await saveLlmResponseForQuery( "deleted while streaming", "late answer", "model-x", runId, ); expect(await historyDatabase.llmResponses.count()).toBe(0); await expect(getLatestLlmResponseForEntry(entry)).resolves.toBeNull(); });});353 unmodified lines35435535635735835936036136236336436136536636736836937016 unmodified lines387388389384385390391392393394395396125 unmodified lines52252352452552652752852953051751851952052152252352452552652752852953153253353453553653753853954054154254354454554654754826 unmodified lines5755765775625785795805815823 unmodified lines586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617353 unmodified lines }}
function storedImageKey(item: ImageResults["items"][number]): string { return item.sourceUrl || item.thumbnail;}
/** * Adds `results` to the images stored for the search instead of replacing them. * Every image write goes through here: the screen can lack images the stored * list has (a late first search merged after the user left and came back), so * replacing it with the screen's list would drop them. A URL is stored once. * replacing it with the screen's list would drop them. An image is stored once, * identified as on screen by its full-size source or thumbnail, so several * images from one page are all kept. * With `newFirst`, the new images go ahead of the stored ones; otherwise after. */export async function mergeSearchImageResults(16 unmodified lines latest.imageResults ?? (latest.results?.type === "image" ? latest.results : undefined) )?.items ?? []; const newUrls = new Set(results.items.map((item) => item.url)); const keptItems = storedItems.filter((item) => !newUrls.has(item.url)); const newKeys = new Set(results.items.map(storedImageKey)); const keptItems = storedItems.filter( (item) => !newKeys.has(storedImageKey(item)), ); await historyDatabase.searches.update(latest.id, { imageResults: { type: "image",125 unmodified lines): Promise<void> { if (!isHistoryEnabled()) return; try { await historyDatabase.transaction( "rw", historyDatabase.searches, historyDatabase.llmResponses, async () => { const latest = await historyDatabase.searches const latest = await historyDatabase.searches .where("searchRunId") .equals(searchRunId) .first();
await historyDatabase.llmResponses.add({ searchRunId, prompt: query, response, model, timestamp: Date.now(), searchId: latest?.id, }); .where("searchRunId") .equals(searchRunId) .first(); if (latest?.id === undefined) return;
await historyDatabase.llmResponses.add({ searchRunId, prompt: query, response, model, timestamp: Date.now(), searchId: latest.id, }); }, ); } catch (error) { addLogEntry(`Error saving LLM response: ${error}`); }26 unmodified lines * `conversationId`. Regenerate and edit rewrite the conversation rather than * append to it, so one transaction deletes the conversation's rows and adds * the new ones, with increasing timestamps to keep their order. Other * conversations are untouched, and an empty list removes the conversation. * conversations are untouched, an empty list removes the conversation, and * non-empty writes are skipped when no search owns `conversationId`. */export async function replaceChatConversation( conversationId: string,3 unmodified lines const firstTimestamp = Date.now(); await historyDatabase.transaction( "rw", historyDatabase.searches, historyDatabase.chatHistory, async () => { await historyDatabase.chatHistory .where("conversationId") .equals(conversationId) .delete(); if (messages.length === 0) return;
const owner = (await historyDatabase.searches .where("searchRunId") .equals(conversationId) .first()) ?? (await historyDatabase.searches .where("query") .equals(conversationId) .filter((search) => !search.searchRunId) .first()); if (!owner) { addLogEntry( `Skipped saving chat conversation for deleted search: ${conversationId}`, ); return; }
await historyDatabase.chatHistory.bulkAdd( messages.map((message, index) => ({ role: message.role,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;}142 unmodified lines143144145146147148149150151152153154155156157158142 unmodified lines expect(getSettings().historyRetentionDays).toBeGreaterThan(0); });
it("turns an unknown stored time range into Anytime", async () => { const { defaultSettings } = await import("./settings"); localStorage.setItem( "settings", JSON.stringify({ ...defaultSettings, searchTimeRange: "fortnight" }), ); const { getSettings } = await import("./pubSub"); expect(getSettings().searchTimeRange).toBe("any"); });
it("repairs a stored empty string on load without a migration", async () => { const { defaultSettings } = await import("./settings"); localStorage.setItem(294 unmodified lines295296297298299300301302303304305306307308309310311312294 unmodified linesexport const [updateTextSearchStale, , getTextSearchStale] = textSearchStalePubSub;
/** * Whether the text results on screen carry no time filter although one was * asked for, which is a fallback provider having answered the search. */export const textSearchTimeFilterPubSub = createPubSub<boolean>(false);
export const [ updateTextSearchTimeFilterNotApplied, , getTextSearchTimeFilterNotApplied,] = textSearchTimeFilterPubSub;
const pageContentsPubSub = createPubSub<PageContents>({});
export const [updatePageContents, , getPageContents] = pageContentsPubSub;123414 unmodified lines19202121222322232425262728293031323334263536373839404142434445464748493334353637505152535455565761 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314414514654 unmodified lines20120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323457 unmodified lines292293294228295296297298110 unmodified lines40941041134534634734841241341441541641741835541942042142297 unmodified lines52052152245952352452552652752852953046353153253353453553653753810 unmodified lines54955055148055255355455555655755855948456056156256356456556656727 unmodified lines5955965975985996006016026036046056066076086096106116126136146156166176186196206216226 unmodified lines62963063153063263363463563663763863935 unmodified lines67567667757267867968068168268368468544 unmodified lines730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784import type { SearchTimeRange } from "@shared/searchTimeRange";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { invalidateConfig } from "./config";import { addLogEntry } from "./logEntries";14 unmodified lines
const mockFetch = vi.fn();
/** Answers every following `/search` fetch with `results`. */function mockSearchResponse(results: string[][]) { mockFetch.mockResolvedValue({/** * A search response, carrying the `headers` a real `Response` always has: the * module reads one of them to tell an answer that carries no time filter from * one that does. */function searchResponse( results: string[][], headers: Record<string, string> = {},) { return { ok: true, json: vi.fn().mockResolvedValue(results), headers: { get: (name: string) => headers[name] ?? null }, }); };}
/** Answers every following `/search` fetch with `results`. */function mockSearchResponse( results: string[][], headers?: Record<string, string>,) { mockFetch.mockResolvedValue(searchResponse(results, headers));}vi.stubGlobal("fetch", mockFetch);vi.stubGlobal("self", { location: new URL("http://localhost:3000"),});
const mockFetchResponse = (results: string[][]) => { mockFetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(results), });const mockFetchResponse = ( results: string[][], headers?: Record<string, string>,) => { mockFetch.mockResolvedValue(searchResponse(results, headers));};
describe("Search Module", () => {61 unmodified lines expect(hashOmitted).toBe(hashUndefined); });
it("should include the time range in the hash so different periods produce different keys", async () => { const { hashQuery } = searchModule.searchServiceInstance; const hashes = await Promise.all( ["any", "day", "week", "month", "year"].map((timeRange) => hashQuery("test query", 10, timeRange as SearchTimeRange), ), ); expect(new Set(hashes).size).toBe(5); });
it("should keep an Anytime key the one it was before the filter existed", async () => { const { hashQuery } = searchModule.searchServiceInstance; // Anytime adds nothing to the hashed input, so the entries cached before // the setting existed are still the ones an Anytime search reads. expect(await hashQuery("test query", 10, "any")).toBe( await hashQuery("test query", 10), ); expect(await hashQuery("test query", 10, 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");54 unmodified lines expect(calledUrl).toContain("limit=10"); });
it("should send the time range as a query parameter", async () => { mockFetchResponse([]);
await searchModule.searchServiceInstance.performSearch<string[][]>( "text", "test", 10, "week", );
const calledUrl = mockFetch.mock.calls[0][0] as string; expect(calledUrl).toContain("time_range=week"); });
it("should send no time range for Anytime", async () => { mockFetchResponse([]);
await searchModule.searchServiceInstance.performSearch<string[][]>( "text", "test", 10, "any", );
const calledUrl = mockFetch.mock.calls[0][0] as string; expect(calledUrl).not.toContain("time_range"); });
it("should throw on non-OK response", async () => { mockFetch.mockResolvedValue({ ok: false,57 unmodified lines "text", "a".repeat(2000), ), ).resolves.toEqual([]); ).resolves.toEqual({ results: [], timeFilterNotApplied: false }); expect(mockFetch).toHaveBeenCalledTimes(1); });
110 unmodified lines .mockResolvedValueOnce("fresh-token-hash"); mockFetch .mockResolvedValueOnce({ ok: false, status: 401 }) .mockResolvedValueOnce({ ok: true, json: vi.fn().mockResolvedValue(mockResults), }); .mockResolvedValueOnce(searchResponse(mockResults));
await expect( searchModule.searchServiceInstance.performSearch<string[][]>( "text", "test query", ), ).resolves.toEqual(mockResults); ).resolves.toEqual({ results: mockResults, timeFilterNotApplied: false });
expect(invalidateConfig).toHaveBeenCalledTimes(1); expect(mockFetch).toHaveBeenCalledTimes(2);97 unmodified lines mockSearchResponse(mockResults);
const firstResults = await searchModule.searchText("cached query"); expect(firstResults).toEqual({ results: mockResults, stale: false }); expect(firstResults).toEqual({ results: mockResults, stale: false, timeFilterNotApplied: false, }); expect(mockFetch).toHaveBeenCalledTimes(1);
const secondResults = await searchModule.searchText("cached query"); expect(secondResults).toEqual({ results: mockResults, stale: false }); expect(secondResults).toEqual({ results: mockResults, stale: false, timeFilterNotApplied: false, }); expect(mockFetch).toHaveBeenCalledTimes(1); expect(addLogEntry).toHaveBeenCalledWith( expect.stringContaining("Text search: Reused 1 results from the cache"),10 unmodified lines mockSearchResponse(mockResults);
const firstResults = await searchModule.searchImages("cached images"); expect(firstResults).toEqual({ results: mockResults, stale: false }); expect(firstResults).toEqual({ results: mockResults, stale: false, timeFilterNotApplied: false, }); expect(mockFetch).toHaveBeenCalledTimes(1);
const secondResults = await searchModule.searchImages("cached images"); expect(secondResults).toEqual({ results: mockResults, stale: false }); expect(secondResults).toEqual({ results: mockResults, stale: false, timeFilterNotApplied: false, }); expect(mockFetch).toHaveBeenCalledTimes(1); expect(addLogEntry).toHaveBeenCalledWith( expect.stringContaining(27 unmodified lines expect(mockFetch).toHaveBeenCalledTimes(2); });
it("should treat different time ranges as separate cache entries", async () => { const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"], ]; mockSearchResponse(mockResults);
await searchModule.searchText("same query", 5, "week"); await searchModule.searchText("same query", 5, "month"); expect(mockFetch).toHaveBeenCalledTimes(2); });
it("should read an Anytime search from the entry cached without a time range", async () => { const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"], ]; mockSearchResponse(mockResults);
await searchModule.searchText("anytime query", 5); await searchModule.searchText("anytime query", 5, "any"); expect(mockFetch).toHaveBeenCalledTimes(1); });
it("should refetch when TTL expires", async () => { const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"],6 unmodified lines searchModule.searchServiceInstance.updateCacheConfig({ ttl: 0 });
const secondResults = await searchModule.searchText("ttl query"); expect(secondResults).toEqual({ results: mockResults, stale: false }); expect(secondResults).toEqual({ results: mockResults, stale: false, timeFilterNotApplied: false, }); expect(mockFetch).toHaveBeenCalledTimes(2); });
35 unmodified lines mockSearchResponse(mockResults);
const first = await searchModule.searchText("stale query"); expect(first).toEqual({ results: mockResults, stale: false }); expect(first).toEqual({ results: mockResults, stale: false, timeFilterNotApplied: false, }); expect(mockFetch).toHaveBeenCalledTimes(1);
searchModule.searchServiceInstance.updateCacheConfig({ ttl: 0 });44 unmodified lines // not exported, so this test pins the pair (cleanup plus recheck). });
describe("Time Filter Not Applied", () => { const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"], ]; const notApplied = { "X-Search-Time-Range-Applied": "false" };
it("should report the note when the server says the period was not applied", async () => { mockSearchResponse(mockResults, notApplied);
const outcome = await searchModule.searchText( "fallback query", 5, "week", );
expect(outcome).toEqual({ results: mockResults, stale: false, timeFilterNotApplied: 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, "week");
const cached = await searchModule.searchText( "cached fallback query", 5, "week", );
expect(mockFetch).toHaveBeenCalledTimes(1); expect(cached.timeFilterNotApplied).toBe(true); });
it("should not report the note when the server applied the period", async () => { mockSearchResponse(mockResults);
const outcome = await searchModule.searchText( "filtered query", 5, "week", );
expect(outcome.timeFilterNotApplied).toBe(false); }); });
describe("URL Construction", () => { it("should include the search token hash in the request URL", async () => { mockFetchResponse([]);1234567113 unmodified lines1211221231201241251261271281291301311321251331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631411641651661675 unmodified lines1731741751531761771781791801811821831841851861601871881891901911921931661941951961971981992001732012022032046 unmodified lines2112122131862142152162172182192202213 unmodified lines22522622719622822923023123223320223423523623723823924024124224324424524624724844 unmodified lines2932942952582962972982993003013023033044 unmodified lines309310311312313314315316317318319101 unmodified lines4214224233764244254264274284294304314324333814344354364374384394404414425 unmodified lines4484494504514524534547 unmodified lines46246346446546646746846947041147147247347447547647747847948048148248348448548623 unmodified lines5105115124474484495135145155165175185195205215225235245255265275283 unmodified lines53253353445953553653753853911 unmodified lines5515525534775545555565577 unmodified lines5655665674915685695705711 unmodified line57357457549957657757857958058158258358458558658758858959059159259359419 unmodified lines614615616617618619620621622623624625626import { 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";113 unmodified lines}
interface SearchOperations<T extends SearchResults> { hashQuery: (query: string, limit?: number) => Promise<string>; hashQuery: ( query: string, limit?: number, timeRange?: SearchTimeRange, ) => Promise<string>; performSearch: ( endpoint: "text" | "images", query: string, limit?: number, ) => Promise<T>; timeRange?: SearchTimeRange, ) => Promise<SearchFetch<T>>;}
/** What one request answered: its results, and what the server said about them. */interface SearchFetch<T> { results: T; /** The server answered from a source that could not apply the time range. */ timeFilterNotApplied: boolean;}
interface CachedSearchOutcome<T> { results: T; stale: boolean; /** * Set when the results carry no time filter although one was asked for. Left * out rather than set false, so a cache entry written before the flag * 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); const key = await operations.hashQuery(query, limit, timeRange); const cachedData = await db.getCachedResult<T>(context.storeName, key);
if (cachedData?.fresh) {5 unmodified lines );
logAndMaybeResetMetrics(); return { results: cachedData.results, stale: false }; return { results: cachedData.results, stale: false, timeFilterNotApplied: cachedData.timeFilterNotApplied, }; }
incrementCacheMetric(context.missMetric); cacheMetrics.incrementTotalOperations();
try { const results = await operations.performSearch( const { results, timeFilterNotApplied } = await operations.performSearch( context.endpoint, query, limit, timeRange, );
await db.cacheResult(context.storeName, key, results); await db.cacheResult(context.storeName, key, results, timeFilterNotApplied); logAndMaybeResetMetrics();
addLogEntry( `${context.logLabel}: Fetched ${results.length} results from the API`, );
return { results, stale: false }; return { results, stale: false, timeFilterNotApplied }; } catch (error) { if ( cachedData &&6 unmodified lines error instanceof Error ? error.message : String(error) }); serving ${cachedData.results.length} result(s) from a previous search`, ); return { results: cachedData.results, stale: true }; return { results: cachedData.results, stale: true, timeFilterNotApplied: cachedData.timeFilterNotApplied, }; } throw error; }3 unmodified linesconst UNAUTHORIZED_STATUS = 401;
type SearchAttempt<T> = | { ok: true; results: T } | { ok: true; results: T; timeFilterNotApplied: boolean } | { ok: false; status: number };
async function buildSearchUrl( endpoint: "text" | "images", query: string, limit?: number, 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 lines return { ok: false, status: response.status }; }
return { ok: true, results: (await response.json()) as T }; 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); } finally {4 unmodified linesinterface SearchCacheEntry { key: string; timestamp: number; /** * Kept with the results so a search served from this cache can still say the * time filter was not applied. Absent on every entry written before it. */ timeFilterNotApplied?: boolean;}
interface TextSearchCache extends SearchCacheEntry {101 unmodified lines async getCachedResult<T extends TextSearchResults | ImageSearchResults>( storeName: "textSearchHistory" | "imageSearchHistory", key: string, ): Promise<{ results: T; fresh: boolean; timestamp: number } | null> { ): Promise<{ results: T; fresh: boolean; timestamp: number; timeFilterNotApplied?: boolean; } | null> { if (!cacheConfig.enabled) return null;
try { const store = this[storeName] as Table< { key: string; results: T; timestamp: number }, { key: string; results: T; timestamp: number; timeFilterNotApplied?: boolean; }, string >; const cachedItem = await store.get(key);5 unmodified lines results: cachedItem.results, fresh, timestamp: cachedItem.timestamp, timeFilterNotApplied: cachedItem.timeFilterNotApplied, }; } catch (error) { addLogEntry(7 unmodified lines storeName: "textSearchHistory" | "imageSearchHistory", key: string, results: T, timeFilterNotApplied?: boolean, ): Promise<void> { if (!cacheConfig.enabled) return;
try { const store = this[storeName] as Table< { key: string; results: T; timestamp: number }, { key: string; results: T; timestamp: number; timeFilterNotApplied?: boolean; }, string >; await store.put({ key, results, timestamp: Date.now(), timeFilterNotApplied, });
const cacheWrites = this._cacheWriteCount;23 unmodified lines});
const searchService = { /** The limit is part of the key, so a different limit never reads stale results. */ async hashQuery(query: string, limit?: number): Promise<string> { const input = limit !== undefined ? `${query}::limit=${limit}` : query; /** * 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);3 unmodified lines endpoint: "text" | "images", query: string, limit?: number, ): Promise<T> { timeRange?: SearchTimeRange, ): Promise<SearchFetch<T>> { if (!["text", "images"].includes(endpoint)) { throw new Error( `Invalid endpoint type: ${endpoint}. Must be "text" or "images"`,11 unmodified lines }
let attempt = await attemptSearch<T>( await buildSearchUrl(endpoint, query, limit), 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), await buildSearchUrl(endpoint, query, limit, timeRange), ); }
1 unmodified line throw new Error(`HTTP error! status: ${attempt.status}`); }
return attempt.results; return { results: attempt.results, timeFilterNotApplied: attempt.timeFilterNotApplied, }; },
async searchText( query: string, limit?: number, timeRange?: SearchTimeRange, ): Promise<CachedSearchOutcome<TextSearchResults>> { try { return await executeCachedSearch<TextSearchResults>( query, limit, timeRange, { storeName: "textSearchHistory", endpoint: "text",19 unmodified lines async searchImages( query: string, limit?: number, timeRange?: SearchTimeRange, ): Promise<CachedSearchOutcome<ImageSearchResults>> { try { return await executeCachedSearch<ImageSearchResults>( query, limit, timeRange, { storeName: "imageSearchHistory", endpoint: "images",1 unmodified line23456789101157 unmodified lines6970717273747528 unmodified lines1041051061021071081091101111129 unmodified lines1221231241251261271281291301311321331341 unmodified line CITATION_EXAMPLE, DEFAULT_SYSTEM_PROMPT,} from "@shared/defaultSystemPrompt";import { type SearchTimeRange, searchTimeRangeOptions,} from "@shared/searchTimeRange";import { DEFAULT_INFERENCE_TYPE, DEFAULT_WLLAMA_GPU_MODEL_ID,57 unmodified lines wllamaModelId: DEFAULT_WLLAMA_MODEL_ID, cpuThreads: getDefaultCpuThreads(), searchResultsLimit: 15, searchTimeRange: "any" as SearchTimeRange, systemPrompt: DEFAULT_SYSTEM_PROMPT, inferenceType: DEFAULT_INFERENCE_TYPE, openAiApiBaseUrl: "",28 unmodified lines * than a finite number replaced by its default. A cleared Mantine NumberInput * 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. * 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,9 unmodified lines coerced[key] = fallback; } } if ( !searchTimeRangeOptions.some( ({ value }) => value === coerced.searchTimeRange, ) ) { coerced.searchTimeRange = defaultSettings.searchTimeRange; } return coerced as typeof defaultSettings;}
248 unmodified lines249250251252252253254248 unmodified lines const { createWllamaInstance } = await import("./wllama"); const wllama = await createWllamaInstance({ suppressNativeLog: true, allowOffline: true, }); const abandon = () => { void releaseModel(wllama);93 unmodified lines949596979899100599 unmodified lines70070170270370470570670770870971071171271371471571671771871972072172293 unmodified lines updateTextSearchStale: vi.fn((value: boolean) => { harness.state.staleFlag = value; }), updateTextSearchTimeFilterNotApplied: vi.fn(), getTextSearchStale: () => harness.state.staleFlag,}));
599 unmodified lines ); });
it("keeps the first search's image from the same page as a follow-up's", async () => { const { finishImages } = await searchWithFollowUpImagesFirst();
const samePageImage: ImageSearchResults[number] = [ "Same page", followUpImage[1], "thumb-other", "https://f.example/other", ]; await finishImages([samePageImage]);
expect(vi.mocked(updateImageSearchResults)).toHaveBeenLastCalledWith([ followUpImage, samePageImage, ]); });
it("keeps a follow-up's images when the first image search finds none", async () => { const { finishImages } = await searchWithFollowUpImagesFirst(); await finishImages([]);7 unmodified lines89101112131417 unmodified lines32333435363738323 unmodified lines362363364365366367368369378 unmodified lines7487497507477487497517527537547557567577587597607617627637647657667677686 unmodified lines7757767777787797807817827837847856 unmodified lines79279379479579679779821 unmodified lines82082182282382482582648 unmodified lines8758768778788798808818828838848648858868878678888898908918928937 unmodified lines saveLlmResponseForQuery, updateSearchResults,} from "./history";import { imageResultKey } from "./imageResultKey";import { addLogEntry } from "./logEntries";import { showAiCompleteNotification } from "./notifications";import { fetchPageContents } from "./pageContent";17 unmodified lines updateTextSearchResults, updateTextSearchStale, updateTextSearchState, updateTextSearchTimeFilterNotApplied,} from "./pubSub";import { searchImages, searchText } from "./search";import { getLatestSearchAttempt, recordSearchAttempt } from "./searchAttempts";323 unmodified lines
updateTextSearchStale(false);
updateTextSearchTimeFilterNotApplied(false);
updateLlmTextSearchResults([]);
updateImageSearchResults([]);378 unmodified lines try { // A query with no keywords left has nothing to send, which is an empty // result set rather than a failed search. let { results: textResults, stale } = searchQuery ? await searchText(searchQuery, getSettings().searchResultsLimit) : { results: [] as TextSearchResults, stale: false }; let { results: 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(6 unmodified lines const keywordOutcome = await searchText( keywordQuery, getSettings().searchResultsLimit, getSettings().searchTimeRange, ); textResults = keywordOutcome.results; stale = keywordOutcome.stale; timeFilterNotApplied = keywordOutcome.timeFilterNotApplied; } }
6 unmodified lines
if (isCurrent()) { updateTextSearchStale(stale); updateTextSearchTimeFilterNotApplied(Boolean(timeFilterNotApplied)); updateTextSearchState("completed"); updateTextSearchResults(textResults); updateLlmTextSearchResults(resultsForLlm);21 unmodified lines addLogEntry(`Text search failed: ${error}`); if (isCurrent()) { updateTextSearchStale(false); updateTextSearchTimeFilterNotApplied(false); updateTextSearchState("failed"); } textSearchFailed = true;48 unmodified lines const { results: imageResults } = await searchImages( searchQuery, getSettings().searchResultsLimit, getSettings().searchTimeRange, ); results.imageResults = imageResults;
// A follow-up can add images while this search is still running; they // stay, ahead of this search's own. const shown = isCurrent() ? getImageSearchResults() : []; const shownUrls = new Set(shown.map(([, url]) => url)); const shownKeys = new Set(shown.map(imageResultKey)); const mergedResults: ImageSearchResults = [ ...shown, ...imageResults.filter(([, url]) => !shownUrls.has(url)), ...imageResults.filter( (result) => !shownKeys.has(imageResultKey(result)), ), ];
if (isCurrent()) {116 unmodified lines117118119120121122116 unmodified lines updateTextSearchResults: vi.fn(), updateTextSearchStale: vi.fn(), updateTextSearchState: vi.fn(), updateTextSearchTimeFilterNotApplied: vi.fn(), };}269 unmodified lines270271272273273274275269 unmodified lines const wllama = await initializeWllama(model.hfRepoId, model.hfFilePath, { wllama: { suppressNativeLog: true, allowOffline: true, }, chatTemplateKwargs: model.chatTemplateKwargs, model: {2 unmodified lines3456678912 unmodified lines22232425252627282 unmodified lines31323334343536373738394040414243444546474849505152535455562 unmodified linesimport { initializeWllama } from "./wllama";
const instance = vi.hoisted(() => ({ loadModelFromHF: vi.fn(), loadModelFromUrl: vi.fn(), createChatCompletion: vi.fn(), exit: vi.fn(),}));12 unmodified linesdescribe("initializeWllama", () => { beforeEach(() => { vi.clearAllMocks(); instance.loadModelFromHF.mockResolvedValue(undefined); instance.loadModelFromUrl.mockResolvedValue(undefined); instance.createChatCompletion.mockResolvedValue(warmupReply); instance.exit.mockResolvedValue(undefined); });2 unmodified lines const result = await initializeWllama("repo", "file.gguf");
expect(result).toBe(instance); expect(instance.loadModelFromHF).toHaveBeenCalledTimes(2); expect(instance.loadModelFromUrl).toHaveBeenCalledTimes(2); expect(instance.exit).toHaveBeenCalledTimes(1); expect(instance.exit.mock.invocationCallOrder[0]).toBeGreaterThan( instance.loadModelFromHF.mock.invocationCallOrder[0], instance.loadModelFromUrl.mock.invocationCallOrder[0], ); expect(instance.exit.mock.invocationCallOrder[0]).toBeLessThan( instance.loadModelFromHF.mock.invocationCallOrder[1], instance.loadModelFromUrl.mock.invocationCallOrder[1], ); });
it("loads the model by its resolve URL, not through the Hugging Face API", async () => { await initializeWllama("repo", "file.gguf");
for (const call of instance.loadModelFromUrl.mock.calls) { expect(call[0]).toEqual({ url: "https://huggingface.co/repo/resolve/main/file.gguf", }); } });
it("releases the instance when the warm-up fails", async () => { const warmupError = new Error("wasm abort"); instance.createChatCompletion.mockRejectedValue(warmupError);48 unmodified lines4950515253525354555631 unmodified lines8889909192919293949549 unmodified lines14514614714814915015115215315415515615715815916016119 unmodified lines18118218317317417517618417818518618718848 unmodified lines try { wllama = await createWllamaInstance(config?.wllama);
await wllama.loadModelFromHF( { repo: hfRepoId, file: hfFilePath }, await wllama.loadModelFromUrl( { url: huggingFaceModelFileUrl(hfRepoId, hfFilePath) }, { ...config?.model, n_threads: 1,31 unmodified lines
await wllama.exit();
await wllama.loadModelFromHF( { repo: hfRepoId, file: hfFilePath }, await wllama.loadModelFromUrl( { url: huggingFaceModelFileUrl(hfRepoId, hfFilePath) }, config?.model, );
49 unmodified lines }}
/** * The URL wllama downloads a Hugging Face model file from. Loading by this * URL instead of by repo id skips the Hugging Face API entirely (wllama's * `getHFModelSource` queries the tree API first), so a fully cached model * loads even when the API is unreachable, and the file cache keeps matching * because this is the same URL the cache keys files by. */function huggingFaceModelFileUrl(hfRepoId: string, hfFilePath: string): string { return `https://huggingface.co/${hfRepoId}/resolve/main/${hfFilePath}`;}
/** * Ids of the catalog models whose files are all in wllama's cache. *19 unmodified lines return new Set( Object.entries(wllamaModels) .filter(([, model]) => // The cache keys files by the URL they were downloaded from, and // `loadModelFromHF` builds that URL as // `https://huggingface.co/${repo}/resolve/main/${file}` (wllama's // `getHFModelSource`), so the catalog entry matches only that URL. validUrls.has( `https://huggingface.co/${model.hfRepoId}/resolve/main/${model.hfFilePath}`, huggingFaceModelFileUrl(model.hfRepoId, model.hfFilePath), ), ) .map(([id]) => id),130 unmodified lines13113213313413513613713813413513613713813914014114236 unmodified lines17918018118218318418520 unmodified lines206207208209210211212213214215216217218219130 unmodified lines
Query parameters:
| Name | Required | Description || ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `q` | yes | Search query, trimmed, 1 to 2000 characters || `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 || Name | Required | Description || ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `q` | yes | Search query, trimmed, 1 to 2000 characters || `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:
36 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 |
20 unmodified lineswhen 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`
Same parameters and failures as `/search/text`, except that the text-search145 unmodified lines146147148149150151152145 unmodified lines| `enableImageSearch` | boolean | `true` | Include image results in searches || `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 |.source-commit+1-1
agents.md+1
changelog.md+8
client/components/Pages/Main/Menu/SearchSettingsForm.tsx+11-1
client/components/Pages/Main/Menu/SettingsForms.test.tsx+29-1
client/components/Search/Form/SearchForm.test.tsx+19
client/components/Search/Form/SearchForm.tsx+29-3
client/components/Search/Results/Graphical/ImageResultsList.test.tsx+26
client/components/Search/Results/Graphical/ImageResultsList.tsx+19-15
client/components/Search/Results/Textual/TextSearchResults.test.tsxAdded+82
client/components/Search/Results/Textual/TextSearchResults.tsx+8-1
client/hooks/useHistoryRestore.test.ts+26
client/hooks/useHistoryRestore.ts+17-1
client/modules/chatHelpers.test.ts+87-16
client/modules/chatHelpers.ts+25-8
client/modules/history.test.ts+105
client/modules/history.ts+54-17
client/modules/imageResultKey.tsAdded+14
client/modules/pubSub.test.ts+10
client/modules/pubSub.ts+12
client/modules/search.test.ts+180-21
client/modules/search.ts+105-21
client/modules/settings.ts+15-1
client/modules/speechToText.ts-1
client/modules/textGeneration.degradation.test.ts+18
client/modules/textGeneration.ts+28-5
client/modules/textGenerationTestUtils.ts+1
client/modules/textGenerationWithWllama.ts-1
client/modules/wllama.initialize.test.ts+15-5
client/modules/wllama.ts+16-9
docs/api.md+15-5
docs/configuration.md+1