A desktop coding agent with free access to frontier models.
TypeScript
feat: show web searches in the chat
Samrat Talukdardb991ec8c2d9
diff --git a/apps/app/src/components/chat/message-list.tsx b/apps/app/src/components/chat/message-list.tsxindex 78145700..ea72fc64 100644--- a/apps/app/src/components/chat/message-list.tsx+++ b/apps/app/src/components/chat/message-list.tsx@@ -50,7 +50,7 @@ import { QuestionTool } from "@/components/tools/question"import { SkillTool } from "@/components/tools/skill"import { TodoWriteTool } from "@/components/tools/todowrite"import { WebfetchTool } from "@/components/tools/webfetch"-import { WebsearchTool } from "@/components/tools/websearch"+import { HostedWebSearchTool, WebsearchTool } from "@/components/tools/websearch"import { useMessageList, useSessionErrorMessage } from "@/components/chat/message-list-provider"import { TaskSuggestions } from "@/components/chat/task-suggestions"import {@@ -113,6 +113,7 @@ import {isTodoWriteToolPart,isWebFetchToolPart,isWebSearchToolPart,+ isHostedWebSearchToolPart,isWriteToolPart,} from "@/lib/build-in-tools"import type { ThreadStatus } from "@/lib/messages"@@ -293,6 +294,10 @@ const ToolMessageInner = ({ part }: ToolMessageProps) => {return <WebsearchTool part={part} />}+ if (isHostedWebSearchToolPart(part)) {+ return <HostedWebSearchTool part={part} />+ }+if (isQuestionToolPart(part)) {return <QuestionTool part={part} />}diff --git a/apps/app/src/components/tools/websearch.tsx b/apps/app/src/components/tools/websearch.tsxindex ad5ecfcc..c39c1aba 100644--- a/apps/app/src/components/tools/websearch.tsx+++ b/apps/app/src/components/tools/websearch.tsx@@ -12,9 +12,10 @@ import {SourceContent,SourceTrigger,} from "@/components/ui/source"-import type { WebSearchToolPart } from "@/lib/build-in-tools"+import type { HostedWebSearchToolPart, WebSearchToolPart } from "@/lib/build-in-tools"import { Tool } from "@/components/ui/tool"import { parseWebSearchResults } from "@/lib/websearch-results"+import { hostedWebSearchSummary } from "@/lib/hosted-web-search"interface WebsearchToolProps {part: WebSearchToolPart@@ -53,4 +54,65 @@ export function WebsearchTool({ part }: WebsearchToolProps) {</ChainOfThoughtStep></ChainOfThought>)-}\ No newline at end of file+}++interface HostedWebSearchToolProps {+ part: HostedWebSearchToolPart+}++/**+ * The model's own web search (run by the provider): one line with what it+ * searched or opened, and the sources it returned as links. No favicons: a+ * favicon would be fetched from a third-party service for every source.+ */+export function HostedWebSearchTool({ part }: HostedWebSearchToolProps) {+ if (part.state === "output-error") {+ return <Tool toolPart={part} />+ }++ if (part.state !== "output-available") {+ return (+ <ChainOfThought>+ <ChainOfThoughtStep>+ <ChainOfThoughtTrigger leftIcon={<Search className="size-4" />} swapIconOnHover={false}>+ Searching the web…+ </ChainOfThoughtTrigger>+ </ChainOfThoughtStep>+ </ChainOfThought>+ )+ }++ const { line, sources } = hostedWebSearchSummary(part.input, part.output)++ if (sources.length === 0) {+ return (+ <ChainOfThought>+ <ChainOfThoughtStep>+ <ChainOfThoughtTrigger leftIcon={<Search className="size-4" />} swapIconOnHover={false}>+ {line}+ </ChainOfThoughtTrigger>+ </ChainOfThoughtStep>+ </ChainOfThought>+ )+ }++ return (+ <ChainOfThought>+ <ChainOfThoughtStep>+ <ChainOfThoughtTrigger leftIcon={<Search className="size-4" />}>+ {line}+ </ChainOfThoughtTrigger>+ <ChainOfThoughtContent>+ <div className="flex flex-wrap items-center gap-2" data-testid="hosted-web-search-sources">+ {sources.map((url) => (+ <Source href={url} key={url}>+ <SourceTrigger />+ <SourceContent title={url} />+ </Source>+ ))}+ </div>+ </ChainOfThoughtContent>+ </ChainOfThoughtStep>+ </ChainOfThought>+ )+}diff --git a/apps/app/src/lib/build-in-tools.ts b/apps/app/src/lib/build-in-tools.tsindex 8a68d512..9ee472ed 100644--- a/apps/app/src/lib/build-in-tools.ts+++ b/apps/app/src/lib/build-in-tools.ts@@ -1,3 +1,4 @@+import type { HostedWebSearchAction } from "./hosted-web-search";import type { ToolUIPart, DynamicToolUIPart } from "ai";export interface ToolMetadata {@@ -372,6 +373,13 @@ export function isWebSearchToolPart(part: ToolUIPart | DynamicToolUIPart): partreturn part.type === "dynamic-tool" && part.toolName === "websearch";}+/** The model's own web search, run by the provider (lib/hosted-web-search.ts). */+export type HostedWebSearchToolPart = BuiltInDynamicToolPart<"web_search", HostedWebSearchAction>;++export function isHostedWebSearchToolPart(part: ToolUIPart | DynamicToolUIPart): part is HostedWebSearchToolPart {+ return part.type === "dynamic-tool" && part.toolName === "web_search";+}+export type QuestionToolPart = BuiltInDynamicToolPart<"question", QuestionInput>;export function isQuestionToolPart(part: ToolUIPart | DynamicToolUIPart): part is QuestionToolPart {diff --git a/apps/app/src/lib/hosted-web-search.ts b/apps/app/src/lib/hosted-web-search.tsnew file mode 100644index 00000000..da480b8e--- /dev/null+++ b/apps/app/src/lib/hosted-web-search.ts@@ -0,0 +1,87 @@+/**+ * A provider-run web search (the model's own `web_search` tool): the engine+ * records it as a `web_search` tool part whose input is the search's action+ * ({ type: "search", query } / { type: "openPage", url } / { type: "findInPage",+ * url, pattern }) and whose output is `{ action, sources: [{ type: "url", url }] }`+ * as JSON text. The one line it shows is the CLI's (engine turn-status.ts+ * hostedSearchLine): "Searched the web for "q" (5 sources)", "Opened+ * host/path", "Searched host/path for "x"", else "Searched the web".+ */++export interface HostedWebSearchAction {+ type?: string+ query?: string+ queries?: string[]+ url?: string+ pattern?: string+}++export interface HostedWebSearchSummary {+ line: string+ /** The source addresses the search returned (http/https only, no duplicates). */+ sources: string[]+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value)+}++/** A page address shortened for one line: host and path, no scheme, query or fragment. */+export function shortPageAddress(url: string): string {+ try {+ const parsed = new URL(url)+ const tail = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/$/, "")+ const text = parsed.host + tail+ return text.length > 72 ? `${text.slice(0, 71)}…` : text+ } catch {+ return url.length > 72 ? `${url.slice(0, 71)}…` : url+ }+}++function text(value: unknown): string | null {+ return typeof value === "string" && value.trim() ? value.trim() : null+}++function parseOutput(output: unknown): Record<string, unknown> {+ if (isRecord(output)) return output+ if (typeof output !== "string" || !output.trim()) return {}+ try {+ const parsed: unknown = JSON.parse(output)+ return isRecord(parsed) ? parsed : {}+ } catch {+ return {}+ }+}++function webUrl(value: unknown): string | null {+ const raw = isRecord(value) ? value.url : value+ if (typeof raw !== "string") return null+ try {+ const url = new URL(raw)+ return url.protocol === "https:" || url.protocol === "http:" ? url.toString() : null+ } catch {+ return null+ }+}++export function hostedWebSearchSummary(input: unknown, output?: unknown): HostedWebSearchSummary {+ const result = parseOutput(output)+ const given = isRecord(input) ? input : {}+ const action = typeof given.type === "string" || text(given.query)+ ? given+ : isRecord(result.action)+ ? result.action+ : given+ const sources = [...new Set((Array.isArray(result.sources) ? result.sources : []).map(webUrl).filter((url): url is string => url !== null))]+ const type = typeof action.type === "string" ? action.type.replace(/_/g, "").toLowerCase() : ""+ const url = text(action.url)+ if (type === "openpage" && url) return { line: `Opened ${shortPageAddress(url)}`, sources }+ if (type === "findinpage" && url) {+ const pattern = text(action.pattern)+ return { line: pattern ? `Searched ${shortPageAddress(url)} for "${pattern}"` : `Searched ${shortPageAddress(url)}`, sources }+ }+ const queries = Array.isArray(action.queries) ? action.queries.map(text).filter((q): q is string => q !== null) : []+ const query = text(action.query) ?? queries[0] ?? null+ const count = sources.length ? ` (${sources.length} ${sources.length === 1 ? "source" : "sources"})` : ""+ return { line: query ? `Searched the web for "${query}"${count}` : `Searched the web${count}`, sources }+}diff --git a/apps/app/src/lib/tool-activity.ts b/apps/app/src/lib/tool-activity.tsindex effaf48c..8aae23ea 100644--- a/apps/app/src/lib/tool-activity.ts+++ b/apps/app/src/lib/tool-activity.ts@@ -1,3 +1,4 @@+import { hostedWebSearchSummary } from "./hosted-web-search"import type { DynamicToolUIPart, ToolUIPart } from "ai"import {isApplyPatchToolPart,@@ -14,6 +15,7 @@ import {isTodoWriteToolPart,isWebFetchToolPart,isWebSearchToolPart,+ isHostedWebSearchToolPart,isWriteToolPart,} from "./build-in-tools"import { parseFilename, truncateText } from "../components/tools/path"@@ -82,6 +84,11 @@ export function getToolActivityLabel(part: AnyToolPart): string {? `Searching the web for ${truncateText(query, 44)}`: "Searching the web"}+ if (isHostedWebSearchToolPart(part)) {+ return part.state === "output-available"+ ? truncateText(hostedWebSearchSummary(part.input, part.output).line, 64)+ : "Searching the web"+ }if (isQuestionToolPart(part)) {return "Asking a question"}diff --git a/apps/app/src/react-app/domains/session/status/session-progress.ts b/apps/app/src/react-app/domains/session/status/session-progress.tsindex f64290ea..aac67914 100644--- a/apps/app/src/react-app/domains/session/status/session-progress.ts+++ b/apps/app/src/react-app/domains/session/status/session-progress.ts@@ -26,7 +26,7 @@ function safeToolActivity(part: UIMessage["parts"][number]): string {case "read": return "Reading files";case "write": case "edit": case "apply_patch": return "Updating files";case "grep": case "glob": return "Searching files";- case "webfetch": case "websearch": return "Researching the web";+ case "webfetch": case "websearch": case "web_search": return "Researching the web";case "task": case "subagent": return "Running a delegated task";case "todowrite": return "Updating the plan";case "question": return "Asking for input";diff --git a/apps/app/tests/hosted-web-search.test.ts b/apps/app/tests/hosted-web-search.test.tsnew file mode 100644index 00000000..ff6faa09--- /dev/null+++ b/apps/app/tests/hosted-web-search.test.ts@@ -0,0 +1,44 @@+import { describe, expect, test } from "bun:test"++import { isHostedWebSearchToolPart, isWebSearchToolPart } from "../src/lib/build-in-tools"+import { hostedWebSearchSummary, shortPageAddress } from "../src/lib/hosted-web-search"+import { getToolActivityLabel } from "../src/lib/tool-activity"++const output = JSON.stringify({+ action: { type: "search", query: "vite 7 release notes" },+ sources: [+ { type: "url", url: "https://vite.dev/blog/announcing-vite7" },+ { type: "url", url: "https://github.com/vitejs/vite/releases" },+ { type: "url", url: "https://vite.dev/blog/announcing-vite7" },+ { type: "url", url: "javascript:alert(1)" },+ { type: "api" },+ ],+})++describe("hosted web search", () => {+ test("the line and the sources, as the CLI shows them", () => {+ expect(hostedWebSearchSummary({ type: "search", query: "vite 7 release notes" }, output)).toEqual({+ line: 'Searched the web for "vite 7 release notes" (2 sources)',+ sources: ["https://vite.dev/blog/announcing-vite7", "https://github.com/vitejs/vite/releases"],+ })+ // An empty input takes the result's action.+ expect(hostedWebSearchSummary({}, output).line).toBe('Searched the web for "vite 7 release notes" (2 sources)')+ expect(hostedWebSearchSummary({ type: "search", queries: ["a b", "c"] }).line).toBe('Searched the web for "a b"')+ expect(hostedWebSearchSummary({ type: "search", query: "x" }, JSON.stringify({ sources: [{ type: "url", url: "https://a.example/" }] })).line).toBe('Searched the web for "x" (1 source)')+ expect(hostedWebSearchSummary({ type: "openPage", url: "https://docs.example.com/guide/install/?x=1#top" }).line).toBe("Opened docs.example.com/guide/install")+ expect(hostedWebSearchSummary({ type: "find_in_page", url: "https://example.com/", pattern: "v2.1" }).line).toBe('Searched example.com for "v2.1"')+ expect(hostedWebSearchSummary({}, "not json")).toEqual({ line: "Searched the web", sources: [] })+ expect(hostedWebSearchSummary(null, undefined)).toEqual({ line: "Searched the web", sources: [] })+ expect(shortPageAddress(`https://example.com/${"a".repeat(100)}`).length).toBe(72)+ })++ test("the engine's web_search part is the hosted one; websearch stays the engine's own tool", () => {+ const hosted = { type: "dynamic-tool", toolName: "web_search", toolCallId: "ws_1", state: "output-available", input: { type: "search", query: "vite 7 release notes" }, output } as const+ const exa = { type: "dynamic-tool", toolName: "websearch", toolCallId: "c1", state: "output-available", input: { query: "q" }, output: "" } as const+ expect(isHostedWebSearchToolPart(hosted as never)).toBe(true)+ expect(isWebSearchToolPart(hosted as never)).toBe(false)+ expect(isHostedWebSearchToolPart(exa as never)).toBe(false)+ expect(getToolActivityLabel(hosted as never)).toBe('Searched the web for "vite 7 release notes" (2 sources)')+ expect(getToolActivityLabel({ ...hosted, state: "input-available" } as never)).toBe("Searching the web")+ })+})