Spaces:
Running
Running
Sync from felladrin/MiniSearch@4cd41ab
Browse filesFiles changed (20)
- agents.md+1
- changelog.md+12
- client/modules/chatHelpers.test.ts+129
- client/modules/chatHelpers.ts+68-5
- client/modules/relatedSearchQuery.test.tsAdded+76
- client/modules/relatedSearchQuery.ts+10-9
- client/modules/searchResultSelection.test.tsAdded+66
- client/modules/searchResultSelection.tsAdded+26
- client/modules/textGeneration.degradation.test.ts+55-1
- client/modules/textGeneration.inference.test.ts+33-1
- client/modules/textGeneration.ts+61-25
- client/modules/textToSpeech.test.ts+104
- client/modules/textToSpeech.ts+34-3
- client/modules/wllama.ts+11
- docs/ai-integration.md+18-11
- docs/conversation-memory.md+1
- docs/overview.md+1-1
- docs/page-content.md+19-2
- docs/reranking.md+2
- package-lock.json+3-3
130 unmodified lines131132133134135136130 unmodified lines- `client/modules/webGpu.ts` - Whether the GPU can run wllama's shaders (API, `subgroup_id`, a real adapter with `subgroups`); decides GPU or CPU and the default model- `client/modules/querySuggestions.ts` - Search suggestion UI, stored in IndexedDB- `client/modules/relatedSearchQuery.ts` - Generates related search queries- `client/modules/followUpQuestions.ts` - Generates follow-up questions via `followUpQuestionPubSub`- `client/modules/accessKey.ts` - Validates and stores access keys using argon2id hashing and localStorage- `client/modules/parentWindow.ts` - PostMessage API for embedding in parent windows130 unmodified lines131132133134135136137130 unmodified lines- `client/modules/webGpu.ts` - Whether the GPU can run wllama's shaders (API, `subgroup_id`, a real adapter with `subgroups`); decides GPU or CPU and the default model- `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/followUpQuestions.ts` - Generates follow-up questions via `followUpQuestionPubSub`- `client/modules/accessKey.ts` - Validates and stores access keys using argon2id hashing and localStorage- `client/modules/parentWindow.ts` - PostMessage API for embedding in parent windows
1 unmodified line2345671 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-18- Search results whose link no browser can open are now dropped, from SearXNG and from the fallback providers alike: links on a host without a domain, and links that are not `http` or `https`. Brave Search now sends its result links through encrypted redirects, which SearXNG's Brave engine passes on as `http:///go/v1/...`. Those results reached the list with "go" as the site name, and the AI response cited them as sources. They are dropped before the result limit applies, so they do not take the place of a usable result, and the server log names the engine that sent them.1 unmodified line23456789101112131415161718191 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-19- When no voice is chosen in Voice Settings, the local engine now picks the best-sounding voice of the answer's language instead of the first one in the catalogue: medium quality first, then low, then x-low. Portuguese, for example, now gets `pt_BR-faber-medium` where it used to get `pt_BR-edresson-low`, at the same 63 MB download. High-quality voices are picked only when a language publishes nothing else, since they cost up to 137 MB against the 63 MB of a medium one. And when the answer is in the browser's language, a voice of the browser's region now wins among the ones of the same quality, so an `en-US` browser gets an American voice.- Raon-1 nano 3B (2083 MB, Apache-2.0, Korean and English) joins the Wllama catalog, labeled "(wllama support pending)": its architecture is not yet in the llama.cpp build the browser engine ships, so it cannot answer until upstream support lands ([ggml-org/llama.cpp#32200](https://github.com/ggml-org/llama.cpp/pull/32200) is open). The sharded copy is published and the entry is ready, so it starts working the day the engine updates.- A follow-up answer now reads the pages behind its own new results, as the first answer does, instead of answering from their titles and snippets alone. A page both searches returned also gets an excerpt picked for the follow-up question, where it used to keep the one picked for the first question.- The search query of a follow-up question now names what the question refers to: when the previous answer says Marvel moved Avengers: Doomsday to December 2026, "why did they delay the release" now searches for "Avengers: Doomsday release delay reasons" instead of a query that names nothing. The query is also written in the language of the question more often, because the model no longer sees the search results while writing it. Measured with Gemma 3 4B in the browser on seven conversations, three runs each: the query kept the subject in 21 of 21 runs (16 before) and the question's language in 20 of 21 (16 before).- The six search results an AI answer reads are now the six with the best relevance score, for the first question and for follow-ups. The result list still shows the search engine's first result at the top, but that result no longer takes one of the six places when its score is low.- A follow-up question with a relative date, such as "what comes out next month", now searches with the month and year written out ("December 2026"), as the first question already did, so the results match the right period.- When a search was still waiting for permission to download the in-browser model and a second one started (for example, by accepting the "Enable AI Responses?" prompt with AI responses already on), allowing the download loaded the model twice at the same time, and both answers failed with a file-lock error. Now only the newest search loads the model.- A follow-up question with a relative date ("who won it last year", "明年的呢") now keeps that date in its search query more often, so the date anchor turns it into the right year instead of the model writing a year itself ("2023" for last year). Measured with Gemma 3 4B in the browser on three such questions, three runs each: the relative date reached the anchor in 6 of 9 runs, against 3 of 9 before. When the model still writes the year itself, it can still be wrong.- The search query of a follow-up question no longer keeps the quote marks some models wrap it in (“ ”, 「 」, « »), as it already did with straight quotes.## 2026-11-18- Search results whose link no browser can open are now dropped, from SearXNG and from the fallback providers alike: links on a host without a domain, and links that are not `http` or `https`. Brave Search now sends its result links through encrypted redirects, which SearXNG's Brave engine passes on as `http:///go/v1/...`. Those results reached the list with "go" as the site name, and the AI response cited them as sources. They are dropped before the result limit applies, so they do not take the place of a usable result, and the server log names the engine that sent them.
11 unmodified lines121314151617181920212211 unmodified lines3435363738394041424344454 unmodified lines50515253545549 unmodified lines10510610710810911043 unmodified lines15415515615715815916016116216311 unmodified linesupdateSearchResults: vi.fn(() => Promise.resolve()),}));vi.mock("./pubSub", () => ({updateImageSearchResults: vi.fn(),updateLlmTextSearchResults: vi.fn(),updateTextSearchResults: vi.fn(),updateTextSearchStale: vi.fn(),}));vi.mock("./relatedSearchQuery", () => ({generateRelatedSearchQuery: vi.fn(() => Promise.resolve("")),}));11 unmodified linesrunFollowUpSearch,} from "./chatHelpers";import { saveChatMessageForQuery } from "./history";import {updateImageSearchResults,updateLlmTextSearchResults,updateTextSearchResults,updateTextSearchStale,} from "./pubSub";import { searchImages, searchText } from "./search";import type { ImageSearchResults, TextSearchResults } from "./types";4 unmodified linesconst mockUpdateImage = vi.mocked(updateImageSearchResults);const mockUpdateLlmText = vi.mocked(updateLlmTextSearchResults);const mockUpdateTextStale = vi.mocked(updateTextSearchStale);describe("refreshTextSearchResults", () => {it("deduplicates by URL and appends fresh results", async () => {49 unmodified linesexpect(mockUpdateTextStale).toHaveBeenCalledWith(true);});});describe("refreshImageSearchResults", () => {43 unmodified lines({enableTextSearch: true,enableImageSearch: true,searchResultsLimit: 10,...overrides,}) as unknown as Parameters<typeof runFollowUpSearch>[2];it("refreshes text results when enabled", async () => {mockSearchText.mockResolvedValueOnce({results: [["Title", "snippet", "https://new.com"]],11 unmodified lines1213141516171819202122232425262711 unmodified lines394041424344454647484950515253544 unmodified lines5960616263646566676849 unmodified lines11811912012112212312412512612712812913013113213313413513613713813914043 unmodified lines18418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129211 unmodified linesupdateSearchResults: vi.fn(() => Promise.resolve()),}));vi.mock("./pubSub", () => ({getPageContents: vi.fn(() => ({})),updateImageSearchResults: vi.fn(),updateLlmTextSearchResults: vi.fn(),updatePageContents: vi.fn(),updateTextSearchResults: vi.fn(),updateTextSearchStale: vi.fn(),}));vi.mock("./pageContent", () => ({fetchPageContents: vi.fn(() => Promise.resolve({})),}));vi.mock("./relatedSearchQuery", () => ({generateRelatedSearchQuery: vi.fn(() => Promise.resolve("")),}));11 unmodified linesrunFollowUpSearch,} from "./chatHelpers";import { saveChatMessageForQuery } from "./history";import { fetchPageContents } from "./pageContent";import {getPageContents,updateImageSearchResults,updateLlmTextSearchResults,updatePageContents,updateTextSearchResults,updateTextSearchStale,} from "./pubSub";import { generateRelatedSearchQuery } from "./relatedSearchQuery";import { searchImages, searchText } from "./search";import type { ImageSearchResults, TextSearchResults } from "./types";4 unmodified linesconst mockUpdateImage = vi.mocked(updateImageSearchResults);const mockUpdateLlmText = vi.mocked(updateLlmTextSearchResults);const mockUpdateTextStale = vi.mocked(updateTextSearchStale);const mockFetchPageContents = vi.mocked(fetchPageContents);const mockGetPageContents = vi.mocked(getPageContents);const mockUpdatePageContents = vi.mocked(updatePageContents);const mockGenerateRelatedSearchQuery = vi.mocked(generateRelatedSearchQuery);describe("refreshTextSearchResults", () => {it("deduplicates by URL and appends fresh results", async () => {49 unmodified linesexpect(mockUpdateTextStale).toHaveBeenCalledWith(true);});it("orders the answer's evidence by score, not by the displayed order", async () => {mockSearchText.mockResolvedValueOnce({results: [["Pinned", "snippet", "https://pinned.com", 12],["Relevant", "snippet", "https://relevant.com", 91],["Weak", "snippet", "https://weak.com", 20],],stale: false,});await refreshTextSearchResults("query", 10, []);expect(mockUpdateLlmText.mock.calls[0]?.[0].map(([title]) => title),).toEqual(["Relevant", "Weak", "Pinned"]);});});describe("refreshImageSearchResults", () => {43 unmodified lines({enableTextSearch: true,enableImageSearch: true,enablePageContentFetch: true,searchResultsLimit: 10,...overrides,}) as unknown as Parameters<typeof runFollowUpSearch>[2];it("reads the pages behind the fresh results and keeps the ones already read", async () => {mockSearchText.mockResolvedValueOnce({results: [["Title", "snippet", "https://new.com"],["Other", "snippet", "https://other.com"],],stale: false,});mockFetchPageContents.mockResolvedValueOnce({"https://new.com": "page text",});mockGetPageContents.mockReturnValueOnce({ "https://old.com": "old text" });await runFollowUpSearch([{ role: "user", content: "hello" }],"hello",makeSettings(),[],[],);expect(mockFetchPageContents).toHaveBeenCalledWith("hello", ["https://new.com","https://other.com",]);expect(mockUpdatePageContents).toHaveBeenCalledWith({"https://old.com": "old text","https://new.com": "page text",});});it("does not read pages when page content fetching is disabled", async () => {mockSearchText.mockResolvedValueOnce({results: [["Title", "snippet", "https://new.com"]],stale: false,});await runFollowUpSearch([{ role: "user", content: "hello" }],"hello",makeSettings({ enablePageContentFetch: false }),[],[],);expect(mockFetchPageContents).not.toHaveBeenCalled();});it("starts the image refresh without waiting for the page read", async () => {mockSearchText.mockResolvedValueOnce({results: [["Title", "snippet", "https://new.com"]],stale: false,});let finishPageRead: (contents: Record<string, string>) => void = () => {};mockFetchPageContents.mockReturnValueOnce(new Promise((resolve) => {finishPageRead = resolve;}),);const followUpSearch = runFollowUpSearch([{ role: "user", content: "hello" }],"hello",makeSettings(),[],[],);await vi.waitFor(() => expect(mockSearchImages).toHaveBeenCalled());finishPageRead({});await followUpSearch;});it("anchors a relative date in the follow-up query to the current year", async () => {vi.useFakeTimers({ toFake: ["Date"] });vi.setSystemTime(new Date("2026-11-19T12:00:00Z"));mockGenerateRelatedSearchQuery.mockResolvedValueOnce("new series on disney plus next month",);mockSearchText.mockResolvedValueOnce({ results: [], stale: false });try {await runFollowUpSearch([{ role: "user", content: "what about next month" }],"what about next month",makeSettings(),[],[],);} finally {vi.useRealTimers();}const anchoredQuery = "new series on disney plus next month December 2026";expect(mockSearchText).toHaveBeenCalledWith(anchoredQuery, 10);expect(mockSearchImages).toHaveBeenCalledWith(anchoredQuery, 10);});it("refreshes text results when enabled", async () => {mockSearchText.mockResolvedValueOnce({results: [["Title", "snippet", "https://new.com"]],
1232 unmodified lines678910111213141516171819202122232 unmodified lines2627282930313233343536373839404142434445464716 unmodified lines64656667686938 unmodified lines10810911011111211319 unmodified lines1331341351361371381391401411421431441451461478 unmodified lines156157158159import {getCurrentSearchRunId,type ImageResults,2 unmodified linesupdateSearchResults,} from "./history";import { addLogEntry } from "./logEntries";import {updateImageSearchResults,updateLlmTextSearchResults,updateTextSearchResults,updateTextSearchStale,} from "./pubSub";import { searchImages, searchText } from "./search";import type { defaultSettings } from "./settings";import { searchResultsToConsider } from "./textGenerationUtilities";import type {ChatMessage,ImageSearchResults,TextSearchResults,} from "./types";2 unmodified lines/*** Fetches fresh text search results and merges them into existing results,* deduplicating by URL. Updates pubSub state for both LLM-visible and UI results.*/export async function refreshTextSearchResults(searchQuery: string,resultsLimit: number,existingResults: TextSearchResults,): Promise<void> {const { results: freshResults, stale } = await searchText(searchQuery,resultsLimit,);if (freshResults.length === 0) return;updateTextSearchStale(stale);updateLlmTextSearchResults(freshResults.slice(0, searchResultsToConsider));const existingUrls = new Set(existingResults.map(([, , url]) => url));const uniqueFreshResults = freshResults.filter(16 unmodified lines})),} satisfies TextResults);}}/**38 unmodified lines}}/*** Saves a user message and its assistant response to chat history.*/19 unmodified lines): Promise<void> {const { generateRelatedSearchQuery } = await import("./relatedSearchQuery");const relatedQuery = await generateRelatedSearchQuery([...messages]);const searchQuery = relatedQuery || currentInput;if (settings.enableTextSearch) {try {await refreshTextSearchResults(searchQuery,settings.searchResultsLimit,existingTextResults,);} catch (error) {addLogEntry(`Error in follow-up search: ${error}`);}8 unmodified linesaddLogEntry(`Error in follow-up image search: ${error}`);});}}12342 unmodified lines78910111213141516171819202122232425262728292 unmodified lines3233343536373839404142434445464748495051525354555657585916 unmodified lines767778798081828338 unmodified lines12212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415519 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072088 unmodified lines217218219220221222import { normalizeRelativeDates } from "@shared/relativeDates";import {getCurrentSearchRunId,type ImageResults,2 unmodified linesupdateSearchResults,} from "./history";import { addLogEntry } from "./logEntries";import { fetchPageContents } from "./pageContent";import {getPageContents,updateImageSearchResults,updateLlmTextSearchResults,updatePageContents,updateTextSearchResults,updateTextSearchStale,} from "./pubSub";import { searchImages, searchText } from "./search";import { selectLlmSearchResults } from "./searchResultSelection";import type { defaultSettings } from "./settings";import { searchResultsToConsider } from "./textGenerationUtilities";import type {ChatMessage,ImageSearchResults,PageContents,TextSearchResults,} from "./types";2 unmodified lines/*** Fetches fresh text search results and merges them into existing results,* deduplicating by URL. Updates pubSub state for both LLM-visible and UI results.** Returns the results the answer is grounded on (empty when nothing came back).*/export async function refreshTextSearchResults(searchQuery: string,resultsLimit: number,existingResults: TextSearchResults,): Promise<TextSearchResults> {const { results: freshResults, stale } = await searchText(searchQuery,resultsLimit,);if (freshResults.length === 0) return [];updateTextSearchStale(stale);const llmResults = selectLlmSearchResults(freshResults,searchResultsToConsider,);updateLlmTextSearchResults(llmResults);const existingUrls = new Set(existingResults.map(([, , url]) => url));const uniqueFreshResults = freshResults.filter(16 unmodified lines})),} satisfies TextResults);}return llmResults;}/**38 unmodified lines}}/*** Reads the pages behind the fresh follow-up results.** The first search reads its pages before answering, but the follow-up path* only replaced the snippets: the new results arrived without page text, so* the answer fell back to titles and snippets, and a URL both searches* returned kept the excerpt picked for the previous question. Reading them* here keeps the answer grounded on the same kind of evidence for both* questions.*/async function readFollowUpPageContents(searchQuery: string,results: TextSearchResults,searchRunId: string,): Promise<void> {const contents: PageContents = await fetchPageContents(searchQuery,results.map(([, , url]) => url),);// A newer search has already started; its pages own the channel now.if (getCurrentSearchRunId() !== searchRunId) return;if (Object.keys(contents).length === 0) return;updatePageContents({ ...getPageContents(), ...contents });}/*** Saves a user message and its assistant response to chat history.*/19 unmodified lines): Promise<void> {const { generateRelatedSearchQuery } = await import("./relatedSearchQuery");const relatedQuery = await generateRelatedSearchQuery([...messages]);// Same anchor as the first search in `startTextSearch`: "next month" names no// year to the engine, and only this machine's clock knows which one is meant.const searchQuery = normalizeRelativeDates(relatedQuery || currentInput,new Date(),{ maxLength: 2000 },).searchQuery;const searchRunId = getCurrentSearchRunId();let pageContentsRead = Promise.resolve();if (settings.enableTextSearch) {try {const freshResults = await refreshTextSearchResults(searchQuery,settings.searchResultsLimit,existingTextResults,);if (freshResults.length > 0 && settings.enablePageContentFetch) {// Started here but awaited last, as in the first search, so the image// refresh below does not wait on the pages.pageContentsRead = readFollowUpPageContents(searchQuery,freshResults,searchRunId,);}} catch (error) {addLogEntry(`Error in follow-up search: ${error}`);}8 unmodified linesaddLogEntry(`Error in follow-up image search: ${error}`);});}await pageContentsRead;}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));vi.mock("./textGeneration", () => ({ generateChatResponse: vi.fn(() => Promise.resolve("")), generateReplyToMessages: vi.fn(() => Promise.resolve("")),}));
import { generateRelatedSearchQuery } from "./relatedSearchQuery";import { generateChatResponse, generateReplyToMessages,} from "./textGeneration";
const mockGenerateReplyToMessages = vi.mocked(generateReplyToMessages);
beforeEach(() => vi.clearAllMocks());
describe("generateRelatedSearchQuery", () => { it("writes the query from the conversation alone, without the search results in front", async () => { mockGenerateReplyToMessages.mockResolvedValueOnce( '"Burj Khalifa height in meters"', );
const query = await generateRelatedSearchQuery([ { role: "user", content: "what is the tallest building in dubai" }, { role: "assistant", content: "The Burj Khalifa." }, { role: "user", content: "what is its height" }, ]);
expect(query).toBe("Burj Khalifa height in meters"); // The answer prompt carries pages in many languages, and with them in // front a small model wrote the query in one of those languages. expect(generateChatResponse).not.toHaveBeenCalled(); const [messages] = mockGenerateReplyToMessages.mock.calls[0]; expect(messages.slice(0, 2)).toEqual([ { role: "user", content: "what is the tallest building in dubai" }, { role: "assistant", content: "The Burj Khalifa." }, ]); expect(messages[2].content).toContain("what is its height"); expect(messages[2].content).toContain("name that thing in the query"); });
it("asks the model to keep a relative date as written, for the date anchor to resolve", async () => { await generateRelatedSearchQuery([ { role: "user", content: "who won the world series" }, { role: "assistant", content: "The Dodgers won the 2026 World Series." }, { role: "user", content: "who won it last year" }, ]);
const [messages] = mockGenerateReplyToMessages.mock.calls[0]; // Given today's date instead, Gemma 3 4B wrote "November 2026" for // "next month" on 2026-11-19; `normalizeRelativeDates` gets it right. expect(messages[2].content).toContain("copy it word for word"); });
it.each([ ["“Avengers: Doomsday release delay reasons”"], ["「Avengers: Doomsday release delay reasons」"], ["«Avengers: Doomsday release delay reasons»"], ])("removes the quote marks around %s", async (reply) => { mockGenerateReplyToMessages.mockResolvedValueOnce(reply);
expect( await generateRelatedSearchQuery([{ role: "user", content: "why" }]), ).toBe("Avengers: Doomsday release delay reasons"); });
it("returns nothing when the generation fails", async () => { mockGenerateReplyToMessages.mockRejectedValueOnce(new Error("offline"));
expect( await generateRelatedSearchQuery([{ role: "user", content: "hello" }]), ).toBe(""); });});1234512 unmodified lines18192021222324252627282930313233343536373839import { addLogEntry } from "./logEntries";import { generateChatResponse } from "./textGeneration";import type { ChatMessage } from "./types";export async function generateRelatedSearchQuery(12 unmodified lines${question}Ensure the generated web search query is in the same language as the question above.Respond with only the search query text, no quotes or additional text.`,};const raw = await generateChatResponse(prompt, () => {});let webSearchQuery = raw.split("\n").reverse()[0]?.trim() ?? "";if (webSearchQuery.startsWith('"') || webSearchQuery.startsWith("'")) {webSearchQuery = webSearchQuery.slice(1);}if (webSearchQuery.endsWith('"') || webSearchQuery.endsWith("'")) {webSearchQuery = webSearchQuery.slice(0, -1);}addLogEntry(`Generated follow-up search query: '${webSearchQuery}'`);1234512 unmodified lines1819202122232425262728293031323334353637383940import { addLogEntry } from "./logEntries";import { generateReplyToMessages } from "./textGeneration";import type { ChatMessage } from "./types";export async function generateRelatedSearchQuery(12 unmodified lines${question}The query must make sense on its own, without the rest of the conversation: if the question refers to something mentioned earlier, name that thing in the query.If the question has a relative date, copy it word for word instead of writing a date.Ensure the generated web search query is in the same language as the question above.Respond with only the search query text, no quotes or additional text.`,};const raw = await generateReplyToMessages(prompt);let webSearchQuery = raw.split("\n").reverse()[0]?.trim() ?? "";// Models also wrap the query in the quote marks of other languages.webSearchQuery = webSearchQuery.replace(/^["'“”‘’「」『』«»]/, "").replace(/["'“”‘’「」『』«»]$/, "");addLogEntry(`Generated follow-up search query: '${webSearchQuery}'`);
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import { describe, expect, it } from "vitest";import { selectLlmSearchResults } from "./searchResultSelection";import type { TextSearchResults } from "./types";
const result = (title: string, score?: number) => [title, `${title} snippet`, `https://example.com/${title}`, score] as const;
describe("selectLlmSearchResults", () => { it("takes the first results in engine order when nothing is scored", () => { const results: TextSearchResults = [ [...result("pinned")], [...result("second")], [...result("third")], [...result("fourth")], ];
expect(selectLlmSearchResults(results, 2).map(([title]) => title)).toEqual([ "pinned", "second", ]); });
it("prefers the highest scores over the pinned first result", () => { const results: TextSearchResults = [ [...result("pinned-ad", 12)], [...result("relevant-a", 91)], [...result("relevant-b", 87)], [...result("weak", 20)], ];
expect(selectLlmSearchResults(results, 2).map(([title]) => title)).toEqual([ "relevant-a", "relevant-b", ]); });
it("keeps the input order between equal scores", () => { const results: TextSearchResults = [ [...result("first", 50)], [...result("second", 50)], [...result("third", 50)], ];
expect(selectLlmSearchResults(results, 2).map(([title]) => title)).toEqual([ "first", "second", ]); });
it("does not mutate the caller's results", () => { const results: TextSearchResults = [ [...result("pinned", 1)], [...result("relevant", 99)], ];
selectLlmSearchResults(results, 1);
expect(results.map(([title]) => title)).toEqual(["pinned", "relevant"]); });
it("returns everything when the limit is larger than the list", () => { const results: TextSearchResults = [[...result("only", 42)]];
expect(selectLlmSearchResults(results, 6)).toHaveLength(1); });});1234567891011121314151617181920212223242526import type { TextSearchResults } from "./types";
/** * Picks the results the answer is grounded on, out of the results the user is * shown. * * The list and the evidence set are not the same thing: the server pins the * engine's first result to the top so the user sees it first, but a pinned * result is not always a relevant one, and taking the first N blindly spends * one of N evidence slots on it. When the reranker scored the batch, the * highest scores are the better evidence, wherever the pin placed them. * * Without scores the engine order is all there is, so it is preserved. */export function selectLlmSearchResults( results: TextSearchResults, limit: number,): TextSearchResults { if (!results.some(([, , , score]) => typeof score === "number")) { return results.slice(0, limit); }
return [...results] .sort((left, right) => (right[3] ?? 0) - (left[3] ?? 0)) .slice(0, limit);}133 unmodified lines13413513613713813914014114214314456 unmodified lines201202203204205206334 unmodified lines541542543544545546133 unmodified linesdefault: { encode: vi.fn(() => [1, 2, 3]) },}));import { saveLlmResponseForQuery } from "./history";import { fetchPageContents } from "./pageContent";import { updateTextSearchStale } from "./pubSub";import { searchImages, searchText } from "./search";import { searchAndRespond } from "./textGeneration";import type { ImageSearchResults, TextSearchResults } from "./types";const mockFetch = vi.fn();56 unmodified linesexpect(harness.state.textSearchState).toBe("completed");});it("keeps the text search completed when the keyword fallback is also empty", async () => {vi.mocked(searchText).mockResolvedValue({ results: [], stale: false });334 unmodified linesharness.onResponseUpdate.current = () => {};});it("ends in a failed state when /inference answers 503", async () => {mockFetch.mockResolvedValue(new Response(null, { status: 503 }));133 unmodified lines13413513613713813914014114214314414514614714814915056 unmodified lines207208209210211212213214215216217218219220221222223224225226227228229230231232233234334 unmodified lines569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600133 unmodified linesdefault: { encode: vi.fn(() => [1, 2, 3]) },}));vi.mock("./textGenerationWithWllama", () => ({generateTextWithWllama: vi.fn(() => Promise.resolve()),generateChatWithWllama: vi.fn(() => Promise.resolve("")),}));import { saveLlmResponseForQuery } from "./history";import { fetchPageContents } from "./pageContent";import { listenToSettingsChanges, updateTextSearchStale } from "./pubSub";import { searchImages, searchText } from "./search";import { searchAndRespond } from "./textGeneration";import { generateTextWithWllama } from "./textGenerationWithWllama";import type { ImageSearchResults, TextSearchResults } from "./types";const mockFetch = vi.fn();56 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],["Relevant", "A snippet", "https://relevant.example", 91],["Weak", "A snippet", "https://weak.example", 20],];vi.mocked(searchText).mockResolvedValueOnce({results: scoredResults,stale: false,});await searchAndRespond();await harness.state.searchPromise;expect(harness.state.textSearchResults).toEqual(scoredResults);expect((harness.state.llmTextSearchResults as TextSearchResults).map(([title]) => title,),).toEqual(["Relevant", "Weak", "Pinned"]);});it("keeps the text search completed when the keyword fallback is also empty", async () => {vi.mocked(searchText).mockResolvedValue({ results: [], stale: false });334 unmodified linesharness.onResponseUpdate.current = () => {};});it("loads the browser model once when two searches wait for the download allowance", async () => {const settings = harness.state.settings;settings.inferenceType = "browser";settings.allowAiModelDownload = false;const listeners: ((value: typeof settings) => void)[] = [];vi.mocked(listenToSettingsChanges).mockImplementation((listener) => {listeners.push(listener as (value: typeof settings) => void);return vi.fn();});try {const first = searchAndRespond();const second = searchAndRespond();await vi.waitFor(() => expect(listeners).toHaveLength(2));settings.allowAiModelDownload = true;for (const listener of listeners) listener(settings);await Promise.all([first, second]);} finally {settings.inferenceType = "internal";settings.allowAiModelDownload = true;}expect(generateTextWithWllama).toHaveBeenCalledTimes(1);});it("ends in a failed state when /inference answers 503", async () => {mockFetch.mockResolvedValue(new Response(null, { status: 503 }));
48 unmodified lines49505152535455565712 unmodified lines70717248 unmodified linesvi.mock("pretty-ms", () => ({default: vi.fn(() => "100ms"),}));import { getSettings } from "./pubSub";import { textGenerationFunctions } from "./textGeneration";const mockGetSettings = vi.mocked(getSettings);12 unmodified linesexpect(textGenerationFunctions.needsModelDownloadGate()).toBe(expected);});});48 unmodified lines49505152535455565758596061626364656612 unmodified lines79808182838485868788899091929394959697989910010110210310448 unmodified linesvi.mock("pretty-ms", () => ({default: vi.fn(() => "100ms"),}));vi.mock("./textGenerationWithWllama", () => ({generateTextWithWllama: vi.fn(() => Promise.resolve()),generateChatWithWllama: vi.fn(() => Promise.resolve("")),}));import gptTokenizer from "gpt-tokenizer";import { getSettings } from "./pubSub";import {generateReplyToMessages,textGenerationFunctions,} from "./textGeneration";import { generateChatWithWllama } from "./textGenerationWithWllama";const mockGetSettings = vi.mocked(getSettings);12 unmodified linesexpect(textGenerationFunctions.needsModelDownloadGate()).toBe(expected);});});describe("generateReplyToMessages", () => {it("drops the oldest messages that do not fit the context, starting on a user message", async () => {vi.mocked(gptTokenizer.encode).mockImplementation((text: string) =>Array.from(text, () => 1),);try {await generateReplyToMessages([{ role: "user", content: "x".repeat(4000) },{ role: "assistant", content: "ok" },{ role: "user", content: "question" },]);} finally {vi.mocked(gptTokenizer.encode).mockImplementation(() => [1, 2, 3]);}expect(generateChatWithWllama).toHaveBeenCalledWith([{ role: "user", content: "question" }],expect.any(Function),);});});
29 unmodified lines303132333435236 unmodified lines27227327427527627749 unmodified lines32732832933033133216 unmodified lines349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378114 unmodified lines49349449549649749849929 unmodified linesupdateTextSearchState,} from "./pubSub";import { searchImages, searchText } from "./search";import { getSystemPrompt } from "./systemPrompt";import {ChatGenerationError,236 unmodified linesconst settings = getSettings();if (needsModelDownloadGate()) {await canDownloadModels();updateTextGenerationState("loadingModel");}const strategy = await getCurrentInferenceStrategy();49 unmodified linesreturn content;}export async function generateChatResponse(newMessages: ChatMessage[],onUpdate: (partialResponse: string) => void,16 unmodified lines).length;const reservedTokens = systemPromptTokens + initialResponseTokens;const availableTokenBudget = defaultContextSize * 0.75 - reservedTokens;const processedMessages: ChatMessage[] = [];const reversedMessages = [...newMessages].reverse();let currentTokenCount = 0;for (let i = 0; i < reversedMessages.length; i++) {const message = reversedMessages[i];const messageTokens = gptTokenizer.encode(message.content).length;if (currentTokenCount + messageTokens > availableTokenBudget) {break;}processedMessages.unshift(message);currentTokenCount += messageTokens;}if (processedMessages.length > 0) {const expectedFirstRole = "user";if (processedMessages[0].role !== expectedFirstRole) {processedMessages.shift();}}if (newMessages.length > processedMessages.length) {const droppedCount = newMessages.length - processedMessages.length;114 unmodified linesupdateTextSearchState("completed");updateTextSearchResults(textResults);const resultsForLlm = textResults.slice(0, searchResultsToConsider);updateLlmTextSearchResults(resultsForLlm);updateSearchResults(getCurrentSearchRunId(), {29 unmodified lines30313233343536236 unmodified lines27327427527627727827928028128249 unmodified lines33233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438516 unmodified lines402403404405406407408409410411114 unmodified lines52652752852953053153253353453529 unmodified linesupdateTextSearchState,} from "./pubSub";import { searchImages, searchText } from "./search";import { selectLlmSearchResults } from "./searchResultSelection";import { getSystemPrompt } from "./systemPrompt";import {ChatGenerationError,236 unmodified linesconst settings = getSettings();if (needsModelDownloadGate()) {await canDownloadModels();// Every search waiting here is released by the same allowance, and each// would load its own copy of the model; two loads at once fail on the// browser's file lock, so only the newest search goes on.if (invocation !== searchInvocation) return;updateTextGenerationState("loadingModel");}const strategy = await getCurrentInferenceStrategy();49 unmodified linesreturn content;}/*** Keeps the newest messages that fit the token budget, starting on a user* message.*/function keepNewestMessagesWithinBudget(messages: ChatMessage[],tokenBudget: number,): ChatMessage[] {const keptMessages: ChatMessage[] = [];let tokenCount = 0;for (const message of [...messages].reverse()) {const messageTokens = gptTokenizer.encode(message.content).length;if (tokenCount + messageTokens > tokenBudget) break;keptMessages.unshift(message);tokenCount += messageTokens;}if (keptMessages.length > 0 && keptMessages[0].role !== "user") {keptMessages.shift();}return keptMessages;}/*** Generates a reply from the given messages alone. Unlike* `generateChatResponse`, it puts no system prompt and no search results in* front of them, for tasks that work on the conversation itself.*/export async function generateReplyToMessages(messages: ChatMessage[],): Promise<string> {const keptMessages = keepNewestMessagesWithinBudget(messages,defaultContextSize * 0.75,);if (keptMessages.length === 0) {throw new Error("The newest message alone does not fit the context");}const strategy = await getCurrentInferenceStrategy();return strategy.generateChat(keptMessages, () => {});}export async function generateChatResponse(newMessages: ChatMessage[],onUpdate: (partialResponse: string) => void,16 unmodified lines).length;const reservedTokens = systemPromptTokens + initialResponseTokens;const availableTokenBudget = defaultContextSize * 0.75 - reservedTokens;const processedMessages = keepNewestMessagesWithinBudget(newMessages,availableTokenBudget,);if (newMessages.length > processedMessages.length) {const droppedCount = newMessages.length - processedMessages.length;114 unmodified linesupdateTextSearchState("completed");updateTextSearchResults(textResults);const resultsForLlm = selectLlmSearchResults(textResults,searchResultsToConsider,);updateLlmTextSearchResults(resultsForLlm);updateSearchResults(getCurrentSearchRunId(), {
40 unmodified lines414243444546341 unmodified lines38838939039139239340 unmodified lineslanguage: { code: "en_US", name_english: "English" },};const portugueseVoice = {key: "pt_BR-faber-medium",name: "faber",341 unmodified linesexpect(worker.sent[0].voiceId).toBe("pt_BR-faber-medium");});it("keeps a chosen voice whatever the answer's language", async () => {mockVoices.mockResolvedValue([englishVoice, portugueseVoice]);settings.selectedVoiceId = "piper:en_US-lessac-high";40 unmodified lines414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091341 unmodified lines43343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649740 unmodified lineslanguage: { code: "en_US", name_english: "English" },};const englishLowVoice = {key: "en_GB-alan-low",name: "alan",quality: "low",language: { code: "en_GB", name_english: "English" },};const englishMediumVoice = {key: "en_GB-alan-medium",name: "alan",quality: "medium",language: { code: "en_GB", name_english: "English" },};const americanMediumVoice = {key: "en_US-amy-medium",name: "amy",quality: "medium",language: { code: "en_US", name_english: "English" },};const portugueseFromPortugalVoice = {key: "pt_PT-tugão-medium",name: "tugão",quality: "medium",language: { code: "pt_PT", name_english: "Portuguese" },};const vietnameseLowVoice = {key: "vi_VN-25hours_single-low",name: "25hours_single",quality: "low",language: { code: "vi_VN", name_english: "Vietnamese" },};const vietnameseXLowVoice = {key: "vi_VN-vivos-x_low",name: "vivos",quality: "x_low",language: { code: "vi_VN", name_english: "Vietnamese" },};const vietnameseAnswer ="Tháp Eiffel được xây dựng vào năm 1889 cho Hội chợ Thế giới ở Paris và cao khoảng 330 mét.";const portugueseVoice = {key: "pt_BR-faber-medium",name: "faber",341 unmodified linesexpect(worker.sent[0].voiceId).toBe("pt_BR-faber-medium");});it("prefers a medium voice over a low one of the same language", async () => {mockVoices.mockResolvedValue([englishLowVoice, englishMediumVoice]);const worker = createFakeWorker();tts.setWorkerFactory(() => worker as unknown as Worker);void tts.speak("Hello there.");await vi.waitFor(() => expect(worker.sent).toHaveLength(1));expect(worker.sent[0].voiceId).toBe("en_GB-alan-medium");});it("prefers a medium voice over a high one, which is a bigger download", async () => {mockVoices.mockResolvedValue([englishVoice, englishMediumVoice]);const worker = createFakeWorker();tts.setWorkerFactory(() => worker as unknown as Worker);void tts.speak("Hello there.");await vi.waitFor(() => expect(worker.sent).toHaveLength(1));expect(worker.sent[0].voiceId).toBe("en_GB-alan-medium");});it("prefers the browser's region among voices of the same quality", async () => {mockVoices.mockResolvedValue([englishMediumVoice, americanMediumVoice]);const worker = createFakeWorker();tts.setWorkerFactory(() => worker as unknown as Worker);void tts.speak("Hello there.");await vi.waitFor(() => expect(worker.sent).toHaveLength(1));expect(worker.sent[0].voiceId).toBe("en_US-amy-medium");});it("prefers a low voice over an x-low one of the same language", async () => {vi.stubGlobal("navigator", { language: "vi-VN" });mockVoices.mockResolvedValue([vietnameseXLowVoice, vietnameseLowVoice]);const worker = createFakeWorker();tts.setWorkerFactory(() => worker as unknown as Worker);void tts.speak(vietnameseAnswer);await vi.waitFor(() => expect(worker.sent).toHaveLength(1));expect(worker.sent[0].voiceId).toBe("vi_VN-25hours_single-low");});it("keeps the catalogue order when the answer's language has no region", async () => {mockVoices.mockResolvedValue([portugueseFromPortugalVoice,portugueseVoice,]);const worker = createFakeWorker();tts.setWorkerFactory(() => worker as unknown as Worker);void tts.speak(portugueseAnswer);await vi.waitFor(() => expect(worker.sent).toHaveLength(1));expect(worker.sent[0].voiceId).toBe("pt_PT-tugão-medium");});it("keeps a chosen voice whatever the answer's language", async () => {mockVoices.mockResolvedValue([englishVoice, portugueseVoice]);settings.selectedVoiceId = "piper:en_US-lessac-high";
247 unmodified lines24824925025125225325425525625710 unmodified lines268269270271272273274275276277247 unmodified linesreturn options;}/*** Resolves the stored setting to a voice the catalogue actually publishes, or* null when there is none. A stored voice that has since been removed falls* back to the language match instead of failing at download time.*/async function resolveLocalVoiceId(storedVoiceId: string,10 unmodified lines}const wanted = primaryLanguage(languageCode);const match = catalogue.find((voice) => primaryLanguage(voice.language.code) === wanted,);return match?.key ?? null;}let workerFactory = () =>247 unmodified lines24824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727810 unmodified lines289290291292293294295296297298299300301302303304305306307308247 unmodified linesreturn options;}/*** Quality order for the automatic pick: `medium` is the sweet spot of quality* and download size, so `high` voices (up to twice as big) only serve* languages that publish nothing else.*/const QUALITY_RANK: Record<Voice["quality"], number> = {medium: 0,low: 1,x_low: 2,high: 3,};/** `en-US` and `en_US` both give `us`; a bare `en` gives the empty string. */function regionOf(code: string): string {const parts = code.replace("_", "-").split("-");return (parts[1] ?? "").toLowerCase();}/*** Resolves the stored setting to a voice the catalogue actually publishes, or* null when there is none. A stored voice that has since been removed falls* back to the language match instead of failing at download time. That match* prefers `medium` quality over `low` and `x_low`, and, when the answer is in* the browser's language, a voice of the browser's region over one of another* region at the same quality.*/async function resolveLocalVoiceId(storedVoiceId: string,10 unmodified lines}const wanted = primaryLanguage(languageCode);const wantedRegion = regionOf(languageCode);const matches = catalogue.filter((voice) => primaryLanguage(voice.language.code) === wanted,);// The sort is stable, so the catalogue order breaks remaining ties. With no// region in the answer's language, every voice mismatches it alike.const regionMismatch = (voice: Voice) =>regionOf(voice.language.code) === wantedRegion ? 0 : 1;matches.sort((a, b) =>QUALITY_RANK[a.quality] - QUALITY_RANK[b.quality] ||regionMismatch(a) - regionMismatch(b),);return matches[0]?.key ?? null;}let workerFactory = () =>
365 unmodified lines366367368369370371365 unmodified lineshfFilePath: "model.shard-00001-of-00007.gguf",fileSizeInMegabytes: 1930,},"granite-4.2-3b": {...createDefaultModelConfig(),label: "Granite 4.2 3B",365 unmodified lines366367368369370371372373374375376377378379380381382365 unmodified lineshfFilePath: "model.shard-00001-of-00007.gguf",fileSizeInMegabytes: 1930,},// Loads only once wllama ships a llama.cpp build with the raon1nano// architecture (upstream ggml-org/llama.cpp#32200 is open); the sharded// repo is published so the entry starts working the moment the wasm does."raon-1-nano-3b": {...createDefaultModelConfig(),label: "Raon-1 nano 3B (wllama support pending)",hfRepoId: "Felladrin/gguf-sharded-Q4_K_M-raon-1-nano",hfFilePath: "raon-1-nano-Q4_K_M-00001-of-00005.gguf",fileSizeInMegabytes: 2083,reasoningBudgetTokens: 1024,},"granite-4.2-3b": {...createDefaultModelConfig(),label: "Granite 4.2 3B",
40 unmodified lines41424344454647192 unmodified lines24024124224324424524615 unmodified lines262263264265266267106 unmodified lines37437537637737837938038138238338438538638738840 unmodified lines- **Every model file must be a shard.** Chromium's OPFS storage silently truncates files past 2000 MiB, so a monolithic GGUF above that size arrives corrupted in the browser. Shards also keep progressive download working.- **The wasm linear memory ceiling is 4 GiB.** Models at ~3.5 GB and above OOM during buffer reserve, so the practical catalog ceiling is around 3.7 GB of weights.Models whose chat template thinks by default (Granite 4.2, Gemma 4, Spark X2.6, Qwen 3 and 3.5, Polaris, DeepSeek R1 Distill, LittleLamb) keep thinking: wllama splits their chain of thought into a `reasoning_content` channel, and MiniSearch wraps it in the configured reasoning markers so the thinking UI shows it while the answer follows. Thinking spends the same token budget as the answer, so these models are slower. To keep a long-winded model from thinking its way out of the context window without ever answering, thinking models ship with `reasoningBudgetTokens` (wllama's `reasoning_budget_tokens`, currently 1024): once the chain of thought runs that long, the engine closes the reasoning channel and forces the final answer. A cut-off chain of thought degrades the answer, so the budget is a backstop, not a target: every model also gets `reasoning_effort: "low"` in its chat template variables, which templates that support it (Granite 4.2, Spark X2.6) answer by thinking less, and the others ignore.`node scripts/wllama-catalog-check.cjs` HEADs every shard of every catalog model on HuggingFace and verifies the claimed sizes; run it after adding or re-sharding a model.192 unmodified linesUpdate PubSub channels (response, textGenerationState)```The AI context includes the top 6 text search results (a fixed value, `searchResultsToConsider` in `client/modules/textGenerationUtilities.ts`), not a user-configurable setting.### Chat Generation15 unmodified linesSave to history database```### Text Generation State Machine`textGenerationStatePubSub` drives the AI response UI through these states:106 unmodified linesWith no voice chosen, `speak()` picks one for the language of the answer,which follows the question's language rather than the browser's. `franc-min`detects it, loaded on the first Listen press rather than with the page, and thefirst local voice of that language reads the answer. With the system engine,or when no local voice speaks that language (Japanese, Korean and Hindi havenone), the language is passed to `speechSynthesis` so the OS picks its ownvoice. The browser's language is used instead when the detector cannot tell,fails to load, or does not know the browser's language at all (Danish, Finnishand Catalan among them), since it would then read an answer in that languageas a neighbouring one. A chosen voice reads every answer, whatever itslanguage.### Third-party requests40 unmodified lines414243444546474849192 unmodified lines24224324424524624724815 unmodified lines264265266267268269270271106 unmodified lines37837938038138238338438538638738838939039139239339439540 unmodified lines- **Every model file must be a shard.** Chromium's OPFS storage silently truncates files past 2000 MiB, so a monolithic GGUF above that size arrives corrupted in the browser. Shards also keep progressive download working.- **The wasm linear memory ceiling is 4 GiB.** Models at ~3.5 GB and above OOM during buffer reserve, so the practical catalog ceiling is around 3.7 GB of weights.One entry is the exception to "measured against the shipped wasm": Raon-1 nano 3B sits in the catalog and the dropdown, labeled "(wllama support pending)", because the `raon1nano` architecture is not yet in the llama.cpp build the wasm ships (upstream [ggml-org/llama.cpp#32200](https://github.com/ggml-org/llama.cpp/pull/32200) is open). It cannot answer until wllama ships that support; the sharded files and the entry are published so it starts working the day it does.Models whose chat template thinks by default (Granite 4.2, Gemma 4, Spark X2.6, Qwen 3 and 3.5, Polaris, DeepSeek R1 Distill, LittleLamb, Raon-1 nano) keep thinking: wllama splits their chain of thought into a `reasoning_content` channel, and MiniSearch wraps it in the configured reasoning markers so the thinking UI shows it while the answer follows. Thinking spends the same token budget as the answer, so these models are slower. To keep a long-winded model from thinking its way out of the context window without ever answering, thinking models ship with `reasoningBudgetTokens` (wllama's `reasoning_budget_tokens`, currently 1024): once the chain of thought runs that long, the engine closes the reasoning channel and forces the final answer. A cut-off chain of thought degrades the answer, so the budget is a backstop, not a target: every model also gets `reasoning_effort: "low"` in its chat template variables, which templates that support it (Granite 4.2, Spark X2.6) answer by thinking less, and the others ignore.`node scripts/wllama-catalog-check.cjs` HEADs every shard of every catalog model on HuggingFace and verifies the claimed sizes; run it after adding or re-sharding a model.192 unmodified linesUpdate PubSub channels (response, textGenerationState)```The AI context includes the 6 best-scored text search results (a fixed value, `searchResultsToConsider` in `client/modules/textGenerationUtilities.ts`, picked by `client/modules/searchResultSelection.ts`), not a user-configurable setting. Without reranker scores, the first 6 are used.### Chat Generation15 unmodified linesSave to history database```Before the answer, a follow-up question gets its own web search, and the query for it is written by `generateRelatedSearchQuery` (`client/modules/relatedSearchQuery.ts`). That call goes through `generateReplyToMessages`, not `generateChatResponse`: it sends the conversation with the same 75% token budget, but without the system prompt and the search results. Those carry pages in many languages: with them in front and the instruction to name the subject, Gemma 3 4B wrote the query for a Chinese question in another language (Turkish, Persian) in 4 of 9 runs, and without them in 2 of 9 (the old prompt, which did not ask for the subject, stayed in Chinese in 9 of 9). The prompt also asks for a query that makes sense on its own, so "why did they delay the release" becomes a query that names what "they" delayed. It also asks the model to copy a relative date ("next month", 明年) as written: `runFollowUpSearch` then anchors it with `normalizeRelativeDates`, while a 4B model given today's date wrote "November 2026" for "next month" on 2026-11-19.### Text Generation State Machine`textGenerationStatePubSub` drives the AI response UI through these states:106 unmodified linesWith no voice chosen, `speak()` picks one for the language of the answer,which follows the question's language rather than the browser's. `franc-min`detects it, loaded on the first Listen press rather than with the page. Thepick prefers a `medium` voice of that language over `low` and `x_low`, andtakes a `high` one only when the language publishes nothing else, since a highvoice costs up to 137 MB against the 63 MB of a typical medium one; amongvoices of the same quality, one of the browser's region wins when the answeris in the browser's language. With the system engine, or when no local voicespeaks that language (Japanese, Korean and Hindi have none), the language ispassed to `speechSynthesis` so the OS picks its own voice. The browser'slanguage is used instead when the detector cannot tell, fails to load, or doesnot know the browser's language at all (Danish, Finnish and Catalan amongthem), since it would then read an answer in that language as a neighbouringone. A chosen voice reads every answer, whatever its language.### Third-party requests
21 unmodified lines22232425262721 unmodified lines## Settings & Extensibility- All inference types share the same summarization contract—no provider-specific logic beyond selecting the backend module at runtime.- The 75%-of-4096 conversation-memory budget in `generateChatResponse` is hardcoded against `defaultContextSize` (4096) and does not currently scale with the user-configurable `openAiContextLength` setting; that setting only caps the `max_tokens` of the outgoing API request, a separate concern from how many prior chat turns are kept in memory.- Future settings (e.g., toggling memory or adjusting the 75% ratio) should hook into the same budgeting helpers to keep behavior predictable.21 unmodified lines2223242526272821 unmodified lines## Settings & Extensibility- All inference types share the same summarization contract—no provider-specific logic beyond selecting the backend module at runtime.- The follow-up search query (`generateRelatedSearchQuery`) uses the same 75% budget through `generateReplyToMessages`, but not the rolling summary: in a conversation longer than the budget, a subject named only in the dropped turns does not reach the query.- The 75%-of-4096 conversation-memory budget in `generateChatResponse` is hardcoded against `defaultContextSize` (4096) and does not currently scale with the user-configurable `openAiContextLength` setting; that setting only caps the `max_tokens` of the outgoing API request, a separate concern from how many prior chat turns are kept in memory.- Future settings (e.g., toggling memory or adjusting the 75% ratio) should hook into the same budgeting helpers to keep behavior predictable.
91 unmodified lines9293949596979891 unmodified lines### Search Flow1. User submits a query via SearchForm2. Relative month and year words (English and Chinese for now) are anchored to absolute ones before the request (`shared/relativeDates.ts`), so "next month" reaches the engines as "December 2026" and a relative phrase cannot leave the index without a year to match; the query as typed still drives the prompt, the history entry, and the UI3. Client checks IndexedDB cache for matching query hash4. On cache miss: authenticated HTTP request to `/search/text` or `/search/images`5. Server verifies request token via `searchToken.ts` (CSRF protection)91 unmodified lines9293949596979891 unmodified lines### Search Flow1. User submits a query via SearchForm2. Relative month and year words (English and Chinese for now) are anchored to absolute ones before the request (`shared/relativeDates.ts`), so "next month" reaches the engines as "December 2026" and a relative phrase cannot leave the index without a year to match (the query a follow-up question generates goes through the same step); the query as typed still drives the prompt, the history entry, and the UI3. Client checks IndexedDB cache for matching query hash4. On cache miss: authenticated HTTP request to `/search/text` or `/search/images`5. Server verifies request token via `searchToken.ts` (CSRF protection)
21 unmodified lines222324252627282911 unmodified lines41424344454621 unmodified lines1. `startTextSearch` (`client/modules/textGeneration.ts`) finishes the textsearch and publishes the results the UI renders.2. The top `searchResultsToConsider` (6) URLs go to `/page-content`, togetherwith the query, via `client/modules/pageContent.ts`.3. `server/pageContentService.ts` reads each page, extracts its readable text,splits it into passages, ranks all passages from all pages together, andselects from the pooled ranking with a per-URL cap and near-duplicate11 unmodified lines`startTextSearch`, so the AI answer waits for it while the rendered results,the image search, and the history write all carry on.## Prompt Shape```21 unmodified lines22232425262728293011 unmodified lines4243444546474849505152535455565758596061626321 unmodified lines1. `startTextSearch` (`client/modules/textGeneration.ts`) finishes the textsearch and publishes the results the UI renders.2. The `searchResultsToConsider` (6) best-scored URLs go to `/page-content`,together with the query, via `client/modules/pageContent.ts`. When noresult carries a reranker score, the first six are used.3. `server/pageContentService.ts` reads each page, extracts its readable text,splits it into passages, ranks all passages from all pages together, andselects from the pooled ranking with a per-URL cap and near-duplicate11 unmodified lines`startTextSearch`, so the AI answer waits for it while the rendered results,the image search, and the history write all carry on.A follow-up question reads the pages behind its own new results too, through`readFollowUpPageContents` (`client/modules/chatHelpers.ts`), because a follow-upsearch often returns pages the first answer never saw. The pages it reads mergeinto the `pageContents` map by URL like the first read's, so a result bothsearches hold keeps one entry, with the excerpt picked for the follow-up'squery, and a newer search that takes over while the read is in flight drops it.Like the first read, it starts when the text results are in and is awaited last,so the follow-up's image refresh does not wait for it.The six results an answer reads, for the first question and for a follow-up,are the six best scored, not the first six of the order the result panelshows: the server keeps the engine's first result pinned at the top of thelist, and a pinned result with a low score would otherwise take one of the sixplaces. `client/modules/searchResultSelection.ts` holds that choice; thedisplayed order is untouched.## Prompt Shape```
99 unmodified lines10010110210310410599 unmodified linesThis mode ensures the original top result is never displaced by the reranker, while still improving the ordering of subsequent results.### Domain PriorityA page from the site the query names gets a small bonus on its semantic score before the filter runs (`server/authorityRanking.ts`, applied in `server/rankSearchResults.ts`). The reranker never sees the URL, so a query like "disney plus next month" ranks a blog roundup and disneyplus.com on their prose alone; the bonus lets the named site overtake a page whose snippet merely talks about it.99 unmodified lines10010110210310410510610799 unmodified linesThis mode ensures the original top result is never displaced by the reranker, while still improving the ordering of subsequent results.The pin only affects the order the result list shows. The six results the AI answer reads are picked by score on the client (`client/modules/searchResultSelection.ts`), so a pinned result with a low score shows first but does not take one of the six places.### Domain PriorityA page from the site the query names gets a small bonus on its semantic score before the filter runs (`server/authorityRanking.ts`, applied in `server/rankSearchResults.ts`). The reranker never sees the URL, so a query like "disney plus next month" ranks a blog roundup and disneyplus.com on their prose alone; the bonus lets the named site overtake a page whose snippet merely talks about it.
2191 unmodified lines2192219321942195219621972198219922002191 unmodified lines}},"node_modules/@testing-library/user-event": {"version": "14.6.10","resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.10.tgz","integrity": "sha512-tA4stGNp3mLGOGO+lh87UA56Tz4c8NVGBSkyIF58O+W/bs2Re9BCI9xihnL70+DsThncFznE0skS88SM1D2hyg==","dev": true,"license": "MIT","engines": {2191 unmodified lines2192219321942195219621972198219922002191 unmodified lines}},"node_modules/@testing-library/user-event": {"version": "14.6.12","resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.12.tgz","integrity": "sha512-8yQV8v+eToBhsUO4oYrZY7fzhpTEMZx4IDx0/iuER/x0Xuy0NdqQOhsaaUNlvXE03N7vQ+4RCXUieKC0NJty9w==","dev": true,"license": "MIT","engines": {
agents.md+1
changelog.md+12
client/modules/chatHelpers.test.ts+129
client/modules/chatHelpers.ts+68-5
client/modules/relatedSearchQuery.test.tsAdded+76
client/modules/relatedSearchQuery.ts+10-9
client/modules/searchResultSelection.test.tsAdded+66
client/modules/searchResultSelection.tsAdded+26
client/modules/textGeneration.degradation.test.ts+55-1
client/modules/textGeneration.inference.test.ts+33-1
client/modules/textGeneration.ts+61-25
client/modules/textToSpeech.test.ts+104
client/modules/textToSpeech.ts+34-3
client/modules/wllama.ts+11
docs/ai-integration.md+18-11
docs/conversation-memory.md+1
docs/overview.md+1-1
docs/page-content.md+19-2
docs/reranking.md+2
package-lock.json+3-3