Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): list a web search's sources and link the page read

Elian Doran5ad517f3a460
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index a30e5944d2..1615a4499a 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2687,7 +2687,9 @@
"backend_scripting": "Backend scripting",
"frontend_scripting": "Frontend scripting",
"dashboards": "Dashboards"
- }
+ },
+ "web_sources_count_one": "({{count}} source)",
+ "web_sources_count_other": "({{count}} sources)"
},
"sidebar_chat": {
"title": "AI Chat",
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.tsx
index 482b015189..03a0b00298 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
@@ -665,4 +665,55 @@ describe("ToolCallCard", () => {
act(() => install?.click());
expect(mocks.openInAppHelpFromUrl).toHaveBeenCalledExactlyOnceWith("b");
});
+
+ it("lists the sources a web search found, whichever provider ran it", () => {
+ const search = (id: string, input: Record<string, unknown>, result: unknown): ToolCall => ({
+ id, toolName: "web_search", input, result: typeof result === "string" ? result : JSON.stringify(result)
+ });
+ const target = renderCard([
+ search("1", { query: "trilium" }, [
+ { type: "web_search_result", url: "https://triliumnotes.org/docs", title: "Docs", pageAge: null, encryptedContent: "x" },
+ { type: "web_search_result", url: "https://github.com/TriliumNext/Trilium", title: null, pageAge: null, encryptedContent: "y" }
+ ]),
+ { id: "2", toolName: "get_note", input: { noteId: "x" }, result: "{}" },
+ search("3", {}, { action: { type: "search", query: "weather" }, sources: [ { type: "url", url: "https://a.com/x" }, { type: "api", name: "oai" } ] }),
+ { id: "4", toolName: "get_note", input: { noteId: "x" }, result: "{}" },
+ search("5", { query: "t" }, "Web search results for query: \"t\"\n\nLinks: [{\"title\":\"T\",\"url\":\"https://t.org/p\"}]\n\nSummary"),
+ { id: "6", toolName: "get_note", input: { noteId: "x" }, result: "{}" },
+ search("7", { query: "q" }, "Searching the web")
+ ]);
+ const [ anthropic, , openai, , claude, , bare ] = [ ...(target.querySelector(".llm-chat-tool-calls")?.children ?? []) ];
+ const sources = (line: Element | undefined) => [ ...(line?.querySelectorAll(".llm-chat-note-result") ?? []) ].map(row => ({
+ text: row.querySelector("a.external")?.textContent,
+ href: row.querySelector("a.external")?.getAttribute("href"),
+ domain: row.querySelector(".llm-chat-note-result-detail")?.textContent
+ }));
+
+ expect(anthropic?.querySelector(".llm-chat-tool-call-result-count")?.textContent).toBe("llm_chat.web_sources_count{\"count\":2}");
+ expect(sources(anthropic)).toEqual([
+ { text: "Docs", href: "https://triliumnotes.org/docs", domain: "triliumnotes.org" },
+ { text: "https://github.com/TriliumNext/Trilium", href: "https://github.com/TriliumNext/Trilium", domain: "github.com" }
+ ]);
+
+ expect(openai?.querySelector(".llm-chat-tool-call-detail")?.textContent).toBe("weather");
+ expect(sources(openai)).toEqual([ { text: "https://a.com/x", href: "https://a.com/x", domain: "a.com" } ]);
+
+ expect(sources(claude)).toEqual([ { text: "T", href: "https://t.org/p", domain: "t.org" } ]);
+
+ expect(bare instanceof HTMLDetailsElement).toBe(false);
+ });
+
+ it("links the page a call read, and previews what it read there", () => {
+ const target = renderCard([ {
+ id: "1",
+ toolName: "read_web_page",
+ input: { url: "https://triliumnotes.org" },
+ result: "The page describes **Trilium**."
+ } ]);
+ const line = target.querySelector("details.llm-chat-tool-call");
+ const link = line?.querySelector<HTMLAnchorElement>(".llm-chat-tool-call-detail a.external");
+ expect(link?.getAttribute("href")).toBe("https://triliumnotes.org");
+ expect(link?.getAttribute("target")).toBe("_blank");
+ expect(line?.querySelector(".llm-chat-note-result-preview")?.textContent).toBe("The page describes Trilium.");
+ });
});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsx
index 0097855868..49c54e12b6 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsx
@@ -9,7 +9,7 @@ import { NewNoteLink } from "../../react/NoteLink.js";
import { EditNoteContentDiff, isSmallEdit, parseNoteContentEdits } from "./EditNoteContentDiff.js";
import { ExpandableSection } from "./ExpandableCard.js";
import { isFailedToolCall, type ToolCall } from "./llm_chat_types.js";
-import { getToolCallView, type ToolCallView } from "./ToolCallViews.js";
+import { ExternalLink, getToolCallView, type ToolCallView } from "./ToolCallViews.js";
interface ToolCallContext {
/** The primary note the tool operates on or created. */
@@ -75,10 +75,27 @@ function getToolCallContext(toolCall: ToolCall): ToolCallContext {
return { noteId: null, parentNoteId: null, detailText: skillTitle };
}
- const detailText = (input?.name ?? input?.query ?? input?.url) as string | undefined;
+ const detailText = (input?.name ?? input?.query ?? input?.url) as string | undefined
+ ?? readWebSearchAction(toolCall);
return { noteId: null, parentNoteId: null, detailText: detailText || null };
}
+/**
+ * The query or page of an OpenAI `web_search` call, which takes no input and names what it did in its
+ * result's `action` instead.
+ */
+function readWebSearchAction(toolCall: ToolCall): string | undefined {
+ if (toolCall.toolName !== "web_search" || !toolCall.result) return undefined;
+ try {
+ const action = JSON.parse(toolCall.result)?.action;
+ if (typeof action?.query === "string") return action.query;
+ if (Array.isArray(action?.queries)) return action.queries.join("; ");
+ return typeof action?.url === "string" ? action.url : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
function toolNameIcon(toolName: string): string {
if (toolName.includes("search")) return "bx bx-search";
// Specific note-content tools, checked before the generic "note" match below.
@@ -121,7 +138,11 @@ function ToolCallLabel({ toolCall, view }: { toolCall: ToolCall; view: ToolCallV
<>
<span className="llm-chat-tool-call-name">{t(`llm.tools.${toolCall.toolName}`, { defaultValue: toolCall.toolName })}</span>
{detailText && (
- <span className="llm-chat-tool-call-detail">{detailText}</span>
+ <span className="llm-chat-tool-call-detail">
+ {toolCall.toolName === "read_web_page" && /^https?:\/\//i.test(detailText)
+ ? <ExternalLink url={detailText}>{detailText}</ExternalLink>
+ : detailText}
+ </span>
)}
{view?.lead}
{deletedTitle && <span className="llm-chat-tool-call-deleted-title">{deletedTitle}</span>}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsx
index a27ca1f888..76de20e837 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsx
@@ -131,6 +131,23 @@ export function getToolCallView(toolCall: ToolCall): ToolCallView | null {
: undefined
};
}
+ case "web_search": {
+ const sources = parseWebSources(toolCall.result);
+ if (!sources?.length) return null;
+ return {
+ summary: t("llm_chat.web_sources_count", { count: sources.length }),
+ body: <WebSourceList sources={sources} />
+ };
+ }
+ case "read_web_page": {
+ // Some agents report only a status title here, which reads as text all the same.
+ if (parseJson(toolCall.result) !== null) return null;
+ const preview = markdownToPlainPreview(toolCall.result.slice(0, CONTENT_PREVIEW_SOURCE_LENGTH));
+ if (!preview) return null;
+ return {
+ body: <div className="llm-chat-note-card"><div className="llm-chat-note-result-preview">{preview}</div></div>
+ };
+ }
case "get_child_notes": {
const children = parseChildNotesResult(toolCall.result);
if (!children) return null;
@@ -290,6 +307,64 @@ function parseIconSearchResult(result: string): IconSearchResult | null {
return { totalResults: parsed.totalResults, icons };
}
+interface WebSource {
+ url: string;
+ title: string | null;
+}
+
+/** The pages a web search found, each an external link with its site beside it. */
+function WebSourceList({ sources }: { sources: WebSource[] }) {
+ return (
+ <div className="llm-chat-note-results">
+ <ul>
+ {sources.map(({ url, title }, idx) => (
+ <li key={idx} className="llm-chat-note-result">
+ <div className="llm-chat-note-result-header">
+ <ExternalLink url={url}>{title || url}</ExternalLink>
+ <span className="llm-chat-note-result-detail">{hostnameOf(url)}</span>
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
+
+/**
+ * The sources of a `web_search` result, in each provider's shape: Anthropic's array of results,
+ * OpenAI's `sources`, or the `Links: [...]` line Claude Code writes into its text. Only web URLs count.
+ */
+function parseWebSources(result: string): WebSource[] | null {
+ let items: unknown = parseJson(result);
+ if (isRecord(items)) {
+ items = items.sources;
+ } else if (items === null) {
+ const links = /^Links: (\[.*\])$/m.exec(result);
+ items = links ? parseJson(links[1]) : null;
+ }
+ if (!Array.isArray(items)) return null;
+ const sources: WebSource[] = [];
+ for (const item of items) {
+ if (isRecord(item) && typeof item.url === "string" && /^https?:\/\//i.test(item.url)) {
+ sources.push({ url: item.url, title: typeof item.title === "string" ? item.title : null });
+ }
+ }
+ return sources;
+}
+
+/** A link to a page outside Trilium, opened in the browser. */
+export function ExternalLink({ url, children }: { url: string; children: ComponentChildren }) {
+ return <a className="tn-link external" href={url} target="_blank" rel="noopener noreferrer">{children}</a>;
+}
+
+function hostnameOf(url: string): string {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return "";
+ }
+}
+
function ChildNoteList({ notes }: { notes: ChildNote[] }) {
return (
<div className="llm-chat-note-results">
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html
index 3b4a32ba2d..6e9fa9d75e 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html
@@ -195,19 +195,21 @@ class="admonition note">
tool and the note or query it worked on; a renamed note shows its previous
title struck through, a deleted note its title struck through, a moved
note where it was moved from and to, an attribute the AI read, set or deleted
- as a pill (struck through once deleted), and an attachment by its title,
- note and size. A line folds open only when there is something to read inline:
- the notes a search found, the icons an icon search found, the type, attributes
+ as a pill (struck through once deleted), an attachment by its title, note
+ and size, and a web page the AI read as a link. A line folds open only
+ when there is something to read inline: the notes a search found, the pages
+ a web search found, the icons an icon search found, the type, attributes
or start of the content of a note the AI read, all the attributes of a
- note, the text of an attachment, the User Guide pages the AI looked up
- or its table of contents (both open in the help panel), the children or
- the whole subtree of a note, what the AI wrote into a note it created,
- rewrote or added to, the changes of an edit, or the reason a tool failed.
- A search also shows how many notes it found, the part of the tree it was
- confined to, if any, and how many of the matches the AI asked for; each
- note it lists opens with a click. To see exactly what the AI sent to a
- tool and what it got back, hover the line and press the <span class="tn-icon bx bx-code-alt"></span> button
- next to it; on touch screens the button is always shown.</p>
+ note, the text of an attachment or of a web page, the User Guide pages
+ the AI looked up or its table of contents (both open in the help panel),
+ the children or the whole subtree of a note, what the AI wrote into a note
+ it created, rewrote or added to, the changes of an edit, or the reason
+ a tool failed. A search also shows how many notes it found, the part of
+ the tree it was confined to, if any, and how many of the matches the AI
+ asked for; each note it lists opens with a click. To see exactly what the
+ AI sent to a tool and what it got back, hover the line and press the <span
+ class="tn-icon bx bx-code-alt"></span> button next to it; on touch screens
+ the button is always shown.</p>
<aside class="admonition warning">
<p>Currently there is <strong>no permission management</strong> implemented
for note tools, meaning that the LLM could potentially remove existing
diff --git a/docs/User Guide/User Guide/AI.md b/docs/User Guide/User Guide/AI.md
index 0138eb42d2..7709b2b567 100644
--- a/docs/User Guide/User Guide/AI.md
+++ b/docs/User Guide/User Guide/AI.md
@@ -133,7 +133,7 @@ Here are a few tools that Trilium provides for the LLM:
* Get the content of an attachment.
* Skills (see the dedicated section).
-Each tool the AI uses appears in the chat as a single line naming the tool and the note or query it worked on; a renamed note shows its previous title struck through, a deleted note its title struck through, a moved note where it was moved from and to, an attribute the AI read, set or deleted as a pill (struck through once deleted), and an attachment by its title, note and size. A line folds open only when there is something to read inline: the notes a search found, the icons an icon search found, the type, attributes or start of the content of a note the AI read, all the attributes of a note, the text of an attachment, the User Guide pages the AI looked up or its table of contents (both open in the help panel), the children or the whole subtree of a note, what the AI wrote into a note it created, rewrote or added to, the changes of an edit, or the reason a tool failed. A search also shows how many notes it found, the part of the tree it was confined to, if any, and how many of the matches the AI asked for; each note it lists opens with a click. To see exactly what the AI sent to a tool and what it got back, hover the line and press the <span class="tn-icon bx bx-code-alt"></span> button next to it; on touch screens the button is always shown.
+Each tool the AI uses appears in the chat as a single line naming the tool and the note or query it worked on; a renamed note shows its previous title struck through, a deleted note its title struck through, a moved note where it was moved from and to, an attribute the AI read, set or deleted as a pill (struck through once deleted), an attachment by its title, note and size, and a web page the AI read as a link. A line folds open only when there is something to read inline: the notes a search found, the pages a web search found, the icons an icon search found, the type, attributes or start of the content of a note the AI read, all the attributes of a note, the text of an attachment or of a web page, the User Guide pages the AI looked up or its table of contents (both open in the help panel), the children or the whole subtree of a note, what the AI wrote into a note it created, rewrote or added to, the changes of an edit, or the reason a tool failed. A search also shows how many notes it found, the part of the tree it was confined to, if any, and how many of the matches the AI asked for; each note it lists opens with a click. To see exactly what the AI sent to a tool and what it got back, hover the line and press the <span class="tn-icon bx bx-code-alt"></span> button next to it; on touch screens the button is always shown.
> [!WARNING]
> Currently there is **no permission management** implemented for note tools, meaning that the LLM could potentially remove existing notes or clutter the tree with notes. Generally most actions are easily reversible (deleting the notes, restoring deleted notes, reverting modifications to a note), but there are some that are harder to revert (e.g. setting an attribute because there is no attribute history).