Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: dispatch on OpenAI agentic web_search action variants (#5787)
Daniel Han7504feb1ae36
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex ce696a83d6b..44624f657f3 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -398,6 +398,48 @@ def _split_pending_citation_tail(text: str) -> tuple[str, str]:return text[:last_open], text[last_open:]+def _extract_web_search_action(item: dict[str, Any]) -> dict[str, Any]:+ """Normalize an OpenAI web_search_call action into card arguments.++ gpt-5.x agentic search emits three action types, discriminated by+ `action.type`: `search` carries queries, `open_page` a url, `find_in_page` a+ url and a pattern. Reading only `action.query` renders the last two as an+ empty `Searching ""` card. Shapes per WebSearchToolCall in+ https://github.com/openai/openai-openapi (openapi.yaml).+ """+ if not isinstance(item, dict):+ return {}+ action = item.get("action") if isinstance(item.get("action"), dict) else {}+ action_type = action.get("type") if isinstance(action.get("type"), str) else ""+ # `queries` is the current field and holds every query the call ran; the+ # singular `query` is deprecated in the spec, so it is only the fallback.+ # Neither is required, so a search action can carry no query at all.+ query = ""+ for source in (action.get("queries"), item.get("queries")):+ if isinstance(source, list):+ joined = ", ".join(q for q in source if isinstance(q, str) and q)+ if joined:+ query = joined+ break+ if not query:+ for legacy in (action.get("query"), item.get("query")):+ if isinstance(legacy, str) and legacy:+ query = legacy+ break+ url = action.get("url") if isinstance(action.get("url"), str) else ""+ pattern = action.get("pattern") if isinstance(action.get("pattern"), str) else ""+ arguments: dict[str, Any] = {}+ if query:+ arguments["query"] = query+ if url:+ arguments["url"] = url+ if pattern:+ arguments["pattern"] = pattern+ if action_type:+ arguments["action_type"] = action_type+ return arguments++# Families that accept `prompt_cache_retention: "24h"`. Everything else 400s# with "prompt_cache_retention is not supported on this model" and the turn# dies (openai/codex#39397), while an unmatched model just falls back to@@ -5862,7 +5904,10 @@ class ExternalProviderClient:item = event.get("item", {})if isinstance(item, dict) and item.get("type") == "web_search_call":item_id = item.get("id", "") or (f"ws_{len(web_search_calls)}")- web_search_calls.setdefault(item_id, {"query": ""})+ web_search_calls.setdefault(+ item_id,+ _extract_web_search_action(item),+ )# Register shell_call eagerly so out-of-order# output links back. Probe env.container_id to# emit container_ready before response.completed.@@ -5917,26 +5962,31 @@ class ExternalProviderClient:yield _chunk_with_text(summary_text)reasoning_emitted = Trueelif item.get("type") == "web_search_call":- # done carries the query; emit tool_start ++ # done carries the action; emit tool_start +# tool_end here. Citations are aggregated and# the last call's result is overwritten at# response.completed.item_id = item.get("id", "") or (f"ws_{len(web_search_calls)}")- action = item.get("action")- query = (- action.get("query", "") if isinstance(action, dict) else ""- )- web_search_calls[item_id] = {"query": query}+ # Overlay, don't replace: a partial done event+ # would drop what the added event carried.+ arguments = {+ **web_search_calls.get(item_id, {}),+ **_extract_web_search_action(item),+ }+ web_search_calls[item_id] = dict(arguments)yield _emit_tool_event({"type": "tool_start","tool_name": "web_search","tool_call_id": item_id,- "arguments": ({"query": query} if query else {}),+ "arguments": arguments,})# Per-card text; last call gets overwritten- # with citations at response.completed.+ # with citations at response.completed. The+ # url variants have no query to echo, and the+ # card names the page from `url` instead.+ query = arguments.get("query") or ""per_call_result = f"Searching: {query}" if query else ""yield _emit_tool_event({diff --git a/studio/backend/tests/test_openai_tool_result_fallbacks.py b/studio/backend/tests/test_openai_tool_result_fallbacks.pyindex 5ea812441fb..3f5be2ad6d8 100644--- a/studio/backend/tests/test_openai_tool_result_fallbacks.py+++ b/studio/backend/tests/test_openai_tool_result_fallbacks.py@@ -370,3 +370,228 @@ def test_shell_call_incomplete_does_not_double_emit(monkeypatch):assert len(ends) == 1assert ends[0]["tool_call_id"] == "scall_done"assert "done" in ends[0]["result"]+++# ── agentic search action variants ─────────────────────────────────────+++def test_open_page_action_reaches_the_card_as_a_url(monkeypatch):+ """`open_page` carries a url and no query; reading only `action.query`+ rendered these as an empty `Searching ""`."""+ sse_events = [+ {+ "type": "response.output_item.done",+ "item": {+ "type": "web_search_call",+ "id": "ws_open",+ "action": {+ "type": "open_page",+ "url": "https://en.wikipedia.org/wiki/Tiger",+ },+ },+ },+ {"type": "response.completed", "response": {}},+ ]+ starts = [+ e+ for e in _tool_events(_drive_stream(sse_events, ["web_search"], monkeypatch))+ if e["type"] == "tool_start"+ ]+ # `_server_tool` is stamped on every server-side call by _emit_tool_event.+ arguments = {k: v for k, v in starts[0]["arguments"].items() if k != "_server_tool"}+ assert arguments == {+ "url": "https://en.wikipedia.org/wiki/Tiger",+ "action_type": "open_page",+ }+++def test_find_in_page_action_carries_its_pattern(monkeypatch):+ sse_events = [+ {+ "type": "response.output_item.done",+ "item": {+ "type": "web_search_call",+ "id": "ws_find",+ "action": {+ "type": "find_in_page",+ "url": "https://en.wikipedia.org/wiki/Tiger",+ "pattern": "population",+ },+ },+ },+ {"type": "response.completed", "response": {}},+ ]+ starts = [+ e+ for e in _tool_events(_drive_stream(sse_events, ["web_search"], monkeypatch))+ if e["type"] == "tool_start"+ ]+ assert starts[0]["arguments"]["pattern"] == "population"+ assert starts[0]["arguments"]["action_type"] == "find_in_page"+++def test_a_search_action_still_carries_its_query(monkeypatch):+ sse_events = [+ {+ "type": "response.output_item.done",+ "item": {+ "type": "web_search_call",+ "id": "ws_q",+ "action": {"type": "search", "query": "popular animals 2026"},+ },+ },+ {"type": "response.completed", "response": {}},+ ]+ events = _tool_events(_drive_stream(sse_events, ["web_search"], monkeypatch))+ starts = [e for e in events if e["type"] == "tool_start"]+ ends = [e for e in events if e["type"] == "tool_end"]+ assert starts[0]["arguments"]["query"] == "popular animals 2026"+ assert ends[0]["result"] == "Searching: popular animals 2026"+++def test_an_older_queries_list_still_resolves_to_a_query(monkeypatch):+ sse_events = [+ {+ "type": "response.output_item.done",+ "item": {+ "type": "web_search_call",+ "id": "ws_plural",+ "action": {"queries": ["renewable energy 2026"]},+ },+ },+ {"type": "response.completed", "response": {}},+ ]+ starts = [+ e+ for e in _tool_events(_drive_stream(sse_events, ["web_search"], monkeypatch))+ if e["type"] == "tool_start"+ ]+ assert starts[0]["arguments"]["query"] == "renewable energy 2026"+++def test_a_partial_done_event_keeps_what_added_recorded(monkeypatch):+ """A done event that omits the action must not revert the card to a blank+ "Web Search"."""+ sse_events = [+ {+ "type": "response.output_item.added",+ "item": {+ "type": "web_search_call",+ "id": "ws_partial",+ "action": {+ "type": "find_in_page",+ "url": "https://example.com/tigers",+ "pattern": "population",+ },+ },+ },+ {+ "type": "response.output_item.done",+ "item": {"type": "web_search_call", "id": "ws_partial"},+ },+ {"type": "response.completed", "response": {}},+ ]+ starts = [+ e+ for e in _tool_events(_drive_stream(sse_events, ["web_search"], monkeypatch))+ if e["type"] == "tool_start"+ ]+ assert starts[0]["arguments"]["url"] == "https://example.com/tigers"+ assert starts[0]["arguments"]["pattern"] == "population"+ assert starts[0]["arguments"]["action_type"] == "find_in_page"+++def test_the_done_event_wins_where_it_has_a_value(monkeypatch):+ sse_events = [+ {+ "type": "response.output_item.added",+ "item": {+ "type": "web_search_call",+ "id": "ws_upd",+ "action": {"type": "search", "query": "first"},+ },+ },+ {+ "type": "response.output_item.done",+ "item": {+ "type": "web_search_call",+ "id": "ws_upd",+ "action": {"type": "search", "query": "second"},+ },+ },+ {"type": "response.completed", "response": {}},+ ]+ starts = [+ e+ for e in _tool_events(_drive_stream(sse_events, ["web_search"], monkeypatch))+ if e["type"] == "tool_start"+ ]+ assert starts[0]["arguments"]["query"] == "second"+++def test_every_query_in_the_call_reaches_the_card(monkeypatch):+ # `queries` is an array in the spec: one search action can run several. Only+ # showing the first silently drops the rest.+ sse_events = [+ {+ "type": "response.output_item.done",+ "item": {+ "type": "web_search_call",+ "id": "ws_multi",+ "action": {+ "type": "search",+ "queries": ["tiger population", "tiger conservation 2026"],+ },+ },+ },+ {"type": "response.completed", "response": {}},+ ]+ starts = [+ e+ for e in _tool_events(_drive_stream(sse_events, ["web_search"], monkeypatch))+ if e["type"] == "tool_start"+ ]+ assert starts[0]["arguments"]["query"] == ("tiger population, tiger conservation 2026")+++def test_queries_wins_over_the_deprecated_query(monkeypatch):+ # The spec marks `query` deprecated in favour of `queries`, so a stream+ # carrying both must be read from the current field.+ sse_events = [+ {+ "type": "response.output_item.done",+ "item": {+ "type": "web_search_call",+ "id": "ws_both",+ "action": {+ "type": "search",+ "query": "stale",+ "queries": ["current"],+ },+ },+ },+ {"type": "response.completed", "response": {}},+ ]+ starts = [+ e+ for e in _tool_events(_drive_stream(sse_events, ["web_search"], monkeypatch))+ if e["type"] == "tool_start"+ ]+ assert starts[0]["arguments"]["query"] == "current"+++def test_a_search_action_with_no_query_at_all_is_tolerated(monkeypatch):+ # Neither field is required by the spec.+ sse_events = [+ {+ "type": "response.output_item.done",+ "item": {"type": "web_search_call", "id": "ws_bare", "action": {"type": "search"}},+ },+ {"type": "response.completed", "response": {}},+ ]+ events = _tool_events(_drive_stream(sse_events, ["web_search"], monkeypatch))+ starts = [e for e in events if e["type"] == "tool_start"]+ ends = [e for e in events if e["type"] == "tool_end"]+ assert "query" not in starts[0]["arguments"]+ assert starts[0]["arguments"]["action_type"] == "search"+ assert ends[0]["result"] == ""diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsxindex 8ce45a92426..527483967b7 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx@@ -13,6 +13,7 @@ import {isSearchImagesToolResult,useToolAwaitingApproval,} from "@/features/chat";+import { openLink } from "@/lib/open-link";import { stringifyToolResult } from "@/lib/strip-ansi";import { memo } from "react";import { SearchImageThumb } from "./search-image";@@ -97,7 +98,16 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({// object here, and .trim() on one crashes the card that was meant to show the call.const query = toolArgText((args as { query?: unknown })?.query);const url = toolArgText((args as { url?: unknown })?.url).trim();- const isUrlFetch = !!url;+ // gpt-5.x agentic search: `open_page` carries a url, `find_in_page` a url and+ // a pattern. Older streams send neither, so a url with a pattern is the same+ // call by shape.+ const pattern = toolArgText((args as { pattern?: unknown })?.pattern);+ const actionType = toolArgText(+ (args as { action_type?: unknown })?.action_type,+ );+ const isFindInPage =+ actionType === "find_in_page" || (!!url && !!pattern.trim());+ const isUrlFetch = !!url && !isFindInPage;const rawImageQueries = (args as { image_queries?: unknown })?.image_queries;const imageQueries = Array.isArray(rawImageQueries)? rawImageQueries@@ -106,20 +116,21 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({.slice(0, 5): [];const imageLabel = imageQueries.join(", ");- const isImageOnly = !isUrlFetch && !query.trim() && imageQueries.length > 0;+ const isImageOnly =+ !isUrlFetch && !isFindInPage && !query.trim() && imageQueries.length > 0;// The header speaks for the result: a call that found nothing must not claim it did.const foundImages = isSearchImagesToolResult(result);+ // new URL() throws on the bare hosts the backend fetches, so mirror that+ // grammar or the card names no host for exactly the URLs it does fetch.+ const bareUrl = url.startsWith("//") ? url.slice(2) : url;+ const candidateUrl = isBareHostFetchedAsHttps(bareUrl)+ ? `https://${bareUrl}`+ : url;+ const safeUrl = isSafeHttpUrl(candidateUrl) ? candidateUrl : "";const displayDomain = (() => {- if (!url) return "";- // new URL() throws on the bare hosts the backend fetches, so mirror that- // grammar or the card names no host for exactly the URLs it does fetch.- const bare = url.startsWith("//") ? url.slice(2) : url;- const candidate = isBareHostFetchedAsHttps(bare) ? `https://${bare}` : url;+ if (!safeUrl) return "";try {- const parsed = new URL(candidate);- if (parsed.protocol !== "http:" && parsed.protocol !== "https:")- return "";- return parsed.hostname.replace(/^www\./, "");+ return new URL(safeUrl).hostname.replace(/^www\./, "");} catch {return "";}@@ -157,21 +168,27 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({><ToolFallbackTriggertoolName={- isUrlFetch- ? displayDomain- ? `Read ${displayDomain}`- : "Read page"- : isImageOnly- ? isRunning- ? `Finding images for “${imageLabel}”`- : foundImages- ? `Found images for “${imageLabel}”`- : `No images for “${imageLabel}”`- : query- ? imageLabel && foundImages- ? `Searched "${query}" · images for ${imageLabel}`- : `Searched "${query}"`- : "Web Search"+ isFindInPage+ ? // Neutral: the action carries no match status, so a finished call+ // is not evidence the pattern was there.+ pattern+ ? `Searched for "${pattern}" in ${displayDomain || "page"}`+ : `Searched ${displayDomain || "page"}`+ : isUrlFetch+ ? displayDomain+ ? `Read ${displayDomain}`+ : "Read page"+ : isImageOnly+ ? isRunning+ ? `Finding images for “${imageLabel}”`+ : foundImages+ ? `Found images for “${imageLabel}”`+ : `No images for “${imageLabel}”`+ : query+ ? imageLabel && foundImages+ ? `Searched "${query}" · images for ${imageLabel}`+ : `Searched "${query}"`+ : "Web Search"}status={status}icon={GlobeIcon}@@ -180,65 +197,106 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({{isRunning ? (<div className="flex items-center text-sm text-muted-foreground"><span>- {isUrlFetch ? (+ {isFindInPage ? (+ pattern ? (+ <>+ Finding “{pattern}” in {displayDomain || "page"}+ …+ </>+ ) : (+ <>Searching {displayDomain || "page"}…</>+ )+ ) : isUrlFetch ? (<>Reading {displayDomain || "page"}…</>) : isImageOnly ? (<>Finding images for “{imageLabel}”…</>- ) : (+ ) : query ? (<>Searching for “{query}”…</>+ ) : (+ <>Searching…</>)}</span></div>- ) : sources.length === 0 && images.length > 0 ? (+ ) : (<div className="flex flex-col gap-2">- <div- className="flex flex-wrap gap-1.5"- data-testid="web-search-images"- >- {images.map((entry) => (- <SearchImageThumb key={entry.id} entry={entry} size="strip" />- ))}- </div>- {resultText && (+ {/* The page a url action read. Above the body rather than inside one+ branch: the terminal citation backfill can replace this card's result+ with the run's sources, and the card must still name what it opened. */}+ {safeUrl ? (+ <a+ href={safeUrl}+ target="_blank"+ rel="noopener noreferrer"+ // Same as the Source pills below: a bare target="_blank" does+ // nothing in the Desktop webview, so hand the url to the opener.+ onClick={(e) => {+ if (openLink(safeUrl)) {+ e.preventDefault();+ }+ }}+ className="break-all text-xs text-primary underline-offset-4 hover:underline"+ >+ {url}+ </a>+ ) : null}+ {sources.length === 0 && images.length > 0 ? (+ <div className="flex flex-col gap-2">+ <div+ className="flex flex-wrap gap-1.5"+ data-testid="web-search-images"+ >+ {images.map((entry) => (+ <SearchImageThumb+ key={entry.id}+ entry={entry}+ size="strip"+ />+ ))}+ </div>+ {resultText && (+ <pre className="max-h-40 overflow-auto whitespace-pre-wrap break-words rounded bg-muted/50 p-2 text-xs">+ {resultText}+ </pre>+ )}+ </div>+ ) : sources.length > 0 ? (+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap gap-1.5">+ {sources.map((source, i) => (+ <Source+ key={`${source.url}-${i}`}+ href={source.url}+ variant="outline"+ size="sm"+ className="inline-flex items-center gap-1.5"+ >+ <SourceIcon url={source.url} size={3} />+ <SourceTitle>{source.title}</SourceTitle>+ </Source>+ ))}+ </div>+ {images.length > 0 && (+ <div+ className="flex flex-wrap gap-1.5"+ data-testid="web-search-images"+ >+ {images.map((entry) => (+ <SearchImageThumb+ key={entry.id}+ entry={entry}+ size="strip"+ />+ ))}+ </div>+ )}+ </div>+ ) : resultText ? (<pre className="max-h-40 overflow-auto whitespace-pre-wrap break-words rounded bg-muted/50 p-2 text-xs">{resultText}</pre>- )}- </div>- ) : sources.length > 0 ? (- <div className="flex flex-col gap-2">- <div className="flex flex-wrap gap-1.5">- {sources.map((source, i) => (- <Source- key={`${source.url}-${i}`}- href={source.url}- variant="outline"- size="sm"- className="inline-flex items-center gap-1.5"- >- <SourceIcon url={source.url} size={3} />- <SourceTitle>{source.title}</SourceTitle>- </Source>- ))}- </div>- {images.length > 0 && (- <div- className="flex flex-wrap gap-1.5"- data-testid="web-search-images"- >- {images.map((entry) => (- <SearchImageThumb key={entry.id} entry={entry} size="strip" />- ))}- </div>- )}- </div>- ) : resultText ? (- <div>- <pre className="max-h-40 overflow-auto whitespace-pre-wrap break-words rounded bg-muted/50 p-2 text-xs">- {resultText}- </pre>+ ) : null}</div>- ) : null}+ )}</ToolFallbackContent></ToolFallbackRoot>);diff --git a/studio/frontend/tests/web-search-action-variants.test.ts b/studio/frontend/tests/web-search-action-variants.test.tsnew file mode 100644index 00000000000..bc505bca609--- /dev/null+++ b/studio/frontend/tests/web-search-action-variants.test.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++const CARD = readFileSync(+ fileURLToPath(+ new URL(+ "../src/components/assistant-ui/tool-ui-web-search.tsx",+ import.meta.url,+ ),+ ),+ "utf8",+);++test("the card tells the three action types apart", () => {+ // Reading only `action.query` rendered open_page and find_in_page as an empty+ // `Searching ""`, which is the bug this branch exists for.+ assert.match(+ CARD,+ /actionType === "find_in_page" \|\| \(!!url && !!pattern\.trim\(\)\)/,+ );+ assert.match(CARD, /const isUrlFetch = !!url && !isFindInPage;/);+ // and an image-only call is still none of the above+ assert.match(CARD, /!isUrlFetch && !isFindInPage && !query\.trim\(\)/);+});++test("a finished find_in_page does not claim it found the pattern", () => {+ // The action names the pattern the model looked for and nothing about whether+ // it matched, so a completed call is not evidence that it did.+ assert.doesNotMatch(CARD, /`Found "\$\{pattern\}"/);+ assert.match(+ CARD,+ /`Searched for "\$\{pattern\}" in \$\{displayDomain \|\| "page"\}`/,+ );+});++test("the url variants show the page they read, whatever else the card has", () => {+ // open_page and find_in_page report no text of their own. The link also has to+ // survive the terminal citation backfill replacing this card's result with the+ // run's sources, which would otherwise take the sources branch and drop it.+ const body = CARD.slice(+ CARD.indexOf(" <ToolFallbackContent>"),+ CARD.indexOf("</ToolFallbackContent>"),+ );+ assert.notEqual(body.length, 0, "the card body moved");+ const link = body.indexOf("href={safeUrl}");+ assert.ok(link !== -1, "the link is gone");+ for (const branch of [+ "{sources.length === 0 && images.length > 0 ? (",+ ") : sources.length > 0 ? (",+ ") : resultText ? (",+ ]) {+ const at = body.indexOf(branch);+ assert.notEqual(at, -1, `branch moved: ${branch}`);+ assert.ok(link < at, `the link must render above ${branch.trim()}`);+ }+ // Only http(s) reaches an href: the url is provider-controlled.+ assert.match(+ CARD,+ /const safeUrl = isSafeHttpUrl\(candidateUrl\) \? candidateUrl : "";/,+ );+});++test("the read-page link opens in Desktop, not just the browser", () => {+ // A bare target="_blank" does nothing in the Tauri webview. Every external+ // link in the app pairs it with an opener; the Source pills in this same card+ // use openLink, so this one does too or Desktop users get a dead link.+ assert.match(CARD, /import \{ openLink \} from "@\/lib\/open-link";/);+ const anchor = CARD.slice(+ CARD.indexOf("href={safeUrl}"),+ CARD.indexOf("</a>", CARD.indexOf("href={safeUrl}")),+ );+ assert.notEqual(anchor.length, 0, "the link moved");+ assert.match(anchor, /onClick=\{\(e\) => \{/);+ assert.match(anchor, /openLink\(safeUrl\)/);+ assert.match(anchor, /e\.preventDefault\(\)/);+});