Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(llm): cover the search provider paths Codecov flagged
Elian Dorana31bdb459ff5
diff --git a/apps/client/src/services/llm_providers.spec.ts b/apps/client/src/services/llm_providers.spec.tsindex 46babd29cc..9a4e1a21db 100644--- a/apps/client/src/services/llm_providers.spec.ts+++ b/apps/client/src/services/llm_providers.spec.ts@@ -1,11 +1,11 @@import type { LlmModelInfo } from "@triliumnext/commons";import { describe, expect, it, vi } from "vitest";-const mocks = vi.hoisted(() => ({ stored: [] as unknown[] }));+const mocks = vi.hoisted(() => ({ stored: [] as unknown[] | null }));vi.mock("./options.js", () => ({ default: { getJson: () => mocks.stored } }));-import { readSelectedModels, readsAttachmentKind, resolveWebSearch, unreadableAttachments } from "./llm_providers.js";+import { readSearchProviders, readSelectedModels, readsAttachmentKind, resolveWebSearch, unreadableAttachments } from "./llm_providers.js";const textOnly: LlmModelInfo = { id: "deepseek-v4-pro", name: "DeepSeek V4 Pro", attachmentKinds: [] };const imagesOnly: LlmModelInfo = { id: "codex", name: "Codex", attachmentKinds: [ "image" ] };@@ -50,6 +50,23 @@ describe("readSelectedModels", () => {});});+describe("readSearchProviders", () => {+ it("lists the search providers in config order, and none when the option is unset", () => {+ mocks.stored = [+ { id: "s1", name: "Brave Search", provider: "brave", kind: "search", apiKey: "k" },+ { id: "o1", name: "OpenAI", provider: "openai" },+ { id: "s2", name: "Tavily", provider: "tavily", kind: "search" }+ ];+ expect(readSearchProviders()).toEqual([+ { id: "s1", name: "Brave Search", provider: "brave" },+ { id: "s2", name: "Tavily", provider: "tavily" }+ ]);++ mocks.stored = null;+ expect(readSearchProviders()).toEqual([]);+ });+});+describe("resolveWebSearch", () => {const TAVILY = { id: "s1", name: "Tavily", provider: "tavily" };const resolve = (modelProvider: string | undefined, overrides: Partial<Parameters<typeof resolveWebSearch>[0]> = {}) =>diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex 7377fa77b4..3b218fc774 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -3,7 +3,7 @@ import "./ChatInputBar.css";import type { AttributeEditor as CKEditorAttributeEditor, CKTextEditor, MentionHostedFeed } from "@triliumnext/ckeditor5";import type { DISPLAYABLE_LOCALE_IDS, LlmReasoningEffort } from "@triliumnext/commons";import { Fragment } from "preact";-import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n.js";import link from "../../../services/link.js";@@ -23,11 +23,11 @@ import { computeContextUsage } from "./chat_context_usage.js";import { insertNewBlock as insertNewBlockCommand, isSelectionInCodeBlock, outdentListItemAtStart } from "./chat_input_editing.js";import { editorHtmlToMarkdown } from "./chat_input_markdown.js";import { shortModelName } from "./model_name.js";-import ChatToolsDropdown from "./ChatToolsDropdown.js";+import ChatToolsDropdown, { useChatWebSearch } from "./ChatToolsDropdown.js";import ReasoningEffortDropdown from "./ReasoningEffortDropdown.js";import { SafeImage } from "./retry_image.js";import { getAttachmentLightbox, getUnreadableReasons, useChatAttachments } from "./useChatAttachments.js";-import { type ModelOption, readSearchProviders, resolveSelectedModel, resolveWebSearch, unreadableAttachments } from "../../../services/llm_providers.js";+import { type ModelOption, resolveSelectedModel, unreadableAttachments } from "../../../services/llm_providers.js";import { type AttachmentBlock, type UseLlmChatReturn } from "./useLlmChat.js";const READ_ONLY_LOCK = "llm-chat-streaming";@@ -91,10 +91,6 @@ export default function ChatInputBar({const editorApiRef = useRef<CKEditorApi | undefined>(undefined);const editorInstanceRef = useRef<CKTextEditor | undefined>(undefined);const [ uiLanguage ] = useTriliumOption("locale");- const [ llmProviders ] = useTriliumOption("llmProviders");- const [ webSearchProviderId, setWebSearchProviderId ] = useTriliumOption("llmWebSearchProvider");- // Read through `options`; `llmProviders` is the dependency so the list follows the settings.- const searchProviders = useMemo(readSearchProviders, [ llmProviders ]);// CKEditor is the heaviest module the client has, and importing it statically here put it// on the startup critical path: the right panel mounts SidebarChat, which pulls this bar,// which pulled the editor — and its math plugin, and mathlive — before the app finished@@ -167,15 +163,6 @@ export default function ChatInputBar({}}, [chat.isStreaming]);- /** Turns web search off for this chat, or on with the chosen source, which every chat shares. */- const handleWebSearchChoose = (choice: string) => {- chat.setEnableWebSearch(choice !== "disabled");- if (choice !== "disabled") {- void setWebSearchProviderId(choice === "builtin" ? "" : choice);- }- onWebSearchChange?.();- };-const handleNoteToolsToggle = (newValue: boolean) => {chat.setEnableNoteTools(newValue);onNoteToolsChange?.();@@ -237,14 +224,7 @@ export default function ChatInputBar({const currentModel = resolveSelectedModel(chat.availableModels, chat.selectedModel, chat.selectedProvider, chat.selectedProviderId);const isSelectedModel = (m: ModelOption) => m === currentModel;const unreadableReasons = getUnreadableReasons(currentModel, chat.pendingAttachments);- // Resolved as `useLlmChat` resolves it for sending, so the menu marks what the turn will use.- const webSearch = resolveWebSearch({- modelProvider: currentModel?.provider,- enableWebSearch: chat.enableWebSearch,- enableNoteTools: chat.enableNoteTools,- searchProviderId: webSearchProviderId,- searchProviders- });+ const { webSearch, searchProviders, chooseWebSearch } = useChatWebSearch(chat, currentModel?.provider, onWebSearchChange);// Null until the window is close enough to matter, and null (rather than a guess) when// the model advertises no window at all. See chat_context_usage.const contextUsage = computeContextUsage({@@ -481,7 +461,7 @@ export default function ChatInputBar({modelProvider={currentModel?.provider}webSearch={webSearch}searchProviders={searchProviders}- onWebSearchChoose={handleWebSearchChoose}+ onWebSearchChoose={chooseWebSearch}disabled={chat.isStreaming}/>{!currentModel?.reasoningEfforts?.length && (diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsxindex 096901ef84..47f0af7c1b 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsx@@ -2,10 +2,26 @@ import { type ComponentChildren, render } from "preact";import { act } from "preact/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";-const mocks = vi.hoisted(() => ({ triggerCommand: vi.fn() }));+const mocks = vi.hoisted(() => ({+ triggerCommand: vi.fn(),+ /** Option values by name, as `useTriliumOption` and `options.getJson()` read them. */+ stored: {} as Record<string, string>,+ /** Every option write. */+ saved: [] as [ string, unknown ][]+}));vi.mock("../../../services/i18n.js", () => ({ t: (key: string) => key }));vi.mock("../../../components/app_context.js", () => ({ default: { triggerCommand: mocks.triggerCommand } }));+vi.mock("../../../services/options.js", () => ({+ default: { getJson: (name: string) => JSON.parse(mocks.stored[name] ?? "null") }+}));+vi.mock("../../react/hooks.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../react/hooks.js")>()),+ useTriliumOption: (name: string) => [+ mocks.stored[name] ?? "",+ async (value: unknown) => void mocks.saved.push([ name, value ])+ ]+}));// Renders the toggle's face, class and tooltip, and the menu, without the popup machinery.vi.mock("../../react/Dropdown.js", () => ({@@ -20,7 +36,7 @@ vi.mock("../../react/Dropdown.js", () => ({}));import type { WebSearchState } from "../../../services/llm_providers.js";-import ChatToolsDropdown from "./ChatToolsDropdown.js";+import ChatToolsDropdown, { useChatWebSearch } from "./ChatToolsDropdown.js";let host: HTMLElement | undefined;@@ -30,6 +46,8 @@ afterEach(() => {host.remove();host = undefined;}+ mocks.stored = {};+ mocks.saved = [];vi.clearAllMocks();});@@ -140,3 +158,57 @@ describe("ChatToolsDropdown", () => {expect(menu.onWebSearchChoose).not.toHaveBeenCalled();});});++describe("useChatWebSearch", () => {+ const OPENAI = { id: "o1", name: "OpenAI", provider: "openai" };++ function mountHook(modelProvider: string | undefined) {+ const chat = { enableWebSearch: true, enableNoteTools: false, setEnableWebSearch: vi.fn() };+ const onChange = vi.fn();+ let result: ReturnType<typeof useChatWebSearch> | undefined;+ function Probe() {+ result = useChatWebSearch(chat, modelProvider, onChange);+ return null;+ }+ host = document.body.appendChild(document.createElement("div"));+ const target = host;+ const rerender = () => act(() => render(<Probe />, target));+ rerender();+ const current = () => {+ expect(result).toBeDefined();+ return result as ReturnType<typeof useChatWebSearch>;+ };+ return { chat, onChange, current, rerender };+ }++ it("resolves the chosen search provider for the model, and lists only the search providers", () => {+ mocks.stored = {+ llmProviders: JSON.stringify([ { ...OPENAI, selectedModels: [] }, { ...TAVILY, kind: "search" } ]),+ llmWebSearchProvider: "s1"+ };+ const { current, rerender } = mountHook("openai");++ expect(current().searchProviders).toEqual([ TAVILY ]);+ expect(current().webSearch).toMatchObject({ choice: "s1", enableWebSearch: true, webSearchProviderId: "s1" });++ // A search provider removed in the settings leaves the model's built-in search.+ mocks.stored.llmProviders = JSON.stringify([ OPENAI ]);+ rerender();+ expect(current().searchProviders).toEqual([]);+ expect(current().webSearch).toMatchObject({ choice: "builtin", enableWebSearch: true, webSearchProviderId: undefined });+ });++ it("turns web search on with the chosen source, which every chat shares, or off for this chat only", () => {+ const { chat, onChange, current } = mountHook(undefined);++ act(() => current().chooseWebSearch("s1"));+ act(() => current().chooseWebSearch("builtin"));+ expect(chat.setEnableWebSearch.mock.calls).toEqual([ [ true ], [ true ] ]);+ expect(mocks.saved).toEqual([ [ "llmWebSearchProvider", "s1" ], [ "llmWebSearchProvider", "" ] ]);++ act(() => current().chooseWebSearch("disabled"));+ expect(chat.setEnableWebSearch).toHaveBeenLastCalledWith(false);+ expect(mocks.saved).toHaveLength(2);+ expect(onChange).toHaveBeenCalledTimes(3);+ });+});diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsxindex dd7d1be916..30d7972be1 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsx@@ -2,16 +2,19 @@ import "./ChatToolsDropdown.css";import clsx from "clsx";import type { ComponentChildren } from "preact";+import { useMemo } from "preact/hooks";import appContext from "../../../components/app_context.js";import { t } from "../../../services/i18n.js";-import type { SearchProviderOption, WebSearchState } from "../../../services/llm_providers.js";+import { readSearchProviders, resolveWebSearch, type SearchProviderOption, type WebSearchState } from "../../../services/llm_providers.js";import ActionButton from "../../react/ActionButton.js";import Dropdown from "../../react/Dropdown.js";import { FormDropdownDivider, FormListHeader, FormListItem, FormListToggleableItem } from "../../react/FormList.js";+import { useTriliumOption } from "../../react/hooks.js";import Icon from "../../react/Icon.js";import MaskedIcon from "../../react/MaskedIcon.js";import { providerIconUrl } from "../options/llm/provider_icons.js";+import type { UseLlmChatReturn } from "./useLlmChat.js";/*** The Tools menu of the chat input bar: what the model can reach this turn, one section per group@@ -92,6 +95,40 @@ export default function ChatToolsDropdown({ enableNoteTools, onNoteToolsChange,);}+/**+ * The chat's web search for a model of `modelProvider`, resolved as `useLlmChat` resolves it for+ * sending so the menu marks what the turn will use, with the search providers to offer and the+ * handler for a choice. `onChange` runs after every choice.+ */+export function useChatWebSearch(+ chat: Pick<UseLlmChatReturn, "enableWebSearch" | "enableNoteTools" | "setEnableWebSearch">,+ modelProvider: string | undefined,+ onChange?: () => void+) {+ const [ llmProviders ] = useTriliumOption("llmProviders");+ const [ searchProviderId, setSearchProviderId ] = useTriliumOption("llmWebSearchProvider");+ // Read through `options`; `llmProviders` is the dependency so the list follows the settings.+ const searchProviders = useMemo(readSearchProviders, [ llmProviders ]);+ const webSearch = resolveWebSearch({+ modelProvider,+ enableWebSearch: chat.enableWebSearch,+ enableNoteTools: chat.enableNoteTools,+ searchProviderId,+ searchProviders+ });++ /** Turns web search off for this chat, or on with the chosen source, which every chat shares. */+ const chooseWebSearch = (choice: string) => {+ chat.setEnableWebSearch(choice !== "disabled");+ if (choice !== "disabled") {+ void setSearchProviderId(choice === "builtin" ? "" : choice);+ }+ onChange?.();+ };++ return { webSearch, searchProviders, chooseWebSearch };+}+/*** One choice of the web search section. A choice the current model can't use stays listed,* disabled, with the reason on an info icon beside it; the marked one is shown as such either way.diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.spec.tsxindex 340b0cc089..cb7f70fc43 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.spec.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.spec.tsx@@ -734,11 +734,27 @@ describe("ToolCallCard", () => {expect(single?.getAttribute("title")).toBe("llm_chat.searched_with{\"name\":\"Tavily\"}");expect(single?.querySelector(".masked-icon")).not.toBeNull();+ // A search that found nothing is a line with nothing to expand, marked the same way.+ const nothingFound: ToolCall = { ...viaTavily("0"), result: JSON.stringify({ query: "trilium", searchProvider: { type: "tavily", name: "Tavily" }, sources: [] }) };+ const bare = renderCard([ nothingFound ]).querySelector(".llm-chat-tool-call");+ expect(bare instanceof HTMLDetailsElement).toBe(false);+ expect(icon(bare)?.getAttribute("title")).toBe("llm_chat.searched_with{\"name\":\"Tavily\"}");+// A run of searches is one line, marked as its searches are.const group = icon(renderCard([ viaTavily("1"), viaTavily("2") ]).querySelector(".llm-chat-tool-call-group"));expect(group?.getAttribute("title")).toBe("llm_chat.searched_with{\"name\":\"Tavily\"}");expect(icon(renderCard([ builtIn ]).querySelector(".llm-chat-tool-call"))?.className).toBe("bx bx-search");++ // A result that names no provider in full, or is no object at all, keeps the magnifier.+ const nameless: ToolCall = { id: "n", toolName: "web_search", input: { query: "q" }, result: JSON.stringify({ searchProvider: { type: "tavily" } }) };+ const empty: ToolCall = { id: "e", toolName: "web_search", input: { query: "q" }, result: "null" };+ for (const call of [ nameless, empty ]) {+ expect(icon(renderCard([ call ]).querySelector(".llm-chat-tool-call"))?.className).toBe("bx bx-search");+ }+ // So does a run that mixes a search provider's searches with the model's own.+ expect(icon(renderCard([ viaTavily("1"), { ...builtIn, id: "2" } ]).querySelector(".llm-chat-tool-call-group"))?.className)+ .toBe("bx bx-search");});it("links the page a call read, and previews what it read there", () => {diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsxindex a538278798..96d23b7338 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx@@ -10,8 +10,8 @@ vi.mock("../../../services/llm_chat.js", () => ({// The chat picker now reads the user's selected models straight from the// `llmProviders` option (no server fetch), so stub that service.const optionsGetJsonMock = vi.hoisted(() => vi.fn());-/** The `llmWebSearchProvider` option. */-const webSearchProvider = vi.hoisted(() => ({ id: "" }));+/** The `llmWebSearchProvider` option, unset unless a test picks a search provider. */+const webSearchProvider = vi.hoisted(() => ({ id: undefined as string | undefined }));vi.mock("../../../services/options.js", () => ({default: { getJson: optionsGetJsonMock, get: () => webSearchProvider.id }}));@@ -88,7 +88,7 @@ describe("useLlmChat", () => {});afterEach(() => {- webSearchProvider.id = "";+ webSearchProvider.id = undefined;if (host) {render(null, host);host.remove();diff --git a/apps/client/src/widgets/type_widgets/options/llm.spec.tsx b/apps/client/src/widgets/type_widgets/options/llm.spec.tsxindex 5ac507f86e..41f07fa916 100644--- a/apps/client/src/widgets/type_widgets/options/llm.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/llm.spec.tsx@@ -12,9 +12,19 @@ const mocks = vi.hoisted(() => ({// alongside it (keyboard actions) expect a list from the same service./** What the server says about the interfaces it is bound to. */network: { addresses: [] as string[], reachableOnNetwork: false },- get: vi.fn(async (url: string) => (url === "network-addresses" ? mocks.network : []))+ get: vi.fn(async (url: string) => (url === "network-addresses" ? mocks.network : [])),+ /** The props of each provider card's modal, by its kind, as last rendered. */+ modals: {} as Record<string, ModalProps>}));+interface ModalProps {+ show: boolean;+ kind: string;+ existingProvider?: { id: string };+ onHidden: () => void;+ onSave: (provider: { id: string; name: string; provider: string; kind?: string; apiKey: string }) => void;+}+// `isStandalone` is a const in the target, read here through a getter so a scenario can flip which// kind of client we are pretending to be. Partial-mock, so the rest of utils stays real.vi.mock("../../../services/utils", async (importOriginal) => ({@@ -58,7 +68,13 @@ vi.mock("./components/OptionsPageHeader", () => ({default: ({ below }: { below?: preact.ComponentChildren }) => <div className="header-stub">{below}</div>}));// Carries a bootstrap modal into the tree, and the MCP card below it is what is being read here.-vi.mock("./llm/AddProviderModal", () => ({ default: () => null, findProviderType: () => undefined }));+vi.mock("./llm/AddProviderModal", () => ({+ default: (props: ModalProps) => {+ mocks.modals[props.kind] = props;+ return null;+ },+ findProviderType: () => undefined+}));import LlmSettings, { buildMcpClientConfig, buildMcpClientCommand } from "./llm";@@ -71,6 +87,7 @@ beforeEach(() => {mocks.standalone = false;mocks.stored = { aiEnabled: "true", mcpEnabled: "true" };mocks.saved = [];+ mocks.modals = {};mocks.network = { addresses: [], reachableOnNetwork: false };host = document.body.appendChild(document.createElement("div"));});@@ -275,6 +292,37 @@ describe("the configured providers", () => {expect(mocks.saved.some(([ name ]) => name === "llmProviders")).toBe(false);});+ it("opens the modal of the card's kind to add or edit, and saves into the shared list", async () => {+ withProviders([+ { id: "a", name: "My OpenAI", provider: "openai", apiKey: "sk" },+ { id: "s", name: "Brave Search", provider: "brave", kind: "search", apiKey: "bk" }+ ]);+ open();+ const written = () => JSON.parse(mocks.saved.at(-1)?.[1] ?? "[]") as { id: string; name: string }[];++ const add = host.querySelector<HTMLButtonElement>("button[name='add-search-provider-button']");+ expect(add).not.toBeNull();+ await act(async () => add?.click());+ expect(mocks.modals.search).toMatchObject({ show: true, existingProvider: undefined });+ expect(mocks.modals.llm?.show).toBe(false);++ // Adding appends, keeping the providers of the other kind.+ act(() => mocks.modals.search?.onSave({ id: "t", name: "Tavily", provider: "tavily", kind: "search", apiKey: "tk" }));+ expect(written().map((provider) => provider.id)).toEqual([ "a", "s", "t" ]);++ const edit = providers().find((option) => option.textContent?.includes("Brave Search"))?.querySelector("button");+ expect(edit).toBeDefined();+ await act(async () => edit?.click());+ expect(mocks.modals.search?.existingProvider?.id).toBe("s");++ // Editing replaces the provider in place.+ act(() => mocks.modals.search?.onSave({ id: "s", name: "Brave", provider: "brave", kind: "search", apiKey: "bk2" }));+ expect(written().map((provider) => provider.name)).toEqual([ "My OpenAI", "Brave", "Tavily" ]);++ act(() => mocks.modals.search?.onHidden());+ expect(mocks.modals.search?.show).toBe(false);+ });+it("lists search providers in a card of their own, and deleting one keeps the chat providers", async () => {withProviders([{ id: "a", name: "My OpenAI", provider: "openai", apiKey: "sk" },diff --git a/packages/trilium-core/src/services/llm/index.spec.ts b/packages/trilium-core/src/services/llm/index.spec.tsindex 2615e7b35e..41a621d762 100644--- a/packages/trilium-core/src/services/llm/index.spec.ts+++ b/packages/trilium-core/src/services/llm/index.spec.ts@@ -208,6 +208,8 @@ describe("llm/index provider registry", () => {expect(getSearchProviderSetup("s1")).toEqual(search);expect(getSearchProviderSetup("a1")).toBeUndefined();expect(getSearchProviderSetup(undefined)).toBeUndefined();+ getOptionOrNullMock.mockReturnValue(null);+ expect(getSearchProviderSetup("s1")).toBeUndefined();getOptionOrNullMock.mockReturnValue("{not json");expect(getSearchProviderSetup("s1")).toBeUndefined();diff --git a/packages/trilium-core/src/services/llm/web_search.spec.ts b/packages/trilium-core/src/services/llm/web_search.spec.tsindex ce35ffc283..df3b409c37 100644--- a/packages/trilium-core/src/services/llm/web_search.spec.ts+++ b/packages/trilium-core/src/services/llm/web_search.spec.ts@@ -110,6 +110,42 @@ describe("searchWeb", () => {});});+describe("searchWeb overrides and sparse answers", () => {+ it("sends every provider to its base URL override, and reads a payload without results as none", async () => {+ const base = "https://proxy.example";+ const cases: [ string, string ][] = [+ [ "brave", `${base}/web/search?q=q&count=8` ],+ [ "exa", `${base}/search` ],+ [ "serper", `${base}/search` ],+ [ "perplexity", `${base}/search` ]+ ];+ for (const [ provider, expectedUrl ] of cases) {+ fetchMock.mockReset();+ respond({});+ expect(await searchWeb({ provider, apiKey: "k", baseURL: base }, "q"), provider).toEqual([]);+ expect(request().url, provider).toBe(expectedUrl);+ }+ });++ it("sends SearXNG its key when it has one, and skips a result that is not an object", async () => {+ respond({ results: [ null, { ...PAGE, content: "Hit" } ] });+ expect(await searchWeb({ provider: "searxng", apiKey: "xk", baseURL: "http://searx.lan" }, "q"))+ .toEqual([ { ...PAGE, snippet: "Hit" } ]);+ expect(request().headers.Authorization).toBe("Bearer xk");+ });++ it("names the provider by its type when it has no name, and reports a failure that is not an Error", async () => {+ const tool = createWebSearchTool({ provider: "tavily", apiKey: "tk" });+ const run = () => tool.execute?.({ query: "q" }, { toolCallId: "1", messages: [], context: {} });++ respond({ results: [] });+ expect(await run()).toMatchObject({ searchProvider: { type: "tavily", name: "tavily" } });++ fetchMock.mockRejectedValueOnce("offline");+ expect(await run()).toEqual({ error: "offline" });+ });+});+describe("createWebSearchTool", () => {const run = (tool: ReturnType<typeof createWebSearchTool>, query: string) =>tool.execute?.({ query }, { toolCallId: "1", messages: [], context: {} });@@ -198,6 +234,14 @@ describe("readWebPage", () => {}});+ it("reads a page without a title or a main element, or without a content type, as HTML", async () => {+ serve("<html><body><p>Only <b>body</b></p></body></html>");+ expect(await readWebPage("https://a.example/")).toBe("Only **body**");++ serve("<p>A fragment</p>", "");+ expect(await readWebPage("https://a.example/fragment")).toBe("A fragment");+ });+it("hands the model a refused address as an error to report", async () => {fetchResourceMock.mockRejectedValueOnce(new Error("URLs pointing to private/internal networks are not allowed"));const tool = createReadWebPageTool();