Spaces:
Running
Running
Sync from felladrin/MiniSearch@c4a67e2
Browse filesFiles changed (21)
- .source-commit+1-1
- agents.md-1
- changelog.md+4
- client/components/AiResponse/AiResponseContent.test.tsx+8-99
- client/components/AiResponse/AiResponseContent.tsx+1-84
- client/components/AiResponse/ChatInputArea.test.tsx+65-5
- client/components/AiResponse/ChatInputArea.tsx+29-3
- client/components/AiResponse/CopyIconButton.tsx+1-5
- client/components/ClearFieldButton.tsxAdded+64
- client/components/Search/Form/QuickSettingsMenu.test.tsxAdded+72
- client/components/Search/Form/QuickSettingsMenu.tsxAdded+87
- client/components/Search/Form/SearchForm.restore.test.tsx+7-5
- client/components/Search/Form/SearchForm.suggestions.test.tsx+7-2
- client/components/Search/Form/SearchForm.test.tsx+34-3
- client/components/Search/Form/SearchForm.tsx+74-30
- client/components/Search/Results/Textual/TextSearchResults.test.tsx+44
- client/components/Search/Results/Textual/TextSearchResults.tsx+8-1
- client/modules/answerExport.test.tsDeleted-278
- client/modules/answerExport.tsDeleted-141
- client/modules/scrollbarGutter.test.tsAdded+15
- client/modules/scrollbarGutter.tsAdded+34
19824a0b1c4a67e2
142 unmodified lines143144145146147148149142 unmodified lines- `client/modules/pageExcerptWorker.ts` - Tokenizes page bodies off the main thread at the search-to-generation handoff- `client/modules/pageExcerptWorkerProtocol.ts` - Message types shared by both sides of the excerpt worker- `client/modules/systemPrompt.ts` - System prompt templates- `client/modules/answerExport.ts` - Builds the Markdown export of an answer, with a file name taken from the query- `client/modules/logEntries.ts` - Application logging with unique IDs- `client/modules/appInfo.ts` - Application metadata and version info- `client/modules/textToSpeech.ts` - Reads answers aloud: engine selection, fallback, and the playback queue142 unmodified lines143144145146147148142 unmodified lines- `client/modules/pageExcerptWorker.ts` - Tokenizes page bodies off the main thread at the search-to-generation handoff- `client/modules/pageExcerptWorkerProtocol.ts` - Message types shared by both sides of the excerpt worker- `client/modules/systemPrompt.ts` - System prompt templates- `client/modules/logEntries.ts` - Application logging with unique IDs- `client/modules/appInfo.ts` - Application metadata and version info- `client/modules/textToSpeech.ts` - Reads answers aloud: engine selection, fallback, and the playback queue
3 unmodified lines4567893 unmodified lines## 2026-11-30- Page excerpts now stay within their shared token budget when they are shortened, leaving the rest of the model's context available for the answer.- Searches whose query text resembles cache-key metadata no longer reuse results cached for a different query or filter.3 unmodified lines456789101112133 unmodified lines## 2026-11-30- The answer card no longer offers "Copy as Markdown" and "Download as Markdown". They sat next to "Copy response" and copied or saved the answer as a standalone Markdown document, with a "Sources" list and a line saying what was searched and when. That is a second way to get what the copy button already gives, and a single answer saved as a file is rarely what you want, so both are gone. Regenerate, read aloud, expand and copy are unchanged.- The "Language not applied to these results" note now shows only when Search Language is set to a language you chose yourself. It used to show on any search a fallback provider answered, and Search Language defaults to Browser language, which sends the browser's own locale without anyone asking, so on an instance that leans on the fallback it appeared on nearly every search and named a language nobody had picked. "Detect from the query" and "Any language" stay quiet too. The time filter half of the note is unchanged.- A long question in the follow-up box no longer scrolls behind its own microphone. The scrollbar sits at the box's right edge whatever the text padding, so the microphone was drawn on top of it and the bar could not be grabbed there. The box now keeps that strip for the scrollbar and the icons start to the left of it, on every platform and whatever width the browser's scrollbar is. The box also gains an "X" next to the microphone that clears what you typed; it shows only when there is something to clear.- The search bar now keeps only its main buttons: Search, Menu, and one button that opens a "Quick settings" panel. History and the time filter moved into that panel, which closes on a second press of the button, on a click outside, or on Escape. Clear became an X at the right end of the search field, next to the microphone, and says it clears the query when you hover it. The field keeps the X's space reserved even when it is empty, so the microphone never shifts sideways into the X just as a dictation lands.- Page excerpts now stay within their shared token budget when they are shortened, leaving the rest of the model's context available for the answer.- Searches whose query text resembles cache-key metadata no longer reuse results cached for a different query or filter.
12345678910111213141516171819202122232425262728293031323334353637383933 unmodified lines737475767778798010 unmodified lines91929394959697989910010110210310410510667 unmodified lines174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251import { MantineProvider } from "@mantine/core";import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { usePubSub } from "create-pubsub/react";import { beforeEach, describe, expect, it, vi } from "vitest";import {buildAnswerFileName,buildAnswerMarkdown,downloadAnswerMarkdown,} from "@/modules/answerExport";import AiResponseContent from "./AiResponseContent";vi.mock("create-pubsub/react", () => ({usePubSub: vi.fn(),}));const liveSources = vi.hoisted(() => ({current: [["Mercury - Wikipedia", "snippet", "https://en.wikipedia.org"]] as [string,string,string,][],}));vi.mock("@/modules/pubSub", async (importOriginal) => ({...(await importOriginal<typeof import("@/modules/pubSub")>()),getQuery: vi.fn(() => "mercury"),getLlmTextSearchResults: vi.fn(() => liveSources.current),}));vi.mock("@/modules/answerExport", () => ({buildAnswerMarkdown: vi.fn(() => "exported markdown"),buildAnswerFileName: vi.fn(() => "mercury.md"),downloadAnswerMarkdown: vi.fn(),}));// Show the text each copy button would put on the clipboard.vi.mock("./CopyIconButton", () => ({default: ({33 unmodified linesconst settings = {enableAiResponseScrolling: false,reasoningStartMarker: "<think>",reasoningEndMarker: "</think>",};function renderContent(10 unmodified linesreturn [generationRate, vi.fn()];});const ui = (state: string) => (<MantineProvider><AiResponseContent textGenerationState={state} response={response} /></MantineProvider>);const result = render(ui(textGenerationState));return {...result,rerenderWith: (state: string) => result.rerender(ui(state)),};}describe("AiResponseContent", () => {67 unmodified lines).toBeInTheDocument();});it("keeps copying the raw response and adds the export next to it", () => {renderContent("completed");expect(buildAnswerMarkdown).toHaveBeenCalledWith(expect.objectContaining({ answer: "Hello world" }),);expect(screen.getByRole("button", { name: "Copy response" }),).toHaveAttribute("data-value", "Hello world");expect(screen.getByRole("button", { name: "Copy as Markdown" }),).toHaveAttribute("data-value", "exported markdown");});it("downloads the built markdown under a name from the query", async () => {renderContent("completed");await userEvent.click(screen.getByRole("button", { name: "Download as Markdown" }),);expect(downloadAnswerMarkdown).toHaveBeenCalledWith("exported markdown","mercury.md",);expect(buildAnswerFileName).toHaveBeenCalledWith("mercury");});it("exports the answer without its reasoning", () => {renderContent("completed", "<think>Let me check.</think>Mercury is small.");expect(buildAnswerMarkdown).toHaveBeenLastCalledWith(expect.objectContaining({ answer: "Mercury is small." }),);});it("keeps the sources the answer finished with after a follow-up replaces them", () => {const { rerenderWith } = renderContent("completed");liveSources.current = [["Follow-up result", "snippet", "https://other.org"],];rerenderWith("completed");expect(buildAnswerMarkdown).toHaveBeenLastCalledWith(expect.objectContaining({sources: [["Mercury - Wikipedia", "snippet", "https://en.wikipedia.org"],],}),);liveSources.current = [["Mercury - Wikipedia", "snippet", "https://en.wikipedia.org"],];});it("strips the prompt's image tag from a source title", () => {liveSources.current = [["(image) A diagram", "", "https://example.com/d"]];renderContent("completed");expect(buildAnswerMarkdown).toHaveBeenLastCalledWith(expect.objectContaining({sources: [["A diagram", "", "https://example.com/d"]],}),);liveSources.current = [["Mercury - Wikipedia", "snippet", "https://en.wikipedia.org"],];});it("offers the export only once the answer is complete", () => {renderContent("generating");expect(screen.queryByRole("button", { name: "Copy as Markdown" }),).not.toBeInTheDocument();1234567891011121333 unmodified lines47484950515210 unmodified lines636465666768697071727374757667 unmodified lines144145146147148149150151152153154155156157158159160import { MantineProvider } from "@mantine/core";import { render, screen } from "@testing-library/react";import { usePubSub } from "create-pubsub/react";import { beforeEach, describe, expect, it, vi } from "vitest";import AiResponseContent from "./AiResponseContent";vi.mock("create-pubsub/react", () => ({usePubSub: vi.fn(),}));// Show the text each copy button would put on the clipboard.vi.mock("./CopyIconButton", () => ({default: ({33 unmodified linesconst settings = {enableAiResponseScrolling: false,};function renderContent(10 unmodified linesreturn [generationRate, vi.fn()];});return render(<MantineProvider><AiResponseContenttextGenerationState={textGenerationState}response={response}/></MantineProvider>,);}describe("AiResponseContent", () => {67 unmodified lines).toBeInTheDocument();});it("copies the raw response", () => {renderContent("completed");expect(screen.getByRole("button", { name: "Copy response" }),).toHaveAttribute("data-value", "Hello world");});it("offers no Markdown export", () => {renderContent("completed");expect(screen.queryByRole("button", { name: "Copy as Markdown" }),).not.toBeInTheDocument();
11 unmodified lines12131415161718192021222324252627282930313233343536373839404142439 unmodified lines5354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101100 unmodified lines20220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423511 unmodified linesimport {IconArrowsMaximize,IconArrowsMinimize,IconDownload,IconHandStop,IconInfoCircle,IconMarkdown,IconRefresh,IconVolume2,} from "@tabler/icons-react";import { usePubSub } from "create-pubsub/react";import { type ReactNode, useEffect, useMemo, useState } from "react";import {buildAnswerFileName,buildAnswerMarkdown,downloadAnswerMarkdown,} from "@/modules/answerExport";import {generationRatePubSub,getLlmTextSearchResults,getQuery,settingsPubSub,textToSpeechStatePubSub,} from "@/modules/pubSub";import { splitReasoning } from "@/modules/reasoning";import { interruptSearch, searchAndRespond } from "@/modules/textGeneration";import { imageResultTag } from "@/modules/textGenerationUtilities";import { speak } from "@/modules/textToSpeech";import type { TextSearchResults } from "@/modules/types";import CopyIconButton from "./CopyIconButton";import FormattedMarkdown from "./FormattedMarkdown";9 unmodified linesconst [generationRate] = usePubSub(generationRatePubSub);const isSpeaking = textToSpeechState === "speaking";const isGenerating = textGenerationState === "generating";const isCompleted = textGenerationState === "completed";const query = getQuery();// Taken when the answer finishes: a follow-up replaces the live list with// its own results, and this card still shows the first answer. The image// tag is the prompt's own marker, not part of a title.const [answerSources, setAnswerSources] = useState<TextSearchResults>([]);useEffect(() => {if (!isCompleted || !response) return;setAnswerSources(getLlmTextSearchResults().map(([title, snippet, url]) => [title.startsWith(imageResultTag)? title.slice(imageResultTag.length): title,snippet,url,]),);}, [isCompleted, response]);const exportMarkdown = useMemo(() =>isCompleted? buildAnswerMarkdown({// The answer only: the reasoning block stays out of the file, as// it stays folded on the card.answer: splitReasoning(response,settings.reasoningStartMarker,settings.reasoningEndMarker,).answer,sources: answerSources,query,exportedAt: new Date(),}): "",[isCompleted,response,answerSources,query,settings.reasoningStartMarker,settings.reasoningEndMarker,],);const ConditionalScrollArea = useMemo(() =>100 unmodified lines</Tooltip>)}<CopyIconButton value={response} tooltipLabel="Copy response" />{isCompleted && (<><CopyIconButtonvalue={exportMarkdown}tooltipLabel="Copy as Markdown"icon={<IconMarkdown size={16} />}/><Tooltiplabel="Download as Markdown"withArrowposition="right"><ActionIconaria-label="Download as Markdown"onClick={() =>downloadAnswerMarkdown(exportMarkdown,buildAnswerFileName(query),)}variant="subtle"color="gray"><IconDownload size={16} /></ActionIcon></Tooltip></>)}</Group></Group></Card.Section>11 unmodified lines12131415161718192021222324252627282930319 unmodified lines414243444546100 unmodified lines14714814915015115211 unmodified linesimport {IconArrowsMaximize,IconArrowsMinimize,IconHandStop,IconInfoCircle,IconRefresh,IconVolume2,} from "@tabler/icons-react";import { usePubSub } from "create-pubsub/react";import { type ReactNode, useMemo } from "react";import {generationRatePubSub,settingsPubSub,textToSpeechStatePubSub,} from "@/modules/pubSub";import { interruptSearch, searchAndRespond } from "@/modules/textGeneration";import { speak } from "@/modules/textToSpeech";import CopyIconButton from "./CopyIconButton";import FormattedMarkdown from "./FormattedMarkdown";9 unmodified linesconst [generationRate] = usePubSub(generationRatePubSub);const isSpeaking = textToSpeechState === "speaking";const isGenerating = textGenerationState === "generating";const ConditionalScrollArea = useMemo(() =>100 unmodified lines</Tooltip>)}<CopyIconButton value={response} tooltipLabel="Copy response" /></Group></Group></Card.Section>
51 unmodified lines5253545556575859606162636465666768697071727374757651 unmodified lines});it("places the dictation button left of the send button", () => {renderChatInputArea();const dictate = screen.getByRole("button", {name: "Dictate a follow-up question",});const send = screen.getByRole("button", { name: "Send message" });// Both float over the right end of the field, so only the offsets say// which is where. Send keeps the edge; dictation sits inside the field,// clear of the 1px border it shares with send.expect(send).toHaveStyle({ right: "0px" });expect(dictate).toHaveStyle({ right: "55px" });// And the tab order follows the same left-to-right reading.expect(dictate.compareDocumentPosition(send) & Node.DOCUMENT_POSITION_FOLLOWING,).toBeTruthy();});it("writes the transcript into the chat input", async () => {chatInputPubSub[0]("tell me");let onTranscript: (text: string) => void = () => {};51 unmodified lines52535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513651 unmodified lines});it("places the dictation button left of the send button", () => {chatInputPubSub[0]("some typed text");renderChatInputArea();const dictate = screen.getByRole("button", {name: "Dictate a follow-up question",});const clear = screen.getByRole("button", {name: "Clear the follow-up question",});const send = screen.getByRole("button", { name: "Send message" });// Send keeps the field's right edge. The clear button sits inside it, past// the strip the browser keeps for the scrollbar, and dictation inside that// again, so neither icon ends up on top of the scrollbar once the text// scrolls. The browser's own gutter is 0 under jsdom.expect(send).toHaveStyle({ right: "0px" });expect(clear).toHaveStyle({ right: "55px" });expect(dictate).toHaveStyle({ right: "93px" });// And the tab order follows the same left-to-right reading.expect(dictate.compareDocumentPosition(clear) & Node.DOCUMENT_POSITION_FOLLOWING,).toBeTruthy();expect(clear.compareDocumentPosition(send) & Node.DOCUMENT_POSITION_FOLLOWING,).toBeTruthy();});it("keeps the typed text clear of both icons", () => {renderChatInputArea();// 34 + 4 + 34 for the two buttons and the gap between them, plus 4 of// gutter. The clear button's slot is reserved even while it is hidden, so// the dictation button does not move when text appears.expect(screen.getByRole("textbox", { name: "Chat input" })).toHaveStyle({paddingRight: "76px",});// And the scrollbar gets a strip of its own at the field's right edge,// always reserved, so the icons do not jump when the ninth line arrives.expect(screen.getByRole("textbox", { name: "Chat input" }).style.getPropertyValue("scrollbar-gutter"),).toBe("stable");});it("shows the clear button only while there is something to clear", async () => {const user = userEvent.setup();renderChatInputArea();expect(screen.queryByRole("button", { name: "Clear the follow-up question" }),).not.toBeInTheDocument();await user.type(screen.getByRole("textbox", { name: "Chat input" }), "hi");expect(screen.getByRole("button", { name: "Clear the follow-up question" }),).toBeInTheDocument();});it("empties the field when the clear button is pressed", async () => {chatInputPubSub[0]("a question to throw away");const user = userEvent.setup();renderChatInputArea();await user.click(screen.getByRole("button", { name: "Clear the follow-up question" }),);await waitFor(() =>expect(screen.getByRole("textbox", { name: "Chat input" })).toHaveValue(""),);// Nothing left to clear, so the button is gone with the text.expect(screen.queryByRole("button", { name: "Clear the follow-up question" }),).not.toBeInTheDocument();});it("writes the transcript into the chat input", async () => {chatInputPubSub[0]("tell me");let onTranscript: (text: string) => void = () => {};
1234567 unmodified lines1415161718192 unmodified lines222324252627282953 unmodified lines83848586878811 unmodified lines1001011021031041051064 unmodified lines111112113114115116117118119import { Button, Group, Textarea } from "@mantine/core";import { IconSend } from "@tabler/icons-react";import { usePubSub } from "create-pubsub/react";import DictationButton, {dictationButtonWidth,} from "@/components/DictationButton";7 unmodified linessettingsPubSub,suppressNextFollowUpPubSub,} from "@/modules/pubSub";/*** Width of the send button, pinned rather than left to Mantine's padding: the2 unmodified lines* slide the two controls on top of each other.*/const sendButtonWidth = 54;/** Keeps the typed text off the dictation button. */const dictationGutter = 4;interface ChatInputAreaProps {onKeyDown: (event: React.KeyboardEvent<HTMLTextAreaElement>) => void;53 unmodified lines}};return (<Group align="flex-end" style={{ position: "relative" }}><Textarea11 unmodified lines// Square on the right, where the send button attaches, so the two// read as one control instead of meeting at a rounded notch.input: {paddingRight: dictationButtonWidth + dictationGutter,borderTopRightRadius: 0,borderBottomRightRadius: 0,},4 unmodified linesgetValue={getChatInput}setValue={setInput}labelScope="a follow-up question"rightOffset={sendButtonWidth}disabled={isGenerating}/><Buttonaria-label="Send message"size="sm"1234567897 unmodified lines171819202122232 unmodified lines2627282930313233343553 unmodified lines899091929394959697989910010110210311 unmodified lines1151161171181191201211224 unmodified lines127128129130131132133134135136137138139140141142143144145import { Button, Group, Textarea } from "@mantine/core";import { IconSend } from "@tabler/icons-react";import { usePubSub } from "create-pubsub/react";import ClearFieldButton, {clearButtonWidth,} from "@/components/ClearFieldButton";import DictationButton, {dictationButtonWidth,} from "@/components/DictationButton";7 unmodified linessettingsPubSub,suppressNextFollowUpPubSub,} from "@/modules/pubSub";import { getScrollbarGutterWidth } from "@/modules/scrollbarGutter";/*** Width of the send button, pinned rather than left to Mantine's padding: the2 unmodified lines* slide the two controls on top of each other.*/const sendButtonWidth = 54;/** Keeps the typed text off the icons floating over the field's right end. */const dictationGutter = 4;/** Keeps the dictation and clear buttons from being mis-clicked for one another. */const iconGap = 4;interface ChatInputAreaProps {onKeyDown: (event: React.KeyboardEvent<HTMLTextAreaElement>) => void;53 unmodified lines}};// The scrollbar is painted at the field's right edge, inside its own// padding, so the field reserves the strip the browser keeps for it (see// `scrollbarGutter`) and the icons start left of that strip instead of// floating on top of the bar once the text is long enough to scroll.const scrollbarGutter = getScrollbarGutterWidth();// The clear button's slot is reserved whether or not it shows, so the// dictation button never slides sideways under a pointer reaching for it.const iconsWidth = clearButtonWidth + iconGap + dictationButtonWidth;return (<Group align="flex-end" style={{ position: "relative" }}><Textarea11 unmodified lines// Square on the right, where the send button attaches, so the two// read as one control instead of meeting at a rounded notch.input: {paddingRight: iconsWidth + dictationGutter,scrollbarGutter: "stable",borderTopRightRadius: 0,borderBottomRightRadius: 0,},4 unmodified linesgetValue={getChatInput}setValue={setInput}labelScope="a follow-up question"rightOffset={sendButtonWidth + scrollbarGutter + clearButtonWidth + iconGap}disabled={isGenerating}/>{input.length > 0 && (<ClearFieldButtonlabel="Clear the follow-up question"onClear={() => setInput("")}rightOffset={sendButtonWidth + scrollbarGutter}disabled={isGenerating}/>)}<Buttonaria-label="Send message"size="sm"
1234567891011121314151617189 unmodified lines28293031323334import { ActionIcon, CopyButton, Tooltip } from "@mantine/core";import { IconCheck, IconCopy } from "@tabler/icons-react";import type { ReactNode } from "react";interface CopyIconButtonProps {value: string;tooltipLabel?: string;/** Shown instead of the copy icon, so two copy buttons side by side differ. */icon?: ReactNode;}export default function CopyIconButton({value,tooltipLabel = "Copy",icon = <IconCopy size={16} />,}: CopyIconButtonProps) {return (<CopyButton value={value} timeout={2000}>9 unmodified linesvariant="subtle"onClick={copy}>{copied ? <IconCheck size={16} /> : icon}</ActionIcon></Tooltip>)}12345678910111213149 unmodified lines24252627282930import { ActionIcon, CopyButton, Tooltip } from "@mantine/core";import { IconCheck, IconCopy } from "@tabler/icons-react";interface CopyIconButtonProps {value: string;tooltipLabel?: string;}export default function CopyIconButton({value,tooltipLabel = "Copy",}: CopyIconButtonProps) {return (<CopyButton value={value} timeout={2000}>9 unmodified linesvariant="subtle"onClick={copy}>{copied ? <IconCheck size={16} /> : <IconCopy size={16} />}</ActionIcon></Tooltip>)}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import { ActionIcon, Tooltip } from "@mantine/core";import { IconX } from "@tabler/icons-react";
/** * The button floats over the right end of the field it fills, so the field * has to reserve this much room for it. Exported rather than repeated, so a * size change here cannot leave a caller's text running underneath it. */export const clearButtonWidth = 34;
/** * Mantine's input border. The button is inset by it so its hover fill stays * inside the field instead of painting over its border. */const fieldBorderWidth = 1;
interface ClearFieldButtonProps { /** * Names the field in the tooltip and the accessible name, as the object of * "Clear": "the follow-up question", "the search query". One string feeds * both, so an icon-only control never says one thing on screen and another * to a screen reader. */ label: string; /** Empties the field. */ onClear: () => void; /** Distance from the field's right edge to the positioned ancestor's, in pixels. */ rightOffset?: number; disabled?: boolean;}
export default function ClearFieldButton({ label, onClear, rightOffset = 0, disabled = false,}: ClearFieldButtonProps) { return ( <Tooltip label={label} withArrow position="top"> <ActionIcon size="lg" variant="subtle" color="gray" onClick={onClear} // Same as the dictation button: a press must not take the focus off // the field, so clearing leaves the caret where the user left it. onMouseDown={(event) => event.preventDefault()} disabled={disabled} aria-label={label} style={{ position: "absolute", right: rightOffset + fieldBorderWidth, top: fieldBorderWidth, bottom: fieldBorderWidth, height: `calc(100% - ${2 * fieldBorderWidth}px)`, width: clearButtonWidth, ...(disabled && { backgroundColor: "transparent" }), }} > <IconX size={18} /> </ActionIcon> </Tooltip> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import { MantineProvider } from "@mantine/core";import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import type { ReactNode } from "react";import QuickSettingsMenu, { type QuickSettingsItem } from "./QuickSettingsMenu";
function renderItem(name: string, control: ReactNode, closeOnAction = false) { return { id: name, control, closeOnAction } satisfies QuickSettingsItem;}
function renderMenu(items: QuickSettingsItem[]) { render( // env="test" renders the panel without its transition, so it is in the // DOM the moment it opens. <MantineProvider env="test"> <QuickSettingsMenu items={items} /> </MantineProvider>, ); return screen.getByRole("button", { name: "Quick settings" });}
/** * The panel stays mounted while it is hidden, so an option can open a drawer * of its own without losing it. Hidden options are still in the document. */function option(name: string) { return screen.getByRole("button", { name, hidden: true });}
describe("QuickSettingsMenu", () => { it("shows the options only between two presses of the button", async () => { const user = userEvent.setup(); const toggle = renderMenu([ renderItem("history", <button type="button">Open history</button>), ]);
expect(option("Open history")).not.toBeVisible(); expect(toggle).toHaveAttribute("aria-expanded", "false");
await user.click(toggle); expect(option("Open history")).toBeVisible(); expect(toggle).toHaveAttribute("aria-expanded", "true");
await user.click(toggle); expect(option("Open history")).not.toBeVisible(); expect(toggle).toHaveAttribute("aria-expanded", "false"); });
it("steps aside when an option opens a surface of its own", async () => { const user = userEvent.setup(); const toggle = renderMenu([ renderItem("history", <button type="button">Open history</button>, true), ]);
await user.click(toggle); await user.click(option("Open history"));
expect(toggle).toHaveAttribute("aria-expanded", "false"); });
it("leaves the panel open when an option only sets something", async () => { const user = userEvent.setup(); const toggle = renderMenu([ renderItem("time-range", <button type="button">Anytime</button>), ]);
await user.click(toggle); await user.click(option("Anytime"));
expect(toggle).toHaveAttribute("aria-expanded", "true"); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687import { ActionIcon, Box, Popover, Stack, Tooltip } from "@mantine/core";import { IconAdjustmentsHorizontal } from "@tabler/icons-react";import { type ReactNode, useCallback, useState } from "react";import { addLogEntry } from "@/modules/logEntries";
/** * One option of the quick settings panel: the control that sets it, and * nothing else. A new option is one more entry in the caller's list, which is * what keeps the search bar down to its two main buttons. A control that needs * a name of its own brings it along. */export interface QuickSettingsItem { id: string; control: ReactNode; /** * Closes the panel when the option is used, for a control that opens a * surface of its own, which the panel would otherwise be left sitting over. */ closeOnAction?: boolean;}
export default function QuickSettingsMenu({ items,}: { items: QuickSettingsItem[];}) { const [opened, setOpened] = useState(false);
// The single place the panel changes state: the button, a click outside and // Escape all come through here, so all three are logged the same way. const change = useCallback((next: boolean) => { setOpened(next); addLogEntry( next ? "User opened quick settings" : "User closed quick settings", ); }, []);
return ( <Popover opened={opened} onChange={change} offset={8} withArrow // The panel stays mounted while hidden, because an option can open a // surface of its own: the history drawer is rendered by a control in // here, and unmounting the panel would take the drawer down with it the // moment it opened. keepMounted keepMountedMode="display-none" > <Tooltip label="Quick settings" withArrow position="top"> <Popover.Target> <ActionIcon // A square as tall as the size="xs" buttons it sits beside, so the // row reads as one row of controls. size={30} // Filled rather than outlined while open: the button is the only // sign the panel is up, and a color swap alone is invisible in the // dark scheme. variant={opened ? "light" : "default"} color={opened ? "blue" : undefined} aria-label="Quick settings" data-quick-settings-open={opened} onClick={() => change(!opened)} > <IconAdjustmentsHorizontal size={16} /> </ActionIcon> </Popover.Target> </Tooltip> <Popover.Dropdown> <Stack gap="xs"> {items.map((item) => ( <Box key={item.id} // Grid so a control without a width of its own fills the panel, // which keeps the options the same width. style={{ display: "grid" }} onClick={item.closeOnAction ? () => change(false) : undefined} > {item.control} </Box> ))} </Stack> </Popover.Dropdown> </Popover> );}60 unmodified lines616263646566676869707172736 unmodified lines80818283848586878863 unmodified lines15215315415515615715860 unmodified linesvi.mock("@/components/DictationButton", () => ({dictationButtonWidth: 34,default: () => null,}));function renderSearchForm(query = "") {const updateQuery = vi.fn();render(<MantineProvider><SearchForm query={query} updateQuery={updateQuery} /></MantineProvider>,);6 unmodified lines*/async function restore(entry: SearchEntry) {entryToRestore = entry;await userEvent.setup().click(screen.getByRole("button", { name: "Restore" }));await waitFor(() => expect(isRestoringFromHistoryPubSub[2]()).toBe(false));await act(() => sleep(0));}63 unmodified linesawait userEvent.setup().click(screen.getByRole("button", { name: /search/i }));await waitFor(() => expect(searchAndRespond).toHaveBeenCalledTimes(1));expect(addToHistory).toHaveBeenCalledTimes(1);60 unmodified lines6162636465666768697071727374756 unmodified lines82838485868788899063 unmodified lines15415515615715815916060 unmodified linesvi.mock("@/components/DictationButton", () => ({dictationButtonWidth: 34,fieldBorderWidth: 1,default: () => null,}));function renderSearchForm(query = "") {const updateQuery = vi.fn();render(// env="test" renders the quick settings panel without its transition.<MantineProvider env="test"><SearchForm query={query} updateQuery={updateQuery} /></MantineProvider>,);6 unmodified lines*/async function restore(entry: SearchEntry) {entryToRestore = entry;const user = userEvent.setup();await user.click(screen.getByRole("button", { name: "Quick settings" }));await user.click(screen.getByRole("button", { name: "Restore" }));await waitFor(() => expect(isRestoringFromHistoryPubSub[2]()).toBe(false));await act(() => sleep(0));}63 unmodified linesawait userEvent.setup().click(screen.getByRole("button", { name: "Search" }));await waitFor(() => expect(searchAndRespond).toHaveBeenCalledTimes(1));expect(addToHistory).toHaveBeenCalledTimes(1);
25 unmodified lines26272829303135 unmodified lines676869707172737 unmodified lines8182838485868725 unmodified linesvi.mock("@/components/DictationButton", () => ({dictationButtonWidth: 34,default: () => null,}));35 unmodified linesconst user = userEvent.setup();renderSearchForm("hello");await user.click(await screen.findByRole("button", { name: "Clear" }));await settle();expect(getQuerySuggestions()).toHaveLength(24);7 unmodified linesconst user = userEvent.setup();renderSearchForm("hello");await user.click(await screen.findByRole("button", { name: "Clear" }));await settle();expect(mockFetch).toHaveBeenCalledTimes(1);25 unmodified lines2627282930313235 unmodified lines6869707172737475767 unmodified lines84858687888990919225 unmodified linesvi.mock("@/components/DictationButton", () => ({dictationButtonWidth: 34,fieldBorderWidth: 1,default: () => null,}));35 unmodified linesconst user = userEvent.setup();renderSearchForm("hello");await user.click(await screen.findByRole("button", { name: "Clear the search query" }),);await settle();expect(getQuerySuggestions()).toHaveLength(24);7 unmodified linesconst user = userEvent.setup();renderSearchForm("hello");await user.click(await screen.findByRole("button", { name: "Clear the search query" }),);await settle();expect(mockFetch).toHaveBeenCalledTimes(1);
84 unmodified lines8586878889909126 unmodified lines11811912012112212312412512612712812913025 unmodified lines15615715815916016116252 unmodified lines21521621721821922084 unmodified linesupdateQuery: (query: string) => void,) => {return render(<MantineProvider><SearchForm query={query} updateQuery={updateQuery} /></MantineProvider>,);26 unmodified linesawait 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");25 unmodified linesawait screen.findByRole("textbox");vi.mocked(getRandomQuerySuggestion).mockClear();await user.click(screen.getByRole("button", { name: "Clear" }));await act(async () => {});expect(getRandomQuerySuggestion).toHaveBeenCalledTimes(1);52 unmodified linesexpect(mockUpdate).toHaveBeenCalledWith("test query");});it.each([{ engine: "wasm", submitWith: "Search" },{ engine: "wasm", submitWith: "Enter" },84 unmodified lines85868788899091929326 unmodified lines12012112212312412512612712812913013113213313425 unmodified lines16016116216316416516616716852 unmodified lines22122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025184 unmodified linesupdateQuery: (query: string) => void,) => {return render(// env="test" makes Mantine render overlays without their transition, so// the quick settings panel is in the DOM as soon as it is opened.<MantineProvider env="test"><SearchForm query={query} updateQuery={updateQuery} /></MantineProvider>,);26 unmodified linesawait waitForPlaceholder();});it("offers the five time ranges in the quick settings panel", 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");await user.click(screen.getByRole("button", { name: "Quick settings" }));const timeRange = screen.getByRole("combobox", { name: /time range/i });expect(timeRange).toHaveValue("Anytime");25 unmodified linesawait screen.findByRole("textbox");vi.mocked(getRandomQuerySuggestion).mockClear();await user.click(screen.getByRole("button", { name: "Clear the search query" }),);await act(async () => {});expect(getRandomQuerySuggestion).toHaveBeenCalledTimes(1);52 unmodified linesexpect(mockUpdate).toHaveBeenCalledWith("test query");});describe("the clear button inside the field", () => {it("empties the field and leaves the caret in it", async () => {const user = userEvent.setup();renderSearchForm("hello", vi.fn());const textarea = await screen.findByRole("textbox");textarea.blur();await user.click(screen.getByRole("button", { name: "Clear the search query" }),);expect(textarea).toHaveValue("");expect(textarea).toHaveFocus();});it("is only there while the field holds text", async () => {renderSearchForm("", vi.fn());await screen.findByRole("textbox");expect(screen.queryByRole("button", { name: "Clear the search query" }),).toBeNull();});});it.each([{ engine: "wasm", submitWith: "Search" },{ engine: "wasm", submitWith: "Enter" },
11 unmodified lines12131415161712 unmodified lines30313233343536373839124 unmodified lines16416516616716816978 unmodified lines2482492502512522532541 unmodified line25625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229311 unmodified linesuseState,} from "react";import { useLocation } from "wouter";import DictationButton, {dictationButtonWidth,} from "@/components/DictationButton";12 unmodified linesimport { sleepUntilIdle } from "@/modules/sleep";import { searchAndRespond } from "@/modules/textGeneration";import HistoryButton from "../History/HistoryButton";/** Keeps the query text off the dictation button that floats over it. */const dictationGutter = 4;function getUrlQuery() {return new URLSearchParams(window.location.search).get("q");}124 unmodified linesaddLogEntry("User cleaned the search query field");};// Stable identities, so `memo` on the dictation button actually holds.const getDictationBase = useCallback(() => pendingDictationRef.current ?? textAreaRef.current?.value ?? "",78 unmodified linesmaxRows={8}autoFocusstyles={{input: { paddingRight: dictationButtonWidth + dictationGutter },}}/><DictationButton1 unmodified linegetValue={getDictationBase}setValue={setDictatedText}labelScope="the search query"/></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 && (<Buttonsize="xs"onClick={handleClearButtonClick}variant="default">Clear</Button>)}{/* Wraps to its own line on a narrow screen instead of shrinkingbelow its label, now that the time-range select shares the row. */}<Buttontype="submit"size="xs"11 unmodified lines12131415161718192012 unmodified lines33343536373839404142434445464748495051525354555657585960616263124 unmodified lines18818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123278 unmodified lines3113123133143153163171 unmodified line31932032132232332432532632732832933033133233333433533633711 unmodified linesuseState,} from "react";import { useLocation } from "wouter";import ClearFieldButton, {clearButtonWidth,} from "@/components/ClearFieldButton";import DictationButton, {dictationButtonWidth,} from "@/components/DictationButton";12 unmodified linesimport { sleepUntilIdle } from "@/modules/sleep";import { searchAndRespond } from "@/modules/textGeneration";import HistoryButton from "../History/HistoryButton";import QuickSettingsMenu, { type QuickSettingsItem } from "./QuickSettingsMenu";/** Keeps the query text off the buttons that float over the field's end. */const dictationGutter = 4;/*** Air between the two icons that float over the field. Their centers end up* 42px apart, which is what keeps a press meant for the microphone from* landing on the clear button, and the other way round.*/const trailingIconGap = 8;/*** How far the field's end is given up to the icons floating over it. The clear* button's width is counted whether or not the field holds text, so the* dictation button never moves when the clear button appears: a transcript* landing in an empty field would otherwise slide the microphone out from* under a finger already aimed at it, into the clear button's place.*/const trailingIconsWidth =clearButtonWidth + trailingIconGap + dictationButtonWidth + dictationGutter;/** One string for the tooltip and the accessible name of the clear button. */const clearQueryLabel = "Clear the search query";function getUrlQuery() {return new URLSearchParams(window.location.search).get("q");}124 unmodified linesaddLogEntry("User cleaned the search query field");};const quickSettingsItems: QuickSettingsItem[] = [...(pubSubSettings.enableHistory? [{id: "history",// The drawer it opens is modal, so the panel has to step aside.closeOnAction: true,control: <HistoryButton onSearchSelect={restoreSearch} />,},]: []),{id: "time-range",control: (<Select// Compact by design: the panel is a quick stop over the results, 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}// The option list stays inside the panel's own element: portaled to// the document, choosing a period would read as a click outside the// panel and close it before the choice lands.comboboxProps={{ withinPortal: false }}onChange={(timeRange) => {if (!timeRange) return;setPubSubSettings({...pubSubSettings,searchTimeRange: timeRange,});}}/>),},];// Stable identities, so `memo` on the dictation button actually holds.const getDictationBase = useCallback(() => pendingDictationRef.current ?? textAreaRef.current?.value ?? "",78 unmodified linesmaxRows={8}autoFocusstyles={{input: { paddingRight: trailingIconsWidth },}}/><DictationButton1 unmodified linegetValue={getDictationBase}setValue={setDictatedText}labelScope="the search query"rightOffset={clearButtonWidth + trailingIconGap}/>{state.textAreaValue.length >= 1 && (<ClearFieldButtonlabel={clearQueryLabel}onClear={handleClearButtonClick}/>)}</div><Group gap="xs"><QuickSettingsMenu items={quickSettingsItems} />{/* Wraps to its own line on a narrow screen instead of shrinkingbelow its label, now that the quick settings button shares it. */}<Buttontype="submit"size="xs"
1 unmodified line2345671 unmodified line9101112131413 unmodified lines28293031323315 unmodified lines49505152535456 unmodified lines1111121131141151161 unmodified lineimport { act, render, screen } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {textSearchLanguagePubSub,textSearchResultsPubSub,textSearchStalePubSub,1 unmodified linetextSearchTimeFilterPubSub,textSearchUnitConversionPubSub,} from "@/modules/pubSub";import type { TextSearchResults as TextSearchResultList } from "@/modules/types";import TextSearchResults from "./TextSearchResults";13 unmodified linesconst [setTextSearchTimeFilterNotApplied] = textSearchTimeFilterPubSub;const [setTextSearchLanguageNotApplied] = textSearchLanguagePubSub;const [setTextSearchUnitConversion] = textSearchUnitConversionPubSub;const results: TextSearchResultList = [["A result", "Its snippet", "https://example.com"],15 unmodified linesbeforeEach(() => {act(() => {setTextSearchState("completed");setTextSearchResults(results);});56 unmodified linesexpect(screen.queryByText(LANGUAGE_NOTE)).not.toBeInTheDocument();});it("shows the conversion the search came back with above the results", () => {act(() => setTextSearchUnitConversion(CONVERSION));renderTextSearchResults();1 unmodified line23456781 unmodified line1011121314151613 unmodified lines3031323334353615 unmodified lines5253545556575856 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601 unmodified lineimport { act, render, screen } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {settingsPubSub,textSearchLanguagePubSub,textSearchResultsPubSub,textSearchStalePubSub,1 unmodified linetextSearchTimeFilterPubSub,textSearchUnitConversionPubSub,} from "@/modules/pubSub";import { defaultSettings } from "@/modules/settings";import type { TextSearchResults as TextSearchResultList } from "@/modules/types";import TextSearchResults from "./TextSearchResults";13 unmodified linesconst [setTextSearchTimeFilterNotApplied] = textSearchTimeFilterPubSub;const [setTextSearchLanguageNotApplied] = textSearchLanguagePubSub;const [setTextSearchUnitConversion] = textSearchUnitConversionPubSub;const [setSettings] = settingsPubSub;const results: TextSearchResultList = [["A result", "Its snippet", "https://example.com"],15 unmodified linesbeforeEach(() => {act(() => {setSettings({ ...defaultSettings, searchLanguage: "es" });setTextSearchState("completed");setTextSearchResults(results);});56 unmodified linesexpect(screen.queryByText(LANGUAGE_NOTE)).not.toBeInTheDocument();});it.each(["browser", "auto", "all"] as const)("says nothing about the language on the %s setting, which asks for no language in particular",(searchLanguage) => {// Search Language defaults to Browser language, which sends the browser's// own locale, so the server reports the language was lost on most// searches that fell back. Nobody asked for that language, so the note// would be noise on every one of them.act(() => {setSettings({ ...defaultSettings, searchLanguage });setTextSearchLanguageNotApplied(true);});renderTextSearchResults();expect(screen.queryByText(LANGUAGE_NOTE)).not.toBeInTheDocument();expect(screen.getByLabelText("Text results")).toBeInTheDocument();},);it("still names the time filter on the default setting", () => {act(() => {setSettings({ ...defaultSettings, searchLanguage: "browser" });setTextSearchTimeFilterNotApplied(true);setTextSearchLanguageNotApplied(true);});renderTextSearchResults();expect(screen.getByText(NOTE)).toBeInTheDocument();expect(screen.queryByText(BOTH_NOTE)).not.toBeInTheDocument();});it("names a language the user picked from the list", () => {act(() => {setSettings({ ...defaultSettings, searchLanguage: "ja" });setTextSearchLanguageNotApplied(true);});renderTextSearchResults();expect(screen.getByText(LANGUAGE_NOTE)).toBeInTheDocument();});it("shows the conversion the search came back with above the results", () => {act(() => setTextSearchUnitConversion(CONVERSION));renderTextSearchResults();
123431 unmodified lines363738394041424344import { Alert, Button, Group, Text } from "@mantine/core";import { IconInfoCircle, IconRefresh } from "@tabler/icons-react";import { usePubSub } from "create-pubsub/react";import {31 unmodified lines// One note naming whichever filters the results are missing, so a search that// came back wide says so instead of passing for the narrow one that was// asked for.const unappliedNote = [timeFilterNotApplied && "time filter",languageNotApplied && "language",].filter(Boolean).join(" and ")1234531 unmodified lines373839404142434445464748495051import { Alert, Button, Group, Text } from "@mantine/core";import { isSpecificSearchLanguage } from "@shared/searchLanguage";import { IconInfoCircle, IconRefresh } from "@tabler/icons-react";import { usePubSub } from "create-pubsub/react";import {31 unmodified lines// One note naming whichever filters the results are missing, so a search that// came back wide says so instead of passing for the narrow one that was// asked for.//// The language half only speaks when the user named a language. Search// Language defaults to Browser language, which sends the browser's own// locale rather than one anyone asked for, so on the default setting a search// that lost its language has nothing to report and stays quiet.const languageAskedFor = isSpecificSearchLanguage(settings.searchLanguage);const unappliedNote = [timeFilterNotApplied && "time filter",languageAskedFor && languageNotApplied && "language",].filter(Boolean).join(" and ")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278import { describe, expect, it, vi } from "vitest";import { buildAnswerFileName, buildAnswerMarkdown, downloadAnswerMarkdown,} from "./answerExport";import type { TextSearchResults } from "./types";
const exportedAt = new Date(2026, 10, 28);
const sources: TextSearchResults = [ [ "Mercury - Wikipedia", "Mercury is the smallest planet in the Solar System.", "https://en.wikipedia.org/wiki/Mercury", ], [ "NASA - Mercury", "Mercury orbits the Sun in 88 days.", "https://www.nasa.gov/mercury", ],];
describe("buildAnswerMarkdown", () => { it("writes the answer, the numbered sources and the footer", () => { const markdown = buildAnswerMarkdown({ answer: "Mercury is the smallest planet. It orbits the Sun in 88 days.", sources, query: "mercury planet", exportedAt, });
expect(markdown).toBe( [ "Mercury is the smallest planet. It orbits the Sun in 88 days.", "", "## Sources", "", "1. [Mercury - Wikipedia](https://en.wikipedia.org/wiki/Mercury)", "2. [NASA - Mercury](https://www.nasa.gov/mercury)", "", 'Searched for "mercury planet" with MiniSearch, exported on 2026-11-28', "", ].join("\n"), ); });
it("numbers the sources without adding markers to the answer", () => { const answer = "Mercury is the smallest planet [usgs.gov](https://www.usgs.gov/).\n\n[USGS][1].";
const markdown = buildAnswerMarkdown({ answer, sources, query: "mercury", exportedAt, });
expect(markdown.startsWith(`${answer}\n\n## Sources`)).toBe(true); expect(markdown).toContain("[usgs.gov](https://www.usgs.gov/)"); expect(markdown).toContain("[USGS][1]"); expect(markdown).not.toMatch(/^\[\d+\]/m); });
it("leaves out the Sources section when the answer has no sources", () => { const markdown = buildAnswerMarkdown({ answer: "Mercury is the smallest planet.", sources: [], query: "mercury", exportedAt, });
expect(markdown).toBe( 'Mercury is the smallest planet.\n\nSearched for "mercury" with MiniSearch, exported on 2026-11-28\n', ); });
it("keeps the export valid when the answer is empty", () => { const markdown = buildAnswerMarkdown({ answer: " \n\n ", sources: [sources[0]], query: "mercury", exportedAt, });
expect(markdown).toBe( [ "## Sources", "", "1. [Mercury - Wikipedia](https://en.wikipedia.org/wiki/Mercury)", "", 'Searched for "mercury" with MiniSearch, exported on 2026-11-28', "", ].join("\n"), ); expect(markdown).not.toMatch(/^#+\s*$/m); });
it("keeps the export valid when the answer and the sources are both empty", () => { expect( buildAnswerMarkdown({ answer: "", sources: [], query: "", exportedAt }), ).toBe("Searched with MiniSearch, exported on 2026-11-28\n"); });
it("skips a source with no URL and keeps the numbering in order", () => { const markdown = buildAnswerMarkdown({ answer: "Answer.", sources: [sources[0], ["No URL", "A snippet.", " "], sources[1]], query: "mercury", exportedAt, });
expect(markdown).toContain( [ "1. [Mercury - Wikipedia](https://en.wikipedia.org/wiki/Mercury)", "2. [NASA - Mercury](https://www.nasa.gov/mercury)", ].join("\n"), ); });
it("escapes brackets in a source title and falls back to the URL", () => { const markdown = buildAnswerMarkdown({ answer: "Answer.", sources: [ ["Grid [F] plan", "A snippet.", "https://example.com/grid"], [" ", "A snippet.", "https://example.com/untitled"], ], query: "grid", exportedAt, });
expect(markdown).toContain( "1. [Grid \\[F\\] plan](https://example.com/grid)", ); expect(markdown).toContain( "2. [https://example.com/untitled](https://example.com/untitled)", ); });
it("keeps markup in a source title and in the query as plain text", () => { const markdown = buildAnswerMarkdown({ answer: "Answer.", sources: [ [ "<img src=x onerror=alert(1)> *bold* `code` a_b & c | d ~e~", "A snippet.", "https://example.com/page", ], ], query: "<b>bees</b>", exportedAt, });
expect(markdown).toContain( "1. [\\<img src=x onerror=alert(1)\\> \\*bold\\* \\`code\\` a\\_b \\& c \\| d \\~e\\~](https://example.com/page)", ); expect(markdown).toContain('Searched for "\\<b\\>bees\\</b\\>"'); });
it("percent-encodes URL characters that would end the link, and drops non-web links", () => { const markdown = buildAnswerMarkdown({ answer: "Answer.", sources: [ ["Spaces", "A snippet.", "https://example.com/a b(c)<d>"], ["Script", "A snippet.", "javascript:alert(1)"], ["Plain", "A snippet.", "https://example.com/plain"], ], query: "links", exportedAt, });
expect(markdown).toContain( "1. [Spaces](https://example.com/a%20b%28c%29%3Cd%3E)", ); expect(markdown).not.toContain("javascript:"); expect(markdown).toContain("2. [Plain](https://example.com/plain)"); });
it("keeps a query that spans lines on one footer line", () => { const markdown = buildAnswerMarkdown({ answer: "Answer.", sources: [], query: "mercury\n probe", exportedAt, });
expect(markdown).toContain('Searched for "mercury probe" with MiniSearch'); });});
describe("buildAnswerFileName", () => { it("keeps the words of the query", () => { expect(buildAnswerFileName("mercury planet")).toBe("mercury planet.md"); expect(buildAnswerFileName("computaรงรฃo quรขntica")).toBe( "computaรงรฃo quรขntica.md", ); });
it("keeps combining marks, in either normal form, inside words", () => { expect(buildAnswerFileName("เคนเคฟเคจเฅเคฆเฅ เคญเคพเคทเคพ")).toBe("เคนเคฟเคจเฅเคฆเฅ เคญเคพเคทเคพ.md"); expect(buildAnswerFileName("computac\u0327a\u0303o")).toBe("computaรงรฃo.md"); });
it("never splits a character when it bounds the length", () => { // A CJK ideograph outside the Basic Multilingual Plane: one letter, two // UTF-16 units. const name = buildAnswerFileName("๐ ".repeat(70)); expect(name).toBe(`${"๐ ".repeat(60)}.md`); });
it("replaces path separators and characters Windows refuses", () => { expect(buildAnswerFileName('a/b\\c:d*e?f"g<h>i|j')).toBe( "a-b-c-d-e-f-g-h-i-j.md", ); expect(buildAnswerFileName("../etc/passwd")).toBe("etc-passwd.md"); expect(buildAnswerFileName('mercury: the "planet"')).toBe( "mercury-the-planet.md", ); });
it("refuses a name Windows reserves for a device", () => { expect(buildAnswerFileName("con")).toBe("_con.md"); expect(buildAnswerFileName("con.txt")).toBe("_con.txt.md"); expect(buildAnswerFileName("com1")).toBe("_com1.md"); });
it("bounds the length of a very long query", () => { expect(buildAnswerFileName(`${"a".repeat(59)} bb`)).toBe( `${"a".repeat(59)}.md`, ); expect(buildAnswerFileName("x".repeat(500)).length).toBe(63); });
it("falls back to a plain name when the query gives nothing", () => { expect(buildAnswerFileName("")).toBe("answer.md"); expect(buildAnswerFileName(" ")).toBe("answer.md"); expect(buildAnswerFileName("???")).toBe("answer.md"); expect(buildAnswerFileName("...")).toBe("answer.md"); });});
describe("downloadAnswerMarkdown", () => { it("saves the markdown and releases the object URL", async () => { let link: HTMLAnchorElement | undefined; let blob: Blob | undefined; const createObjectURL = vi.fn((value: Blob) => { blob = value; return "blob:answer"; }); const revokeObjectURL = vi.fn();
vi.stubGlobal("URL", { createObjectURL, revokeObjectURL }); vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function ( this: HTMLAnchorElement, ) { link = this; });
vi.useFakeTimers(); try { downloadAnswerMarkdown("Answer.", "mercury.md"); // Not released during the click, only a moment later. expect(revokeObjectURL).not.toHaveBeenCalled(); vi.advanceTimersByTime(1000); } finally { vi.useRealTimers(); vi.spyOn(HTMLAnchorElement.prototype, "click").mockRestore(); vi.unstubAllGlobals(); }
expect(blob?.type).toBe("text/markdown"); expect(await blob?.text()).toBe("Answer."); expect(link?.download).toBe("mercury.md"); expect(link?.href).toBe("blob:answer"); expect(revokeObjectURL).toHaveBeenCalledWith("blob:answer"); expect(document.querySelector("a")).toBeNull(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import type { TextSearchResults } from "./types";
interface AnswerExportParts { /** The answer's Markdown, as it was written. */ answer: string; /** The results the answer was grounded on, in the order they were read. */ sources: TextSearchResults; /** What was typed in the search field. */ query: string; /** When the file is exported. */ exportedAt: Date;}
const maxFileNameBaseLength = 60;const windowsReservedFileNames = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;// Marks are allowed so scripts that write vowels as combining marks (Devanagari,// Thai) keep whole words instead of getting a dash inside each one.const unsupportedFileNameCharacters = /[^\p{L}\p{M}\p{N} ._-]/gu;
/** * Renders an answer as a standalone Markdown document: the answer, then the * results it was grounded on, then one line saying what was searched and when. * * An answer cites its sources with inline Markdown links, so the source list * only lists what was read: no `[1]` marker is added to the answer, and the * answer's own text and links are never rewritten. Nothing but the query, the * answer, the source titles and URLs and the date goes into the file. */export function buildAnswerMarkdown({ answer, sources, query, exportedAt,}: AnswerExportParts): string { const sections: string[] = []; const body = answer.trim(); if (body) { sections.push(body); }
const items: string[] = []; for (const [title, , url] of sources) { const link = buildMarkdownLink(title, url); if (link) { items.push(`${items.length + 1}. ${link}`); } } if (items.length) { sections.push(`## Sources\n\n${items.join("\n")}`); }
// The export date, not the search date: an answer restored from history is // exported long after its search ran. const searchedFor = escapeInlineMarkdown(singleLine(query)); sections.push( `Searched${searchedFor ? ` for "${searchedFor}"` : ""} with MiniSearch, exported on ${formatDate(exportedAt)}`, );
return `${sections.join("\n\n")}\n`;}
/** A file name that survives every file system, bounded in length, ending in `.md`. */export function buildAnswerFileName(query: string): string { const cleaned = singleLine(query.normalize("NFC")) .replace(unsupportedFileNameCharacters, "-") .replace(/\s*-\s*/g, "-") .replace(/-{2,}/g, "-") .replace(/^[-.]+|[-.]+$/g, ""); // Counted in code points, so the cut never splits a surrogate pair. const base = Array.from(cleaned) .slice(0, maxFileNameBaseLength) .join("") .replace(/[-. ]+$/g, ""); // Windows reserves a device name whatever follows its first dot, so // `con.txt.md` fails as surely as `con.md`. const stem = windowsReservedFileNames.test(base.split(".")[0] ?? "") ? `_${base}` : base;
return `${stem || "answer"}.md`;}
/** Saves text as a file through an object URL, which is released afterwards. */export function downloadAnswerMarkdown( markdown: string, fileName: string,): void { const url = URL.createObjectURL( new Blob([markdown], { type: "text/markdown" }), ); const link = document.createElement("a"); link.href = url; link.download = fileName; document.body.append(link); link.click(); link.remove(); // Released a moment later rather than at once: some browsers, Safari among // them, have failed downloads whose URL was revoked right after the click. setTimeout(() => URL.revokeObjectURL(url), 1000);}
function buildMarkdownLink(title: string, url: string): string { const destination = url.trim(); // Only web links: a source URL comes from a third-party page. if (!/^https?:\/\//i.test(destination)) { return ""; }
const text = escapeInlineMarkdown(singleLine(title)) || escapeInlineMarkdown(destination); // Percent-encoded rather than wrapped in `<โฆ>`, so the URL keeps every // character and nothing in it can end the link early. const encodedDestination = destination.replace( /[\s()<>\\`]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`, );
return `[${text}](${encodedDestination})`;}
/** * Escapes what Markdown reads inside a line: emphasis, code spans, links, * images, raw HTML, entities, strikethrough and table pipes. A source title * comes from a third-party page, so a `<img onerror>` in it must stay text. */function escapeInlineMarkdown(text: string): string { return text.replace(/[\\`*_[\]<>!&~|]/g, "\\$&");}
function singleLine(text: string): string { return text.replace(/\s+/g, " ").trim();}
function formatDate(date: Date): string { const month = String(date.getMonth() + 1).padStart(2, "0"); const day = String(date.getDate()).padStart(2, "0");
return `${date.getFullYear()}-${month}-${day}`;}123456789101112131415import { getScrollbarGutterWidth } from "@/modules/scrollbarGutter";
it("measures the scrollbar gutter without leaving the probe in the page", () => { const bodyChildren = document.body.childElementCount;
const width = getScrollbarGutterWidth();
expect(Number.isInteger(width)).toBe(true); expect(width).toBeGreaterThanOrEqual(0); expect(document.body.childElementCount).toBe(bodyChildren);});
it("answers the same width every time it is asked", () => { expect(getScrollbarGutterWidth()).toBe(getScrollbarGutterWidth());});12345678910111213141516171819202122232425262728293031323334/** * The strip a browser keeps at the inline end of a scrollable box for its * scrollbar, in pixels. * * A scrollbar is painted inside the box's padding box, at its inline end, so * the box's own `padding-right` does not move it: an icon floating over that * padding lands on top of the bar. A field that floats icons there asks for * the strip to be reserved (`scrollbar-gutter: stable`) and offsets them by * this much, which puts them left of the bar whatever the platform draws. It * measured 15px in Chrome on macOS, and 0 where the browser reserves nothing, * which leaves the layout as it was. * * Measured rather than assumed, because the width is the platform's and not * the page's. Cached: it cannot change within a page's lifetime. */let cachedWidth: number | null = null;
export function getScrollbarGutterWidth(): number { if (cachedWidth !== null) return cachedWidth;
const probe = document.createElement("div"); probe.setAttribute("aria-hidden", "true"); // `overflow: scroll` alone reports 0 wherever the platform's scrollbars // float over the content instead of taking space; `scrollbar-gutter` is // what makes the browser hand back the width it would reserve for them. probe.style.cssText = "position:absolute;top:0;left:0;width:100px;height:100px;" + "overflow:scroll;scrollbar-gutter:stable;visibility:hidden"; document.body.append(probe); cachedWidth = Math.max(0, probe.offsetWidth - probe.clientWidth); probe.remove();
return cachedWidth;}.source-commit+1-1
agents.md-1
changelog.md+4
client/components/AiResponse/AiResponseContent.test.tsx+8-99
client/components/AiResponse/AiResponseContent.tsx+1-84
client/components/AiResponse/ChatInputArea.test.tsx+65-5
client/components/AiResponse/ChatInputArea.tsx+29-3
client/components/AiResponse/CopyIconButton.tsx+1-5
client/components/ClearFieldButton.tsxAdded+64
client/components/Search/Form/QuickSettingsMenu.test.tsxAdded+72
client/components/Search/Form/QuickSettingsMenu.tsxAdded+87
client/components/Search/Form/SearchForm.restore.test.tsx+7-5
client/components/Search/Form/SearchForm.suggestions.test.tsx+7-2
client/components/Search/Form/SearchForm.test.tsx+34-3
client/components/Search/Form/SearchForm.tsx+74-30
client/components/Search/Results/Textual/TextSearchResults.test.tsx+44
client/components/Search/Results/Textual/TextSearchResults.tsx+8-1
client/modules/answerExport.test.tsDeleted-278
client/modules/answerExport.tsDeleted-141
client/modules/scrollbarGutter.test.tsAdded+15
client/modules/scrollbarGutter.tsAdded+34