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: show web search images inline in chat (#9490)
Nilay7a04468d0742
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex f496305ccf9..ffcffaa0302 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -23751,6 +23751,7 @@ class LlamaCppBackend:from core.inference.tool_stream_exec import (accepts_kwarg,accepts_output_callback,+ search_images_kwargs,stream_tool_execution,)from core.inference.tools import (@@ -25466,6 +25467,7 @@ class LlamaCppBackend:)if accepts_output_callback(execute_tool):kwargs["output_callback"] = _output_callback+ kwargs.update(search_images_kwargs(execute_tool, _decision.tool_name))return execute_tool(_decision.tool_name,_decision.arguments,diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.pyindex 4a933c9e244..3780c5e6807 100644--- a/studio/backend/core/inference/safetensors_agentic.py+++ b/studio/backend/core/inference/safetensors_agentic.py@@ -453,6 +453,11 @@ def _accepts_output_callback(func: Callable[..., str]) -> bool:return _accepts_kwarg(func, "output_callback")+def _search_images_kwargs(func: Callable[..., str], tool_name: str) -> dict[str, bool]:+ from core.inference.tool_stream_exec import search_images_kwargs+ return search_images_kwargs(func, tool_name)++def _call_single_turn(single_turn, conversation: list, active_tools: list[dict]):"""Call a single-turn generator with active tool schemas when supported."""try:@@ -1339,6 +1344,7 @@ def run_safetensors_tool_loop()if _accepts_output_callback(execute_tool):kwargs["output_callback"] = _output_callback+ kwargs.update(_search_images_kwargs(execute_tool, _decision.tool_name))return execute_tool(_decision.tool_name, _decision.arguments, **kwargs)try:diff --git a/studio/backend/core/inference/search_images.py b/studio/backend/core/inference/search_images.pynew file mode 100644index 00000000000..8b0c648905f--- /dev/null+++ b/studio/backend/core/inference/search_images.py@@ -0,0 +1,625 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++# web_search image results: a registry keyed by opaque ids plus a thumbnail proxy,+# so neither the model nor the browser sees an image URL.++from __future__ import annotations++import io+import json+import re+import secrets+import threading+import time+from pathlib import Path+from typing import Any++from loggers import get_logger++logger = get_logger(__name__)++SEARCH_IMAGES_SENTINEL = "\n__WEB_IMAGES__:"+IMAGE_ID_RE = re.compile(r"^[0-9a-f]{12}$")++MAX_IMAGES_PER_SEARCH = 6+MAX_THUMBNAIL_BYTES = 3 * 1024 * 1024+THUMBNAIL_EDGE_PX = 320+THUMBNAIL_FETCH_TIMEOUT_S = 10+# Read from the header before decoding. Low because draft() only subsamples JPEG:+# a 77 KB 6000x4000 PNG decodes to ~100 MB of RGB.+MAX_IMAGE_PIXELS = 6_000_000+_ALLOWED_FORMATS = frozenset({"JPEG", "PNG", "GIF", "WEBP"})++_REGISTRY_TTL_S = 24 * 3600+_REGISTRY_MAX_ENTRIES = 2000+# The cache outlives the registry, so reopened chats keep their pictures.+_CACHE_MAX_FILES = 2000+_CACHE_DIRNAME = "search_thumbs"+_MAX_CONCURRENT_FETCHES = 4++_registry: dict[str, dict[str, Any]] = {}+_registry_lock = threading.Lock()+# Bumped by clear_cache. A fetch that started before the clear must not publish its+# thumbnail after it: the write is done under _registry_lock and skipped if this moved.+_cache_generation = 0+# The generation at which a CLEAR-EVERYTHING last ran, and the generation at which each+# individually reaped id was taken. A selective clear must not abort an in-flight fetch for+# an id it deliberately spared: thumbnail_bytes would answer None, the endpoint 404s, and+# SearchImageThumb renders nothing and never retries -- its effect depends only on (id,+# nearViewport), so "re-fetches on the next request" is not true, there is no next request.+# Bounded; on overflow the per-id record is dropped and the full-clear generation is moved+# instead, which over-aborts rather than republishing a thumbnail a clear removed.+_full_clear_generation = 0+_reaped_at: dict[str, int] = {}+_REAPED_AT_MAX = 4096+# The newest generation whose per-id records have been dropped to stay under that cap. A fetch+# that started at or after this is still answered exactly, because nothing covering it was+# dropped; only one older than every record we still hold has to be given up on. Fetches are+# bounded by THUMBNAIL_FETCH_TIMEOUT_S, so outliving 4096 reaped images is not a real case.+_reaped_floor_generation = 0+# Ids whose files a clear could not unlink -- on Windows another process holding the+# JPEG open is enough. The cache-first read and the sidecar read both go around the+# registry, so without this they would go on serving a picture the user had cleared.+_cleared_unservable: set[str] = set()+_fetch_slots = threading.BoundedSemaphore(_MAX_CONCURRENT_FETCHES)+_inflight: dict[str, threading.Lock] = {}+_inflight_lock = threading.Lock()+++def search_images_enabled() -> bool:+ try:+ from storage.studio_db import list_chat_settings+ return list_chat_settings().get("searchImages") is True+ except Exception: # noqa: BLE001 - a settings read must never break a tool call+ return False+++def _clean_text(value: Any, limit: int = 200) -> str:+ text = " ".join(str(value or "").split())+ return text[:limit]+++def _domain_of(url: str) -> str:+ from urllib.parse import urlparse+ try:+ host = (urlparse(url).hostname or "").lower()+ except ValueError:+ return ""+ return host[4:] if host.startswith("www.") else host+++def _names_public_host(url: str) -> bool:+ # Pre-filter only; the fetch re-resolves and pins the host regardless.+ import ipaddress+ from urllib.parse import urlparse++ try:+ host = (urlparse(url).hostname or "").lower().rstrip(".")+ except ValueError:+ return False+ if not host or host == "localhost" or host.endswith((".localhost", ".local", ".internal")):+ return False+ try:+ return ipaddress.ip_address(host).is_global+ except ValueError:+ return True+++def _prune_registry_locked(now: float) -> None:+ expired = [key for key, entry in _registry.items() if now - entry["created"] > _REGISTRY_TTL_S]+ for key in expired:+ _registry.pop(key, None)+ if len(_registry) > _REGISTRY_MAX_ENTRIES:+ oldest = sorted(_registry.items(), key = lambda item: item[1]["created"])+ for key, _entry in oldest[: len(_registry) - _REGISTRY_MAX_ENTRIES]:+ _registry.pop(key, None)+++def register_images(+ raw_results: list[dict[str, Any]],+ website_policy: dict | None = None,+ max_images: int = MAX_IMAGES_PER_SEARCH,+ subject: str | None = None,+ expected_generation: int | None = None,+) -> list[dict[str, str]]:+ # Public entries only; the URLs stay in this process.+ from .web_access_policy import check_url_access++ public: list[dict[str, str]] = []+ persist: list[tuple[str, dict[str, Any], int]] = []+ now = time.monotonic()+ with _registry_lock:+ generation = _cache_generation+ if expected_generation is not None and expected_generation != generation:+ return []+ _prune_registry_locked(now)+ for item in raw_results:+ if len(public) >= max_images:+ break+ if not isinstance(item, dict):+ continue+ thumbnail = str(item.get("thumbnail") or item.get("image") or "").strip()+ source = str(item.get("url") or "").strip()+ if not thumbnail or not source:+ continue+ ok_thumb, _r1, _h1 = check_url_access(thumbnail, website_policy)+ ok_source, _r2, _h2 = check_url_access(source, website_policy)+ if not (ok_thumb and ok_source):+ continue+ if not (_names_public_host(thumbnail) and _names_public_host(source)):+ continue+ image_id = secrets.token_hex(6)+ _registry[image_id] = {+ "thumbnail": thumbnail,+ "source": source,+ "created": now,+ # Kept with the entry: the proxy fetch happens on a later request, and+ # without it every redirect hop would be re-checked against no policy.+ "policy": website_policy,+ }+ entry = {+ "id": image_id,+ "title": _clean_text(item.get("title")),+ "domain": _domain_of(source)[:100],+ "source": source[:2048],+ }+ if subject:+ entry["subject"] = _clean_text(subject, 80)+ public.append(entry)+ persist.append((image_id, _registry[image_id], generation))+ for image_id, stored, registered_generation in persist:+ _persist_entry(image_id, stored, registered_generation)+ if persist:+ # Here too, not only after a thumbnail write: a user who never opens a picture+ # would otherwise accumulate sidecars with nothing ever bounding them.+ _evict_cache()+ return public+++def cache_generation() -> int:+ with _registry_lock:+ return _cache_generation+++def _lookup_locked(image_id: str) -> dict[str, Any] | None:+ """Registry read with the TTL applied. The caller holds ``_registry_lock``."""+ entry = _registry.get(image_id)+ if entry is None:+ return None+ if time.monotonic() - entry["created"] > _REGISTRY_TTL_S:+ _registry.pop(image_id, None)+ return None+ return dict(entry)+++def lookup_image(image_id: str) -> dict[str, Any] | None:+ if not IMAGE_ID_RE.fullmatch(image_id or ""):+ return None+ with _registry_lock:+ return _lookup_locked(image_id)+++def format_images_for_model(entries: list[dict[str, str]]) -> str:+ if not entries:+ return ""+ lines = [+ "Images from this search. To show one, write its token exactly as given, e.g. "+ "[[img:" + entries[0]["id"] + "]], on its own line after the text it illustrates. "+ "Use only these tokens, and only where the image clearly matches. For a picture of "+ "a specific thing you name, call web_search with image_queries instead.",+ ]+ for entry in entries:+ label = entry["title"] or "(untitled)"+ domain = f" — {entry['domain']}" if entry["domain"] else ""+ lines.append(f"- [[img:{entry['id']}]] {label}{domain}")+ return "\n".join(lines)+++def images_envelope(entries: list[dict[str, str]]) -> str:+ if not entries:+ return ""+ return SEARCH_IMAGES_SENTINEL + json.dumps(entries, ensure_ascii = True, separators = (",", ":"))+++def is_image_entry(entry: object) -> bool:+ return (+ isinstance(entry, dict)+ and isinstance(entry.get("id"), str)+ and bool(IMAGE_ID_RE.fullmatch(entry["id"]))+ and isinstance(entry.get("title"), str)+ and isinstance(entry.get("domain"), str)+ and isinstance(entry.get("source"), str)+ and (entry.get("subject") is None or isinstance(entry.get("subject"), str))+ )+++def split_images_envelope(result: str) -> tuple[str, list[dict[str, str]]]:+ # Payload ends at the next "\n__", as _strip_files_sentinel and the frontend do,+ # so a sibling sentinel after ours does not make it unreadable.+ start = result.rfind(SEARCH_IMAGES_SENTINEL)+ if start == -1:+ return result, []+ payload_start = start + len(SEARCH_IMAGES_SENTINEL)+ end = result.find("\n__", payload_start)+ if end == -1:+ end = len(result)+ try:+ entries = json.loads(result[payload_start:end])+ except (ValueError, RecursionError):+ return result, []+ if not isinstance(entries, list) or not entries or not all(is_image_entry(e) for e in entries):+ return result, []+ return (result[:start] + result[end:]).rstrip(), entries+++def strip_images_suffix(result: str) -> str:+ return split_images_envelope(result)[0]+++def _cache_dir() -> Path:+ from utils.paths import ensure_dir, studio_root+ return ensure_dir(studio_root() / _CACHE_DIRNAME)+++def _cache_path(image_id: str) -> Path:+ return _cache_dir() / f"{image_id}.jpg"+++def _meta_path(image_id: str) -> Path:+ return _cache_dir() / f"{image_id}.json"+++def _persist_entry(image_id: str, entry: dict[str, Any], generation: int) -> None:+ """Keep an id resolvable across a restart.++ The envelope in saved chat history carries ids, not URLs, and the browser only+ asks for a thumbnail once it nears the viewport -- so a picture that was never+ scrolled to has no bytes on disk, and the in-memory registry does not survive the+ process. Reopening that chat used to 404 forever. This is the same information the+ cached JPEG already reveals, and `clear_cache` removes both together.+ """+ try:+ payload = json.dumps(+ {+ "thumbnail": entry["thumbnail"],+ "source": entry["source"],+ "policy": entry.get("policy"),+ },+ ensure_ascii = True,+ )+ with _registry_lock:+ # Per id, like the thumbnail write: a selective clear bumps the generation+ # without touching this image, and dropping its sidecar then costs the id its+ # only way back after a restart.+ if _reaped_since_locked(image_id, generation):+ return+ # writer-unique, like the JPEG: a torn read must not be possible.+ tmp = _meta_path(image_id).with_suffix(f".{secrets.token_hex(4)}.tmp")+ tmp.write_text(payload, encoding = "utf-8")+ tmp.replace(_meta_path(image_id))+ except (OSError, TypeError, ValueError) as exc:+ # Best effort: losing this costs a 404 on an unseen picture, never the search.+ logger.debug("search image metadata write failed: %s", exc)+++def _load_persisted_entry(image_id: str) -> dict[str, Any] | None:+ try:+ raw = json.loads(_meta_path(image_id).read_text(encoding = "utf-8"))+ except (OSError, ValueError):+ return None+ if not isinstance(raw, dict):+ return None+ thumbnail = raw.get("thumbnail")+ source = raw.get("source")+ if not isinstance(thumbnail, str) or not isinstance(source, str):+ return None+ # Re-checked on the way back in: what was public when it was written is not+ # necessarily public now, and this bypasses register_images' own gate.+ if not (_names_public_host(thumbnail) and _names_public_host(source)):+ return None+ policy = raw.get("policy")+ return {+ "thumbnail": thumbnail,+ "source": source,+ # No TTL: a disk entry follows the cache beside it, which is capped by file+ # count rather than age. time.monotonic() from a previous process is meaningless.+ "created": time.monotonic(),+ "policy": policy if isinstance(policy, dict) else None,+ }+++def _evict_cache() -> None:+ # Capped per kind. Metadata is written for every registered image but bytes only+ # for the ones actually viewed, so the sidecars outnumber the JPEGs and need their+ # own bound; and an evicted JPEG keeps its sidecar, which is what lets it be+ # fetched again rather than 404.+ for pattern in ("*.jpg", "*.json"):+ try:+ files = sorted(_cache_dir().glob(pattern), key = lambda p: p.stat().st_mtime)+ except OSError:+ continue+ for path in files[: max(0, len(files) - _CACHE_MAX_FILES)]:+ try:+ path.unlink()+ except OSError:+ pass+ try:+ for stale in _cache_dir().glob("*.tmp"):+ if time.time() - stale.stat().st_mtime > 300:+ stale.unlink(missing_ok = True)+ except OSError:+ pass+++def _encode_thumbnail(raw: bytes) -> bytes | None:+ from PIL import Image++ # Pillow's own process-wide bomb check is left at its default.+ try:+ with Image.open(io.BytesIO(raw)) as im:+ if im.format not in _ALLOWED_FORMATS:+ return None+ width, height = im.size+ if width <= 0 or height <= 0 or width * height > MAX_IMAGE_PIXELS:+ return None+ if getattr(im, "n_frames", 1) > 1:+ im.seek(0)+ im.draft("RGB", (THUMBNAIL_EDGE_PX * 2, THUMBNAIL_EDGE_PX * 2))+ converted = im.convert("RGBA") if im.mode in ("RGBA", "LA", "P") else im.convert("RGB")+ if converted.mode == "RGBA":+ flat = Image.new("RGB", converted.size, (255, 255, 255))+ flat.paste(converted, mask = converted.getchannel("A"))+ converted = flat+ converted.thumbnail((THUMBNAIL_EDGE_PX, THUMBNAIL_EDGE_PX), Image.LANCZOS)+ out = io.BytesIO()+ converted.save(out, format = "JPEG", quality = 82, optimize = True)+ return out.getvalue()+ except Exception as exc: # noqa: BLE001 - provider bytes; any decode failure is a miss+ logger.debug("search thumbnail decode failed (%s)", type(exc).__name__)+ return None+++def _fetch_thumbnail_bytes(url: str, website_policy: dict | None = None) -> bytes | None:+ from . import tools++ error, body, _content_type = tools._fetch_url_raw(+ url,+ timeout = THUMBNAIL_FETCH_TIMEOUT_S,+ extra_headers = {"Accept": "image/*"},+ deadline = time.monotonic() + THUMBNAIL_FETCH_TIMEOUT_S * 2,+ raw_bytes_max = MAX_THUMBNAIL_BYTES,+ website_policy = website_policy,+ )+ if error is not None or not isinstance(body, (bytes, bytearray)) or not body:+ if error is not None:+ logger.debug("search thumbnail fetch refused: %s", error)+ return None+ return _encode_thumbnail(bytes(body))+++def _drop_if_cleared(image_id: str) -> bool:+ """False while a clear's leftover files for this id are still on disk.++ The unlink is retried on the way through: the process that had the JPEG open+ has usually let go by the next request, and once both files are gone the id is+ ordinary again -- nothing resolves it, so it 404s like any other unknown one.+ """+ with _registry_lock:+ if image_id not in _cleared_unservable:+ return True+ for path in (_cache_path(image_id), _meta_path(image_id)):+ try:+ path.unlink(missing_ok = True)+ except OSError:+ return False+ _cleared_unservable.discard(image_id)+ return True+++def thumbnail_bytes(image_id: str) -> bytes | None:+ # Cache first: it survives the restart the in-memory registry does not.+ if not IMAGE_ID_RE.fullmatch(image_id or ""):+ return None+ # Ahead of that read and of the sidecar below, which both go around the registry.+ if not _drop_if_cleared(image_id):+ return None+ path = _cache_path(image_id)+ try:+ if path.is_file():+ return path.read_bytes()+ except OSError:+ pass+ # Generation and entry in ONE acquisition, generation first. Taking them+ # separately let a clear land in the gap: this call would then read the POST-clear+ # generation, the check before the write would match, and the thumbnail the clear+ # had just deleted would be written back. Reading it first is the safe order --+ # a clear after this point leaves us holding a stale value, which fails the check.+ with _registry_lock:+ generation = _cache_generation+ entry = _lookup_locked(image_id)+ if entry is None:+ # Not in memory: the process may have restarted since the search. The metadata+ # on disk outlives it, the same way the cached bytes do.+ entry = _load_persisted_entry(image_id)+ if entry is None:+ return None++ with _inflight_lock:+ gate = _inflight.setdefault(image_id, threading.Lock())+ try:+ with gate:+ try:+ if path.is_file():+ return path.read_bytes()+ except OSError:+ pass+ with _fetch_slots:+ data = _fetch_thumbnail_bytes(entry["thumbnail"], entry.get("policy"))+ if data is None:+ return None+ with _registry_lock:+ if _reaped_since_locked(image_id, generation):+ # A clear that covered THIS id landed while the fetch was in flight.+ # The chat that asked for it is gone, so publish nothing and hand back+ # nothing -- writing here would restore a thumbnail the clear had+ # removed, and the cache-first path above would keep serving it.+ #+ # Asked per id, not off the bare generation: a selective clear bumps+ # that too, and aborting on it took down fetches for the images the+ # clear had gone out of its way to spare.+ return None+ try:+ # Writer-unique: racing writers must not publish a torn JPEG.+ tmp = path.with_suffix(f".{secrets.token_hex(4)}.tmp")+ tmp.write_bytes(data)+ tmp.replace(path)+ except OSError as exc:+ logger.debug("search thumbnail cache write failed: %s", exc)+ try:+ tmp.unlink(missing_ok = True)+ except OSError:+ pass+ # Outside the lock: a glob plus a stat per file, and nothing here needs it.+ _evict_cache()+ return data+ finally:+ with _inflight_lock:+ # Only drop the gate this call owns.+ if _inflight.get(image_id) is gate and not gate.locked():+ _inflight.pop(image_id, None)+++def registered_image_ids() -> set[str] | None:+ """Every id a clear starting now would be responsible for, in memory and on disk.++ Taken before the caller's slow work so the reap that follows can be limited to it.+ A clear is global while the chat delete it accompanies is not, so anything that+ registers after this snapshot belongs to a chat the delete is keeping.+ """+ ids: set[str] = set()+ with _registry_lock:+ ids.update(_registry)+ for pattern in ("*.jpg", "*.json"):+ try:+ ids.update(path.stem for path in _cache_dir().glob(pattern))+ except OSError:+ # Unreadable dir, so the snapshot is incomplete and cannot bound a reap.+ # None is the sentinel clear_cache reads as "clear everything", which is+ # what a clear did before this snapshot existed. An empty set is NOT that+ # sentinel: it is a selective reap of nothing, and would leave the+ # registry populated and its images still fetchable after a clear.+ return None+ return ids+++def snapshot_and_fence_registrations() -> set[str] | None:+ """``registered_image_ids``, plus a fence closing the window it opens.++ Bounding the reap to a snapshot means anything registered after it is spared. The+ reasoning was that such an image belongs to a chat created since, which the clear is+ keeping -- but a lookup already running when the clear started belongs to an answer the+ clear is DELETING, and it publishes into that same window. `/search-images/lookup` is+ the plain case: it carries no thread, so no cancellation reaches it, and it samples the+ cache generation on entry, before the reap moves it. Its images then survived Clear all+ with their sidecars, which say what was searched for.++ Bumping the generation HERE, at the clear boundary rather than at the reap seconds+ later, refuses exactly those: ``register_images`` compares against the generation its+ caller sampled, so work that started before this moment publishes nothing. Work that+ starts after samples the new value, registers normally, and is spared as intended.++ The bump is inside the same lock as the registry read, so a registration cannot slip+ between being missed by the snapshot and being caught by the fence. It does not abort+ in-flight FETCHES: those are keyed per id now, and a bare generation move is not one of+ the signals they read.+ """+ global _cache_generation+ ids: set[str] = set()+ with _registry_lock:+ ids.update(_registry)+ _cache_generation += 1+ for pattern in ("*.jpg", "*.json"):+ try:+ ids.update(path.stem for path in _cache_dir().glob(pattern))+ except OSError:+ # Same fallback as registered_image_ids: an incomplete snapshot cannot bound a+ # reap, and None is the sentinel clear_cache reads as "clear everything".+ return None+ return ids+++def _reaped_since_locked(image_id: str, generation: int) -> bool:+ """Whether a clear covering ``image_id`` landed after ``generation``. Caller holds the lock."""+ if _full_clear_generation > generation:+ return True+ if generation < _reaped_floor_generation:+ # Older than every record still held, so this cannot be shown to have been spared.+ return True+ return _reaped_at.get(image_id, 0) > generation+++def clear_cache(only_ids: set[str] | None = None) -> None:+ """Drop registered images and their cached bytes. Called when the user clears all+ chats: the thumbnails say what was searched for.++ ``only_ids`` limits the reap to a snapshot taken before the caller's slow work, so+ an image registered meanwhile -- by another tab or the LAN listener, for a chat the+ clear is not deleting -- keeps its bytes instead of 404ing out of ``thumbnail_bytes``.+ The generation still bumps either way -- ``register_images`` compares against it to+ refuse a registration racing a clear -- but the in-flight fetch check is per id, so a+ spared image's fetch is left alone. Aborting it would 404 a card that never retries.+ """+ global _cache_generation, _full_clear_generation, _reaped_floor_generation+ # The unlinks are under the lock too, so an in-flight fetch cannot slip its write+ # in between the bump and the delete and leave a cleared thumbnail on disk.+ with _registry_lock:+ if only_ids is None:+ _registry.clear()+ else:+ for image_id in only_ids:+ _registry.pop(image_id, None)+ _cache_generation += 1+ if only_ids is None:+ # Nothing survives, so every in-flight fetch has to abort. One number says so+ # for all of them, including ids this process has never seen.+ _full_clear_generation = _cache_generation+ _reaped_at.clear()+ else:+ if len(_reaped_at) + len(only_ids) > _REAPED_AT_MAX:+ # Out of room. Drop the OLDEST records rather than promoting this to a+ # full clear: doing that aborts every fetch in flight, including ones for+ # images this clear deliberately spared, and an aborted fetch is not a+ # cheap retry -- the card 404s and useSearchThumbnail never asks again.+ # Raising the floor instead gives up only on fetches older than every+ # record still held, which the fetch timeout makes unreachable in practice.+ keep_from = sorted(_reaped_at.values())[len(_reaped_at) // 2 :]+ floor = keep_from[0] - 1 if keep_from else _cache_generation+ for stale_id in [key for key, at in _reaped_at.items() if at <= floor]:+ _reaped_at.pop(stale_id, None)+ _reaped_floor_generation = max(_reaped_floor_generation, floor)+ for image_id in only_ids:+ _reaped_at[image_id] = _cache_generation+ for pattern in ("*.jpg", "*.json", "*.tmp"):+ try:+ paths = list(_cache_dir().glob(pattern))+ except OSError:+ continue+ for path in paths:+ # `.tmp` stems carry a writer suffix, so they never match a snapshot id+ # and are always swept: one was never servable, and a torn write left+ # behind by a crashed fetch has no owner to spare it for.+ if only_ids is not None and pattern != "*.tmp" and path.stem not in only_ids:+ continue+ # Per file, as _evict_cache does: one that cannot be unlinked --+ # a JPEG another process holds open on Windows -- must not leave+ # every later one on disk, where the cache-first read in+ # thumbnail_bytes would go on serving it after a clear.+ try:+ path.unlink(missing_ok = True)+ except OSError:+ # Still on disk, so remember the id and refuse to serve it until+ # the unlink does land. `.jpg`/`.json` share a stem; a `.tmp` was+ # never servable, and its stem carries the writer suffix.+ if pattern != "*.tmp":+ _cleared_unservable.add(path.stem)diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.pyindex 9b776be13d7..66524c94881 100644--- a/studio/backend/core/inference/studio_tool_loop.py+++ b/studio/backend/core/inference/studio_tool_loop.py@@ -74,6 +74,7 @@ from core.inference.tool_stream_exec import (TOOL_HEARTBEAT_INTERVAL_S,accepts_kwarg,accepts_output_callback,+ search_images_kwargs,stream_tool_execution,)from core.inference.tools import build_rag_autoinject, execute_tool, is_high_risk_tool_call@@ -1277,6 +1278,7 @@ async def stream_with_studio_tools(passif accepts_output_callback(execute_tool):kwargs["output_callback"] = output_callback+ kwargs.update(search_images_kwargs(execute_tool, call.tool_name))return execute_tool(call.tool_name, call.arguments, **kwargs)# The same wrapper the local loops run tools through: live stdout fordiff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.pyindex d246e2da68a..54b1e60a2cb 100644--- a/studio/backend/core/inference/tool_loop_controller.py+++ b/studio/backend/core/inference/tool_loop_controller.py@@ -254,6 +254,17 @@ def status_for_tool(tool_name: str, arguments: Mapping[str, Any]) -> str:host = host[4:]return f"Reading: {host}"return "Reading page..."+ image_queries = arguments.get("image_queries")+ images = (+ ", ".join(str(q) for q in image_queries[:5])+ if isinstance(image_queries, list) and image_queries+ else ""+ )+ query = str(arguments.get("query") or "").strip()+ if images and not query:+ return f"Finding images: {images}"+ if images:+ return f"Searching: {query} (images: {images})"return f"Searching: {arguments.get('query', '')}"if tool_name == "python":preview = str(arguments.get("code") or "").strip().split("\n")[0][:60]@@ -360,6 +371,9 @@ _SANDBOX_TOOLS = frozenset({"python", "terminal"})def strip_result_for_model(result: str, tool_name: "str | None" = None) -> str:"""Remove frontend-only sentinels (image paths, RAG source map) beforefeeding the result back to the model."""+ if tool_name is None or tool_name == "web_search":+ from .search_images import strip_images_suffix+ result = strip_images_suffix(result)result = _strip_mcp_image_suffix(result)if tool_name is None or tool_name in _SANDBOX_TOOLS:result = _strip_files_sentinel(result)diff --git a/studio/backend/core/inference/tool_stream_exec.py b/studio/backend/core/inference/tool_stream_exec.pyindex 58cd560d48c..9fa01933e6d 100644--- a/studio/backend/core/inference/tool_stream_exec.py+++ b/studio/backend/core/inference/tool_stream_exec.py@@ -52,6 +52,20 @@ def accepts_output_callback(func: Callable[..., str]) -> bool:return accepts_kwarg(func, "output_callback")+def search_images_kwargs(func: Callable[..., str], tool_name: str) -> dict[str, bool]:+ """``{"search_images": True}`` when web_search should also return images, else ``{}``.++ Read per call rather than per request so the Settings toggle applies to the+ next search without a reload, and only for web_search so other tools never+ pay the settings read.+ """+ if tool_name != "web_search" or not accepts_kwarg(func, "search_images"):+ return {}+ from .search_images import search_images_enabled++ return {"search_images": True} if search_images_enabled() else {}++# Cadence of heartbeat events while a tool blocks with no output. Well under# common proxy idle caps (Cloudflare ~100 s, nginx default 60 s).TOOL_HEARTBEAT_INTERVAL_S = 10.0diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 51b6d7efade..444c5d7babb 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -6,6 +6,7 @@import astimport codecs+import copyimport fnmatchimport functoolsimport hashlib@@ -9390,6 +9391,25 @@ WEB_SEARCH_TOOL = {}+def web_search_tool_with_images() -> dict:+ # web_search plus image_queries, offered while the Search images setting is on.+ tool = copy.deepcopy(WEB_SEARCH_TOOL)+ fn = tool["function"]+ fn["description"] += (+ " To show pictures, pass image_queries: the exact names of the specific things you "+ 'will mention, one per entry (e.g. ["German Shepherd", "Labrador"]), never a list '+ "title. Each returns an [[img:...]] token; put it on its own line under that item. "+ "image_queries may also be sent alone after the answer."+ )+ fn["parameters"]["properties"]["image_queries"] = {+ "type": "array",+ "items": {"type": "string"},+ "maxItems": 5,+ "description": "Specific things to fetch one picture each for, named exactly as in your answer.",+ }+ return tool++def _build_sandbox_paths_note() -> str:"""Platform and working-directory note, on BOTH tool descriptions.@@ -10022,6 +10042,7 @@ def execute_tool(conversation_budget_tokens: int | None = None,conversation_token_counter = None,context_tokens = _UNSET_CONTEXT_TOKENS,+ search_images: bool = False,) -> str:"""Execute a tool by name with the given arguments; returns a string.@@ -10125,6 +10146,8 @@ def execute_tool(timeout = effective_timeout,cancel_event = cancel_event,website_policy = website_policy,+ include_images = search_images,+ image_queries = arguments.get("image_queries"),)# Both run with the session's sandbox as cwd, so a chat deleted mid-call# must not unlink it from under them.@@ -11355,9 +11378,14 @@ def _fetch_url_raw(deadline: float | None = None,cancel_event = None,website_policy: dict | None = None,-) -> tuple[str | None, str, str]:+ raw_bytes_max: int | None = None,+) -> tuple[str | None, "str | bytes", str]:"""Fetch a URL with SSRF protection; return ``(error, body_text, content_type)``.+ ``raw_bytes_max`` switches to binary mode: the body is returned as ``bytes``+ untouched (no PDF or text handling) and refused past that many bytes. The+ same scheme, host, redirect and budget gates apply either way.+``error`` is a user-facing message string when the fetch failed (theexisting "Blocked:" / "Failed to fetch URL:" wording), else ``None``.Blocks private/loopback/link-local targets and caps the download size.@@ -11478,8 +11506,13 @@ def _fetch_url_raw(# Success: read the capped body enforcing the budget between chunks# (see _read_capped_body), so a slow-drip server can't stretch a# single resp.read past the deadline.- declared_pdf = content_type == "application/pdf"- read_limit = _MAX_PDF_FETCH_BYTES + 1 if declared_pdf else max_bytes+ declared_pdf = raw_bytes_max is None and content_type == "application/pdf"+ if raw_bytes_max is not None:+ read_limit = raw_bytes_max + 1+ elif declared_pdf:+ read_limit = _MAX_PDF_FETCH_BYTES + 1+ else:+ read_limit = max_bytesbody_error, raw_bytes = _read_capped_body(resp,read_limit,@@ -11492,6 +11525,10 @@ def _fetch_url_raw(# A missing or wrong PDF MIME type is common: once the initial text-sized# read identifies PDF magic, finish the bounded download to reach the EOF xref.+ if raw_bytes_max is not None:+ if len(raw_bytes) > raw_bytes_max:+ return f"(content exceeds the {raw_bytes_max} byte limit)", "", content_type+ return None, raw_bytes, content_typeif not declared_pdf and len(raw_bytes) == max_bytes and _has_pdf_magic(raw_bytes):tail_error, tail = _read_capped_body(resp,@@ -12065,6 +12102,48 @@ def _search_failure_message(exc: BaseException, timeout: int) -> str:return f"Search failed: {exc}"+def _image_search_or_none(subjects: list, timeout, cancel_event, website_policy) -> "str | None":+ """``_image_search`` that reports a failure as None instead of raising.++ Every caller sits inside ``_web_search``'s own ``except``, which would turn a+ raise into "Search failed: ..." and throw away the text results the search had+ already found. A picture is a garnish: it must not become the answer.+ """+ try:+ return _image_search(+ subjects,+ timeout = timeout,+ cancel_event = cancel_event,+ website_policy = website_policy,+ )+ except Exception as exc: # noqa: BLE001 - a garnish must not become the answer+ logger.debug("image lookup failed (%s)", type(exc).__name__)+ return None+++def _empty_result_with_requested_images(+ empty_text: str, subjects: list, include_images: bool, timeout, cancel_event, website_policy+) -> str:+ """``empty_text`` plus the pictures the model asked for by name, if any.++ An ``image_queries`` call is an explicit request, and it succeeds on its own when+ sent without a query -- so returning the bare "No results found." because the TEXT+ sweep came back empty dropped images that were there to be had. Only the named+ subjects are looked up here; the per-query image pile has no answer to garnish.+ """+ if not subjects:+ return empty_text+ if not include_images:+ # Replayed history keeps teaching the parameter; say so, don't drop it.+ return empty_text + "\n\n---\n\n" + IMAGE_SEARCH_DISABLED+ if cancel_event is not None and cancel_event.is_set():+ return empty_text+ found = _image_search_or_none(subjects, timeout, cancel_event, website_policy)+ if found is None:+ return empty_text+ return empty_text + "\n\n---\n\n" + found++def _web_search(query: str,max_results: int = 5,@@ -12072,11 +12151,17 @@ def _web_search(url: str | None = None,cancel_event = None,website_policy: dict | None = None,+ include_images: bool = False,+ image_queries = None,) -> str:"""Search the web and return formatted results.ddgs fans the query out across its search engines, so a single engine refusing is alreadycovered. If ``url`` is provided, fetches that page directly instead of searching.+ ``include_images`` adds image results registered server-side and offered to the model+ as ``[[img:<id>]]`` tokens, with a frontend-only envelope appended: one picture per+ ``image_queries`` subject when the model named them, else a handful for the query.+ ``image_queries`` alone (no query) is a pure image lookup."""# Direct URL fetch mode.if url and url.strip():@@ -12088,6 +12173,17 @@ def _web_search(website_policy = website_policy,)+ subjects = _clean_image_queries(image_queries)+ if subjects and not (query and query.strip()):+ if not include_images:+ return IMAGE_SEARCH_DISABLED+ # Ahead of the try below, so this one has to carry its own guard: execute_tool+ # returns a string for every input, and a raise here would escape _web_search.+ found = _image_search_or_none(subjects, timeout, cancel_event, website_policy)+ if found is None:+ return "No images found for: " + ", ".join(subjects)+ return found+if not query or not query.strip():return "No query provided."# A disconnect sets cancel_event; DDGS.text() is blocking and cannot be@@ -12109,11 +12205,19 @@ def _web_search((website_policy or {}).get(key) for key in ("allowedDomains", "blockedDomains"))wanted = max_results * _POLICY_OVERFETCH if restricted else max_results- results = DDGS(timeout = timeout).text(effective_query, max_results = wanted)+ client = DDGS(timeout = timeout)+ results = client.text(effective_query, max_results = wanted)if cancel_event is not None and cancel_event.is_set():return "Search cancelled."if not results:- return EMPTY_SEARCH_RESULTS[0]+ return _empty_result_with_requested_images(+ EMPTY_SEARCH_RESULTS[0],+ subjects,+ include_images,+ timeout,+ cancel_event,+ website_policy,+ )parts = []for r in results:if len(parts) >= max_results:@@ -12126,16 +12230,186 @@ def _web_search(snippet = " ".join(str(r.get("body") or "").split())parts.append(f"Title: {title}\nURL: {href}\nSnippet: {snippet}")if not parts:- return EMPTY_SEARCH_RESULTS[1]+ return _empty_result_with_requested_images(+ EMPTY_SEARCH_RESULTS[1],+ subjects,+ include_images,+ timeout,+ cancel_event,+ website_policy,+ )text = "\n\n---\n\n".join(parts)text += ("\n\n---\n\nIMPORTANT: These are only short snippets. ""To get the full page content, call web_search with "'the url parameter (e.g. {"url": "<URL>"}).')+ if include_images and subjects:+ # The model named what it will show: one picture per subject, no generic pile.+ found = _image_search_or_none(subjects, timeout, cancel_event, website_policy)+ if found is not None:+ text += "\n\n---\n\n" + found+ elif include_images:+ text += _web_search_images_suffix(+ client,+ effective_query,+ wanted,+ cancel_event,+ website_policy,+ )+ elif subjects:+ # Replayed history keeps teaching the parameter; say so, don't drop it.+ text += "\n\n---\n\n" + IMAGE_SEARCH_DISABLEDreturn text+ except Exception as e:+ failure = _search_failure_message(e, timeout)+ # ddgs signals an empty sweep by RAISING, so that exit is an empty result too+ # and owes the named subjects their pictures. A genuine failure keeps its+ # message alone: pictures under an error read as a partial answer.+ if failure == EMPTY_SEARCH_RESULTS[0]:+ return _empty_result_with_requested_images(+ failure,+ subjects,+ include_images,+ timeout,+ cancel_event,+ website_policy,+ )+ return failure+++IMAGE_SEARCH_MAX_QUERIES = 5+IMAGE_SEARCH_PER_QUERY = 2+IMAGE_SEARCH_DISABLED = (+ "Image search is turned off. It can be enabled under Settings > Chat > Web search."+)+++def _clean_image_queries(queries) -> list[str]:+ # Strings only, trimmed, deduped case-insensitively, capped; anything else is [].+ if isinstance(queries, str):+ queries = [queries]+ if not isinstance(queries, list):+ return []+ cleaned: list[str] = []+ for raw in queries:+ if not isinstance(raw, (str, int, float)):+ continue+ subject = " ".join(str(raw).split())[:80]+ if subject and subject.lower() not in {c.lower() for c in cleaned}:+ cleaned.append(subject)+ if len(cleaned) >= IMAGE_SEARCH_MAX_QUERIES:+ break+ return cleaned+++def _image_search(+ queries,+ timeout: int = _EXEC_TIMEOUT,+ cancel_event = None,+ website_policy: dict | None = None,+) -> str:+ # One lookup per subject, concurrently; same registry and tokens as web_search.+ from concurrent.futures import ThreadPoolExecutor++ from .search_images import cache_generation, images_envelope, register_images++ cleaned = _clean_image_queries(queries)+ if not cleaned:+ return "No subjects provided."+ if cancel_event is not None and cancel_event.is_set():+ return "Search cancelled."+ expected_generation = cache_generation()+ try:+ from ddgs import DDGS++ from .web_access_policy import scope_search_queryexcept Exception as e:return _search_failure_message(e, timeout)+ if not callable(getattr(DDGS, "images", None)):+ return "Image search is unavailable in this install."++ def lookup(subject: str) -> list:+ # A client per call: ddgs instances are not documented thread-safe.+ try:+ return list(+ DDGS(timeout = timeout).images(+ scope_search_query(subject, website_policy),+ max_results = IMAGE_SEARCH_PER_QUERY * 4,+ safesearch = "moderate",+ )+ or []+ )+ except Exception as exc: # noqa: BLE001 - one subject failing must not lose the rest+ logger.debug("image lookup skipped %r (%s)", subject, type(exc).__name__)+ return []++ with ThreadPoolExecutor(max_workers = len(cleaned)) as pool:+ raw_by_subject = list(pool.map(lookup, cleaned))+ if cancel_event is not None and cancel_event.is_set():+ return "Search cancelled."++ sections: list[str] = []+ entries_all: list[dict[str, str]] = []+ for subject, raw in zip(cleaned, raw_by_subject):+ entries = register_images(+ raw,+ website_policy,+ max_images = IMAGE_SEARCH_PER_QUERY,+ subject = subject,+ expected_generation = expected_generation,+ )+ if not entries:+ sections.append(f"{subject}: no image found")+ continue+ entries_all.extend(entries)+ # One token per subject; spares ride along in the envelope as fallbacks.+ first = entries[0]+ domain = f" — {first['domain']}" if first["domain"] else ""+ sections.append(+ f"{subject}:\n- [[img:{first['id']}]] {first['title'] or '(untitled)'}{domain}"+ )+ if not entries_all:+ return "No images found for: " + ", ".join(cleaned)+ header = (+ "Images by subject. To show one, write its token exactly as given, e.g. "+ f"[[img:{entries_all[0]['id']}]], on its own line directly under the text about that "+ "subject. Use only these tokens; one per subject is enough."+ )+ return header + "\n\n" + "\n\n".join(sections) + images_envelope(entries_all)+++def _web_search_images_suffix(client, query, wanted, cancel_event, website_policy) -> str:+ # "" when images are unavailable; never raises, the text results stand on their own.+ from .search_images import (+ MAX_IMAGES_PER_SEARCH,+ cache_generation,+ format_images_for_model,+ images_envelope,+ register_images,+ )++ images_fn = getattr(client, "images", None)+ if not callable(images_fn):+ return ""+ # Before the sweep, like _image_search: clear-all is what bumps this, and an+ # entry registered after one would keep serving a picture the user cleared.+ expected_generation = cache_generation()+ try:+ raw = images_fn(+ query, max_results = max(wanted, MAX_IMAGES_PER_SEARCH * 2), safesearch = "moderate"+ )+ except Exception as exc: # noqa: BLE001 - optional extra; the text results stand on their own+ logger.debug("web_search image lookup skipped (%s)", type(exc).__name__)+ return ""+ if cancel_event is not None and cancel_event.is_set():+ return ""+ entries = register_images(+ list(raw or []), website_policy, expected_generation = expected_generation+ )+ if not entries:+ return ""+ return "\n\n---\n\n" + format_images_for_model(entries) + images_envelope(entries)def _check_signal_escape_patterns(code: str):diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 43a40bdc308..05f865706a3 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -370,6 +370,15 @@ class UnloadRequest(BaseModel):)+class SearchImagesLookupRequest(BaseModel):+ subjects: list[str] = Field(+ ...,+ min_length = 1,+ max_length = 5,+ description = "Specific things to fetch one picture each for.",+ )++class TranscribeRequest(BaseModel):"""Speech-to-text request for the dictation STT sidecar."""diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex a92ed45fd6c..8ef2a679333 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -29,6 +29,10 @@ from storage.studio_db import (ProjectWorkspaceError,build_chat_history_export,clear_chat_history,+ clear_chat_history_with_replay_status,+ mark_clear_operation_caches_cleared,+ record_clear_operation_reap_scope,+ unreaped_clear_operation_image_ids,count_chat_threads,count_forks_for_message,delete_chat_attachment,@@ -428,6 +432,8 @@ class ChatSettingsPayload(BaseModel):preserveThinking: Optional[bool] = NonecollapseHtmlArtifacts: Optional[bool] = NoneallowArtifactNetworkAccess: Optional[bool] = None+ # Read by the web_search tool at call time, so it lives with the install, not one browser.+ searchImages: Optional[bool] = NoneautoHealToolCalls: Optional[bool] = NonenudgeToolCalls: Optional[bool] = NonemaxToolCallsPerMessage: Optional[int] = Field(default = None, ge = 1)@@ -1346,20 +1352,55 @@ async def clear_history(else [thread["id"] for thread in await run_in_threadpool(list_chat_threads)])- def _clear_rows() -> tuple[list[str], list[str]]:+ def _clear_rows() -> tuple[list[str], list[str], bool, Optional[set]]:+ """The clear, and the image snapshot the reap will be bounded to.++ Both in ONE threadpool call, so there is no await between them. Split across two,+ the event loop can run another request in the gap: a chat created there survives+ the transaction, but its images register before the snapshot and the reap takes+ them, leaving its cards 404ing out of thumbnail_bytes.++ Narrowed, NOT closed, and the difference is worth stating. Another worker thread can+ still register between the commit and the read a few instructions later, and only one+ thing would truly close that: holding ``_registry_lock`` across the transaction. That+ lock is what every image registration in the process takes, and this transaction is a+ BEGIN IMMEDIATE that waits out contention for seconds, so paying for it means stalling+ every search in every chat for the length of a clear. The window bought back is a few+ instructions wide and its cost is one chat's thumbnails re-fetching. Not worth it.+ """+ from core.inference.search_images import snapshot_and_fence_registrations+if payload is None:cleared, cleared_runs = clear_chat_history()- else:- cleared, cleared_runs = clear_chat_history(- payload.ids,- operation_id = payload.operationId,+ return cleared, cleared_runs, False, snapshot_and_fence_registrations()+ # Answered by the transaction itself. Read separately beforehand it is a guess:+ # a concurrent retry of the same operation id sees the same unrecorded ledger,+ # and the one BEGIN IMMEDIATE puts second replays while still believing it+ # cleared. `replayed` here is whichever the transaction actually did.+ cleared, cleared_runs, replayed = clear_chat_history_with_replay_status(+ payload.ids,+ operation_id = payload.operationId,+ )+ if replayed:+ # A replay takes no snapshot of its own -- the chats created since the original+ # clear are not its to reap. It may still have to FINISH that clear's reap,+ # though, if the process died between the commit and the cleanup.+ return (+ cleared,+ cleared_runs,+ True,+ unreaped_clear_operation_image_ids(payload.operationId),)- return cleared, cleared_runs+ snapshot = snapshot_and_fence_registrations()+ # Recorded before the reap runs, so a crash in the seconds of cleanup that follow+ # leaves a retry able to finish exactly this set and nothing wider.+ record_clear_operation_reap_scope(payload.operationId, snapshot)+ return cleared, cleared_runs, False, snapshot# The clear reports what it deleted, which is what gets cleaned up: a thread# added between the listing above and the delete is gone too, and its# sandbox would otherwise be stranded.- cleared, cleared_runs = await run_in_threadpool(_clear_rows)+ cleared, cleared_runs, replayed, reapable_image_ids = await run_in_threadpool(_clear_rows)# A chat started between the listing and the transaction is in `cleared`# but was never cancelled, and a generation still running would dispatch a# tool and rebuild the sandbox this call is about to remove.@@ -1380,6 +1421,29 @@ async def clear_history(# delete_files matches DELETE /threads: off by default, since the files are# the user's, but a caller clearing everything can ask for them too.removed, kept = await _remove_sandboxes(list(dict.fromkeys(thread_ids + cleared)), delete_files)+ # Search thumbnails are keyed by id, not thread, so this is the one place they+ # can be reaped; they reveal what was searched for. Runs for both _clear_rows+ # branches -- each calls clear_chat_history(), which drops every thread -- so this+ # is NOT gated on `payload is None`, which the frontend never sends and which+ # therefore meant the reap never ran.+ #+ # A REPLAY must not reap the registry wholesale: the transaction above deliberately keeps+ # chats created since the original clear, and this registry is global, so wiping it takes+ # the images of a chat this call is not deleting and leaves its cards 404ing out of+ # thumbnail_bytes. Ordinarily it has nothing to do -- the request that recorded the+ # operation reaps them, and Starlette does not cancel a handler when the client hangs up,+ # so the attempt this retry replaces still runs to here.+ #+ # The exception is a process that DIED in between. The operation is recorded and the+ # thumbnails of every deleted chat are still on disk, saying what was searched for, and+ # only a replay is left to notice. `reapable_image_ids` is then the original clear's own+ # snapshot, read back off the ledger, so finishing its reap is bounded to exactly what it+ # was responsible for and cannot reach a newer chat's images.+ if not replayed or reapable_image_ids:+ from core.inference.search_images import clear_cache+ await run_in_threadpool(clear_cache, reapable_image_ids)+ if payload is not None:+ await run_in_threadpool(mark_clear_operation_caches_cleared, payload.operationId)return {"status": "deleted","deletedThreadIds": cleared,diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 9a717d92d60..cdb83432fbe 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -2401,6 +2401,7 @@ from models.inference import (_InferenceRuntimeFields,LoadRequest,UnloadRequest,+ SearchImagesLookupRequest,TranscribeRequest,SttLoadRequest,GenerateRequest,@@ -3694,6 +3695,15 @@ _TOOL_BASE_NUDGE = ("format.")_TOOL_WEB_COMPACT_TIP = "When using web_search, do not repeat the same search query."+# Only with the Search images setting on. Small models call the tool before they know+# their list, so the answer-first path is spelled out.+_TOOL_IMAGES_TIP = (+ "When your answer names specific things worth seeing (breeds, products, places, "+ "dishes, people), call web_search with image_queries listing those exact names, one "+ "per entry, never a list title. If you only know the names after writing the list, "+ "write the answer first, then call web_search with image_queries alone. Put each "+ "returned [[img:...]] token on its own line directly under its item."+)_TOOL_WEB_EXPANDED_TIP = ("When using web_search and a result URL is relevant, fetch its full content ""by calling web_search with the url parameter. Do not repeat the same search "@@ -3759,6 +3769,12 @@ def _build_tool_action_nudge(if isinstance(tool, dict) and isinstance(tool.get("function"), dict)}has_web = "web_search" in tool_names+ has_images = any(+ "image_queries"+ in ((tool.get("function") or {}).get("parameters") or {}).get("properties", {})+ for tool in tools+ if isinstance(tool, dict) and (tool.get("function") or {}).get("name") == "web_search"+ )code_tools = [name for name in _LOCAL_CODE_TOOLS if name in tool_names]has_code = bool(code_tools)has_artifact = "render_html" in tool_names@@ -3772,6 +3788,8 @@ def _build_tool_action_nudge(tool_tip_parts: list[str] = []if has_web:tool_tip_parts.append(_TOOL_WEB_COMPACT_TIP if compact_web_tip else _TOOL_WEB_EXPANDED_TIP)+ if has_images:+ tool_tip_parts.append(_TOOL_IMAGES_TIP)if has_code:tool_tip_parts.append(_TOOL_CODE_TIP)if full_access:@@ -3976,6 +3994,7 @@ async def _select_request_tools(# meeting a large catalogue at a compaction boundary have been seen calling a# guessed tool name. Read-only and always-safe, so it prompts for nothing.tools = [t for t in tools if t["function"]["name"] == "search_conversation"]+ tools = _tools_for_search_images(tools)# Built-ins only, so this runs before the MCP append: an MCP tool's# description is the server's to write, and Full access says nothing about# how that server runs.@@ -3986,6 +4005,25 @@ async def _select_request_tools(return tools+def _search_images_enabled() -> bool:+ from core.inference.search_images import search_images_enabled+ return search_images_enabled()+++def _tools_for_search_images(tools: list[dict]) -> list[dict]:+ # web_search also takes image_queries while the setting is on; every path that+ # hands the model a schema swaps it here. Name check first: the setting hits SQLite.+ if not any(t["function"]["name"] == "web_search" for t in tools):+ return tools+ if not _search_images_enabled():+ return tools+ from core.inference.tools import web_search_tool_with_images++ return [+ web_search_tool_with_images() if t["function"]["name"] == "web_search" else t for t in tools+ ]++_COMPACTED_SESSION_NUDGE = ("This conversation is long, so older turns have been removed from your context. ""The relevant ones are retrieved and shown to you automatically when that happens. "@@ -21713,8 +21751,10 @@ async def anthropic_messages(if _server_tools_requested_pre:from core.inference.tools import ALL_TOOLS as _ALL_TOOLS_PRE- _selected_pre = _select_anthropic_server_tools(- _ALL_TOOLS_PRE, requested_studio_tools, payload.enabled_tools+ _selected_pre = _tools_for_search_images(+ _select_anthropic_server_tools(+ _ALL_TOOLS_PRE, requested_studio_tools, payload.enabled_tools+ ))_perm_mode_pre = getattr(payload, "permission_mode", None)_confirm_opt_out_pre = getattr(payload, "confirm_tool_calls", None) is False@@ -22197,10 +22237,12 @@ async def anthropic_messages(# tool) were already rejected before the auto-switch above, so an invalid# confirm-gated request never evicts the resident model; the selection# here just picks the tools for the actual server-tool loop.- openai_tools = _select_anthropic_server_tools(- ALL_TOOLS,- requested_studio_tools,- payload.enabled_tools,+ openai_tools = _tools_for_search_images(+ _select_anthropic_server_tools(+ ALL_TOOLS,+ requested_studio_tools,+ payload.enabled_tools,+ ))# Mirrors _select_request_tools: this path builds its own selection, so# the Full access swap has to be repeated rather than inherited.@@ -26320,6 +26362,45 @@ async def get_gallery_image_file()+@studio_router.post("/search-images/lookup")+async def lookup_search_images(+ payload: SearchImagesLookupRequest, current_subject: str = Depends(get_current_subject)+):+ # Illustrates a finished answer whose model never asked; same lookup as the tool.+ from core.inference import search_images+ from core.inference.tools import IMAGE_SEARCH_DISABLED, _image_search++ if not search_images.search_images_enabled():+ raise HTTPException(status_code = 403, detail = IMAGE_SEARCH_DISABLED)+ raw = await asyncio.to_thread(_image_search, payload.subjects, 20)+ text, images = search_images.split_images_envelope(raw)+ return {"text": text, "images": images}+++@studio_router.get("/search-images/{image_id}")+async def get_search_image_thumbnail(+ image_id: str, current_subject: str = Depends(get_current_subject)+):+ # Id-only on purpose: no URL parameter, so this cannot become a generic image proxy.+ from core.inference import search_images++ # fullmatch, as the store does: `$` also matches before a trailing newline.+ if not search_images.IMAGE_ID_RE.fullmatch(image_id or ""):+ raise HTTPException(status_code = 404, detail = "Image not found.")+ data = await asyncio.to_thread(search_images.thumbnail_bytes, image_id)+ if data is None:+ raise HTTPException(status_code = 404, detail = "Image not found.")+ return Response(+ content = data,+ media_type = "image/jpeg",+ headers = {+ "Cache-Control": "private, max-age=86400",+ "X-Content-Type-Options": "nosniff",+ "Content-Disposition": f'inline; filename="{image_id}.jpg"',+ },+ )++@studio_router.patch("/images/gallery/{image_id}", response_model = GalleryImage)async def update_gallery_image_flags(image_id: str,diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex d90d175e7c3..632cb68bc45 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -429,7 +429,9 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:id TEXT NOT NULL PRIMARY KEY,active_research_run_ids_json TEXT NOT NULL,deleted_thread_ids_json TEXT NOT NULL DEFAULT '[]',- cleared_at INTEGER NOT NULL+ cleared_at INTEGER NOT NULL,+ reapable_image_ids_json TEXT,+ caches_cleared_at INTEGER) WITHOUT ROWID""")@@ -440,6 +442,17 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:conn.execute("ALTER TABLE chat_clear_operations ADD COLUMN deleted_thread_ids_json TEXT NOT NULL DEFAULT '[]'")+ # The thumbnail reap happens AFTER this transaction commits, behind seconds of archive and+ # sandbox cleanup. A crash in that window leaves the operation recorded and the cache+ # unreaped, and the retry that follows replays -- skipping the one cleanup that had not+ # run. These two columns let the replay finish it: the ids the original clear was+ # responsible for, and whether the reap has since completed. NULL in either means the+ # answer is unknown (a row written by an older build), which is treated as done, since a+ # replay must never reap on a guess.+ if "reapable_image_ids_json" not in chat_clear_operation_cols:+ conn.execute("ALTER TABLE chat_clear_operations ADD COLUMN reapable_image_ids_json TEXT")+ if "caches_cleared_at" not in chat_clear_operation_cols:+ conn.execute("ALTER TABLE chat_clear_operations ADD COLUMN caches_cleared_at INTEGER")conn.execute("""CREATE TABLE IF NOT EXISTS chat_messages (@@ -2168,6 +2181,89 @@ def delete_chat_threads(ids: list[str]) -> list[str]:return delete_chat_threads_with_active_research_runs(ids)+def unreaped_clear_operation_image_ids(operation_id: Optional[str]) -> Optional[set]:+ """The ids a recorded clear was responsible for but never reaped, or None.++ None means there is nothing for a replay to finish: no such operation, a row from a build+ that did not record the snapshot, or a reap that already completed. A replay must never+ reap on a guess -- the whole point of bounding it is that the images of chats created+ since the original clear are NOT its to take -- so anything unknown answers None.++ Exists because the reap runs after the clear's transaction commits, behind seconds of+ archive and sandbox cleanup. Killed in that window, the operation is recorded and the+ thumbnails of every deleted chat are still on disk; the retry that follows replays and,+ without this, skips the one cleanup that had not run. Those files say what was searched+ for, so leaving them is the worse of the two failures this module weighs.+ """+ if operation_id is None:+ return None+ try:+ conn = get_connection()+ try:+ row = conn.execute(+ """+ SELECT reapable_image_ids_json, caches_cleared_at+ FROM chat_clear_operations WHERE id = ?+ """,+ (operation_id,),+ ).fetchone()+ if row is None or row["caches_cleared_at"] is not None:+ return None+ stored = row["reapable_image_ids_json"]+ if stored is None:+ return None+ return set(json.loads(stored))+ finally:+ conn.close()+ except Exception: # noqa: BLE001 -- an unreadable ledger just means nothing to finish+ return None+++def record_clear_operation_reap_scope(+ operation_id: Optional[str], image_ids: Optional[set]+) -> None:+ """Persist what this clear's reap is responsible for, before it runs.++ Written as its own statement rather than in the clear's INSERT: the snapshot is taken+ immediately after that transaction commits, and moving the commit later to include it+ would widen the window where a concurrent retry sees no ledger row at all.++ A None snapshot means "clear everything", which no replay may repeat blindly, so it is+ stored as an explicit absence and read back as nothing to finish."""+ if operation_id is None:+ return+ try:+ conn = get_connection()+ try:+ conn.execute(+ "UPDATE chat_clear_operations SET reapable_image_ids_json = ? WHERE id = ?",+ (None if image_ids is None else json.dumps(sorted(image_ids)), operation_id),+ )+ conn.commit()+ finally:+ conn.close()+ except Exception: # noqa: BLE001 -- best effort; failing here must not fail the clear+ logger.debug("could not record the reap scope for clear %s", operation_id)+++def mark_clear_operation_caches_cleared(operation_id: Optional[str]) -> None:+ """Record that the thumbnail reap for this clear finished, so a replay does not redo it."""+ if operation_id is None:+ return+ try:+ conn = get_connection()+ try:+ conn.execute(+ "UPDATE chat_clear_operations SET caches_cleared_at = ? WHERE id = ?",+ (int(datetime.now(timezone.utc).timestamp() * 1000), operation_id),+ )+ conn.commit()+ finally:+ conn.close()+ except Exception: # noqa: BLE001 -- a missed mark costs one redundant reap on a retry+ logger.debug("could not mark the reap complete for clear %s", operation_id)++def clear_chat_history_with_active_research_runs(additional_thread_ids: Iterable[str] = (), operation_id: Optional[str] = None) -> tuple[list[str], list[str]]:@@ -2181,11 +2277,35 @@ def clear_chat_history_with_active_research_runs(def clear_chat_history(additional_thread_ids: Iterable[str] = (), operation_id: Optional[str] = None) -> "tuple[list[str], list[str]]":- """Delete every chat thread. Returns (thread ids removed, research runs cascaded).+ """Delete every chat thread. Returns (thread ids removed, research runs cascaded)."""+ removed, active_runs, _replayed = clear_chat_history_with_replay_status(+ additional_thread_ids,+ operation_id = operation_id,+ )+ return removed, active_runs- Both taken inside the same transaction: another process can add a thread- between a listing and this call, its sandbox has to be cleaned up too, and++def clear_chat_history_with_replay_status(+ additional_thread_ids: Iterable[str] = (), operation_id: Optional[str] = None+) -> "tuple[list[str], list[str], bool]":+ """`clear_chat_history`, plus whether this call replayed a recorded outcome.++ Returns (thread ids removed, research runs cascaded, replayed).++ The first two are taken inside the same transaction: another process can add a+ thread between a listing and this call, its sandbox has to be cleaned up too, andafter the cascade nothing can tell the supervisor which runs to stop.++ `replayed` comes from that same transaction because it cannot be established+ outside one. Two requests carrying the same operation id can both read an+ unrecorded ledger before either commits, so both would conclude they performed+ the clear; BEGIN IMMEDIATE then serialises them and the loser silently replays.+ A caller trusting the outside read would run the second request's cleanup of+ global, non-id-keyed state -- the thumbnail cache -- against threads created+ since the winner committed, which this call deliberately kept. That is exactly+ the retry the operation id exists to make safe: the frontend reissues the same+ id when its first attempt times out, and Starlette does not cancel the handler+ the client hung up on, so both really are in flight at once."""conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)try:@@ -2202,7 +2322,7 @@ def clear_chat_history(conn.commit()# The original request already signalled its workers. Replaying that signal can# leave a cancellation event behind after the worker has exited.- return list(json.loads(completed["deleted_thread_ids_json"])), []+ return list(json.loads(completed["deleted_thread_ids_json"])), [], True_ensure_chat_attachment_inventory_current(conn)removed = sorted(str(row[0]) for row in conn.execute("SELECT id FROM chat_threads"))status_placeholders = ",".join("?" for _ in _ACTIVE_RESEARCH_RUN_STATUSES)@@ -2234,7 +2354,7 @@ def clear_chat_history(),)conn.commit()- return removed, active_runs+ return removed, active_runs, Falseexcept Exception:conn.rollback()raisediff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.pyindex 1a4f333dc6b..883062c61fc 100644--- a/studio/backend/tests/test_chat_history_routes.py+++ b/studio/backend/tests/test_chat_history_routes.py@@ -7,6 +7,7 @@ import osimport reimport sqlite3import sys+import threadingfrom types import SimpleNamespaceimport pytest@@ -192,12 +193,12 @@ def test_clear_history_fences_pending_thread_ids(monkeypatch):def clear_with_ids(thread_ids = (), operation_id = None):captured.extend(thread_ids)captured_operation_ids.append(operation_id)- return list(thread_ids), []+ return list(thread_ids), [], Falseasync def remove_sandboxes(_thread_ids, _delete_files):return 0, []- monkeypatch.setattr(chat_history, "clear_chat_history", clear_with_ids)+ monkeypatch.setattr(chat_history, "clear_chat_history_with_replay_status", clear_with_ids)monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)@@ -221,6 +222,44 @@ def test_clear_history_fences_pending_thread_ids(monkeypatch):assert captured_operation_ids == ["clear-operation-1"]+def test_clear_history_reaps_search_thumbnails_with_a_body(monkeypatch):+ """DELETE /api/chat is clear-all either way, and the frontend always sends a body.++ Gating the thumbnail reap on `payload is None` meant it never ran, so "Clear all+ chats" left every cached thumbnail — which says what was searched for — on disk.+ """+ from core.inference import search_images++ reaped: list[bool] = []+ monkeypatch.setattr(search_images, "clear_cache", lambda only_ids = None: reaped.append(True))++ async def remove_sandboxes(_thread_ids, _delete_files):+ return 0, []++ monkeypatch.setattr(+ chat_history,+ "clear_chat_history_with_replay_status",+ lambda thread_ids = (), operation_id = None: ([], [], False),+ )+ monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)+ monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)+ monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)+ monkeypatch.setattr(+ chat_history, "_remove_conversation_archives", lambda _ids, cutoff = None: None+ )+ request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))++ asyncio.run(+ chat_history.clear_history(+ request,+ chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-2"),+ current_subject = "test-user",+ )+ )++ assert reaped == [True]++def test_project_delete_cancels_research_before_workspace_cleanup(monkeypatch):project = {"id": "project-1",@@ -662,3 +701,466 @@ def test_get_thread_fork_counts(monkeypatch):current_subject = "test-user",)assert response.counts == {"m1": 2, "m2": 1}+++def _clear_thread_row(thread_id: str) -> dict:+ return {+ "id": thread_id,+ "title": "Test Chat",+ "modelType": "base",+ "modelId": "test-model",+ "pairId": None,+ "archived": False,+ "createdAt": 1_700_000_000_000,+ }+++def test_a_clear_does_not_reap_an_image_registered_while_it_was_running(tmp_path, monkeypatch):+ """The reap is global; the delete it accompanies is not.++ Between the transaction committing and the reap there is archive and sandbox cleanup+ that can run for seconds. A chat created in that window survives the delete, so+ wiping the whole registry afterwards took ITS thumbnails and left its cards 404ing+ out of thumbnail_bytes. Independent of the replay case: this one is a first clear.++ The snapshot is taken before the slow work, so an id registered during it is not the+ clear's to reap.+ """+ from core.inference import search_images+ from storage import studio_db++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(search_images, "_registry", {})+ monkeypatch.setattr(search_images, "_cleared_unservable", set())+ monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")+ (tmp_path / "thumbs").mkdir(parents = True, exist_ok = True)++ old = search_images.register_images(+ [+ {+ "title": "before",+ "image": "https://img.example.com/a.jpg",+ "thumbnail": "https://tse1.mm.bing.net/th?id=a",+ "url": "https://example.com/a",+ "source": "Bing",+ }+ ]+ )+ assert old, "fixture must register: the whole test turns on this id being reapable"+ old_id = old[0]["id"]++ late: dict[str, str] = {}++ async def remove_sandboxes(_thread_ids, _delete_files):+ # Stands in for the concurrent client: another tab registers an image for a chat+ # created after the transaction, while this slow cleanup is still running.+ entries = search_images.register_images(+ [+ {+ "title": "during",+ "image": "https://img.example.com/b.jpg",+ "thumbnail": "https://tse1.mm.bing.net/th?id=b",+ "url": "https://example.com/b",+ "source": "Bing",+ }+ ]+ )+ late["id"] = entries[0]["id"]+ return 0, []++ monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)+ monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)+ monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)+ monkeypatch.setattr(+ chat_history, "_remove_conversation_archives", lambda _ids, cutoff = None: None+ )+ request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))++ studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))+ asyncio.run(+ chat_history.clear_history(+ request,+ chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-race"),+ current_subject = "test-user",+ )+ )++ assert late.get("id"), "the stand-in never registered, so this asserts nothing"+ assert search_images.lookup_image(late["id"]) is not None, (+ "an image registered while the clear was running belongs to a chat the clear "+ "kept, so reaping it 404s that chat's cards"+ )+ assert (+ search_images.lookup_image(old_id) is None+ ), "the clear still has to reap what it was responsible for"+++def test_replayed_clear_keeps_the_thumbnails_of_a_chat_it_did_not_delete(tmp_path, monkeypatch):+ """A retry under a recorded operationId replays, so it must not reap the global cache.++ The frontend retries DELETE /chat once under the SAME operationId after its 30s+ abort, and Starlette does not cancel the first handler when the client hangs up, so+ the retry lands behind a transaction that already committed. That transaction+ deliberately leaves chats created since alone -- but the thumbnail registry is+ global, so reaping it again took the images of a chat this call is not deleting and+ left its cards 404ing.+ """+ from core.inference import search_images+ from storage import studio_db++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(studio_db, "_schema_ready", False)++ reaped: list[str] = []+ monkeypatch.setattr(search_images, "clear_cache", lambda only_ids = None: reaped.append("reaped"))++ async def remove_sandboxes(_thread_ids, _delete_files):+ return 0, []++ monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)+ monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)+ monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)+ monkeypatch.setattr(+ chat_history, "_remove_conversation_archives", lambda _ids, cutoff = None: None+ )+ request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))++ def clear():+ return asyncio.run(+ chat_history.clear_history(+ request,+ chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-retry"),+ current_subject = "test-user",+ )+ )++ studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))+ assert clear()["deletedThreadIds"] == ["before-clear"]+ assert reaped == ["reaped"], "the first clear has to reap: the thumbnails say what was searched"++ # The image-bearing chat the delayed retry must not touch.+ studio_db.upsert_chat_thread(_clear_thread_row("after-clear"))++ replay = clear()+ assert replay["deletedThreadIds"] == ["before-clear"]+ assert studio_db.get_chat_thread("after-clear") is not None+ assert reaped == ["reaped"], "the replay reaped a surviving chat's thumbnails"+++def test_the_replay_bit_comes_from_the_clear_transaction(monkeypatch, tmp_path):+ """Two concurrent retries of one operationId: exactly one of them performed the clear.++ Establishing `replayed` with a read taken before the transaction is a guess. Both+ requests carrying the same operationId see the same unrecorded ledger, so both+ conclude they cleared; BEGIN IMMEDIATE then serialises them and the loser silently+ replays while still believing otherwise. It would go on to reap the thumbnail+ registry -- which is global, and so is not covered by the ids the transaction+ deliberately kept -- taking the images of chats created since the winner committed.+ This is the retry the operationId exists to make safe: the frontend reissues the+ same id after its 30s abort, and Starlette does not cancel the handler the client+ hung up on, so both really do run at once.+ """+ from core.inference import search_images+ from storage import studio_db++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(studio_db, "_schema_ready", False)++ reaps: list[str] = []+ reap_lock = threading.Lock()++ def record_reap(only_ids = None):+ with reap_lock:+ reaps.append("reaped")++ monkeypatch.setattr(search_images, "clear_cache", record_reap)++ async def remove_sandboxes(_thread_ids, _delete_files):+ return 0, []++ monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)+ monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)+ monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)+ monkeypatch.setattr(+ chat_history, "_remove_conversation_archives", lambda _ids, cutoff = None: None+ )+ request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))++ studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))++ # Released together, so both are past the point the old code decided `replayed` at+ # before either transaction commits -- which is the whole race.+ start = threading.Barrier(2)+ failures: list[BaseException] = []++ def clear():+ try:+ start.wait(timeout = 10)+ asyncio.run(+ chat_history.clear_history(+ request,+ chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-concurrent"),+ current_subject = "test-user",+ )+ )+ except BaseException as exc: # noqa: BLE001 -- re-raised on the main thread+ failures.append(exc)++ threads = [threading.Thread(target = clear) for _ in range(2)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout = 30)+ if failures:+ raise failures[0]++ assert reaps == ["reaped"], (+ "only the request that actually performed the clear may reap the global "+ f"thumbnail registry; got {len(reaps)} reaps"+ )+++def test_clear_history_does_not_read_the_replay_ledger_outside_the_transaction():+ """The structural half of the race above, which no scheduling can hide.++ `replayed` has to be whatever the transaction did, so it is returned by the call+ that does the clear. A separate ledger read reintroduces the window even if the+ threads in the test above happen to serialise.+ """+ source = inspect.getsource(chat_history.clear_history)+ assert "clear_chat_history_with_replay_status" in source+ assert (+ "chat_clear_operation_is_recorded" not in source+ ), "a pre-transaction ledger read cannot tell a replay from a concurrent clear"+++def test_a_chat_created_in_the_gap_after_the_clear_keeps_its_images(monkeypatch, tmp_path):+ """The snapshot has to be taken at the clear boundary, not one await later.++ `await run_in_threadpool(...)` is a yield point. With the clear and the snapshot in+ separate calls, the event loop can run another request in between: a chat created there+ survives the transaction (the clear only deletes what it saw), but its images register+ before the snapshot, so the reap that follows takes them and its cards 404 out of+ thumbnail_bytes. One threadpool call for both removes that gap.++ It does not make the two atomic -- another worker THREAD can still land between the+ commit and the read, and closing that would mean holding the image registry's lock across+ the whole transaction, stalling every search in the process for the length of a clear.+ This pins the gap that was worth removing.++ The interleave is forced rather than raced: `run_in_threadpool` is wrapped so the other+ tab registers its image immediately after the FIRST hop returns, which is exactly the+ window in question.+ """+ from core.inference import search_images+ from storage import studio_db++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(search_images, "_registry", {})+ monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")+ (tmp_path / "thumbs").mkdir(parents = True, exist_ok = True)++ reaped: list = []+ monkeypatch.setattr(search_images, "clear_cache", lambda only_ids = None: reaped.append(only_ids))++ async def remove_sandboxes(_thread_ids, _delete_files):+ return 0, []++ monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)+ monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)+ monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)+ monkeypatch.setattr(+ chat_history, "_remove_conversation_archives", lambda _ids, cutoff = None: None+ )++ # The other tab's image, registered in the gap. Straight into the registry: this is about+ # WHEN the id becomes visible to the snapshot, not about how it got there.+ late_image_id = "beefbeefbeef"+ hops = {"n": 0}+ # The route imports it inside the handler, so the patch has to land on the module it+ # imports FROM, not on routes.chat_history.+ import starlette.concurrency++ real_run_in_threadpool = starlette.concurrency.run_in_threadpool++ async def interleaving_run_in_threadpool(func, *args, **kwargs):+ result = await real_run_in_threadpool(func, *args, **kwargs)+ hops["n"] += 1+ if hops["n"] == 1:+ search_images._registry[late_image_id] = {+ "thumbnail": "https://example.invalid/x.jpg",+ "source": "https://example.invalid/",+ "created": 0.0,+ "policy": None,+ }+ return result++ monkeypatch.setattr(starlette.concurrency, "run_in_threadpool", interleaving_run_in_threadpool)+ request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))++ studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))+ asyncio.run(+ chat_history.clear_history(+ request,+ chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-gap"),+ current_subject = "test-user",+ )+ )++ assert reaped, "the clear still has to reap what it was responsible for"+ snapshot = reaped[0]+ assert snapshot is not None, "a real clear reaps a bounded set, not everything"+ assert late_image_id not in snapshot, (+ "an image registered after the clear committed belongs to a chat the clear kept, "+ "so the reap must not be allowed to take it"+ )+++def test_the_clear_and_its_image_snapshot_share_one_threadpool_hop():+ """The structural half of the race above, which no test scheduling can hide."""+ source = inspect.getsource(chat_history.clear_history)+ assert source.count("run_in_threadpool(_clear_rows)") == 1+ assert (+ "run_in_threadpool(snapshot_and_fence_registrations)" not in source+ ), "a second hop for the snapshot reopens the gap the first one closed"+ body = source.split("def _clear_rows(", 1)[1].split("\n # The clear reports", 1)[0]+ assert (+ "snapshot_and_fence_registrations()" in body+ ), "the snapshot belongs inside the clear's hop, and it carries the registration fence"+++def test_a_replay_finishes_a_reap_the_original_clear_died_before_running(monkeypatch, tmp_path):+ """A crash between the clear's commit and its thumbnail reap must not lose the reap.++ The reap runs after the transaction, behind seconds of archive and sandbox cleanup. Killed+ in that window the operation is already recorded, so the retry the frontend sends replays+ -- and a replay deliberately reaps nothing, because the chats created since the original+ clear are not its to take. The thumbnails of every deleted chat then stay on disk for good,+ saying what was searched for, which is the worse of the two failures this path weighs.++ The ledger now carries the original clear's own snapshot and whether the reap finished, so+ the replay can complete exactly that set. The crash is simulated by making the first reap+ raise, which is the same state a SIGKILL leaves behind: committed, recorded, unreaped.+ """+ from core.inference import search_images+ from storage import studio_db++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(search_images, "_registry", {})+ monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")+ (tmp_path / "thumbs").mkdir(parents = True, exist_ok = True)++ doomed_image_id = "aaaabbbbcccc"+ search_images._registry[doomed_image_id] = {+ "thumbnail": "https://example.invalid/x.jpg",+ "source": "https://example.invalid/",+ "created": 0.0,+ "policy": None,+ }++ reaps: list = []++ def reap(only_ids = None):+ reaps.append(only_ids)+ if len(reaps) == 1:+ raise RuntimeError("process died before the reap finished")++ monkeypatch.setattr(search_images, "clear_cache", reap)++ async def remove_sandboxes(_thread_ids, _delete_files):+ return 0, []++ monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)+ monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)+ monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)+ monkeypatch.setattr(+ chat_history, "_remove_conversation_archives", lambda _ids, cutoff = None: None+ )+ request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))++ def clear():+ return asyncio.run(+ chat_history.clear_history(+ request,+ chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-crash"),+ current_subject = "test-user",+ )+ )++ studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))+ with pytest.raises(RuntimeError):+ clear()+ assert reaps == [{doomed_image_id}], "the first attempt got as far as its own reap"++ # A chat started after the crash, whose images the replay must NOT take.+ studio_db.upsert_chat_thread(_clear_thread_row("after-crash"))+ later_image_id = "ddddeeeeffff"+ search_images._registry[later_image_id] = {+ "thumbnail": "https://example.invalid/y.jpg",+ "source": "https://example.invalid/",+ "created": 0.0,+ "policy": None,+ }++ clear()+ assert len(reaps) == 2, "the replay has to finish the reap the crash interrupted"+ finished = reaps[1]+ assert finished == {+ doomed_image_id+ }, "bounded to the original clear's own snapshot, so a chat created since keeps its images"+ assert later_image_id not in finished++ # And a further retry has nothing left to do.+ clear()+ assert len(reaps) == 2, "the finished reap must be recorded, not repeated on every retry"+++def test_a_plain_replay_with_nothing_outstanding_still_reaps_nothing(monkeypatch, tmp_path):+ """The ordinary retry. The first attempt completed its reap, so the replay must stay out+ of the global registry entirely -- that is what the replay branch is for."""+ from core.inference import search_images+ from storage import studio_db++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(search_images, "_registry", {})+ monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")+ (tmp_path / "thumbs").mkdir(parents = True, exist_ok = True)++ reaps: list = []+ monkeypatch.setattr(search_images, "clear_cache", lambda only_ids = None: reaps.append(only_ids))++ async def remove_sandboxes(_thread_ids, _delete_files):+ return 0, []++ monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)+ monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda _ids: None)+ monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda _request, _ids: None)+ monkeypatch.setattr(+ chat_history, "_remove_conversation_archives", lambda _ids, cutoff = None: None+ )+ request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))++ def clear():+ return asyncio.run(+ chat_history.clear_history(+ request,+ chat_history.ChatClearRequest(ids = [], operationId = "clear-operation-plain"),+ current_subject = "test-user",+ )+ )++ studio_db.upsert_chat_thread(_clear_thread_row("before-clear"))+ clear()+ assert len(reaps) == 1+ clear()+ assert len(reaps) == 1, "a replay behind a completed reap must not touch the registry"diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.pyindex 6bf4239f001..2a29c82f3c9 100644--- a/studio/backend/tests/test_sandbox_files_and_storage_roots.py+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py@@ -2469,10 +2469,12 @@ def test_clearing_every_chat_reports_what_it_deleted(tmp_path, monkeypatch):from routes import chat_historyfrom storage import studio_db- source = inspect.getsource(studio_db.clear_chat_history)+ # The body lives in the _with_replay_status variant; clear_chat_history drops its+ # third element for callers that do not need it. Same transaction either way.+ source = inspect.getsource(studio_db.clear_chat_history_with_replay_status)assert "SELECT id FROM chat_threads" in sourceassert source.index("SELECT id FROM chat_threads") < source.index("DELETE FROM chat_threads")- assert "return removed, active_runs" in source+ assert "return removed, active_runs, False" in sourceroute = inspect.getsource(chat_history.clear_history)assert "cleared, cleared_runs = clear_chat_history()" in route@@ -4240,7 +4242,7 @@ def test_clearing_every_chat_cancels_the_research_it_removed():from routes import chat_historyfrom storage import studio_db- storage = inspect.getsource(studio_db.clear_chat_history)+ storage = inspect.getsource(studio_db.clear_chat_history_with_replay_status)assert "SELECT id FROM research_runs" in storageassert storage.index("SELECT id FROM research_runs") < storage.index("DELETE FROM chat_threads")diff --git a/studio/backend/tests/test_search_images.py b/studio/backend/tests/test_search_images.pynew file mode 100644index 00000000000..3c37fa87247--- /dev/null+++ b/studio/backend/tests/test_search_images.py@@ -0,0 +1,1258 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""web_search image results: server-side registry, model-facing tokens, the+frontend envelope, and the thumbnail proxy that keeps image hosts away from the+browser."""++from __future__ import annotations++import asyncio+import io+import json+import sys+import threading+from email.message import Message+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth.authentication import get_current_subject+from core.inference import search_images, tools+from core.inference.tool_loop_controller import strip_result_for_model+from core.inference.tool_stream_exec import accepts_kwarg, search_images_kwargs+from routes.inference import studio_router++RAW_IMAGES = [+ {+ "title": "Golden Retriever\nportrait",+ "image": "https://img.example.com/golden.jpg",+ "thumbnail": "https://tse1.mm.bing.net/th?id=golden",+ "url": "https://www.akc.org/dog-breeds/golden-retriever/",+ "source": "Bing",+ },+ {+ "title": "Local only",+ "image": "http://127.0.0.1/secret.png",+ "thumbnail": "http://127.0.0.1/secret.png",+ "url": "https://example.com/ok",+ },+ {+ "title": "Bad source",+ "thumbnail": "https://cdn.example.com/t.jpg",+ "url": "javascript:alert(1)",+ },+ {"title": "Missing thumbnail", "url": "https://example.com/page"},+ "not a dict",+]++[email protected](autouse = True)+def _isolated_state(monkeypatch, tmp_path):+ monkeypatch.setattr(search_images, "_registry", {})+ monkeypatch.setattr(search_images, "_inflight", {})+ monkeypatch.setattr(search_images, "_cleared_unservable", set())+ monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path)+++def _png_bytes(size = (64, 48), color = (200, 30, 30)) -> bytes:+ from PIL import Image++ out = io.BytesIO()+ Image.new("RGB", size, color).save(out, format = "PNG")+ return out.getvalue()+++def test_register_images_keeps_urls_server_side_and_filters_unsafe_results():+ entries = search_images.register_images(RAW_IMAGES)++ assert len(entries) == 1+ entry = entries[0]+ assert search_images.IMAGE_ID_RE.match(entry["id"])+ assert entry["title"] == "Golden Retriever portrait"+ assert entry["domain"] == "akc.org"+ assert entry["source"] == "https://www.akc.org/dog-breeds/golden-retriever/"+ # The thumbnail URL never reaches the model or the frontend.+ assert "bing" not in json.dumps(entry)+ stored = search_images.lookup_image(entry["id"])+ assert stored["thumbnail"] == "https://tse1.mm.bing.net/th?id=golden"+++def test_register_images_honours_the_website_policy():+ from core.inference.web_access_policy import normalize_website_policy++ policy = normalize_website_policy({"allowedDomains": ["example.com"]})+ entries = search_images.register_images(RAW_IMAGES, policy)+ assert entries == []+++def test_register_images_caps_the_count():+ many = [+ {+ "title": f"img {i}",+ "thumbnail": f"https://cdn.example.com/{i}.jpg",+ "url": f"https://example.com/{i}",+ }+ for i in range(20)+ ]+ assert len(search_images.register_images(many)) == search_images.MAX_IMAGES_PER_SEARCH+++def test_lookup_rejects_malformed_ids():+ assert search_images.lookup_image("../../etc/passwd") is None+ assert search_images.lookup_image("") is None+ assert search_images.lookup_image("ABCDEFABCDEF") is None+++def test_strip_images_suffix_only_removes_a_valid_envelope():+ entries = search_images.register_images(RAW_IMAGES)+ body = "Title: A\nURL: https://a.test\nSnippet: s"+ wrapped = body + search_images.images_envelope(entries)++ assert search_images.strip_images_suffix(wrapped) == body+ assert strip_result_for_model(wrapped, "web_search") == body+ # A sibling sentinel after ours bounds the payload, exactly as the frontend+ # parser and _strip_files_sentinel do; the ids must not survive into the model.+ trailing = wrapped + "\n__FILES__:[]"+ text, entries = search_images.split_images_envelope(trailing)+ assert text == body + "\n__FILES__:[]"+ assert [e["id"] for e in entries] == [e["id"] for e in entries if e["id"]]+ assert entries and "__WEB_IMAGES__" not in text+ assert entries[0]["id"] not in strip_result_for_model(trailing, "web_search")++ # Tool text that merely mentions the marker is content, not an envelope.+ literal = "see\n__WEB_IMAGES__:not json"+ assert search_images.strip_images_suffix(literal) == literal+ foreign = 'x\n__WEB_IMAGES__:[{"id":"zzz"}]'+ assert search_images.strip_images_suffix(foreign) == foreign+++def test_web_search_appends_tokens_and_envelope_when_images_are_on(monkeypatch):+ calls = {}++ class FakeDDGS:+ def __init__(self, **_kwargs):+ pass++ def text(+ self,+ query,+ max_results = 5,+ ):+ return [{"title": "AKC", "href": "https://akc.org/x", "body": "Breeds"}]++ def images(+ self,+ query,+ max_results = 5,+ **kwargs,+ ):+ calls["images"] = (query, max_results, kwargs)+ return RAW_IMAGES++ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))++ plain = tools._web_search("dog breeds")+ assert "[[img:" not in plain+ assert "images" not in calls++ result = tools._web_search("dog breeds", include_images = True)+ assert "Title: AKC" in result+ assert "[[img:" in result+ assert search_images.SEARCH_IMAGES_SENTINEL in result+ assert calls["images"][0] == "dog breeds"+ assert calls["images"][2]["safesearch"] == "moderate"++ model_text = strip_result_for_model(result, "web_search")+ assert search_images.SEARCH_IMAGES_SENTINEL not in model_text+ assert "[[img:" in model_text+ assert "bing.net" not in model_text++ envelope = json.loads(result.rsplit(search_images.SEARCH_IMAGES_SENTINEL, 1)[1])+ assert [e["domain"] for e in envelope] == ["akc.org"]+ token_id = envelope[0]["id"]+ assert f"[[img:{token_id}]]" in model_text+++def test_web_search_survives_an_image_engine_failure(monkeypatch):+ class FakeDDGS:+ def __init__(self, **_kwargs):+ pass++ def text(+ self,+ query,+ max_results = 5,+ ):+ return [{"title": "AKC", "href": "https://akc.org/x", "body": "Breeds"}]++ def images(+ self,+ query,+ max_results = 5,+ **kwargs,+ ):+ raise RuntimeError("engine down")++ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))+ result = tools._web_search("dog breeds", include_images = True)+ assert "Title: AKC" in result+ assert search_images.SEARCH_IMAGES_SENTINEL not in result+++def test_web_search_without_an_images_method_is_unchanged(monkeypatch):+ class FakeDDGS:+ def __init__(self, **_kwargs):+ pass++ def text(+ self,+ query,+ max_results = 5,+ ):+ return [{"title": "AKC", "href": "https://akc.org/x", "body": "Breeds"}]++ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))+ assert tools._web_search("q", include_images = True) == tools._web_search("q")+++def test_execute_tool_forwards_search_images(monkeypatch):+ seen = {}++ def fake_search(query, **kwargs):+ seen.update(kwargs)+ return "ok"++ monkeypatch.setattr(tools, "_web_search", fake_search)+ tools.execute_tool("web_search", {"query": "q"}, search_images = True)+ assert seen["include_images"] is True+ tools.execute_tool("web_search", {"query": "q"})+ assert seen["include_images"] is False+++class _SubjectDDGS:+ calls: list[str] = []++ def __init__(self, **_kwargs):+ pass++ def images(+ self,+ query,+ max_results = 5,+ **kwargs,+ ):+ _SubjectDDGS.calls.append(query)+ if query == "Nothing Here":+ return []+ if query == "Broken":+ raise RuntimeError("engine down")+ slug = query.replace(" ", "_")+ return [+ {+ "title": f"{query} photo",+ "thumbnail": f"https://cdn.example.com/{slug}.jpg",+ "url": f"https://example.com/{slug}",+ },+ {+ "title": f"{query} again",+ "thumbnail": f"https://cdn.example.com/{slug}-2.jpg",+ "url": f"https://example.com/{slug}-2",+ },+ {+ "title": f"{query} third",+ "thumbnail": f"https://cdn.example.com/{slug}-3.jpg",+ "url": f"https://example.com/{slug}-3",+ },+ ]+++def test_image_search_returns_tokens_grouped_by_subject(monkeypatch):+ _SubjectDDGS.calls = []+ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = _SubjectDDGS))++ result = tools._image_search(+ ["German Shepherd", " german shepherd ", "Labrador", "Nothing Here", "Broken"],+ )++ # Deduped case-insensitively; each subject searched once (concurrently, any order).+ assert sorted(_SubjectDDGS.calls) == sorted(+ ["German Shepherd", "Labrador", "Nothing Here", "Broken"]+ )+ model_text = strip_result_for_model(result, "web_search")+ assert search_images.SEARCH_IMAGES_SENTINEL not in model_text+ assert "German Shepherd:\n- [[img:" in model_text+ assert "Labrador:\n- [[img:" in model_text+ assert "Nothing Here: no image found" in model_text+ assert "Broken: no image found" in model_text+ # The header example plus exactly one token per found subject; spares ride only in+ # the envelope.+ assert model_text.count("[[img:") == 1 + 2+ envelope = json.loads(result.rsplit(search_images.SEARCH_IMAGES_SENTINEL, 1)[1])+ assert len(envelope) == 2 * tools.IMAGE_SEARCH_PER_QUERY+ assert all(search_images.is_image_entry(e) for e in envelope)+ assert [e["subject"] for e in envelope] == ["German Shepherd"] * 2 + ["Labrador"] * 2+ assert "cdn.example.com" not in model_text+++def test_image_queries_alone_are_a_pure_image_lookup(monkeypatch):+ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = _SubjectDDGS))+ off = tools.execute_tool("web_search", {"image_queries": ["Pug"]})+ assert off == tools.IMAGE_SEARCH_DISABLED+ on = tools.execute_tool("web_search", {"image_queries": ["Pug"]}, search_images = True)+ assert "Pug:\n- [[img:" in on+ assert "Title:" not in on+ assert tools._image_search([]) == "No subjects provided."+ assert tools._image_search("Pug").count("Pug:") == 1+ assert tools._image_search({"bad": 1}) == "No subjects provided."+ # Without image_queries an empty call is still the old "No query provided."+ assert tools.execute_tool("web_search", {}, search_images = True) == "No query provided."+++def test_web_search_with_image_queries_gives_one_picture_per_subject(monkeypatch):+ class Both(_SubjectDDGS):+ def text(+ self,+ query,+ max_results = 5,+ ):+ return [{"title": "AKC", "href": "https://akc.org/x", "body": "Breeds"}]++ _SubjectDDGS.calls = []+ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = Both))+ result = tools._web_search(+ "top dog breeds", include_images = True, image_queries = ["Pug", "Beagle"]+ )+ assert "Title: AKC" in result+ assert "Pug:\n- [[img:" in result and "Beagle:\n- [[img:" in result+ # The subjects replace the generic pile: no query-wide image lookup ran.+ assert sorted(_SubjectDDGS.calls) == ["Beagle", "Pug"]+ # With the setting off, named subjects are acknowledged rather than dropped.+ off = tools._web_search("top dog breeds", include_images = False, image_queries = ["Pug"])+ assert "Title: AKC" in off and tools.IMAGE_SEARCH_DISABLED in off and "[[img:" not in off+ envelope = json.loads(result.rsplit(search_images.SEARCH_IMAGES_SENTINEL, 1)[1])+ assert {e["subject"] for e in envelope} == {"Pug", "Beagle"}+++def test_named_subjects_survive_a_text_sweep_that_finds_nothing(monkeypatch):+ # image_queries is an explicit request that succeeds on its own without a query, so+ # an empty TEXT sweep must not take the pictures down with it.+ class NoText(_SubjectDDGS):+ def text(+ self,+ query,+ max_results = 5,+ ):+ return []++ # ddgs signals an empty sweep by raising; the name is what tools.py matches on.+ class DDGSException(Exception):+ pass++ class RaisesEmpty(_SubjectDDGS):+ def text(+ self,+ query,+ max_results = 5,+ ):+ raise DDGSException("No results found for the given query.")++ class OnlyBlocked(_SubjectDDGS):+ def text(+ self,+ query,+ max_results = 5,+ ):+ return [{"title": "X", "href": "https://blocked.example/x", "body": "b"}]++ for engine in (NoText, RaisesEmpty):+ _SubjectDDGS.calls = []+ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = engine))+ result = tools._web_search("top dog breeds", include_images = True, image_queries = ["Pug"])+ assert tools.EMPTY_SEARCH_RESULTS[0] in result+ assert "Pug:\n- [[img:" in result+ assert sorted(_SubjectDDGS.calls) == ["Pug"]+ # With the setting off the parameter is acknowledged, not silently dropped.+ off = tools._web_search("top dog breeds", include_images = False, image_queries = ["Pug"])+ assert tools.IMAGE_SEARCH_DISABLED in off and "[[img:" not in off+ # No image_queries: the empty answer stays exactly as it was.+ assert (+ tools._web_search("top dog breeds", include_images = True)+ == (tools.EMPTY_SEARCH_RESULTS[0])+ )++ # Every hit filtered out by the website policy is the same empty answer.+ _SubjectDDGS.calls = []+ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = OnlyBlocked))+ scoped = tools._web_search(+ "top dog breeds",+ include_images = True,+ image_queries = ["Pug"],+ # The image hosts stay allowed; only the text hit's domain is out of scope.+ website_policy = {"allowedDomains": ["akc.org", "cdn.example.com", "example.com"]},+ )+ assert tools.EMPTY_SEARCH_RESULTS[1] in scoped and "Pug:\n- [[img:" in scoped+ # One image lookup, scoped by the same policy the text sweep used.+ assert len(_SubjectDDGS.calls) == 1 and _SubjectDDGS.calls[0].startswith("Pug")+++def test_a_genuine_search_failure_carries_no_pictures(monkeypatch):+ class Boom(_SubjectDDGS):+ def text(+ self,+ query,+ max_results = 5,+ ):+ raise RuntimeError("upstream exploded")++ _SubjectDDGS.calls = []+ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = Boom))+ result = tools._web_search("top dog breeds", include_images = True, image_queries = ["Pug"])+ # Pictures under an error would read as a partial answer.+ assert result.startswith("Search failed:") and "[[img:" not in result+ assert _SubjectDDGS.calls == []+++def test_clear_all_chats_beats_a_thumbnail_write_already_in_flight(monkeypatch, tmp_path):+ # The fetch copies its registry entry up front, so without the generation check it+ # could land tmp.replace() after the clear and restore a thumbnail on disk, where+ # the cache-first path would keep serving it.+ entry = search_images.register_images(RAW_IMAGES)[0]++ def clear_then_serve(url, **kwargs):+ search_images.clear_cache()+ return None, _png_bytes((60, 40)), "image/png"++ monkeypatch.setattr(tools, "_fetch_url_raw", clear_then_serve)+ assert search_images.thumbnail_bytes(entry["id"]) is None+ assert list(tmp_path.glob("*.jpg")) == []+ assert list(tmp_path.glob("*.tmp")) == []+ # A fetch with no clear racing it still caches, so the guard is not just "never write".+ monkeypatch.setattr(+ tools,+ "_fetch_url_raw",+ lambda url, **kwargs: (None, _png_bytes((60, 40)), "image/png"),+ )+ fresh = search_images.register_images(RAW_IMAGES)[0]+ assert search_images.thumbnail_bytes(fresh["id"]) is not None+ assert (tmp_path / f"{fresh['id']}.jpg").is_file()+++def test_clear_all_chats_beats_metadata_waiting_to_publish(monkeypatch, tmp_path):+ real_persist = search_images._persist_entry++ def clear_then_persist(*args):+ search_images.clear_cache()+ real_persist(*args)++ monkeypatch.setattr(search_images, "_persist_entry", clear_then_persist)+ entry = search_images.register_images(RAW_IMAGES)[0]++ assert search_images.lookup_image(entry["id"]) is None+ assert list(tmp_path.glob("*.json")) == []+++def test_clear_all_chats_invalidates_an_image_lookup_already_in_a_thread(monkeypatch, tmp_path):+ started = threading.Event()+ release = threading.Event()++ class BlockingDDGS:+ def __init__(self, **_kwargs):+ pass++ def images(+ self,+ query,+ max_results = 5,+ **kwargs,+ ):+ started.set()+ release.wait(2)+ return RAW_IMAGES++ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = BlockingDDGS))++ async def race_clear_against_lookup():+ task = asyncio.create_task(asyncio.to_thread(tools._image_search, ["Pug"], 20))+ try:+ assert await asyncio.to_thread(started.wait, 1)+ search_images.clear_cache()+ finally:+ release.set()+ return await task++ result = asyncio.run(race_clear_against_lookup())+ assert search_images.SEARCH_IMAGES_SENTINEL not in result+ assert search_images._registry == {}+ assert list(tmp_path.glob("*.json")) == []+++def test_clear_all_chats_invalidates_the_plain_query_image_sweep(monkeypatch, tmp_path):+ # The same race on the path with no image_queries: the sweep runs while the user+ # clears every chat, and without the generation it registers afterwards anyway --+ # the sidecar then outlives the clear and keeps the picture fetchable.+ started = threading.Event()+ release = threading.Event()++ class BlockingClient:+ def images(+ self,+ query,+ max_results = 5,+ **kwargs,+ ):+ started.set()+ release.wait(2)+ return RAW_IMAGES++ async def race_clear_against_sweep():+ task = asyncio.create_task(+ asyncio.to_thread(+ tools._web_search_images_suffix, BlockingClient(), "dog breeds", 5, None, None+ )+ )+ try:+ assert await asyncio.to_thread(started.wait, 1)+ search_images.clear_cache()+ finally:+ release.set()+ return await task++ assert asyncio.run(race_clear_against_sweep()) == ""+ assert search_images._registry == {}+ assert list(tmp_path.glob("*.json")) == []++ # No clear racing it: the same sweep still returns its images, so the guard is+ # not simply "never register".+ assert search_images.SEARCH_IMAGES_SENTINEL in tools._web_search_images_suffix(+ BlockingClient(), "dog breeds", 5, None, None+ )+++def test_a_clear_between_the_two_registry_reads_still_wins(monkeypatch, tmp_path):+ # The exact interleaving the first fix missed: the entry and the cache generation+ # were read under SEPARATE acquisitions, so a clear landing in the gap handed this+ # call the post-clear generation, the check before the write matched, and the+ # thumbnail the clear had just deleted was written straight back.+ entry = search_images.register_images(RAW_IMAGES)[0]+ real_lookup = search_images._lookup_locked++ def clearing_lookup(image_id):+ found = real_lookup(image_id)+ # Inline rather than clear_cache(): the caller already holds _registry_lock. It has+ # to move _full_clear_generation as well, because that -- not the bare generation --+ # is what a clear-everything raises to abort every in-flight fetch. Bumping only the+ # generation simulates a clear that spared this id, which is a different test.+ search_images._registry.clear()+ search_images._cache_generation += 1+ search_images._full_clear_generation = search_images._cache_generation+ for stale in tmp_path.glob("*"):+ stale.unlink()+ return found++ monkeypatch.setattr(search_images, "_lookup_locked", clearing_lookup)+ monkeypatch.setattr(+ tools, "_fetch_url_raw", lambda url, **kw: (None, _png_bytes((40, 30)), "image/png")+ )+ assert search_images.thumbnail_bytes(entry["id"]) is None+ assert list(tmp_path.glob("*.jpg")) == []+++def test_an_id_still_resolves_after_a_restart_that_never_cached_it(monkeypatch, tmp_path):+ # Chat history keeps ids, not URLs, and the browser only asks for a thumbnail once+ # it nears the viewport -- so a picture nobody scrolled to has no bytes on disk. The+ # in-memory registry does not survive the process, and reopening used to 404 forever.+ entry = search_images.register_images(RAW_IMAGES)[0]+ assert (tmp_path / f"{entry['id']}.json").is_file()+ assert not (tmp_path / f"{entry['id']}.jpg").exists(), "never materialized"++ search_images._registry.clear() # the restart+ monkeypatch.setattr(+ tools, "_fetch_url_raw", lambda url, **kw: (None, _png_bytes((40, 30)), "image/png")+ )+ data = search_images.thumbnail_bytes(entry["id"])+ assert data is not None and data[:3] == b"\xff\xd8\xff"++ # Clear all chats takes the metadata with the bytes, so nothing resolves afterwards.+ search_images.clear_cache()+ assert list(tmp_path.glob("*.json")) == [] and list(tmp_path.glob("*.jpg")) == []+ assert search_images.thumbnail_bytes(entry["id"]) is None+++def test_persisted_metadata_is_re_checked_on_the_way_back_in(monkeypatch, tmp_path):+ entry = search_images.register_images(RAW_IMAGES)[0]+ search_images._registry.clear()+ # A host that is no longer public must not be fetched just because it once was.+ (tmp_path / f"{entry['id']}.json").write_text(+ json.dumps({"thumbnail": "http://127.0.0.1/secret.png", "source": "http://127.0.0.1/x"})+ )+ monkeypatch.setattr(+ tools, "_fetch_url_raw", lambda url, **kw: pytest.fail("must not fetch a private host")+ )+ assert search_images.thumbnail_bytes(entry["id"]) is None+ # Corrupt or truncated metadata is a miss, never an error.+ (tmp_path / f"{entry['id']}.json").write_text("{not json")+ assert search_images.thumbnail_bytes(entry["id"]) is None+++def test_web_search_tool_with_images_adds_the_field_without_touching_the_base():+ with_images = tools.web_search_tool_with_images()+ props = with_images["function"]["parameters"]["properties"]+ assert "image_queries" in props+ assert "image_queries" not in tools.WEB_SEARCH_TOOL["function"]["parameters"]["properties"]+ assert with_images["function"]["name"] == "web_search"+++def test_image_search_caps_the_subject_count(monkeypatch):+ _SubjectDDGS.calls = []+ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = _SubjectDDGS))+ tools._image_search([f"Breed {i}" for i in range(9)])+ assert len(_SubjectDDGS.calls) == tools.IMAGE_SEARCH_MAX_QUERIES+++def test_status_line_names_the_image_queries():+ from core.inference.tool_loop_controller import status_for_tool++ assert status_for_tool("web_search", {"image_queries": ["a", "b"]}) == "Finding images: a, b"+ assert (+ status_for_tool("web_search", {"query": "dogs", "image_queries": ["a"]})+ == "Searching: dogs (images: a)"+ )+ assert status_for_tool("web_search", {"query": "dogs"}) == "Searching: dogs"+++def test_request_tools_swap_in_image_queries_only_with_the_setting(monkeypatch):+ # asyncio.run, not pytest.mark.asyncio: pytest-asyncio is not a backend dependency.+ asyncio.run(_request_tools_swap_case(monkeypatch))+++async def _request_tools_swap_case(monkeypatch):+ import routes.inference as inference_routes++ def has_image_queries(tools_list):+ return [+ "image_queries" in t["function"]["parameters"].get("properties", {})+ for t in tools_list+ if t["function"]["name"] == "web_search"+ ]++ payload = SimpleNamespace(+ enabled_tools = ["web_search", "python"],+ rag_scope = None,+ bypass_permissions = False,+ )+ monkeypatch.setattr(inference_routes, "_search_images_enabled", lambda: True)+ selected = await inference_routes._select_request_tools(+ payload, tools_on = True, mcp_allowed = False+ )+ assert [t["function"]["name"] for t in selected] == ["web_search", "python"]+ assert has_image_queries(selected) == [True]++ monkeypatch.setattr(inference_routes, "_search_images_enabled", lambda: False)+ selected = await inference_routes._select_request_tools(+ payload, tools_on = True, mcp_allowed = False+ )+ assert has_image_queries(selected) == [False]++ payload.enabled_tools = ["python"]+ monkeypatch.setattr(inference_routes, "_search_images_enabled", lambda: True)+ selected = await inference_routes._select_request_tools(+ payload, tools_on = True, mcp_allowed = False+ )+ assert [t["function"]["name"] for t in selected] == ["python"]+++def test_search_images_kwargs_follow_the_setting_and_the_signature(monkeypatch):+ monkeypatch.setattr(search_images, "search_images_enabled", lambda: True)++ def new_style(+ name,+ arguments,+ search_images = False,+ **kwargs,+ ):+ return ""++ def old_style(+ name,+ arguments,+ cancel_event = None,+ timeout = None,+ ):+ return ""++ assert accepts_kwarg(new_style, "search_images")+ assert not accepts_kwarg(old_style, "search_images")+ assert search_images_kwargs(new_style, "web_search") == {"search_images": True}+ assert search_images_kwargs(new_style, "python") == {}+ assert search_images_kwargs(old_style, "web_search") == {}++ monkeypatch.setattr(search_images, "search_images_enabled", lambda: False)+ assert search_images_kwargs(new_style, "web_search") == {}+++def test_search_images_enabled_reads_the_install_setting(monkeypatch):+ import storage.studio_db as db++ monkeypatch.setattr(db, "list_chat_settings", lambda: {"searchImages": True})+ assert search_images.search_images_enabled() is True+ monkeypatch.setattr(db, "list_chat_settings", lambda: {"searchImages": "yes"})+ assert search_images.search_images_enabled() is False+ monkeypatch.setattr(db, "list_chat_settings", lambda: (_ for _ in ()).throw(RuntimeError()))+ assert search_images.search_images_enabled() is False+++class _FakeResp:+ def __init__(self, body: bytes, content_type: str | None):+ self._body = body+ self._pos = 0+ self.headers = Message()+ if content_type is not None:+ self.headers["Content-Type"] = content_type++ def read(self, n: int | None = None) -> bytes:+ chunk = self._body[self._pos :] if n is None else self._body[self._pos : self._pos + n]+ self._pos += len(chunk)+ return chunk+++class _FakeOpener:+ def __init__(self, resp):+ self._resp = resp++ def open(+ self,+ req,+ timeout = None,+ ):+ return self._resp+++def _serve_bytes(+ monkeypatch,+ body: bytes,+ content_type: str = "image/png",+):+ monkeypatch.setattr(+ tools, "_validate_and_resolve_host", lambda host, port: (True, "", "93.184.216.34")+ )+ monkeypatch.setattr(+ tools.urllib.request,+ "build_opener",+ lambda *a, **k: _FakeOpener(_FakeResp(body, content_type)),+ )+++def test_fetch_url_raw_binary_mode_returns_bytes_and_caps_size(monkeypatch):+ _serve_bytes(monkeypatch, b"\x89PNG" + b"x" * 100)+ error, body, content_type = tools._fetch_url_raw(+ "https://example.com/a.png", timeout = 5, raw_bytes_max = 1024+ )+ assert error is None+ assert body == b"\x89PNG" + b"x" * 100+ assert content_type == "image/png"++ error, body, _ = tools._fetch_url_raw("https://example.com/a.png", timeout = 5, raw_bytes_max = 50)+ assert error is not None+ assert body == ""+++def test_fetch_url_raw_binary_mode_still_blocks_private_hosts():+ error, body, _ = tools._fetch_url_raw("http://127.0.0.1/x.png", timeout = 5, raw_bytes_max = 1024)+ assert error is not None+ assert body == ""+++def test_thumbnail_bytes_reencodes_and_caches(monkeypatch, tmp_path):+ entry = search_images.register_images(RAW_IMAGES)[0]+ _serve_bytes(monkeypatch, _png_bytes((800, 600)))++ data = search_images.thumbnail_bytes(entry["id"])+ assert data is not None and data[:3] == b"\xff\xd8\xff"+ from PIL import Image++ with Image.open(io.BytesIO(data)) as im:+ assert im.format == "JPEG"+ assert max(im.size) <= search_images.THUMBNAIL_EDGE_PX+ cached = tmp_path / f"{entry['id']}.jpg"+ assert cached.is_file()++ # Served from disk afterwards: no second fetch, even once the registry forgot the id+ # (a restart), so a reopened chat keeps its pictures.+ monkeypatch.setattr(+ tools.urllib.request, "build_opener", lambda *a, **k: pytest.fail("refetched")+ )+ assert search_images.thumbnail_bytes(entry["id"]) == data+ search_images._registry.clear()+ assert search_images.thumbnail_bytes(entry["id"]) == data+ assert search_images.thumbnail_bytes("../" + entry["id"]) is None+++ "body,content_type",+ [+ (b"<svg xmlns='http://www.w3.org/2000/svg'><script>1</script></svg>", "image/svg+xml"),+ (b"<html>not an image</html>", "image/png"),+ (b"", "image/png"),+ ],+)+def test_thumbnail_bytes_rejects_non_raster_bodies(monkeypatch, body, content_type):+ entry = search_images.register_images(RAW_IMAGES)[0]+ _serve_bytes(monkeypatch, body, content_type)+ assert search_images.thumbnail_bytes(entry["id"]) is None+++def test_thumbnail_bytes_rejects_decompression_bombs(monkeypatch):+ entry = search_images.register_images(RAW_IMAGES)[0]+ monkeypatch.setattr(search_images, "MAX_IMAGE_PIXELS", 1000)+ _serve_bytes(monkeypatch, _png_bytes((100, 100)))+ assert search_images.thumbnail_bytes(entry["id"]) is None+++def test_thumbnail_bytes_unknown_id():+ assert search_images.thumbnail_bytes("0123456789ab") is None+++def test_thumbnail_fetch_keeps_the_website_policy_of_the_search(monkeypatch):+ # register_images checks the policy, but the proxy fetch happens on a later+ # request: without carrying it, every redirect hop off an allowed image host+ # was re-checked against no policy at all.+ policy = {"allowedDomains": ["tse1.mm.bing.net", "akc.org"]}+ entry = search_images.register_images(RAW_IMAGES, policy)[0]+ seen = {}++ def fake_fetch(url, **kwargs):+ seen["url"] = url+ seen["website_policy"] = kwargs.get("website_policy")+ return None, _png_bytes((40, 30)), "image/png"++ monkeypatch.setattr(tools, "_fetch_url_raw", fake_fetch)+ assert search_images.thumbnail_bytes(entry["id"]) is not None+ assert seen["url"] == "https://tse1.mm.bing.net/th?id=golden"+ assert seen["website_policy"] == policy+++def client():+ app = FastAPI()+ app.include_router(studio_router, prefix = "/api/inference")+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ return TestClient(app)+++def test_route_serves_registered_thumbnails_only(client, monkeypatch):+ entry = search_images.register_images(RAW_IMAGES)[0]+ _serve_bytes(monkeypatch, _png_bytes())++ ok = client.get(f"/api/inference/search-images/{entry['id']}")+ assert ok.status_code == 200+ assert ok.headers["content-type"] == "image/jpeg"+ assert ok.headers["x-content-type-options"] == "nosniff"+ assert ok.content[:3] == b"\xff\xd8\xff"++ assert client.get("/api/inference/search-images/0123456789ab").status_code == 404+ assert client.get("/api/inference/search-images/..%2F..%2Fetc").status_code == 404+ assert client.get("/api/inference/search-images/not-hex-at-all").status_code == 404+++def test_lookup_route_returns_subject_images_only_when_enabled(client, monkeypatch):+ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = _SubjectDDGS))+ monkeypatch.setattr(search_images, "search_images_enabled", lambda: False)+ assert (+ client.post("/api/inference/search-images/lookup", json = {"subjects": ["Pug"]}).status_code+ == 403+ )++ monkeypatch.setattr(search_images, "search_images_enabled", lambda: True)+ response = client.post(+ "/api/inference/search-images/lookup", json = {"subjects": ["Pug", "Beagle"]}+ )+ assert response.status_code == 200+ body = response.json()+ assert "Pug:\n- [[img:" in body["text"]+ assert search_images.SEARCH_IMAGES_SENTINEL not in body["text"]+ assert {e["subject"] for e in body["images"]} == {"Pug", "Beagle"}+ assert all("thumbnail" not in e for e in body["images"])+ assert (+ client.post("/api/inference/search-images/lookup", json = {"subjects": []}).status_code == 422+ )+ assert (+ client.post("/api/inference/search-images/lookup", json = {"subjects": ["a"] * 6}).status_code+ == 422+ )+++def test_route_has_no_url_parameter(client):+ # A URL-taking proxy would be an open fetch relay; the route must ignore one.+ response = client.get(+ "/api/inference/search-images/0123456789ab", params = {"url": "https://evil.test/x"}+ )+ assert response.status_code == 404+++def test_route_requires_auth():+ app = FastAPI()+ app.include_router(studio_router, prefix = "/api/inference")+ anonymous = TestClient(app)+ entry = search_images.register_images(RAW_IMAGES)[0]+ response = anonymous.get(f"/api/inference/search-images/{entry['id']}")+ assert response.status_code in (401, 403)+++def test_one_locked_thumbnail_does_not_strand_the_rest_of_the_clear(monkeypatch, tmp_path):+ # A JPEG another process holds open on Windows raises on unlink. Aborting the+ # sweep there left every later file on disk, and thumbnail_bytes reads the+ # cache before the registry, so those ids kept serving after a clear.+ entries = [search_images.register_images(RAW_IMAGES)[0] for _ in range(3)]+ monkeypatch.setattr(+ tools, "_fetch_url_raw", lambda url, **kw: (None, _png_bytes((40, 30)), "image/png")+ )+ for entry in entries:+ assert search_images.thumbnail_bytes(entry["id"]) is not None+ stuck = tmp_path / f"{entries[1]['id']}.jpg"+ real_unlink = Path.unlink++ def unlink(self, *args, **kwargs):+ if self == stuck:+ raise OSError(13, "in use by another process")+ return real_unlink(self, *args, **kwargs)++ monkeypatch.setattr(Path, "unlink", unlink)+ search_images.clear_cache()+ monkeypatch.undo()++ left = {path.name for path in tmp_path.iterdir()}+ assert left == {stuck.name}, f"only the locked file may survive, found {sorted(left)}"+ assert search_images._registry == {}+ for entry in entries:+ if entry["id"] == entries[1]["id"]:+ continue+ assert search_images.thumbnail_bytes(entry["id"]) is None+++def test_a_thumbnail_the_clear_could_not_unlink_is_not_served(monkeypatch, tmp_path):+ # Same Windows situation as above, from the reader's side: the cache-first read+ # and the sidecar read both go around the registry, so the file the clear left+ # behind would have gone on answering for a picture the user had cleared.+ entry = search_images.register_images(RAW_IMAGES)[0]+ monkeypatch.setattr(+ tools, "_fetch_url_raw", lambda url, **kw: (None, _png_bytes((40, 30)), "image/png")+ )+ assert search_images.thumbnail_bytes(entry["id"]) is not None+ stuck = tmp_path / f"{entry['id']}.jpg"+ real_unlink = Path.unlink+ held = [True]++ def unlink(self, *args, **kwargs):+ if self == stuck and held[0]:+ raise OSError(13, "in use by another process")+ return real_unlink(self, *args, **kwargs)++ monkeypatch.setattr(Path, "unlink", unlink)+ search_images.clear_cache()+ assert stuck.is_file()+ assert search_images.thumbnail_bytes(entry["id"]) is None+ # Once the other process lets go, the retry reaps it and the id is ordinary again.+ held[0] = False+ assert search_images.thumbnail_bytes(entry["id"]) is None+ assert not stuck.exists()+ assert list(tmp_path.iterdir()) == []+++def test_a_sidecar_the_clear_could_not_unlink_cannot_resurrect_an_id(monkeypatch, tmp_path):+ # The sidecar carries the thumbnail and source URLs, so a surviving one is the+ # half of the pair that matters: it is what lets a cleared id be fetched again.+ entry = search_images.register_images(RAW_IMAGES)[0]+ stuck = tmp_path / f"{entry['id']}.json"+ real_unlink = Path.unlink++ def unlink(self, *args, **kwargs):+ if self == stuck:+ raise OSError(13, "in use by another process")+ return real_unlink(self, *args, **kwargs)++ monkeypatch.setattr(Path, "unlink", unlink)+ search_images.clear_cache()+ assert stuck.is_file()+ monkeypatch.setattr(+ tools, "_fetch_url_raw", lambda url, **kw: (None, _png_bytes((40, 30)), "image/png")+ )+ assert search_images.thumbnail_bytes(entry["id"]) is None+ assert not (tmp_path / f"{entry['id']}.jpg").exists()+++def test_the_route_rejects_an_id_with_a_trailing_newline():+ # `$` matches before a trailing newline, so `.match` alone let one through to+ # the store, which refused it with fullmatch. Refuse it at the door instead.+ assert search_images.IMAGE_ID_RE.fullmatch("0123456789ab\n") is None+ assert (+ search_images.is_image_entry(+ {"id": "0123456789ab\n", "title": "t", "domain": "d", "source": "https://example.com/"}+ )+ is False+ )+ app = FastAPI()+ app.include_router(studio_router, prefix = "/api/inference")+ app.dependency_overrides[get_current_subject] = lambda: "tester"+ client = TestClient(app)+ response = client.get("/api/inference/search-images/0123456789ab%0A")+ assert response.status_code == 404+++def _fake_ddgs_with_text(monkeypatch):+ class FakeDDGS:+ def __init__(self, **_kwargs):+ pass++ def text(+ self,+ query,+ max_results = 5,+ ):+ return [{"title": "AKC", "href": "https://akc.org/x", "body": "Breeds"}]++ def images(+ self,+ query,+ max_results = 5,+ **kwargs,+ ):+ return RAW_IMAGES++ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))+++def test_a_failing_subject_lookup_does_not_discard_the_text_results(monkeypatch):+ # The named-subject branch sits inside _web_search's own `except`, so a raise+ # there came back as "Search failed: ..." with the results thrown away. The two+ # sibling branches already swallow; this one has to as well.+ _fake_ddgs_with_text(monkeypatch)++ def boom(*_args, **_kwargs):+ raise RuntimeError("can't start new thread")++ monkeypatch.setattr(tools, "_image_search", boom)+ result = tools._web_search(+ "dog breeds", include_images = True, image_queries = ["Golden Retriever"]+ )+ assert "Title: AKC" in result+ assert "Search failed" not in result+ assert search_images.SEARCH_IMAGES_SENTINEL not in result+++def test_a_failing_image_only_lookup_still_returns_a_string(monkeypatch):+ # This branch is evaluated before the try, so it carries its own guard:+ # execute_tool answers with a string for every input the model can send.+ _fake_ddgs_with_text(monkeypatch)++ def boom(*_args, **_kwargs):+ raise RuntimeError("can't start new thread")++ monkeypatch.setattr(tools, "_image_search", boom)+ result = tools._web_search("", include_images = True, image_queries = ["Golden Retriever"])+ assert result == "No images found for: Golden Retriever"+++def test_an_unreadable_cache_dir_snapshots_as_clear_everything(monkeypatch, tmp_path):+ """The OSError fallback has to be the full-clear sentinel, not an empty selection.++ `registered_image_ids` bounds the reap that follows it. When it cannot enumerate+ the cache its snapshot is incomplete, so the only safe answer is None -- which+ `clear_cache` reads as "clear everything", the behaviour a clear had before the+ snapshot existed. Returning `set()` instead reads as a selective reap of nothing:+ "Clear all chats" would leave the registry populated and every thumbnail -- which+ says what the user searched for -- still fetchable.+ """++ class _UnreadableDir(type(tmp_path)):+ def glob(self, _pattern):+ raise OSError("permission denied")++ entries = search_images.register_images(RAW_IMAGES)+ assert entries, "need a registered image for the reap to have something to miss"+ monkeypatch.setattr(search_images, "_cache_dir", lambda: _UnreadableDir(tmp_path))++ snapshot = search_images.registered_image_ids()+ assert snapshot is None, "an incomplete snapshot must not bound the reap"++ search_images.clear_cache(snapshot)+ assert search_images._registry == {}, "a clear that could not snapshot must still clear"+ assert search_images.lookup_image(entries[0]["id"]) is None+++def test_a_selective_clear_does_not_abort_a_fetch_for_an_image_it_spared(monkeypatch, tmp_path):+ """The whole point of the snapshot is that a spared image keeps working.++ `clear_cache` bumps the generation for a selective reap too, and the in-flight check used+ to compare that bare number: a fetch already running for an id the clear went out of its+ way to spare therefore aborted, thumbnail_bytes answered None and the endpoint 404ed. The+ frontend does not recover from that -- SearchImageThumb sets `failed`, renders nothing,+ and its effect depends only on (id, nearViewport), so nothing re-runs it. The card is gone+ until the component remounts.+ """+ spared = search_images.register_images(RAW_IMAGES)[0]+ # Only one of RAW_IMAGES survives the policy filter, and this needs a second id purely+ # as something for the clear to reap. Straight into the registry: what matters is that+ # it is NOT the id being fetched.+ doomed_id = "0123456789ab"+ search_images._registry[doomed_id] = dict(search_images._registry[spared["id"]])+ real_lookup = search_images._lookup_locked++ def clearing_lookup(image_id):+ found = real_lookup(image_id)+ # A selective clear landing mid-fetch, reaping the OTHER image. Inline because the+ # caller already holds _registry_lock; the bookkeeping matches clear_cache's.+ search_images._registry.pop(doomed_id, None)+ search_images._cache_generation += 1+ search_images._reaped_at[doomed_id] = search_images._cache_generation+ return found++ monkeypatch.setattr(search_images, "_lookup_locked", clearing_lookup)+ monkeypatch.setattr(+ tools, "_fetch_url_raw", lambda url, **kw: (None, _png_bytes((40, 30)), "image/png")+ )++ assert (+ search_images.thumbnail_bytes(spared["id"]) is not None+ ), "a clear that deliberately kept this image must not take its in-flight fetch down"+ assert list(tmp_path.glob(f"{spared['id']}.jpg")), "and its bytes belong on disk"+++def test_a_selective_clear_still_aborts_the_fetch_for_an_image_it_reaped(monkeypatch, tmp_path):+ """The other half. Publishing here would write back a thumbnail the clear just deleted,+ and the cache-first read would go on serving it."""+ doomed = search_images.register_images(RAW_IMAGES)[0]+ real_lookup = search_images._lookup_locked++ def clearing_lookup(image_id):+ found = real_lookup(image_id)+ search_images._registry.pop(doomed["id"], None)+ search_images._cache_generation += 1+ search_images._reaped_at[doomed["id"]] = search_images._cache_generation+ for stale in tmp_path.glob("*"):+ stale.unlink()+ return found++ monkeypatch.setattr(search_images, "_lookup_locked", clearing_lookup)+ monkeypatch.setattr(+ tools, "_fetch_url_raw", lambda url, **kw: (None, _png_bytes((40, 30)), "image/png")+ )++ assert search_images.thumbnail_bytes(doomed["id"]) is None+ assert list(tmp_path.glob("*.jpg")) == []+++def test_an_overflowing_reap_record_drops_the_oldest_not_everything(monkeypatch, tmp_path):+ """The per-id record is bounded, and running out of room must not abort live fetches.++ Clearing it and promoting the clear to a full-clear marker was the first attempt. That+ aborts every fetch in flight, including ones for images the clear deliberately spared,+ and an aborted fetch is not a cheap retry: thumbnail_bytes answers None, the endpoint+ 404s, and useSearchThumbnail records a permanent failure for that id.++ Dropping the OLDEST records and raising a floor keeps every fetch that started at or+ after the floor exactly answerable. The assertion is taken across the clear that+ actually overflows, which is the only moment the two strategies differ.+ """+ monkeypatch.setattr(search_images, "_REAPED_AT_MAX", 4)+ monkeypatch.setattr(search_images, "_reaped_at", {})+ monkeypatch.setattr(search_images, "_reaped_floor_generation", 0)+ monkeypatch.setattr(search_images, "_full_clear_generation", 0)++ # Two clears that fit, then one that does not.+ search_images.clear_cache({"000000000000", "000000000001"})+ search_images.clear_cache({"000001000000", "000001000001"})+ in_flight_generation = search_images.cache_generation()+ search_images.clear_cache({"000002000000", "000002000001"})++ assert search_images._reaped_at, "records must survive the overflow; clearing them was the bug"+ assert (+ search_images._reaped_at.get("000002000000") == search_images.cache_generation()+ ), "the reap that overflowed is exactly the one that must still be remembered"++ with search_images._registry_lock:+ # A fetch already running for an image no clear ever named. Promoting the overflow+ # to a full clear took this down with everything else.+ assert search_images._reaped_since_locked("ffffffffffff", in_flight_generation) is False+ # And the ids that clear really did take are still known to be reaped.+ assert search_images._reaped_since_locked("000002000000", in_flight_generation) is True+++def test_the_overflow_floor_still_refuses_a_fetch_older_than_every_record(monkeypatch):+ """The one case the floor gives up on, kept honest: older than anything still held."""+ monkeypatch.setattr(search_images, "_REAPED_AT_MAX", 4)+ monkeypatch.setattr(search_images, "_reaped_at", {})+ monkeypatch.setattr(search_images, "_reaped_floor_generation", 0)++ for round_index in range(4):+ search_images.clear_cache({f"{round_index:06d}{index:06d}" for index in range(2)})++ floor = search_images._reaped_floor_generation+ assert floor > 0, "the cap has to have forced a floor for this to mean anything"+ with search_images._registry_lock:+ assert search_images._reaped_since_locked("ffffffffffff", floor - 1) is True+ assert search_images._reaped_since_locked("ffffffffffff", floor) is False+++def test_a_full_clear_still_aborts_every_fetch_including_unknown_ids():+ """The blunt signal is still right for a clear-everything: nothing survives it."""+ before = search_images.cache_generation()+ search_images.clear_cache()+ with search_images._registry_lock:+ assert search_images._reaped_since_locked("ffffffffffff", before) is True+++def test_a_lookup_already_running_when_a_clear_starts_publishes_nothing(monkeypatch, tmp_path):+ """Bounding the reap to a snapshot spares whatever registers after it. That is right for+ a chat created since the clear, and wrong for a lookup the clear is deleting the answer+ of -- `/search-images/lookup` carries no thread, so no cancellation reaches it, and it+ samples the cache generation on entry.++ Without a fence at the clear boundary its images register into the window between the+ snapshot and the reap, the selective reap spares them, and Clear all leaves their+ sidecars on disk saying what was searched for.+ """+ monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path)++ # What _image_search does on entry, before it goes to the network.+ sampled = search_images.cache_generation()++ # The clear reaches its boundary while that lookup is still out.+ snapshot = search_images.snapshot_and_fence_registrations()+ assert snapshot is not None++ # The lookup comes back and tries to publish.+ published = search_images.register_images(RAW_IMAGES, expected_generation = sampled)++ assert (+ published == []+ ), "an answer this clear is deleting must not get its images registered behind it"+ assert list(tmp_path.glob("*.json")) == [], "and no sidecar may be written either"+++def test_a_lookup_that_starts_after_the_clear_boundary_still_registers(monkeypatch, tmp_path):+ """The complement. A chat created after the clear is exactly what the snapshot spares,+ so its lookups must go through untouched."""+ monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path)++ search_images.snapshot_and_fence_registrations()+ sampled = search_images.cache_generation()+ published = search_images.register_images(RAW_IMAGES, expected_generation = sampled)++ assert published, "a lookup that started after the boundary belongs to a surviving chat"+++def test_the_fence_does_not_abort_an_in_flight_fetch(monkeypatch, tmp_path):+ """The fence moves the generation, and fetch invalidation is per id now, so a fetch+ already running for an image the clear will spare must be unaffected. Reading the bare+ generation here would undo the per-id work."""+ monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path)+ started_at = search_images.cache_generation()++ search_images.snapshot_and_fence_registrations()++ with search_images._registry_lock:+ assert search_images._reaped_since_locked("ffffffffffff", started_at) is Falsediff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex 4d573c231d7..8f701b2b0f2 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -11,6 +11,18 @@ import {isRenderableRenderHtmlToolPart,isSvgFence,} from "@/features/chat/artifacts/html-fences";+// Leaf module, not the feature barrel: SEARCH_IMAGE_TAG is read at module scope+// below, and the barrel sits in an import cycle with this file (TDZ at load).+// eslint-disable-next-line no-restricted-imports+import {+ holdBackPartialSearchImageToken,+ parseSearchImagesSignature,+ placeSubjectImages,+ precedingTextForMessagePart,+ rewriteSearchImageTokens,+ SEARCH_IMAGE_TAG,+ searchImagesSignature,+} from "@/features/chat/search-images/search-images";import { copyToClipboard } from "@/lib/copy-to-clipboard";import { preprocessLaTeX } from "@/lib/latex";import { downloadFile, isDownloadCancelled } from "@/lib/native-files";@@ -18,7 +30,12 @@ import { openLink } from "@/lib/open-link";import { safeMarkdownUrl } from "@/lib/safe-markdown-url";import { Tick02Icon } from "@/lib/tick-icon";import { toast } from "@/lib/toast";-import { INTERNAL, useAuiState, useMessagePartText } from "@assistant-ui/react";+import {+ INTERNAL,+ useAui,+ useAuiState,+ useMessagePartText,+} from "@assistant-ui/react";import { Copy01Icon, Download01Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { createMathPlugin } from "@streamdown/math";@@ -54,6 +71,7 @@ import {} from "./markdown-block-boundary";import "katex/dist/katex.min.css";import { AudioPlayer } from "./audio-player";+import { SearchImageElement, SearchImagesContext } from "./search-image";import { unslothDarkTheme, unslothLightTheme } from "./code-themes";import { stabilizeStreamingMarkdown } from "./streaming-markdown";import {@@ -108,7 +126,13 @@ const STREAMDOWN_COMPONENTS = {{children}</a>),+ // Module-scoped: Streamdown's memo comparator ignores `components`.+ [SEARCH_IMAGE_TAG]: SearchImageElement,};+// Through the sanitizer; the component drops tokens it cannot resolve.+const STREAMDOWN_ALLOWED_TAGS = {+ [SEARCH_IMAGE_TAG]: ["token"],+} satisfies NonNullable<StreamdownProps["allowedTags"]>;const COPY_RESET_MS = 2000;const MERMAID_SOURCE_RE = /```mermaid\s*([\s\S]*?)```/i;const ACTION_PANEL_CLASS =@@ -631,8 +655,17 @@ function useCoalescedStreamingText(return text;}+/** False inside the reasoning block, which renders through this same component. */+export const SearchImagesEnabledContext = createContext(true);+const MarkdownTextImpl = () => {+ const allowSearchImages = useContext(SearchImagesEnabledContext);+ const aui = useAui();const { text, status } = useMessagePartText();+ const partIndex =+ aui.part.source === "message" && aui.part.query.type === "index"+ ? aui.part.query.index+ : 0;// Parts are keyed by index, so switching conversations hands this instance a// different message, and Streamdown only extends its parsed blocks: key it per// message. The cache generation joins the key for the case the Markdown string@@ -642,11 +675,57 @@ const MarkdownTextImpl = () => {const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>message.parts.some(isRenderableRenderHtmlToolPart),);+ // A string, not the Map: selector results are compared by identity.+ const searchImagesKey = useAuiState(({ message }) =>+ allowSearchImages ? searchImagesSignature(message.parts) : "",+ );+ const searchImages = useMemo(+ () => parseSearchImagesSignature(searchImagesKey),+ [searchImagesKey],+ );+ // What earlier text parts said, so a subject named in two of them gets one card.+ const precedingText = useAuiState(({ message }) =>+ allowSearchImages+ ? precedingTextForMessagePart(message.parts, partIndex)+ : "",+ );+ const messageTextKey = useAuiState(({ message }) =>+ allowSearchImages+ ? JSON.stringify(+ message.parts+ .filter((part) => part.type === "text")+ .map((part) => part.text),+ )+ : "[]",+ );+ const messageTexts = useMemo(+ () => JSON.parse(messageTextKey) as string[],+ [messageTextKey],+ );const isStreaming = status.type === "running";const displayText = useCoalescedStreamingText(text, isStreaming, messageId);const processedText = useMemo(- () => stabilizeStreamingMarkdown(preprocessLaTeX(displayText), isStreaming),- [displayText, isStreaming],+ () =>+ stabilizeStreamingMarkdown(+ preprocessLaTeX(+ rewriteSearchImageTokens(+ placeSubjectImages(+ // No images means nothing to hold back, not even a trailing `[`.+ holdBackPartialSearchImageToken(+ displayText,+ isStreaming && searchImages.size > 0,+ ),+ searchImages,+ isStreaming,+ precedingText,+ messageTexts,+ ),+ searchImages,+ ),+ ),+ isStreaming,+ ),+ [displayText, isStreaming, messageTexts, precedingText, searchImages],);const incrementalCacheRef = useRef({messageId,@@ -672,24 +751,27 @@ const MarkdownTextImpl = () => {<RenderHtmlToolPresenceContext.Providervalue={messageHasRenderableRenderHtmlTool}>- <div data-status={status.type} className="min-w-0 max-w-full">- <Streamdown- key={`${messageId}:${incrementalCache.renderGeneration}`}- mode="streaming"- parseIncompleteMarkdown={!incrementalRender}- parseMarkdownIntoBlocksFn={incrementalRender?.parseMarkdownIntoBlocks}- isAnimating={isStreaming}- animated={STREAMDOWN_IMMEDIATE_UPDATES}- plugins={STREAMDOWN_PLUGINS}- components={STREAMDOWN_COMPONENTS}- urlTransform={safeMarkdownUrl}- controls={STREAMDOWN_CONTROLS}- shikiTheme={STREAMDOWN_SHIKI_THEME}- BlockComponent={StreamdownBlock}- >- {incrementalRender?.markdown ?? processedText}- </Streamdown>- </div>+ <SearchImagesContext.Provider value={searchImages}>+ <div data-status={status.type} className="min-w-0 max-w-full">+ <Streamdown+ key={`${messageId}:${incrementalCache.renderGeneration}`}+ mode="streaming"+ parseIncompleteMarkdown={!incrementalRender}+ parseMarkdownIntoBlocksFn={incrementalRender?.parseMarkdownIntoBlocks}+ isAnimating={isStreaming}+ animated={STREAMDOWN_IMMEDIATE_UPDATES}+ plugins={STREAMDOWN_PLUGINS}+ components={STREAMDOWN_COMPONENTS}+ allowedTags={STREAMDOWN_ALLOWED_TAGS}+ urlTransform={safeMarkdownUrl}+ controls={STREAMDOWN_CONTROLS}+ shikiTheme={STREAMDOWN_SHIKI_THEME}+ BlockComponent={StreamdownBlock}+ >+ {incrementalRender?.markdown ?? processedText}+ </Streamdown>+ </div>+ </SearchImagesContext.Provider></RenderHtmlToolPresenceContext.Provider>);};diff --git a/studio/frontend/src/components/assistant-ui/reasoning.tsx b/studio/frontend/src/components/assistant-ui/reasoning.tsxindex d61f60132eb..456cc299a27 100644--- a/studio/frontend/src/components/assistant-ui/reasoning.tsx+++ b/studio/frontend/src/components/assistant-ui/reasoning.tsx@@ -5,7 +5,10 @@/* eslint-disable react-refresh/only-export-components */-import { MarkdownText } from "@/components/assistant-ui/markdown-text";+import {+ MarkdownText,+ SearchImagesEnabledContext,+} from "@/components/assistant-ui/markdown-text";import {Collapsible,CollapsibleContent,@@ -322,7 +325,11 @@ function ReasoningText({);}-const ReasoningImpl: ReasoningMessagePartComponent = () => <MarkdownText />;+const ReasoningImpl: ReasoningMessagePartComponent = () => (+ <SearchImagesEnabledContext.Provider value={false}>+ <MarkdownText />+ </SearchImagesEnabledContext.Provider>+);const COPY_RESET_MS = 2000;diff --git a/studio/frontend/src/components/assistant-ui/search-image.tsx b/studio/frontend/src/components/assistant-ui/search-image.tsxnew file mode 100644index 00000000000..50fb649e2c1--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/search-image.tsx@@ -0,0 +1,187 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"use client";++import { authFetch } from "@/features/auth";+import { type SearchImageEntry, searchImagePath } from "@/features/chat";+import { openLink } from "@/lib/open-link";+import { cn } from "@/lib/utils";+import {+ createContext,+ memo,+ useContext,+ useEffect,+ useRef,+ useState,+} from "react";++// Provided once per message part by MarkdownText, so every chip reads the same map.+export const SearchImagesContext = createContext<+ ReadonlyMap<string, SearchImageEntry>+>(new Map());++type LoadState =+ | { status: "idle" }+ | { status: "loaded"; url: string }+ | { status: "failed" };++const IDLE: LoadState = { status: "idle" };++function useSearchThumbnail(id: string, nearViewport: boolean): LoadState {+ // Keyed by id so a re-used element for another image reads idle, not the+ // previous image's blob, without resetting state inside the effect.+ const [state, setState] = useState<{ id: string; load: LoadState }>({+ id,+ load: IDLE,+ });++ useEffect(() => {+ if (!nearViewport) return;+ const controller = new AbortController();+ let objectUrl: string | null = null;++ authFetch(searchImagePath(id), { signal: controller.signal })+ .then(async (response) => {+ if (!response.ok) {+ // Guarded like the success path below: a non-ok response for the id this+ // element used to hold would otherwise write that id's state back, and the+ // render below falls through to idle for it -- a skeleton that never resolves+ // because the effect has no reason to run again.+ if (controller.signal.aborted) return;+ setState({ id, load: { status: "failed" } });+ return;+ }+ const blob = await response.blob();+ if (controller.signal.aborted) return;+ objectUrl = URL.createObjectURL(blob);+ setState({ id, load: { status: "loaded", url: objectUrl } });+ })+ .catch(() => {+ if (!controller.signal.aborted) {+ setState({ id, load: { status: "failed" } });+ }+ });++ return () => {+ controller.abort();+ if (objectUrl) URL.revokeObjectURL(objectUrl);+ };+ }, [id, nearViewport]);++ return state.id === id ? state.load : IDLE;+}++function useNearViewport<T extends Element>() {+ const ref = useRef<T>(null);+ const [near, setNear] = useState(+ () => typeof IntersectionObserver === "undefined",+ );+ useEffect(() => {+ if (near) return;+ const element = ref.current;+ if (!element) return;+ const observer = new IntersectionObserver(+ (entries) => {+ if (entries.some((entry) => entry.isIntersecting)) {+ setNear(true);+ observer.disconnect();+ }+ },+ { rootMargin: "200px" },+ );+ observer.observe(element);+ return () => observer.disconnect();+ }, [near]);+ return [ref, near] as const;+}++export function SearchImageThumb({+ entry,+ className,+ size = "card",+}: {+ entry: SearchImageEntry;+ className?: string;+ size?: "card" | "strip";+}) {+ const [ref, nearViewport] = useNearViewport<HTMLAnchorElement>();+ const image = useSearchThumbnail(entry.id, nearViewport);+ // Only a card the backend actually served gets a live link.+ const href = image.status === "loaded" ? entry.source : undefined;+ const label = entry.title || entry.domain || "Image";++ if (image.status === "failed") return null;++ return (+ <a+ ref={ref}+ href={href}+ rel="noopener noreferrer"+ title={entry.domain ? `${label} · ${entry.domain}` : label}+ aria-label={label}+ onClick={(event) => {+ if (href && openLink(href)) event.preventDefault();+ }}+ className={cn(+ "group inline-flex shrink-0 flex-col overflow-hidden rounded-lg border border-border bg-muted/40 text-left no-underline transition-colors hover:border-primary/50",+ size === "card" ? "max-w-[320px]" : "size-16",+ className,+ )}+ >+ <span+ className={cn(+ "block overflow-hidden bg-muted",+ size === "card" ? "h-40 w-full min-w-[160px]" : "size-full",+ )}+ >+ {image.status === "loaded" ? (+ <img+ src={image.url}+ alt={label}+ loading="lazy"+ decoding="async"+ className="size-full object-cover"+ />+ ) : (+ <span className="block size-full animate-pulse bg-muted" />+ )}+ </span>+ {size === "card" && (+ <span className="flex min-w-0 flex-col gap-0.5 px-2 py-1.5">+ {entry.title && (+ <span className="truncate text-xs font-medium text-foreground">+ {entry.title}+ </span>+ )}+ {entry.domain && (+ <span className="truncate text-ui-10 text-muted-foreground">+ {entry.domain}+ </span>+ )}+ </span>+ )}+ </a>+ );+}++// Rendered by Streamdown for <search-image token="…">; a token the message cannot+// resolve renders nothing, so an invented one never shows as text or markup.+export const SearchImageElement = memo(function SearchImageElement(props: {+ token?: string;+}) {+ const images = useContext(SearchImagesContext);+ const entry = props.token ? images.get(props.token) : undefined;+ if (!entry) return null;+ // Explicitly block: a list item styles its paragraphs `[&>p]:inline`, so an+ // inline card would flow into the sentence and the text would wrap around it.+ // `empty:hidden` keeps a thumb that failed to load from leaving a gap.+ return (+ <span+ className="my-2 flex flex-wrap gap-2 empty:hidden"+ data-search-image={entry.id}+ >+ <SearchImageThumb entry={entry} />+ </span>+ );+});diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex d68d6e150e6..58bce5e1586 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -64,6 +64,7 @@ import {isStudioDictationAvailable,notifyStudioDictationUnavailable,YoutubeTranscriptPrompt,+ stripSearchImageTokens,} from "@/features/chat";import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";import {@@ -7594,7 +7595,9 @@ const CopyButton: FC = () => {const handleCopy = async () => {// getCopyText reads content only, and a long paste sits in an attachment.const pasted = attachmentsPastedText(aui.message().getState().attachments);- const text = [aui.message().getCopyText(), pasted]+ // The image tokens are renderer markup, not prose: strip them or the clipboard+ // gets `[[img:0123456789ab]]` where the picture was.+ const text = [stripSearchImageTokens(aui.message().getCopyText()), pasted].filter((part) => part.length > 0).join("\n\n");if (await copyToClipboard(text)) {@@ -7647,7 +7650,9 @@ const EditAssistantMessageButton: FC = () => {async function exportMessageMarkdown(content: string): Promise<void> {try {await downloadFile(- content,+ // Same rule as the copy button and the whole-chat export: the tokens are+ // renderer markup, so a saved answer must not carry them as prose.+ stripSearchImageTokens(content),`message-${Date.now()}.md`,"text/markdown",);@@ -7773,9 +7778,13 @@ const AssistantActionBar: FC = () => {// reasoning, tool calls and citations would be dropped and a// tool-only reply would read as empty. Same conversion the// whole-chat save runs.- const text = replySourceMarkdown(- aui.message().getState().content,- toolResultModelText,+ // Stripped: a project source is retrieved back into context, so+ // saved tokens would teach the model ids that resolve to nothing.+ const text = stripSearchImageTokens(+ replySourceMarkdown(+ aui.message().getState().content,+ toolResultModelText,+ ),);if (!text.trim()) {toast.info("No content to save.");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 a20236e3729..204d1a93a2a 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@@ -3,11 +3,16 @@"use client";-import { type ToolCallMessagePartComponent, useAuiState } from "@assistant-ui/react";+import {+ type ToolCallMessagePartComponent,+ useAuiState,+} from "@assistant-ui/react";import { GlobeIcon } from "lucide-react";+import { isSearchImagesToolResult } from "@/features/chat";import { stringifyToolResult } from "@/lib/strip-ansi";import { memo, useEffect, useState } from "react";+import { SearchImageThumb } from "./search-image";import { Source, SourceIcon, SourceTitle } from "./sources";import {ToolFallbackContent,@@ -28,7 +33,8 @@ const RE_SNIPPET = /Snippet:\s*(.+)/s;// Mirrors _normalize_url_scheme: a dotted host, optionally followed by a port// that may be empty ("example.com:" fetches on the default port) but otherwise// has to be in range, so the card names a host only when the backend fetches it.-const RE_BARE_HOST = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+(?::(\d{0,5}))?(?:[/?#]|$)/;+const RE_BARE_HOST =+ /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+(?::(\d{0,5}))?(?:[/?#]|$)/;function isBareHostFetchedAsHttps(value: string): boolean {const match = RE_BARE_HOST.exec(value);@@ -81,9 +87,22 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({result,status,}) => {- const query = (args as { query?: string })?.query ?? "";- const url = ((args as { url?: string })?.url ?? "").trim();+ // Coerced, like image_queries below: a local model routinely emits a number or an+ // object here, and .trim() on one crashes the card that was meant to show the call.+ const query = String((args as { query?: unknown })?.query ?? "");+ const url = String((args as { url?: unknown })?.url ?? "").trim();const isUrlFetch = !!url;+ const rawImageQueries = (args as { image_queries?: unknown })?.image_queries;+ const imageQueries = Array.isArray(rawImageQueries)+ ? rawImageQueries+ .map((q) => String(q).trim())+ .filter(Boolean)+ .slice(0, 5)+ : [];+ const imageLabel = imageQueries.join(", ");+ const isImageOnly = !isUrlFetch && !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);const displayDomain = (() => {if (!url) return "";// new URL() throws on the bare hosts the backend fetches, so mirror that@@ -92,19 +111,32 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({const candidate = isBareHostFetchedAsHttps(bare) ? `https://${bare}` : url;try {const parsed = new URL(candidate);- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return "";+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")+ return "";return parsed.hostname.replace(/^www\./, "");} catch {return "";}})();const isRunning = status?.type === "running";- const resultText = result == null ? "" : stringifyToolResult(result);+ const withImages = isSearchImagesToolResult(result);+ const resultText =+ result == null+ ? ""+ : withImages+ ? stringifyToolResult(result.text)+ : stringifyToolResult(result);+ const images = withImages ? result.webImages : [];const sources = resultText ? parseSearchResults(resultText) : [];// Collapse when LLM starts generating text after the tool callconst hasText = useAuiState(({ message }) =>- message.content.some((p) => p.type === "text" && "text" in p && (p as { text: string }).text.length > 0),+ message.content.some(+ (p) =>+ p.type === "text" &&+ "text" in p &&+ (p as { text: string }).text.length > 0,+ ),);const [open, setOpen] = useState(isRunning);useEffect(() => {@@ -120,10 +152,20 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({<ToolFallbackTriggertoolName={isUrlFetch- ? displayDomain ? `Read ${displayDomain}` : "Read page"- : query- ? `Searched "${query}"`- : "Web Search"+ ? 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}@@ -132,26 +174,57 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({{isRunning ? (<div className="flex items-center text-sm text-muted-foreground"><span>- {isUrlFetch- ? <>Reading {displayDomain || "page"}…</>- : <>Searching for “{query}”…</>- }+ {isUrlFetch ? (+ <>Reading {displayDomain || "page"}…</>+ ) : isImageOnly ? (+ <>Finding images for “{imageLabel}”…</>+ ) : (+ <>Searching for “{query}”…</>+ )}</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 && (+ <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-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"+ <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">- <SourceIcon url={source.url} size={3} />- <SourceTitle>{source.title}</SourceTitle>- </Source>- ))}+ {images.map((entry) => (+ <SearchImageThumb key={entry.id} entry={entry} size="strip" />+ ))}+ </div>+ )}</div>) : resultText ? (<div>diff --git a/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.ts b/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.tsindex 3a5042f61dc..91024e1793e 100644--- a/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.ts+++ b/studio/frontend/src/features/chat/adapters/studio-speech-synthesis-adapter.ts@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { authFetch } from "@/features/auth";+import { stripSearchImageTokens } from "../search-images/search-images";import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";import { toast } from "@/lib/toast";import type { SpeechSynthesisAdapter } from "@assistant-ui/react";@@ -336,7 +337,9 @@ export class StudioSpeechSynthesisAdapter implements SpeechSynthesisAdapter {);}- speak(text: string): SpeechSynthesisAdapter.Utterance {+ speak(spokenText: string): SpeechSynthesisAdapter.Utterance {+ // Renderer markup: without this the reader says the token id out loud.+ const text = stripSearchImageTokens(spokenText);const subscribers = new Set<() => void>();const handleEnd = (diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 2ba65500943..e4f74eff384 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -7,7 +7,7 @@ import {committedServerTuningState,serverTuningLoadPayload,} from "../lib/server-tuning-fields";-import { getAuthToken } from "@/features/auth";+import { authFetch, getAuthToken } from "@/features/auth";import { prepareHfTokenForUse } from "@/features/hf-auth";import { DOWNLOAD_KIND } from "@/features/hub/download-manager/constants";import {@@ -38,6 +38,18 @@ import {sandboxSessionIdFor,} from "@/components/assistant-ui/sandbox-files";import { apiUrl } from "@/lib/api-base";+import {+ answerTextFromParts,+ extractSearchImages,+ isSearchImageEntry,+ isSearchImagesToolResult,+ missingListSubjects,+ SEARCH_IMAGE_TOOL,+ searchResultText,+ stripSearchImageTokens,+ type SearchImageEntry,+ type SearchImagesToolResult,+} from "../search-images/search-images";import { parseParamCountB } from "@/lib/model-size";import { createLoadingToastIcon, toast } from "@/lib/toast";import { notifyPromptQueueRunFailed } from "../utils/prompt-queue-boundary";@@ -129,6 +141,7 @@ import {resolveToolsEnabledOnLoad,saveSpeculativeType,awaitThreadScopedPairing,+ flushPendingChatSettings,useChatRuntimeStore,} from "../stores/chat-runtime-store";import { resolveFitMaxSeqLength, resolveManualAutoCtxPin } from "../presets/preset-policy";@@ -1041,7 +1054,11 @@ export function toolResultModelText(result: unknown,toolName?: string,): unknown {- if (isMcpImageToolResult(result) || isSandboxWrapper(result, toolName)) {+ if (+ isMcpImageToolResult(result) ||+ isSearchImagesToolResult(result) ||+ isSandboxWrapper(result, toolName)+ ) {return result.text;}return result;@@ -1105,11 +1122,19 @@ function serializeToolResultPart(content = result.length > 0 ? result : JSON.stringify({ result: "" });} else if (isMcpImageToolResult(result) ||+ isSearchImagesToolResult(result) ||isSandboxWrapper(result, tc.toolName ?? "")) {// Replay the stdout the model saw, not the card's sessionId/images/files:// stringifying the wrapper feeds it internal metadata instead of the output.- content = result.text.length > 0 ? result.text : JSON.stringify({ result: "" });+ // The image tokens go with them: a token resolves against the message whose+ // search produced it, so a model copying one out of replayed history names+ // an id the next message cannot resolve and the picture silently does not+ // render. Without them it searches again, and that token does resolve.+ const replayText = isSearchImagesToolResult(result)+ ? stripSearchImageTokens(result.text)+ : result.text;+ content = replayText.length > 0 ? replayText : JSON.stringify({ result: "" });} else {try {content = JSON.stringify(result);@@ -1135,7 +1160,9 @@ function canReplayToolCallWithoutRoleTool(part: ToolCallMessagePart): boolean {}function sanitizeAssistantReplayText(text: string): string {- return text.replace(+ // Same reason as the tool result above: the tokens the model wrote last turn+ // are renderer markup scoped to that message, not prose it should repeat.+ return stripSearchImageTokens(text).replace(/data:audio\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/g,"[audio]",);@@ -1576,6 +1603,43 @@ export function messagesContainImage(messages: RunMessages): boolean {return false;}+// A recording or a clip the user supplied is their own content in exactly the sense the+// text-attachment rule already covers: the model answers from what is inside it, so the+// subjects of that answer must not reach the image engines either. Matched on the part+// TYPE rather than through the base64 extractors above -- a clip whose payload does not+// parse is still a clip, and a predicate that fails open on it is the wrong way round.+// Video arrives as a file part carrying a video mime type, the shape+// extractVideoPartBase64 reads.+function isPrivateMediaPart(part: { type: string }): boolean {+ if (part.type === "audio") return true;+ return (+ part.type === "file" &&+ /^video\//i.test((part as { mimeType?: string }).mimeType ?? "")+ );+}++export function messagesUsePrivateContent(messages: RunMessages): boolean {+ if (messagesContainImage(messages)) return true;+ return messages.some((message) => {+ if (+ (message.content ?? []).some(+ (part) =>+ (part.type === "tool-call" &&+ (part as { toolName?: string }).toolName === "search_knowledge_base") ||+ isPrivateMediaPart(part),+ )+ ) {+ return true;+ }+ if (!("attachments" in message)) return false;+ return (message.attachments ?? []).some((attachment) =>+ (attachment.content ?? []).some(+ (part) => part.type === "text" || isPrivateMediaPart(part),+ ),+ );+ });+}+export function findLatestUserAudioBase64(messages: RunMessages,includePendingAudio = true,@@ -3815,6 +3879,16 @@ export function createOpenAIStreamAdapter(const composerProjectIdAtSend =useChatRuntimeStore.getState().activeProjectId ?? null;await useChatRuntimeStore.getState().hydratePersistedSettings();+ // After the hydrate, not before: the backend reads some settings out of+ // SQLite at call time rather than taking them from the request -- Search+ // images picks the web_search schema that way -- and the mirror is a+ // trailing-edge debounce, so sending inside that window would run on the+ // value from before the toggle. Edits made while the initial GET was still+ // out are held back and only reach the debounce when hydration replays+ // them, so a flush ahead of it would find nothing queued and miss exactly+ // the first message after a startup edit. No wait at all unless something+ // is actually queued or in flight.+ await flushPendingChatSettings();// Every run reaches here: the composer, Reload, Continue, and send from the edit// composer. Waiting for the open chat's own settings in this one place is what// keeps the message-level controls from starting a run on the installation@@ -6117,6 +6191,11 @@ export function createOpenAIStreamAdapter(SANDBOX_FILE_TOOLS.has(toolCallParts[idx].toolName ?? "")? extractCreatedFiles(rawEvent): { text: rawEvent, files: [] as SandboxFile[] };+ // Same rule: only from the tool that emits it.+ const { text: searchText, images: webImages } =+ toolCallParts[idx].toolName === SEARCH_IMAGE_TOOL+ ? extractSearchImages(rawResult)+ : { text: rawResult, images: [] as SearchImageEntry[] };const imgMarker = "\n__IMAGES__:";const imgIdx = rawResult.lastIndexOf(imgMarker);const mcpImgMarker = "\n__MCP_IMAGES__:";@@ -6130,6 +6209,7 @@ export function createOpenAIStreamAdapter(files?: SandboxFile[];}| McpImageToolResult+ | SearchImagesToolResult| {image_b64: string;image_mime: string;@@ -6212,6 +6292,8 @@ export function createOpenAIStreamAdapter(sessionId: sandboxSessionId || "_default",files: createdFiles,};+ } else if (webImages.length > 0) {+ parsedResult = { text: searchText, webImages };} else {parsedResult = rawResult;}@@ -6780,9 +6862,8 @@ export function createOpenAIStreamAdapter() {return [];}- return parseSourcesFromResult(- typeof tc.result === "string" ? tc.result : "",- );+ // An image-bearing result is an object; citations live on `.text`.+ return parseSourcesFromResult(searchResultText(tc.result));});const meta = serverMetadata;@@ -6850,7 +6931,107 @@ export function createOpenAIStreamAdapter(incompleteReason = "length";}+ // Before the lookup below: its network time is not generation time.const finishedAt = Date.now();++ // Small models list things and never ask for their pictures, so fetch the+ // missing ones and record the web_search call they should have made.+ // Local tool loop only (a hosted provider would be replayed a tool it never+ // saw), never over the user's own documents, never behind an approval prompt.+ // The THREAD, not this turn and not the current toggle state. A follow-up+ // answers from a search_knowledge_base result replayed in context without+ // retrieving again, and turning RAG off afterwards clears both flags while+ // those names are still sitting in the conversation -- so "list those product+ // names" could hand private-document subjects to the image engines. Once a+ // chat has retrieved private documents it stays ineligible.+ const answerUsedPrivateDocs =+ ragEnabled ||+ projectRagEnabled ||+ messagesUsePrivateContent(messages) ||+ toolCallParts.some((part) => part.toolName === "search_knowledge_base");+ // This run's own values, destructured from the runtime it started with,+ // not the store as it stands now. Both are per-chat, and a run finishing+ // after the user moved to a chat on "auto" would read that chat's+ // permission level and look images up for an answer whose own chat had+ // asked to be consulted first. (searchImages stays a live read: it+ // describes the installation, so navigating cannot change it, and a user+ // who has just switched it off should not get one last lookup.)+ const toolCallsNeedApproval = confirmToolCalls && permissionMode === "ask";+ if (+ incompleteReason === null &&+ !isExternalRequest &&+ supportsTools &&+ toolsEnabled &&+ !answerUsedPrivateDocs &&+ !toolCallsNeedApproval &&+ useChatRuntimeStore.getState().searchImages+ ) {+ // Rendered parts, not the raw stream: `cumulativeText` carries <think>.+ const answerText = answerTextFromParts(+ buildAssistantContent(mergeContinuation(cumulativeText)),+ );+ const subjects = missingListSubjects(answerText, toolCallParts);+ if (subjects.length > 0) {+ // Bounded so a slow engine cannot hold a finished answer open.+ // Linked by hand: AbortSignal.any is newer than the Safari floor.+ const lookupAbort = new AbortController();+ const onRunAbort = () => lookupAbort.abort();+ runAbort.signal.addEventListener("abort", onRunAbort, { once: true });+ const lookupTimer = setTimeout(() => lookupAbort.abort(), 15_000);+ try {+ // authFetch, not a raw fetch: an access token that expired during a long+ // generation is refreshed and the call retried, where a stale bearer just+ // 401s into the catch below and the pictures never arrive. Unlike the+ // cancel POST above, a login redirect here is right -- the answer is+ // already finished, so nothing is interrupted by it.+ const response = await authFetch(+ "/api/inference/search-images/lookup",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ subjects }),+ signal: lookupAbort.signal,+ },+ );+ if (response.ok) {+ const data = (await response.json()) as {+ text?: unknown;+ images?: unknown;+ };+ const webImages = Array.isArray(data.images)+ ? data.images.filter(isSearchImageEntry)+ : [];+ if (webImages.length > 0) {+ const args = { image_queries: subjects };+ toolCallParts.push({+ type: "tool-call" as const,+ // No colon: replayed ids must satisfy ^[a-zA-Z0-9_-]+$.+ // Guarded: randomUUID is undefined over plain HTTP on a LAN.+ toolCallId: `auto-images-${+ typeof crypto !== "undefined" && "randomUUID" in crypto+ ? crypto.randomUUID()+ : `${Date.now()}-${Math.random().toString(36).slice(2)}`+ }`,+ toolName: "web_search",+ argsText: JSON.stringify(args),+ args,+ result: {+ text: typeof data.text === "string" ? data.text : "",+ webImages,+ },+ textCursor: cumulativeText.length,+ } as PositionedToolCallPart);+ }+ }+ } catch {+ // Pictures are a garnish: a failed lookup leaves the answer as written.+ } finally {+ clearTimeout(lookupTimer);+ runAbort.signal.removeEventListener("abort", onRunAbort);+ }+ }+ }+const finalTiming = buildTiming(streamStartTime,totalChunks,diff --git a/studio/frontend/src/features/chat/api/chat-settings-api.ts b/studio/frontend/src/features/chat/api/chat-settings-api.tsindex 4a22946a670..10e6d6a7a49 100644--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts@@ -41,6 +41,8 @@ export interface PersistedChatSettings {preserveThinking?: boolean;collapseHtmlArtifacts?: boolean;allowArtifactNetworkAccess?: boolean;+ /** web_search also returns image results the model can place inline. */+ searchImages?: boolean;autoHealToolCalls?: boolean;nudgeToolCalls?: boolean;maxToolCallsPerMessage?: number;diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 7720be5709f..7c08e5b860c 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -193,6 +193,12 @@ export { clearAllChats, countAllChats } from "./utils/clear-all-chats";export { offerToDeleteKeptSandboxes } from "./utils/offer-kept-sandbox-files";export { pasteClipboardFiles } from "./utils/clipboard-files";export { extractYoutubeVideoId } from "./utils/youtube-url";+export {+ isSearchImagesToolResult,+ searchImagePath,+ stripSearchImageTokens,+ type SearchImageEntry,+} from "./search-images/search-images";export { YoutubeTranscriptPrompt } from "./components/youtube-transcript-prompt";export {formatMcpToolName,diff --git a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsxindex 49f222f9e07..51ceb10c39f 100644--- a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx+++ b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx@@ -68,6 +68,7 @@ import {renderConversationBlocks,} from "../utils/conversation-markdown";import { planChatItemSources } from "../utils/project-source-plan";+import { stripSearchImageTokens } from "../search-images/search-images.ts";import { saveMarkdownAsProjectSource } from "@/features/rag";function newId(): string {@@ -475,7 +476,9 @@ async function saveConversationAsProjectSource(const markdown = buildConversationMarkdown(messages.map((msg) => ({role: String(msg.role ?? ""),- content: messageToMarkdown(msg),+ // As the markdown exporter does: a project source is retrieved back into+ // context, so the renderer's tokens must not be saved as prose.+ content: stripSearchImageTokens(messageToMarkdown(msg)),})),);if (!markdown) {diff --git a/studio/frontend/src/features/chat/search-images/search-images.ts b/studio/frontend/src/features/chat/search-images/search-images.tsnew file mode 100644index 00000000000..9b4e226eb0a--- /dev/null+++ b/studio/frontend/src/features/chat/search-images/search-images.ts@@ -0,0 +1,584 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// web_search image results: the backend keeps the URLs and hands out opaque+// `[[img:<id>]]` tokens, which resolve here against that tool call's envelope.++import { findCodeBlockRegions, isInRegion } from "../../../lib/latex.ts";++export const SEARCH_IMAGES_MARKER = "\n__WEB_IMAGES__:";+export const SEARCH_IMAGE_TAG = "search-image";+// The only tool whose result may carry the envelope; elsewhere the marker is content.+export const SEARCH_IMAGE_TOOL = "web_search";+const IMAGE_ID_RE = /^[0-9a-f]{12}$/;+const TOKEN_RE = /\[\[img:([0-9a-f]{12})\]\]/g;+// A token cut off mid-stream: any suffix of "[[img:xxxxxxxxxxxx]]" short of the close.+const PARTIAL_TOKEN_RE = /\[(?:\[(?:i(?:m(?:g(?::[0-9a-f]{0,12}\]?)?)?)?)?)?$/;++export interface SearchImageEntry {+ id: string;+ title: string;+ domain: string;+ source: string;+ /** What was searched for, so the renderer can place the card itself. */+ subject?: string;+}++export interface SearchImagesToolResult {+ text: string;+ webImages: SearchImageEntry[];+}++export function isSearchImageEntry(value: unknown): value is SearchImageEntry {+ if (typeof value !== "object" || value === null) return false;+ const v = value as Record<string, unknown>;+ return (+ typeof v.id === "string" &&+ IMAGE_ID_RE.test(v.id) &&+ typeof v.title === "string" &&+ typeof v.domain === "string" &&+ typeof v.source === "string" &&+ // Re-checked so a spoofed envelope cannot put another scheme in an <a href>.+ /^https?:\/\//i.test(v.source) &&+ (v.subject === undefined || typeof v.subject === "string")+ );+}++export function isSearchImagesToolResult(+ value: unknown,+): value is SearchImagesToolResult {+ if (typeof value !== "object" || value === null) return false;+ const v = value as { text?: unknown; webImages?: unknown };+ return (+ typeof v.text === "string" &&+ Array.isArray(v.webImages) &&+ v.webImages.length > 0 &&+ v.webImages.every(isSearchImageEntry)+ );+}++/** Split a trailing image envelope off a web_search result; unchanged when absent or malformed. */+export function extractSearchImages(raw: string): {+ text: string;+ images: SearchImageEntry[];+} {+ const start = raw.lastIndexOf(SEARCH_IMAGES_MARKER);+ if (start === -1) return { text: raw, images: [] };+ const payloadStart = start + SEARCH_IMAGES_MARKER.length;+ let end = raw.indexOf("\n__", payloadStart);+ if (end === -1) end = raw.length;+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw.slice(payloadStart, end));+ } catch {+ return { text: raw, images: [] };+ }+ if (+ !Array.isArray(parsed) ||+ parsed.length === 0 ||+ !parsed.every(isSearchImageEntry)+ ) {+ return { text: raw, images: [] };+ }+ return {+ text: (raw.slice(0, start) + raw.slice(end)).trimEnd(),+ images: parsed,+ };+}++/** Result text in either shape; citations come from this, and an image-bearing result is an object. */+export function searchResultText(result: unknown): string {+ if (typeof result === "string") return result;+ if (isSearchImagesToolResult(result)) return result.text;+ return "";+}++export function searchImagePath(id: string): string {+ return `/api/inference/search-images/${encodeURIComponent(id)}`;+}++/**+ * `[[img:<id>]]` -> `<search-image token="…">`, skipping code; unknown ids are dropped.+ * `token`, not `id`: rehype-sanitize prefixes `id` values with `user-content-`.+ */+export function rewriteSearchImageTokens(+ text: string,+ known: { has(id: string): boolean },+): string {+ if (!text.includes("[[img:")) return text;+ const codeRegions = findCodeBlockRegions(text);+ return text.replace(TOKEN_RE, (match, id: string, offset: number) => {+ if (isInRegion(offset, codeRegions)) return match;+ if (!known.has(id)) return "";+ return `<${SEARCH_IMAGE_TAG} token="${id}"></${SEARCH_IMAGE_TAG}>`;+ });+}++/**+ * Drop every `[[img:<id>]]` the model wrote. The tokens are markup for the renderer,+ * so anything that hands the answer to the user as plain text — clipboard, markdown+ * export, read-aloud — has to strip them or they show up verbatim.+ */+export function stripSearchImageTokens(text: string): string {+ if (!text.includes("[[img:")) return text;+ const codeRegions = findCodeBlockRegions(text);+ // One pass over the original, so the code-region offsets stay valid. A token sits+ // in its own block, so the first branch takes the blank line that introduces it+ // too; dropping the token alone would leave a widening gap. Code is left alone, as+ // in rewriteSearchImageTokens: there the token is prose about the feature.+ return text.replace(+ /\n\n[ \t]*\[\[img:[0-9a-f]{12}\]\][ \t]*(?=\n\n|\n?$)|\[\[img:[0-9a-f]{12}\]\]/g,+ (match, offset: number) => (isInRegion(offset, codeRegions) ? match : ""),+ );+}++function escapeRegExp(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++/** Whether a `[[img:<id>]]` the model wrote sits somewhere it will actually render. */+function tokenPlacedOutsideCode(+ text: string,+ id: string,+ codeRegions: Array<[number, number]>,+): boolean {+ const needle = `[[img:${id}]]`;+ for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + 1)) {+ if (!isInRegion(at, codeRegions)) return true;+ }+ return false;+}++/** Offset of the first match outside `regions`, or null. Resets `pattern` for reuse. */+function firstMatchOutsideCode(+ pattern: RegExp,+ text: string,+ regions: Array<[number, number]>,+): number | null {+ if (!text) return null;+ pattern.lastIndex = 0;+ let match: RegExpExecArray | null;+ while ((match = pattern.exec(text)) !== null) {+ // The leading group is a boundary char, not part of the name.+ const at = match.index + match[1].length;+ if (!isInRegion(at, regions)) return at;+ // Zero-width matches cannot happen (the name is non-empty), so no manual bump.+ }+ return null;+}++const LIST_MARKER_RE = /^(\s*(?:[-*+•]|\d{1,2}[.)])\s+)/;+const HEADING_LINE_RE = /^\s*#{1,6}\s/;+const BLOCK_BREAK_RE = /^(?:\s*$|\s*(?:[-*+•]|\d{1,2}[.)])\s|\s*#{1,6}\s|\s*(?:```|~~~))/;+// Display math, which BLOCK_BREAK_RE cannot see: a blank line inside `$$ ... $$`+// read as the end of the block, and the card was spliced into the equation, so+// KaTeX got markup instead of LaTeX. Bounded like latex.ts, so an unclosed `$$`+// cannot run the scan over the whole answer.+const DISPLAY_MATH_RE = /\$\$[\s\S]{0,4096}?\$\$|\\\[[\s\S]{0,4096}?\\\]/g;++function findDisplayMathRegions(text: string): Array<[number, number]> {+ const regions: Array<[number, number]> = [];+ if (!text.includes("$$") && !text.includes("\\[")) return regions;+ DISPLAY_MATH_RE.lastIndex = 0;+ let match: RegExpExecArray | null;+ while ((match = DISPLAY_MATH_RE.exec(text)) !== null) {+ regions.push([match.index, match.index + match[0].length]);+ }+ return regions;+}++/**+ * End of the block containing `index` — models wrap a list item across several+ * lines, and inserting at the end of the first one splits the sentence in half.+ */+function blockEndFrom(+ text: string,+ index: number,+ mathRegions: Array<[number, number]> = [],+): number {+ let at = text.indexOf("\n", index);+ while (at !== -1) {+ const nextBreak = text.indexOf("\n", at + 1);+ const line = text.slice(at + 1, nextBreak === -1 ? text.length : nextBreak);+ if (BLOCK_BREAK_RE.test(line) && !isInRegion(at + 1, mathRegions)) return at;+ at = nextBreak;+ }+ return text.length;+}++/** Whether two lowercased subject names refer to the same thing, on word boundaries. */+function namesSameThing(a: string, b: string): boolean {+ if (a === b) return true;+ const [shorter, longer] = a.length <= b.length ? [a, b] : [b, a];+ return new RegExp(+ `(^|[^\\p{L}\\p{N}])${escapeRegExp(shorter)}([^\\p{L}\\p{N}]|$)`,+ "u",+ ).test(longer);+}++/**+ * Put each subject's image under the first line naming it. Subjects the answer never+ * names are left out, tokens the model placed win, and streaming text is untouched.+ */+export function placeSubjectImages(+ text: string,+ images: ReadonlyMap<string, SearchImageEntry>,+ isStreaming: boolean,+ // Earlier text parts, so a subject named twice is illustrated once.+ alreadyNamed = "",+ messageTexts: readonly string[] = [text],+): string {+ if (isStreaming || images.size === 0) return text;+ const bySubject = new Map<string, SearchImageEntry>();+ for (const entry of images.values()) {+ const key = entry.subject?.trim().toLowerCase();+ if (!key || bySubject.has(key)) continue;+ bySubject.set(key, entry);+ }+ if (bySubject.size === 0) return text;++ const codeRegions = findCodeBlockRegions(text);+ const mathRegions = findDisplayMathRegions(text);+ const insertions: Array<{ at: number; chunk: string }> = [];+ const namedRegions = findCodeBlockRegions(alreadyNamed);+ const messageParts = messageTexts.map((part) => ({+ text: part,+ codeRegions: findCodeBlockRegions(part),+ }));+ for (const [key, entry] of bySubject) {+ // Outside code only, the same rule the subject match follows:+ // rewriteSearchImageTokens leaves a token inside a fence as literal text, so+ // counting that as "the model already placed it" showed no picture at all.+ if (+ messageParts.some(({ text: part, codeRegions: regions }) =>+ tokenPlacedOutsideCode(part, entry.id, regions),+ )+ ) {+ continue;+ }+ // On the original text: lowercasing can change length and shift every offset.+ // Global, so a mention inside code can be stepped over rather than ending the+ // search: `\`Go\`` in a snippet used to abandon the subject that a later prose+ // item names, and the picture was silently dropped.+ const pattern = new RegExp(+ `(^|[^\\p{L}\\p{N}])${escapeRegExp(key)}(?![\\p{L}\\p{N}])`,+ "giu",+ );+ // An earlier text part already carries this subject's card -- unless it only+ // said so in code, which shows no card and so must not suppress this one.+ if (firstMatchOutsideCode(pattern, alreadyNamed, namedRegions) !== null) continue;+ // Where the NAME starts, not the boundary char before it: same line either way,+ // and the code-region test is about the name.+ const at = firstMatchOutsideCode(pattern, text, codeRegions);+ if (at === null) continue;+ const lineStart = text.lastIndexOf("\n", at) + 1;+ const newline = text.indexOf("\n", at);+ const lineEnd = newline === -1 ? text.length : newline;+ const line = text.slice(lineStart, lineEnd);+ const marker = LIST_MARKER_RE.exec(line);+ if (HEADING_LINE_RE.test(line)) {+ // A heading is a one-line block, so its own end is the insertion point.+ insertions.push({ at: lineEnd, chunk: `\n\n[[img:${entry.id}]]` });+ } else if (marker) {+ // Indented to the item's content column, so the card is a block inside the+ // item rather than a lazy continuation of its sentence, and the list keeps+ // its numbering.+ insertions.push({+ at: blockEndFrom(text, at, mathRegions),+ chunk: `\n\n${" ".repeat(marker[1].length)}[[img:${entry.id}]]`,+ });+ } else {+ insertions.push({+ at: blockEndFrom(text, at, mathRegions),+ chunk: `\n\n[[img:${entry.id}]]`,+ });+ }+ }+ if (insertions.length === 0) return text;++ insertions.sort((a, b) => b.at - a.at);+ let out = text;+ for (const { at, chunk } of insertions) {+ out = `${out.slice(0, at)}${chunk}${out.slice(at)}`;+ }+ return out;+}++// Split marker from subject, and never let two whitespace quantifiers span the same+// run: the single-regex form nested `\s+`, `\s*` and a body class that also matched+// spaces, which backtracked at ~O(n^3.5) -- 250 spaces in one bullet froze the thread+// for 13s. The body is anchored on non-space edges so the surrounding runs cannot+// overlap it; `.trim()` below made those edges dead weight anyway.+const LIST_ITEM_MARKER_RE = /^[ \t]*(?:\d{1,2}[.)]|[-*+•])[ \t]+/;+const LIST_ITEM_RE =+ /^(?:\*\*|__)?[ \t\r]*([^\s*_\n][^*_\n]{0,58}?[^\s*_\n])(?:[ \t\r]*(?:\*\*|__))?[ \t\r]*(?::|[-–—][ \t\r]|\(|$)/;+const HEADING_RE =+ /^[ \t]*#{2,4}[ \t]+(?:\d{1,2}[.)][ \t]+)?([^\s\n#][^\n#]{0,58}?[^\s\n#])(?:[ \t\r]*#*)?[ \t\r]*$/;+const MAX_AUTO_SUBJECTS = 5;+// Items that start with an instruction: "Install Python", "Preheat the oven".+const STEP_VERBS = new Set([+ "add",+ "apply",+ "avoid",+ "build",+ "call",+ "change",+ "check",+ "choose",+ "click",+ "close",+ "configure",+ "confirm",+ "connect",+ "copy",+ "create",+ "define",+ "delete",+ "disable",+ "download",+ "enable",+ "ensure",+ "enter",+ "find",+ "fix",+ "follow",+ "get",+ "go",+ "import",+ "install",+ "keep",+ "launch",+ "let",+ "load",+ "log",+ "make",+ "mix",+ "move",+ "navigate",+ "open",+ "paste",+ "pick",+ "place",+ "plan",+ "preheat",+ "prepare",+ "press",+ "pull",+ "push",+ "put",+ "read",+ "remove",+ "rename",+ "repeat",+ "replace",+ "restart",+ "review",+ "run",+ "save",+ "select",+ "set",+ "sign",+ "start",+ "stop",+ "take",+ "test",+ "try",+ "turn",+ "type",+ "update",+ "upgrade",+ "use",+ "verify",+ "visit",+ "wait",+ "write",+]);++function looksLikeStep(name: string): boolean {+ const first = name+ .split(/\s+/)[0]+ ?.toLowerCase()+ .replace(/[^a-z]/g, "");+ return first !== undefined && STEP_VERBS.has(first);+}++// Section labels that lead list items in comparisons and reviews, not things.+const ABSTRACT_HEADS = new Set([+ "advantages",+ "benefits",+ "bottom line",+ "caveats",+ "con",+ "conclusion",+ "cons",+ "cost",+ "disadvantages",+ "drawbacks",+ "example",+ "examples",+ "features",+ "key takeaways",+ "limitations",+ "note",+ "notes",+ "option",+ "options",+ "overview",+ "performance",+ "price",+ "pro",+ "pros",+ "risks",+ "summary",+ "takeaways",+ "tip",+ "tips",+ "tldr",+ "tl;dr",+ "verdict",+ "warning",+ "why it matters",+]);++function isAbstractHead(name: string): boolean {+ return ABSTRACT_HEADS.has(name.toLowerCase().replace(/\s+/g, " ").trim());+}++/** Text parts only: a model's reasoning must never be illustrated. */+export function answerTextFromParts(+ parts: ReadonlyArray<{ type: string; text?: unknown }>,+): string {+ return parts+ .filter(+ (part): part is { type: "text"; text: string } =>+ part.type === "text" && typeof part.text === "string",+ )+ .map((part) => part.text)+ .join("\n\n");+}++export function precedingTextForMessagePart(+ parts: ReadonlyArray<{ type: string; text?: unknown }>,+ partIndex: number,+): string {+ return answerTextFromParts(parts.slice(0, partIndex));+}++/**+ * The lead of each listed item or small heading (`1. **German Shepherd:** …`).+ * Short names only; a procedure, a code answer or a single item yields nothing.+ */+export function extractListSubjects(text: string): string[] {+ if (text.includes("```") || text.includes("~~~")) return [];+ const codeRegions = findCodeBlockRegions(text);+ const named: string[] = [];+ const seen = new Set<string>();+ let steps = 0;+ let offset = 0;+ for (const line of text.split("\n")) {+ const at = offset;+ offset += line.length + 1;+ if (isInRegion(at, codeRegions)) continue;+ const marker = LIST_ITEM_MARKER_RE.exec(line);+ const match = marker+ ? LIST_ITEM_RE.exec(line.slice(marker[0].length))+ : HEADING_RE.exec(line);+ if (!match) continue;+ const name = match[1].replace(/[\s:.,;!?]+$/g, "").trim();+ const words = name.split(/\s+/);+ if (+ name.length < 2 ||+ words.length > 6 ||+ /https?:|www\.|\d{3,}/i.test(name) ||+ !/\p{L}/u.test(name)+ ) {+ continue;+ }+ if (looksLikeStep(name)) {+ steps += 1;+ continue;+ }+ if (isAbstractHead(name)) continue;+ const key = name.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ named.push(name);+ }+ // Proportional, so "Choose the Civic if:" at the end of a comparison is not a how-to.+ if (steps >= named.length) return [];+ return named.length >= 2 ? named.slice(0, MAX_AUTO_SUBJECTS) : [];+}++/** List subjects the model has not already fetched a picture for. */+export function missingListSubjects(+ text: string,+ parts: ReadonlyArray<{ type: string; toolName?: string; result?: unknown }>,+): string[] {+ const listed = extractListSubjects(text);+ if (listed.length === 0) return [];+ const covered: string[] = [];+ for (const entry of collectSearchImages(parts).values()) {+ const subject = entry.subject?.trim().toLowerCase();+ if (subject) covered.push(subject);+ }+ // Word boundaries: "cat" must not swallow "Caterpillar".+ return listed.filter((name) => {+ const key = name.toLowerCase();+ return !covered.some((c) => namesSameThing(c, key));+ });+}++/** While streaming, hold back a half-arrived token so it never flashes as literal text. */+export function holdBackPartialSearchImageToken(+ text: string,+ isStreaming: boolean,+): string {+ if (!isStreaming) return text;+ const match = PARTIAL_TOKEN_RE.exec(text);+ if (!match) return text;+ const codeRegions = findCodeBlockRegions(text);+ if (isInRegion(match.index, codeRegions)) return text;+ return text.slice(0, match.index);+}++/** The `[[img:<id>]]` ids a message can resolve, read from its web_search tool parts. */+export function collectSearchImages(+ parts: ReadonlyArray<{ type: string; toolName?: string; result?: unknown }>,+): Map<string, SearchImageEntry> {+ const images = new Map<string, SearchImageEntry>();+ for (const part of parts) {+ if (+ part.type !== "tool-call" ||+ part.toolName !== SEARCH_IMAGE_TOOL+ )+ continue;+ if (!isSearchImagesToolResult(part.result)) continue;+ for (const entry of part.result.webImages) {+ if (!images.has(entry.id)) images.set(entry.id, entry);+ }+ }+ return images;+}++/** A stable string for the same set of entries, so a store subscription can select it. */+export function searchImagesSignature(+ parts: ReadonlyArray<{ type: string; toolName?: string; result?: unknown }>,+): string {+ const entries = Array.from(collectSearchImages(parts).values());+ return entries.length === 0 ? "" : JSON.stringify(entries);+}++export function parseSearchImagesSignature(+ signature: string,+): Map<string, SearchImageEntry> {+ if (!signature) return new Map();+ try {+ const parsed = JSON.parse(signature) as unknown;+ if (!Array.isArray(parsed)) return new Map();+ return new Map(+ parsed.filter(isSearchImageEntry).map((entry) => [entry.id, entry]),+ );+ } catch {+ return new Map();+ }+}diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 65e06454aec..8124e0e9586 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -101,6 +101,7 @@ export const CHAT_COLLAPSE_HTML_ARTIFACTS_KEY ="unsloth_chat_collapse_html_artifacts";export const CHAT_ALLOW_ARTIFACT_NETWORK_ACCESS_KEY ="unsloth_chat_allow_artifact_network_access";+export const CHAT_SEARCH_IMAGES_KEY = "unsloth_chat_search_images";export const CHAT_MCP_ENABLED_KEY = "unsloth_chat_mcp_enabled";export const CHAT_CONFIRM_TOOL_CALLS_KEY = "unsloth_chat_confirm_tool_calls";export const CHAT_EXPAND_QUANTIZATIONS_KEY =@@ -461,13 +462,27 @@ async function flushSettingsPatch(keepalive = false): Promise<void> {}}+// Flushes handed to the network and not yet answered. pendingPatch and+// pendingTimer are both empty across that window, so they cannot answer "is a+// settings write still outstanding" on their own.+let unsettledFlushes = 0;++function enqueueSettingsFlush(): Promise<void> {+ unsettledFlushes += 1;+ inflightFlush = inflightFlush+ .catch(() => undefined)+ .then(() => flushSettingsPatch())+ .finally(() => {+ unsettledFlushes -= 1;+ });+ return inflightFlush;+}+function scheduleSettingsFlush(): void {if (pendingTimer !== null) clearTimeout(pendingTimer);pendingTimer = setTimeout(() => {pendingTimer = null;- inflightFlush = inflightFlush- .catch(() => undefined)- .then(() => flushSettingsPatch());+ void enqueueSettingsFlush();}, SETTINGS_DEBOUNCE_MS);}@@ -476,6 +491,44 @@ function saveSettingsPatch(patch: SettingsPatch): void {scheduleSettingsFlush();}+// A wedged PATCH must not hold a send open. Past this the run goes ahead on the+// value the server already has, which is exactly where it stood before.+const SETTINGS_FLUSH_TIMEOUT_MS = 2000;++/**+ * Send the debounced settings patch now and wait for it.+ *+ * Some settings are read by the backend out of SQLite at call time rather than+ * being carried in the request -- Search images picks the web_search schema that+ * way -- and the mirror above is a trailing-edge debounce, so a message sent+ * inside that window would run on the value before the toggle. Returns+ * immediately when nothing is queued, which is every send but one right after a+ * settings change.+ */+export async function flushPendingChatSettings(): Promise<void> {+ const queued = pendingTimer !== null || Object.keys(pendingPatch).length > 0;+ // Not just what is queued: the debounce may have fired already and handed its+ // patch to a request the server has not answered, which leaves both of those+ // empty while the value the backend reads is still the old one.+ if (!queued && unsettledFlushes === 0) return;+ if (pendingTimer !== null) {+ clearTimeout(pendingTimer);+ pendingTimer = null;+ }+ if (queued) void enqueueSettingsFlush();+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ inflightFlush.catch(() => undefined),+ new Promise<void>((resolve) => {+ timer = setTimeout(resolve, SETTINGS_FLUSH_TIMEOUT_MS);+ }),+ ]);+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+}+// Best-effort flush of any pending patch when the page is going away. keepalive// lets the PUT outlive the unload; without it the browser cancels the fetch and// the user's last slider drag is dropped.@@ -650,6 +703,7 @@ const MIRRORED_SETTINGS = {storageKey: CHAT_ALLOW_ARTIFACT_NETWORK_ACCESS_KEY,...BOOLEAN_SETTING,},+ searchImages: { storageKey: CHAT_SEARCH_IMAGES_KEY, ...BOOLEAN_SETTING },mcpEnabledForChat: { storageKey: CHAT_MCP_ENABLED_KEY, ...BOOLEAN_SETTING },confirmToolCalls: {storageKey: CHAT_CONFIRM_TOOL_CALLS_KEY,@@ -2487,6 +2541,8 @@ type ChatRuntimeStore = {showCanvasMenuItem: boolean;collapseHtmlArtifacts: boolean;allowArtifactNetworkAccess: boolean;+ // web_search also returns images the model can place inline; read by the backend per call.+ searchImages: boolean;mcpEnabledForChat: boolean;ragEnabled: boolean;ragSource: RagSource;@@ -2843,6 +2899,7 @@ type ChatRuntimeStore = {setShowCanvasMenuItem: (enabled: boolean) => void;setCollapseHtmlArtifacts: (enabled: boolean) => void;setAllowArtifactNetworkAccess: (enabled: boolean) => void;+ setSearchImages: (enabled: boolean) => void;setMcpEnabledForChat: (enabled: boolean) => void;setConfirmToolCalls: (enabled: boolean) => void;setBypassPermissions: (enabled: boolean) => void;@@ -2944,6 +3001,7 @@ type ScalarSettingKey =| "preserveThinking"| "collapseHtmlArtifacts"| "allowArtifactNetworkAccess"+ | "searchImages"| "autoHealToolCalls"| "nudgeToolCalls"| "maxToolCallsPerMessage"@@ -2993,6 +3051,7 @@ const SCALAR_SETTING_KEYS = ["preserveThinking","collapseHtmlArtifacts","allowArtifactNetworkAccess",+ "searchImages","autoHealToolCalls","nudgeToolCalls","maxToolCallsPerMessage",@@ -3687,6 +3746,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({CHAT_ALLOW_ARTIFACT_NETWORK_ACCESS_KEY,false,),+ searchImages: loadBool(CHAT_SEARCH_IMAGES_KEY, false),mcpEnabledForChat: loadBool(CHAT_MCP_ENABLED_KEY, false),// Mirrors permissionMode (gate requested for ask/auto) so both controls// agree on load.@@ -4720,6 +4780,11 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({);return { allowArtifactNetworkAccess };}),+ setSearchImages: (searchImages) =>+ set(() => {+ saveBool(CHAT_SEARCH_IMAGES_KEY, searchImages);+ return { searchImages };+ }),setMcpEnabledForChat: (mcpEnabledForChat) =>set((state) => {saveBool(CHAT_MCP_ENABLED_KEY, mcpEnabledForChat);diff --git a/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts b/studio/frontend/src/features/chat/utils/conversation-markdown-export.tsindex 63ee6d0ef22..d05aaccc147 100644--- a/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts+++ b/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts@@ -7,6 +7,7 @@ import {type ConversationMarkdownMessage,buildConversationMarkdown,} from "./conversation-markdown.ts";+import { stripSearchImageTokens } from "../search-images/search-images.ts";type StoredConversationMessage = {readonly role: unknown;@@ -47,7 +48,8 @@ export function createConversationMarkdownExporter<const normalizedMessages: ConversationMarkdownMessage[] = messages.map((message) => ({role: String(message.role ?? ""),- content: renderMessage(message),+ // Renderer markup, never prose: an exported answer must not carry raw tokens.+ content: stripSearchImageTokens(renderMessage(message)),}),);const markdown = buildConversationMarkdown(normalizedMessages);diff --git a/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.tsindex c9e9a36fca5..dd39ea219a5 100644--- a/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts+++ b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts@@ -18,6 +18,7 @@ const MIRRORED_BOOLEAN_KEYS = ["deepResearchEnabled","artifactsEnabled","showCanvasMenuItem",+ "searchImages","mcpEnabledForChat","confirmToolCalls","ragOcrScanned",diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex d36a35144af..1668d49b513 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -98,6 +98,8 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {"settings.chat.artifacts.title","settings.chat.artifacts.collapseHtmlBlocks","settings.chat.artifacts.allowNetworkAccess",+ "settings.chat.webSearch.title",+ "settings.chat.webSearch.images","settings.chat.modelDisclaimer","settings.chat.projectsSection",],diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsxindex 79573e42954..f119ef7d51f 100644--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx@@ -167,6 +167,10 @@ export function ChatTab() {const setAllowArtifactNetworkAccess = useChatRuntimeStore((state) => state.setAllowArtifactNetworkAccess,);+ const searchImages = useChatRuntimeStore((state) => state.searchImages);+ const setSearchImages = useChatRuntimeStore(+ (state) => state.setSearchImages,+ );const hydratePersistedSettings = useChatRuntimeStore((state) => state.hydratePersistedSettings,);@@ -396,6 +400,15 @@ export function ChatTab() {/></SettingsRow></SettingsSection>++ <SettingsSection title={t("settings.chat.webSearch.title")}>+ <SettingsRow+ label={t("settings.chat.webSearch.images")}+ description={t("settings.chat.webSearch.imagesDescription")}+ >+ <Switch checked={searchImages} onCheckedChange={setSearchImages} />+ </SettingsRow>+ </SettingsSection></div>);}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 747d7b237e9..30dd86b6e35 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -1109,6 +1109,12 @@ export const ar = {collapseByDefaultDescription:"إبقاء التفكير مطويًا أثناء تفكير النموذج بدلًا من فتحه تلقائيًا. وسّع أي كتلة لقراءتها.",},+ webSearch: {+ title: "البحث على الويب",+ images: "عرض الصور من البحث على الويب",+ imagesDescription:+ "يتيح للبحث على الويب إرجاع صور، ويجلب صورة لكل عنصر تعدّده الإجابة. يجلب Studio الصور المصغّرة ويغيّر حجمها، لذا لا يتصل المتصفح بمضيفي الصور أبدًا.",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "طي كتل HTML",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 16c652781e2..8d14f946cfe 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -1145,6 +1145,12 @@ export const de = {collapseByDefaultDescription:"Das Denken bleibt eingeklappt, während das Modell denkt, statt automatisch aufzuklappen. Zum Lesen einen Block ausklappen.",},+ webSearch: {+ title: "Websuche",+ images: "Bilder aus der Websuche anzeigen",+ imagesDescription:+ "Lässt die Websuche Bilder liefern und holt eines für jeden Punkt, den eine Antwort auflistet. Vorschaubilder lädt und verkleinert Studio, der Browser kontaktiert keine Bildhosts.",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "HTML-Blöcke einklappen",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 682dddf5591..a300afee547 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -1105,6 +1105,12 @@ export const en = {collapseByDefaultDescription:"Keep reasoning collapsed while the model thinks instead of streaming it open. Expand any block to read it.",},+ webSearch: {+ title: "Web search",+ images: "Show images from web search",+ imagesDescription:+ "Let web search return pictures, and fetch one for each thing an answer lists. Thumbnails are downloaded and resized by Studio, so the browser never contacts image hosts.",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "Collapse HTML blocks",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 810417777dc..fd61f9bcbea 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -1136,6 +1136,12 @@ export const es = {collapseByDefaultDescription:"Mantén el razonamiento contraído mientras el modelo piensa, en lugar de abrirlo automáticamente. Expande cualquier bloque para leerlo.",},+ webSearch: {+ title: "Búsqueda web",+ images: "Mostrar imágenes de la búsqueda web",+ imagesDescription:+ "Permite que la búsqueda web devuelva imágenes y obtiene una por cada elemento que enumera una respuesta. Studio descarga y redimensiona las miniaturas, así que el navegador nunca contacta con los servidores de imágenes.",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "Contraer bloques HTML",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex b4a69b51623..1884e18edf0 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -1142,6 +1142,12 @@ export const fr = {collapseByDefaultDescription:"Garde la réflexion repliée pendant que le modèle réfléchit, au lieu de l’ouvrir automatiquement. Dépliez un bloc pour le lire.",},+ webSearch: {+ title: "Recherche web",+ images: "Afficher les images de la recherche web",+ imagesDescription:+ "Permet à la recherche web de renvoyer des images et en récupère une pour chaque élément listé dans une réponse. Studio télécharge et redimensionne les vignettes : le navigateur ne contacte jamais les hébergeurs d'images.",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "Réduire les blocs HTML",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 54ae5aeac21..de281956701 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -1116,6 +1116,12 @@ export const hi = {collapseByDefaultDescription:"मॉडल के सोचते समय रीज़निंग अपने आप खुलने के बजाय संक्षिप्त रहती है। पढ़ने के लिए किसी भी ब्लॉक को विस्तृत करें।",},+ webSearch: {+ title: "वेब खोज",+ images: "वेब खोज से छवियाँ दिखाएँ",+ imagesDescription:+ "वेब खोज को छवियाँ लौटाने दें और उत्तर में सूचीबद्ध हर चीज़ के लिए एक छवि लाएँ। थंबनेल Studio द्वारा लाए और छोटे किए जाते हैं, इसलिए ब्राउज़र कभी छवि होस्ट से संपर्क नहीं करता।",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "HTML ब्लॉक संक्षिप्त करें",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 3ce0c59582b..7142215cb18 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -1110,6 +1110,12 @@ export const it = {collapseByDefaultDescription:"Mantieni il ragionamento compresso mentre il modello pensa, invece di aprirlo automaticamente. Espandi un blocco per leggerlo.",},+ webSearch: {+ title: "Ricerca web",+ images: "Mostra immagini dalla ricerca web",+ imagesDescription:+ "Consente alla ricerca web di restituire immagini e ne recupera una per ogni elemento elencato in una risposta. Le miniature vengono scaricate e ridimensionate da Studio, quindi il browser non contatta mai gli host delle immagini.",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "Comprimi i blocchi HTML",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 5b8720c0bfe..5b6f8b143f6 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -1098,6 +1098,12 @@ export const ja = {collapseByDefaultDescription:"モデルの思考中も自動で展開せず、折りたたんだままにします。読みたいときはブロックを展開してください。",},+ webSearch: {+ title: "ウェブ検索",+ images: "ウェブ検索の画像を表示",+ imagesDescription:+ "ウェブ検索で画像も取得し、回答に列挙された項目ごとに1枚ずつ探します。サムネイルは Studio が取得して縮小するため、ブラウザが画像ホストに接続することはありません。",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "HTMLブロックを折りたたむ",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex da0fa1aeed6..8fc1ae0c05d 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -1108,6 +1108,12 @@ export const ko = {collapseByDefaultDescription:"모델이 생각하는 동안 사고 과정을 자동으로 펼치지 않고 접어 둡니다. 읽으려면 블록을 펼치세요.",},+ webSearch: {+ title: "웹 검색",+ images: "웹 검색 이미지 표시",+ imagesDescription:+ "웹 검색이 이미지를 반환하고, 답변에 나열된 항목마다 하나씩 가져옵니다. 썸네일은 Studio가 가져와 축소하므로 브라우저가 이미지 호스트에 접속하지 않습니다.",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "HTML 블록 접기",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 4b81ba9a067..b3510b584a9 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -1124,6 +1124,12 @@ export const ptBR = {collapseByDefaultDescription:"Mantém o raciocínio recolhido enquanto o modelo pensa, em vez de abri-lo automaticamente. Expanda um bloco para lê-lo.",},+ webSearch: {+ title: "Busca na web",+ images: "Mostrar imagens da busca na web",+ imagesDescription:+ "Permite que a busca na web retorne imagens e busca uma para cada item que uma resposta lista. As miniaturas são baixadas e redimensionadas pelo Studio, então o navegador nunca acessa os servidores de imagens.",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "Recolher blocos HTML",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 00410441fdf..6abfa20a34d 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -1121,6 +1121,12 @@ export const ru = {collapseByDefaultDescription:"Размышления остаются свёрнутыми, пока модель думает, вместо автоматического раскрытия. Разверните блок, чтобы прочитать его.",},+ webSearch: {+ title: "Веб-поиск",+ images: "Показывать изображения из веб-поиска",+ imagesDescription:+ "Позволяет веб-поиску возвращать изображения и подбирает по одному для каждого пункта, который перечисляет ответ. Миниатюры загружает и уменьшает Studio, поэтому браузер никогда не обращается к хостам изображений.",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "Сворачивать блоки HTML",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 6d4dde4c8e6..47c95f0ccae 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -1085,6 +1085,12 @@ export const zhCN = {collapseByDefaultDescription:"模型思考时保持折叠,而不是自动展开。需要阅读时展开对应区块。",},+ webSearch: {+ title: "网页搜索",+ images: "显示网页搜索图片",+ imagesDescription:+ "让网页搜索返回图片,并为回答中列出的每一项各获取一张。缩略图由 Studio 获取并缩放,浏览器不会直接访问图片来源。",+ },artifacts: {title: "Canvas",collapseHtmlBlocks: "折叠 HTML 块",diff --git a/studio/frontend/src/lib/latex.ts b/studio/frontend/src/lib/latex.tsindex 0baf4f00f4d..831c446f14d 100644--- a/studio/frontend/src/lib/latex.ts+++ b/studio/frontend/src/lib/latex.ts@@ -52,7 +52,7 @@ function mergeRegions(* Find code-block regions (``` ... ```, ~~~ ... ~~~, and ` ... `) to skip.* Returns a sorted, non-overlapping array of [start, end] index pairs.*/-function findCodeBlockRegions(content: string): Array<[number, number]> {+export function findCodeBlockRegions(content: string): Array<[number, number]> {// Fenced code blocks: ```...``` and ~~~...~~~ (both are code in GFM)const fenced: Array<[number, number]> = [];const fencedRe = /```[\s\S]*?```|~~~[\s\S]*?~~~/g;@@ -116,7 +116,7 @@ function findLinkDestinationRegions(content: string): Array<[number, number]> {* Binary search to check if a position falls inside any region. Regions must be* sorted by start and non-overlapping.*/-function isInRegion(+export function isInRegion(position: number,regions: Array<[number, number]>,): boolean {diff --git a/studio/frontend/tests/project-attachment-target-adoption.test.ts b/studio/frontend/tests/project-attachment-target-adoption.test.tsindex 5217b6dab5d..3b77e4fad18 100644--- a/studio/frontend/tests/project-attachment-target-adoption.test.ts+++ b/studio/frontend/tests/project-attachment-target-adoption.test.ts@@ -141,7 +141,9 @@ test("the run keeps the project it started in", () => {);assert.match(source,- /const composerProjectIdAtSend =\s*useChatRuntimeStore\.getState\(\)\.activeProjectId \?\? null;\s*await useChatRuntimeStore\.getState\(\)\.hydratePersistedSettings\(\);/,+ // Whichever await comes first: the property is that the read is the run's+ // last synchronous statement, not which call follows it.+ /const composerProjectIdAtSend =\s*useChatRuntimeStore\.getState\(\)\.activeProjectId \?\? null;\s*(?:\/\/[^\n]*\n\s*)*await /,"captured before the first await",);assert.match(diff --git a/studio/frontend/tests/search-images.test.ts b/studio/frontend/tests/search-images.test.tsnew file mode 100644index 00000000000..bbd466096d3--- /dev/null+++ b/studio/frontend/tests/search-images.test.ts@@ -0,0 +1,1019 @@+// 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";++import ts from "typescript";++import {+ SEARCH_IMAGES_MARKER,+ answerTextFromParts,+ collectSearchImages,+ extractListSubjects,+ extractSearchImages,+ holdBackPartialSearchImageToken,+ isSearchImagesToolResult,+ missingListSubjects,+ parseSearchImagesSignature,+ placeSubjectImages,+ precedingTextForMessagePart,+ rewriteSearchImageTokens,+ searchImagePath,+ searchImagesSignature,+ searchResultText,+ stripSearchImageTokens,+} from "../src/features/chat/search-images/search-images.ts";+import { safeMarkdownUrl } from "../src/lib/safe-markdown-url.ts";++const ENTRY = {+ id: "0123456789ab",+ title: "Golden Retriever",+ domain: "akc.org",+ source: "https://www.akc.org/golden",+};+const OTHER = { ...ENTRY, id: "abcdef012345", title: "Labrador" };+const KNOWN = new Set([ENTRY.id, OTHER.id]);++const adapterSource = readFileSync(+ fileURLToPath(new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url)),+ "utf8",+);++function liftAdapterFunction(opener: string): string {+ const start = adapterSource.indexOf(opener);+ assert.ok(start >= 0, `${opener} is no longer defined in chat-adapter.ts`);+ const end = adapterSource.indexOf("\n}", start);+ assert.ok(end > start, `could not find the end of ${opener}`);+ return adapterSource.slice(start, end + 2).replace("export function", "function");+}++const privateContentPredicateJs = ts.transpileModule(+ [+ liftAdapterFunction("export function messagesContainImage("),+ liftAdapterFunction("function isPrivateMediaPart("),+ liftAdapterFunction("export function messagesUsePrivateContent("),+ "return messagesUsePrivateContent;",+ ].join("\n\n"),+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },+).outputText;++const messagesUsePrivateContent = new Function(privateContentPredicateJs)() as (+ messages: unknown[],+) => boolean;++test("private message history blocks automatic image lookup", () => {+ assert.equal(+ messagesUsePrivateContent([+ {+ role: "user",+ content: [{ type: "text", text: "read this" }],+ attachments: [+ {+ type: "document",+ content: [{ type: "text", text: "private product name" }],+ },+ ],+ },+ { role: "user", content: [{ type: "text", text: "list those names" }] },+ ]),+ true,+ );+ assert.equal(+ messagesUsePrivateContent([+ {+ role: "user",+ content: [{ type: "image", image: "data:image/png;base64,cHJpdmF0ZQ==" }],+ },+ ]),+ true,+ );+ assert.equal(+ messagesUsePrivateContent([+ {+ role: "user",+ content: [],+ attachments: [+ {+ type: "image",+ content: [+ { type: "image", image: "data:image/png;base64,cHJpdmF0ZQ==" },+ ],+ },+ ],+ },+ ]),+ true,+ );+ assert.equal(+ messagesUsePrivateContent([+ {+ role: "assistant",+ content: [{ type: "tool-call", toolName: "search_knowledge_base" }],+ },+ ]),+ true,+ );+});++test("ordinary text and web search history allow automatic image lookup", () => {+ assert.equal(+ messagesUsePrivateContent([+ { role: "user", content: [{ type: "text", text: "list dog breeds" }] },+ {+ role: "assistant",+ content: [{ type: "tool-call", toolName: "web_search" }],+ },+ ]),+ false,+ );+});++test("extractSearchImages splits a valid envelope off the result text", () => {+ const raw = `Title: A\nURL: https://a.test\nSnippet: s${SEARCH_IMAGES_MARKER}${JSON.stringify([ENTRY])}`;+ const { text, images } = extractSearchImages(raw);+ assert.equal(text, "Title: A\nURL: https://a.test\nSnippet: s");+ assert.deepEqual(images, [ENTRY]);+});++test("extractSearchImages leaves malformed or foreign envelopes alone", () => {+ for (const raw of [+ "plain text",+ `x${SEARCH_IMAGES_MARKER}not json`,+ `x${SEARCH_IMAGES_MARKER}[]`,+ `x${SEARCH_IMAGES_MARKER}[{"id":"zz"}]`,+ `x${SEARCH_IMAGES_MARKER}[{"id":"0123456789ab","title":"t","domain":"d","source":"https://d.test/p","thumbnail":"https://leak"}]`.replace(+ ',"thumbnail":"https://leak"',+ "",+ ) + "\n__OTHER__:tail",+ ]) {+ const { text, images } = extractSearchImages(raw);+ if (raw.endsWith("tail")) {+ // A later sentinel bounds the payload and survives the strip.+ assert.deepEqual(+ images.map((e) => e.id),+ ["0123456789ab"],+ );+ assert.equal(text, "x\n__OTHER__:tail");+ } else {+ assert.equal(text, raw);+ assert.deepEqual(images, []);+ }+ }+});++test("isSearchImagesToolResult accepts only the wrapper shape", () => {+ assert.ok(isSearchImagesToolResult({ text: "t", webImages: [ENTRY] }));+ assert.ok(!isSearchImagesToolResult({ text: "t", webImages: [] }));+ assert.ok(+ !isSearchImagesToolResult({+ text: "t",+ images: [{ data: "", mimeType: "" }],+ }),+ );+ assert.ok(!isSearchImagesToolResult("string"));+ assert.ok(+ !isSearchImagesToolResult({+ text: "t",+ webImages: [{ ...ENTRY, id: "../x" }],+ }),+ );+ assert.ok(+ !isSearchImagesToolResult({+ text: "t",+ webImages: [{ ...ENTRY, source: "javascript:alert(1)" }],+ }),+ );+});++test("rewriteSearchImageTokens swaps known tokens for elements and drops unknown ones", () => {+ const out = rewriteSearchImageTokens(+ `Lab:\n[[img:${OTHER.id}]]\nand [[img:ffffffffffff]] gone`,+ KNOWN,+ );+ assert.equal(+ out,+ `Lab:\n<search-image token="${OTHER.id}"></search-image>\nand gone`,+ );+});++test("rewriteSearchImageTokens never touches code", () => {+ const fenced = "```\n[[img:0123456789ab]]\n```\n`[[img:0123456789ab]]` text";+ assert.equal(rewriteSearchImageTokens(fenced, KNOWN), fenced);+});++test("rewriteSearchImageTokens is a no-op without tokens", () => {+ const text = "plain [[not an image]] text";+ assert.equal(rewriteSearchImageTokens(text, KNOWN), text);+});++test("holdBackPartialSearchImageToken trims a token still arriving", () => {+ for (const partial of [+ "[",+ "[[",+ "[[i",+ "[[img",+ "[[img:",+ "[[img:0123",+ "[[img:0123456789ab",+ "[[img:0123456789ab]",+ ]) {+ assert.equal(+ holdBackPartialSearchImageToken(`Golden ${partial}`, true),+ "Golden ",+ );+ }+ assert.equal(+ holdBackPartialSearchImageToken("done [[img:0123456789ab]]", true),+ "done [[img:0123456789ab]]",+ );+ assert.equal(+ holdBackPartialSearchImageToken("array[0][[1]", true),+ "array[0][[1]",+ );+ assert.equal(holdBackPartialSearchImageToken("see [link", true), "see [link");+ assert.equal(+ holdBackPartialSearchImageToken("Golden [[img:", false),+ "Golden [[img:",+ );+ // Inside closed code nothing is held back; an open fence is still streaming, so trimming is harmless.+ assert.equal(+ holdBackPartialSearchImageToken("```\n[[img:\n```", true),+ "```\n[[img:\n```",+ );+});++test("collectSearchImages reads only web_search wrappers and the signature is stable", () => {+ const parts = [+ { type: "text", text: "hi" },+ {+ type: "tool-call",+ toolName: "python",+ result: { text: "x", webImages: [OTHER] },+ },+ { type: "tool-call", toolName: "web_search", result: "plain" },+ {+ type: "tool-call",+ toolName: "web_search",+ result: { text: "t", webImages: [ENTRY] },+ },+ {+ type: "tool-call",+ toolName: "web_search",+ result: { text: "t", webImages: [ENTRY, OTHER] },+ },+ ];+ const images = collectSearchImages(parts);+ assert.deepEqual([...images.keys()], [ENTRY.id, OTHER.id]);+ const signature = searchImagesSignature(parts);+ assert.equal(signature, searchImagesSignature([...parts]));+ assert.deepEqual(+ [...parseSearchImagesSignature(signature).values()],+ [ENTRY, OTHER],+ );+ assert.equal(searchImagesSignature([{ type: "text" }]), "");+ assert.equal(parseSearchImagesSignature("").size, 0);+});++test("placeSubjectImages puts a subject's image under the paragraph naming it", () => {+ const shepherd = { ...ENTRY, id: "aaaaaaaaaaaa", subject: "German Shepherd" };+ const lab = { ...ENTRY, id: "bbbbbbbbbbbb", subject: "Labrador" };+ const pug = { ...ENTRY, id: "cccccccccccc", subject: "Pug" };+ const images = new Map([+ [shepherd.id, shepherd],+ [lab.id, lab],+ [pug.id, pug],+ ]);+ const text =+ "Top breeds:\n\n1. **German Shepherd** - loyal.\n2. **Labrador** - friendly.\n\nEnjoy!";+ const out = placeSubjectImages(text, images, false);+ // Pug is never named in the answer, so its image is left out rather than piled+ // at the end; the tool card still shows it.+ assert.equal(+ out,+ "Top breeds:\n\n1. **German Shepherd** - loyal.\n\n [[img:aaaaaaaaaaaa]]\n2. **Labrador** - friendly.\n\n [[img:bbbbbbbbbbbb]]\n\nEnjoy!",+ );+ assert.equal(+ placeSubjectImages(+ "## German Shepherd\nLoyal.\n\nNext",+ new Map([[shepherd.id, shepherd]]),+ false,+ ),+ "## German Shepherd\n\n[[img:aaaaaaaaaaaa]]\nLoyal.\n\nNext",+ );+ assert.equal(+ placeSubjectImages(+ "The German Shepherd is loyal.\nVery.\n\nNext",+ new Map([[shepherd.id, shepherd]]),+ false,+ ),+ "The German Shepherd is loyal.\nVery.\n\n[[img:aaaaaaaaaaaa]]\n\nNext",+ );+});++test("placeSubjectImages never splits a list item a model wrapped over lines", () => {+ const golden = { ...ENTRY, id: "aaaaaaaaaaaa", subject: "Golden Retriever" };+ const images = new Map([[golden.id, golden]]);+ // The screenshot bug: the card landed after "and", cutting the sentence in half.+ const wrapped =+ "4. **Golden Retriever:** Known for being gentle, patient, and\ndevoted, making them excellent family companions.\n5. **Poodle:** Clever.";+ const out = placeSubjectImages(wrapped, images, false);+ assert.ok(+ out.includes("patient, and\ndevoted, making them excellent family companions."),+ "the sentence must stay intact",+ );+ // Its own block, indented to the item's content column so the list keeps numbering.+ assert.ok(out.includes("family companions.\n\n [[img:aaaaaaaaaaaa]]\n5. "));+});++test("placeSubjectImages respects tokens the model placed, streaming, and code", () => {+ const shepherd = { ...ENTRY, id: "aaaaaaaaaaaa", subject: "German Shepherd" };+ const images = new Map([[shepherd.id, shepherd]]);+ const placed = "German Shepherd\n\n[[img:aaaaaaaaaaaa]]\n\ndone";+ assert.equal(placeSubjectImages(placed, images, false), placed);+ assert.equal(+ placeSubjectImages("German Shepherd is", images, true),+ "German Shepherd is",+ );+ // Named only inside code, or not named at all: nothing is inserted anywhere.+ const code = "```\nGerman Shepherd\n```";+ assert.equal(placeSubjectImages(code, images, false), code);+ assert.equal(placeSubjectImages("Nothing here", images, false), "Nothing here");+ // Entries without a subject (web_search images) are never auto-placed.+ assert.equal(+ placeSubjectImages("Labrador", new Map([[ENTRY.id, ENTRY]]), false),+ "Labrador",+ );+ // Word boundaries: "Pug" must not match inside "Pugilist", so nothing is placed.+ const pug = { ...ENTRY, id: "cccccccccccc", subject: "Pug" };+ assert.equal(+ placeSubjectImages("Pugilist", new Map([[pug.id, pug]]), false),+ "Pugilist",+ );+ assert.equal(+ placeSubjectImages("A Pug naps.", new Map([[pug.id, pug]]), false),+ "A Pug naps.\n\n[[img:cccccccccccc]]",+ );+});++test("answerTextFromParts keeps the answer and drops reasoning", () => {+ const parts = [+ { type: "reasoning", text: "1. **Analyze the Request:** plan\n2. **Pick a tool:** web" },+ { type: "text", text: "1. **Labrador Retriever:** friendly." },+ { type: "tool-call", toolName: "web_search" },+ { type: "text", text: "2. **Poodle:** clever." },+ ];+ const answer = answerTextFromParts(parts);+ assert.equal(answer, "1. **Labrador Retriever:** friendly.\n\n2. **Poodle:** clever.");+ // The reasoning list must never become a subject to illustrate.+ assert.deepEqual(extractListSubjects(answer), ["Labrador Retriever", "Poodle"]);+ assert.equal(answerTextFromParts([{ type: "reasoning", text: "x" }]), "");+});++test("extractListSubjects reads the lead of each listed item", () => {+ const answer = [+ "Here are five popular breeds:",+ "",+ "1. **Labrador Retriever:** Friendly and outgoing.",+ "2. **French Bulldog** - Compact companion.",+ "3. German Shepherd: Loyal.",+ "- **Poodle** (Standard, Miniature, Toy)",+ "### Golden Retriever",+ "4. **labrador retriever:** duplicate",+ "5. **See https://akc.org for the full 2026 list:** not a subject",+ "6. **This is a long descriptive sentence about a dog that goes on:** no",+ ].join("\n");+ assert.deepEqual(extractListSubjects(answer), [+ "Labrador Retriever",+ "French Bulldog",+ "German Shepherd",+ "Poodle",+ "Golden Retriever",+ ]);+ // One item is not a list; prose is not a list.+ assert.deepEqual(extractListSubjects("1. **Only one:** thing"), []);+ assert.deepEqual(extractListSubjects("Dogs are great. Cats too."), []);+ // Section labels are skipped; procedures and code answers are never illustrated.+ assert.deepEqual(+ extractListSubjects("- **Pros:** fast\n- **Cons:** pricey\n- **Honda Civic:** a\n- **Mazda 3:** b"),+ ["Honda Civic", "Mazda 3"],+ );+ // A mostly-step list is a procedure and is never illustrated.+ assert.deepEqual(+ extractListSubjects(+ "1. **Install Python:** from python.org.\n2. **Open the terminal:** and run it.",+ ),+ [],+ );+ assert.deepEqual(+ extractListSubjects(+ "1. **Download the installer:** a\n2. **Run it:** b\n3. **Homebrew:** c\n4. **Verify the install:** d",+ ),+ [],+ );+ // A comparison that merely ends in a "Choose X if" line keeps its subjects.+ assert.deepEqual(+ extractListSubjects(+ "## Honda Civic\nSporty.\n\n## Toyota Corolla\nCalm.\n\n## Choose the Civic if\nyou want fun.",+ ),+ ["Honda Civic", "Toyota Corolla"],+ );+ assert.deepEqual(+ extractListSubjects(+ "1. **Labrador Retriever:** a\n2. **Poodle:** b\n\n```py\nprint(1)\n```",+ ),+ [],+ );+});++test("the inline card is block-level, so a list item cannot flow text around it", () => {+ // A list item styles its paragraphs `[&>p]:inline`. An inline card lands in the+ // middle of the sentence and the text wraps around it, which is what shipped once.+ const source = readFileSync(+ new URL("../src/components/assistant-ui/search-image.tsx", import.meta.url),+ "utf8",+ );+ const wrapper = /data-search-image=\{entry\.id\}/.test(source)+ ? source.slice(source.indexOf("if (!entry) return null;"))+ : "";+ assert.match(wrapper, /className="[^"]*\bflex\b/, "wrapper must not be inline");+ assert.match(wrapper, /empty:hidden/, "an unloaded card must not leave a gap");+});++test("searchResultText reaches the citations inside an image-bearing result", () => {+ const blocks = "Title: A\nURL: https://a.test\nSnippet: s";+ assert.equal(searchResultText(blocks), blocks);+ // The shape that used to make the whole Sources row vanish.+ assert.equal(searchResultText({ text: blocks, webImages: [ENTRY] }), blocks);+ assert.equal(searchResultText({ text: "t", images: [{ data: "", mimeType: "" }] }), "");+ assert.equal(searchResultText(undefined), "");+});++test("placeSubjectImages never splices a token into a code fence", () => {+ const pug = { ...ENTRY, id: "cccccccccccc", subject: "Pug" };+ const images = new Map([[pug.id, pug]]);+ const text =+ "The Pug is small. Here is code:\n```python\nprint(1)\n\nprint(2)\n```\nDone.";+ const out = placeSubjectImages(text, images, false);+ // The card goes under the paragraph that names the Pug, and the fence is+ // reached neither as an insertion point nor as somewhere to splice into.+ assert.ok(!/```python\nprint\(1\)\n\n\[\[img:/.test(out));+ assert.equal(+ out,+ "The Pug is small. Here is code:\n\n[[img:cccccccccccc]]\n```python\nprint(1)\n\nprint(2)\n```\nDone.",+ );+});++test("placeSubjectImages illustrates a subject once per message", () => {+ const pug = { ...ENTRY, id: "cccccccccccc", subject: "Pug" };+ const images = new Map([[pug.id, pug]]);+ const first = "A Pug is small.";+ assert.equal(+ placeSubjectImages(first, images, false, ""),+ "A Pug is small.\n\n[[img:cccccccccccc]]",+ );+ // The later text part sees what the earlier one already named, so it adds nothing.+ assert.equal(placeSubjectImages("The Pug again.", images, false, first), "The Pug again.");+});++test("equal text parts derive preceding text from the current part position", () => {+ const text = "A Pug is small.";+ const parts = [+ { type: "text", text },+ { type: "tool-call", toolName: "web_search" },+ { type: "text", text },+ ];+ const precedingText = precedingTextForMessagePart(parts, 2);+ assert.equal(precedingText, text);++ const pug = { ...ENTRY, id: "cccccccccccc", subject: "Pug" };+ assert.equal(+ placeSubjectImages(text, new Map([[pug.id, pug]]), false, precedingText),+ text,+ );+});++test("a token in a later text part prevents an earlier duplicate card", () => {+ const pug = { ...ENTRY, id: "cccccccccccc", subject: "Pug" };+ const images = new Map([[pug.id, pug]]);+ const first = "A Pug is small.";+ const later = "Here it is.\n\n[[img:cccccccccccc]]";+ assert.equal(placeSubjectImages(first, images, false, "", [first, later]), first);+ const codeOnly = "```\n[[img:cccccccccccc]]\n```";+ assert.equal(+ placeSubjectImages(first, images, false, "", [first, codeOnly]),+ `${first}\n\n[[img:cccccccccccc]]`,+ );+ const unclosedFence = `${first}\n\n\`\`\``;+ assert.equal(+ placeSubjectImages(unclosedFence, images, false, "", [unclosedFence, later]),+ unclosedFence,+ );+});++test("missingListSubjects matches coverage on word boundaries", () => {+ const answer = "1. **Caterpillar:** a\n2. **Catalina Island:** b\n3. **Pug:** c";+ const covered = (subject: string) => [+ {+ type: "tool-call",+ toolName: "web_search",+ result: { text: "t", webImages: [{ ...ENTRY, subject }] },+ },+ ];+ // "cat" must not swallow Caterpillar or Catalina Island.+ assert.deepEqual(missingListSubjects(answer, covered("cat")), [+ "Caterpillar",+ "Catalina Island",+ "Pug",+ ]);+ // A longer subject that contains the item as a whole word still covers it.+ assert.deepEqual(missingListSubjects(answer, covered("a Pug dog")), [+ "Caterpillar",+ "Catalina Island",+ ]);+});++test("missingListSubjects leaves out what the model already fetched", () => {+ const answer =+ "1. **Pug:** small.\n2. **Golden Retriever:** kind.\n3. **Beagle:** loud.";+ assert.deepEqual(missingListSubjects(answer, [{ type: "text" }]), [+ "Pug",+ "Golden Retriever",+ "Beagle",+ ]);+ const partial = [+ {+ type: "tool-call",+ toolName: "web_search",+ result: {+ text: "t",+ webImages: [{ ...ENTRY, subject: "golden retriever dog" }],+ },+ },+ ];+ assert.deepEqual(missingListSubjects(answer, partial), ["Pug", "Beagle"]);+ const generic = [+ {+ type: "tool-call",+ toolName: "web_search",+ result: { text: "t", webImages: [ENTRY] },+ },+ ];+ assert.deepEqual(missingListSubjects(answer, generic), [+ "Pug",+ "Golden Retriever",+ "Beagle",+ ]);+ assert.deepEqual(missingListSubjects("Just prose.", [{ type: "text" }]), []);+});++test("thumbnails load from Studio's own endpoint, which the img policy allows", () => {+ const path = searchImagePath(ENTRY.id);+ assert.equal(path, "/api/inference/search-images/0123456789ab");+ const imgNode = { tagName: "img" } as Parameters<typeof safeMarkdownUrl>[2];+ assert.equal(safeMarkdownUrl(path, "src", imgNode), path);+ assert.equal(+ safeMarkdownUrl("blob:https://studio/abc", "src", imgNode),+ "blob:https://studio/abc",+ );+ // The deny rule this feature routes around stays in force for remote images.+ assert.equal(+ safeMarkdownUrl("https://img.example.com/x.png", "src", imgNode),+ null,+ );+ assert.equal(+ safeMarkdownUrl("//img.example.com/x.png", "src", imgNode),+ null,+ );+});++test("extractListSubjects stays linear on a bullet padded with whitespace", () => {+ // The single-regex form backtracked at ~O(n^3.5): 250 leading spaces in one+ // bullet blocked the render thread for 13 s, and this runs on every finished+ // answer while the setting is on.+ const padded = `- ${" ".repeat(5000)}${"x".repeat(80)}y\n- Beagle: small`;+ const started = Date.now();+ assert.deepEqual(extractListSubjects(padded), []);+ assert.ok(Date.now() - started < 1000, "must not backtrack");+});++test("extractListSubjects reads the same leads after the marker split", () => {+ const text = [+ "1. **German Shepherd:** loyal",+ " 10. Golden Retriever: great family dog",+ "3) Poodle (standard)",+ "* Labrador Retriever - friendly",+ ].join("\n");+ assert.deepEqual(extractListSubjects(text), [+ "German Shepherd",+ "Golden Retriever",+ "Poodle",+ "Labrador Retriever",+ ]);+});++test("placeSubjectImages never splices a token into display math", () => {+ const pug = { ...ENTRY, id: "cccccccccccc", subject: "Pug" };+ const images = new Map([[pug.id, pug]]);+ // A blank line inside `$$ ... $$` used to read as the end of the block, so the+ // card landed mid-equation and KaTeX was handed markup instead of LaTeX.+ const text = "The Pug weighs:\n$$\na = 1\n\nb = 2\n$$\nDone.";+ const out = placeSubjectImages(text, images, false);+ assert.ok(!/a = 1\n\n\s*\[\[img:/.test(out), "the equation must stay intact");+ assert.ok(out.includes("$$\na = 1\n\nb = 2\n$$"));+ assert.ok(out.includes("[[img:cccccccccccc]]"));+});++test("stripSearchImageTokens takes the tokens and their blank line", () => {+ assert.equal(+ stripSearchImageTokens("Golden Retriever\n\n[[img:0123456789ab]]\n\nDone."),+ "Golden Retriever\n\nDone.",+ );+ // Untouched without a token, and an unknown-length id is not a token.+ assert.equal(stripSearchImageTokens("plain answer"), "plain answer");+ assert.equal(stripSearchImageTokens("[[img:nothex]]"), "[[img:nothex]]");+ // Two cards in a row collapse to one gap, not three blank lines.+ assert.equal(+ stripSearchImageTokens("A\n\n[[img:0123456789ab]]\n\n[[img:abcdef012345]]\n\nB"),+ "A\n\nB",+ );+ // Inline, and inside code — the same rule rewriteSearchImageTokens follows.+ assert.equal(stripSearchImageTokens("see [[img:0123456789ab]] here"), "see here");+ assert.equal(+ stripSearchImageTokens("```\n[[img:0123456789ab]]\n```"),+ "```\n[[img:0123456789ab]]\n```",+ );+});++test("placeSubjectImages steps past a subject that code mentions first", () => {+ const go = { ...ENTRY, id: "cccccccccccc", subject: "Go" };+ const images = new Map([[go.id, go]]);+ // The first occurrence is inside code, which shows no card. Abandoning the subject+ // there dropped the picture for the prose item that names it further down.+ const text = "Run `Go` first.\n\n1. **Go:** compiled and fast\n2. **Rust:** strict";+ const out = placeSubjectImages(text, images, false);+ assert.ok(out.includes("Run `Go` first."), "the snippet must stay as written");+ assert.ok(out.includes("compiled and fast\n\n [[img:cccccccccccc]]"));+});++test("placeSubjectImages ignores an earlier part that only named a subject in code", () => {+ const go = { ...ENTRY, id: "cccccccccccc", subject: "Go" };+ const images = new Map([[go.id, go]]);+ // A code-only mention earlier carries no card, so it must not suppress this one.+ const out = placeSubjectImages("Go is compiled.", images, false, "Type `Go` to start.");+ assert.equal(out, "Go is compiled.\n\n[[img:cccccccccccc]]");+ // A real earlier mention still wins: one card per message.+ assert.equal(+ placeSubjectImages("Go is compiled.", images, false, "Go is a language."),+ "Go is compiled.",+ );+});++test("placeSubjectImages still places a subject whose token only sits in code", () => {+ const pug = { ...ENTRY, id: "cccccccccccc", subject: "Pug" };+ const images = new Map([[pug.id, pug]]);+ // rewriteSearchImageTokens leaves a token inside a fence alone, so it renders no+ // picture; counting it as "already placed" meant the answer showed nothing at all.+ const text = "Here is the token:\n\n```\n[[img:cccccccccccc]]\n```\n\nThe Pug is small.";+ const out = placeSubjectImages(text, images, false);+ assert.ok(out.includes("```\n[[img:cccccccccccc]]\n```"), "the fence stays as written");+ assert.ok(+ out.endsWith("The Pug is small.\n\n[[img:cccccccccccc]]"),+ `a real card must still be placed, got ${JSON.stringify(out)}`,+ );+ // A token the model placed in prose still wins, so nothing is placed twice.+ const placed = "The Pug is small.\n\n[[img:cccccccccccc]]";+ assert.equal(placeSubjectImages(placed, images, false), placed);+});++// A replayed turn keeps its tokens in the model's context, but they resolve+// against the message whose search produced them: repeating one in a later+// answer renders nothing at all. So history is replayed without them, and the+// model has to search again to get a token this message can resolve.+const sanitizeAssistantReplayJs = ts.transpileModule(+ [+ liftAdapterFunction("function sanitizeAssistantReplayText("),+ "return sanitizeAssistantReplayText;",+ ].join("\n\n"),+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },+).outputText;++const sanitizeAssistantReplayText = new Function(+ "stripSearchImageTokens",+ sanitizeAssistantReplayJs,+)(stripSearchImageTokens) as (text: string) => string;++test("a token from an earlier turn is unresolvable in the message that repeats it", () => {+ const earlier = [+ {+ type: "tool-call",+ toolName: "web_search",+ result: { text: `- [[img:${ENTRY.id}]] ${ENTRY.title}`, webImages: [ENTRY] },+ },+ ];+ const repeatText = `Here it is again:\n\n[[img:${ENTRY.id}]]`;+ const later = [{ type: "text", text: repeatText }];++ assert.equal(collectSearchImages(earlier).size, 1);+ assert.equal(collectSearchImages(later).size, 0);+ // Silently nothing, which is why the token must not survive into replay.+ assert.equal(+ rewriteSearchImageTokens(repeatText, collectSearchImages(later)),+ "Here it is again:\n\n",+ );+});++test("replayed assistant text carries no image tokens", () => {+ assert.equal(+ sanitizeAssistantReplayText(`The retriever:\n\n[[img:${ENTRY.id}]]\n\nand more.`),+ "The retriever:\n\nand more.",+ );+ // The audio placeholder this shares the chokepoint with is untouched.+ assert.equal(+ sanitizeAssistantReplayText("clip: data:audio/mp3;base64,QUJD"),+ "clip: [audio]",+ );+ assert.equal(sanitizeAssistantReplayText("plain answer"), "plain answer");+});++test("a replayed web_search result carries no image tokens either", () => {+ const branch = adapterSource.slice(+ adapterSource.indexOf("function serializeToolResultPart("),+ adapterSource.indexOf("function sanitizeAssistantReplayText("),+ );+ assert.ok(branch.length > 0, "serializeToolResultPart moved");+ assert.match(+ branch,+ /isSearchImagesToolResult\(result\)\s*\?\s*stripSearchImageTokens\(result\.text\)/,+ "the replayed web_search result must be stripped of its tokens",+ );+});++// Search images is read by the backend out of SQLite when the tool schema is+// picked, not carried in the request, and the mirror to /api/chat/settings is a+// 400 ms trailing-edge debounce -- so a message sent right after the toggle used+// to run on the previous value. The store and the adapter cannot be imported in+// a bare node test (a .tsx barrel sits in both graphs), so these pin the source+// the way the sibling store tests do.+const storeSource = readFileSync(+ fileURLToPath(+ new URL("../src/features/chat/stores/chat-runtime-store.ts", import.meta.url),+ ),+ "utf8",+);++test("a queued settings patch is sent before a run reads it", () => {+ const flush = storeSource.slice(+ storeSource.indexOf("export async function flushPendingChatSettings("),+ );+ assert.ok(flush.length > 0, "flushPendingChatSettings is gone");+ const body = flush.slice(0, flush.indexOf("\n}\n") + 2);+ // Nothing queued and nothing in flight is the common case and must not cost a+ // send anything.+ assert.match(body, /if \(!queued && unsettledFlushes === 0\) return;/);+ // The debounce is cut short rather than waited out.+ assert.match(body, /clearTimeout\(pendingTimer\)/);+ // Bounded: a wedged PATCH must not hold the composer open.+ assert.match(body, /Promise\.race\(/);+ assert.match(storeSource, /const SETTINGS_FLUSH_TIMEOUT_MS = \d+;/);+});++test("a patch already handed to the server is waited for too", () => {+ // Between the debounce firing and the response, pendingPatch and pendingTimer+ // are both empty while the value the backend reads is still the old one, so+ // the fast path above cannot be decided from those two alone.+ const enqueue = storeSource.slice(+ storeSource.indexOf("function enqueueSettingsFlush("),+ );+ const body = enqueue.slice(0, enqueue.indexOf("\n}\n") + 2);+ assert.match(body, /unsettledFlushes \+= 1;/);+ assert.match(body, /\.finally\(\(\) => \{\s*unsettledFlushes -= 1;/);+ // Chained onto the same queue, so two flushes cannot overlap.+ assert.match(body, /inflightFlush = inflightFlush/);+ // The debounce goes through it rather than posting its own chain.+ const schedule = storeSource.slice(+ storeSource.indexOf("function scheduleSettingsFlush("),+ );+ assert.match(+ schedule.slice(0, schedule.indexOf("\n}\n")),+ /void enqueueSettingsFlush\(\);/,+ );+});++test("the run flushes those settings after it hydrates and before it sends", () => {+ const start = adapterSource.indexOf("await flushPendingChatSettings();");+ assert.ok(start > 0, "the run no longer flushes pending chat settings");+ const hydrate = adapterSource.indexOf(+ "await useChatRuntimeStore.getState().hydratePersistedSettings();",+ );+ // After, not before: a setting changed while the initial GET was still out is+ // held back and only reaches the debounce when hydration replays it.+ assert.ok(hydrate > 0 && hydrate < start, "the flush must follow the hydrate");+ // Awaited, not fired and forgotten, or the run races the patch it just sent.+ assert.match(+ adapterSource.slice(start - 6, start + 34),+ /await flushPendingChatSettings\(\);/,+ );+});++test("the automatic lookup reads this run's approval level, not the open chat's", () => {+ const gate = adapterSource.slice(+ adapterSource.indexOf("const toolCallsNeedApproval ="),+ adapterSource.indexOf("const subjects = missingListSubjects("),+ );+ assert.ok(gate.length > 0, "the automatic-lookup gate moved");+ // confirmToolCalls and permissionMode are per-chat, and a background run can+ // finish after the user has opened a chat on "auto": reading the store here+ // would look images up for an answer whose own chat asked to be consulted.+ assert.match(+ gate,+ /const toolCallsNeedApproval = confirmToolCalls && permissionMode === "ask";/,+ );+ assert.doesNotMatch(gate, /getState\(\)\.confirmToolCalls/);+ assert.doesNotMatch(gate, /getState\(\)\.permissionMode/);+ // Both come out of the runtime the run captured before it started.+ const captured = adapterSource.slice(+ adapterSource.indexOf("let runtime = useChatRuntimeStore.getState();"),+ adapterSource.indexOf("const toolCallsNeedApproval ="),+ );+ assert.match(captured, /\n\s*confirmToolCalls,\n/);+ assert.match(captured, /\n\s*permissionMode,\n/);+});++test("every export path strips the tokens, not just the clipboard", () => {+ // The tokens are renderer markup. A per-message export, a reply saved as a+ // project source and a whole chat saved as one all reach disk (or back into+ // model context) by a different route than the copy button.+ const threadSource = readFileSync(+ fileURLToPath(+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),+ ),+ "utf8",+ );+ const exporter = threadSource.slice(+ threadSource.indexOf("async function exportMessageMarkdown("),+ threadSource.indexOf("const AssistantActionBar"),+ );+ assert.ok(exporter.length > 0, "exportMessageMarkdown moved");+ assert.match(+ exporter,+ /downloadFile\(\s*(\/\/[^\n]*\n\s*)*stripSearchImageTokens\(content\)/,+ "the per-message markdown export must strip the tokens",+ );+ assert.match(+ threadSource,+ /stripSearchImageTokens\(\s*replySourceMarkdown\(/,+ "a reply saved as a project source must strip the tokens",+ );+ const dialogSource = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",+ import.meta.url,+ ),+ ),+ "utf8",+ );+ const saveSource = dialogSource.slice(+ dialogSource.indexOf("async function saveConversationAsProjectSource("),+ dialogSource.indexOf("export async function saveChatItemAsProjectSource("),+ );+ assert.ok(saveSource.length > 0, "saveConversationAsProjectSource moved");+ assert.match(+ saveSource,+ /stripSearchImageTokens\(messageToMarkdown\(msg\)\)/,+ "a chat saved as a project source must strip the tokens",+ );+});++test("the web search card survives a query that is not a string", () => {+ // Local models emit `"query": 42` and `"query": {}` routinely, and .trim() on+ // one threw straight through the renderer.+ const cardSource = readFileSync(+ fileURLToPath(+ new URL(+ "../src/components/assistant-ui/tool-ui-web-search.tsx",+ import.meta.url,+ ),+ ),+ "utf8",+ );+ const args = cardSource.slice(+ cardSource.indexOf("const query ="),+ cardSource.indexOf("const isUrlFetch ="),+ );+ assert.ok(args.length > 0, "the args derivation moved");+ const derive = new Function(+ "args",+ ts.transpileModule(`${args}\nreturn [query.trim(), url];`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText,+ ) as (args: unknown) => [string, string];+ assert.deepEqual(derive({ query: 42 }), ["42", ""]);+ assert.deepEqual(derive({ query: null, url: 7 }), ["", "7"]);+ assert.deepEqual(derive({}), ["", ""]);+ assert.deepEqual(derive({ query: " dogs " }), ["dogs", ""]);+});++test("a thumbnail response that lands after the id changed is ignored", () => {+ // Render falls through to idle for a state written under the previous id, and+ // the effect has no reason to run again: a skeleton that never resolves.+ const source = readFileSync(+ fileURLToPath(+ new URL("../src/components/assistant-ui/search-image.tsx", import.meta.url),+ ),+ "utf8",+ );+ const effect = source.slice(+ source.indexOf("authFetch(searchImagePath(id)"),+ source.indexOf("function useNearViewport"),+ );+ assert.ok(effect.length > 0, "the thumbnail effect moved");+ const notOk = effect.slice(effect.indexOf("if (!response.ok)"));+ assert.match(+ notOk.slice(0, notOk.indexOf("return;") + 7),+ /controller\.signal\.aborted/,+ "the not-ok branch must check the abort like the success branch does",+ );+});+++// A voice note or a clip is the user's own content in the sense the text-attachment rule+// already covers, and the answer's subjects go to external image engines. Both arrive+// with no text part beside them: AudioAttachmentAdapter.send emits exactly+// [{ type: "audio", ... }], so nothing else in the predicate could have caught them.+test("an audio or video input blocks automatic image lookup", () => {+ assert.equal(+ messagesUsePrivateContent([+ {+ role: "user",+ content: [],+ attachments: [+ {+ type: "file",+ content: [+ { type: "audio", audio: { data: "cHJpdmF0ZQ==", format: "wav" } },+ ],+ },+ ],+ },+ { role: "user", content: [{ type: "text", text: "list what it mentions" }] },+ ]),+ true,+ "a recording the user attached must not have its subjects searched for",+ );+ assert.equal(+ messagesUsePrivateContent([+ {+ role: "user",+ content: [{ type: "audio", audio: "cHJpdmF0ZQ==" }],+ },+ ]),+ true,+ "the compare view puts audio on the message itself, not in an attachment",+ );+ assert.equal(+ messagesUsePrivateContent([+ {+ role: "user",+ content: [],+ attachments: [+ {+ type: "file",+ content: [{ type: "file", data: "cHJpdmF0ZQ==", mimeType: "video/mp4" }],+ },+ ],+ },+ ]),+ true,+ "video reaches the model the same way and leaks the same way",+ );+ // Matched on the type, not on a payload that parses: a clip whose base64 is malformed+ // is still a clip, and failing open on it is the wrong way round.+ assert.equal(+ messagesUsePrivateContent([+ { role: "user", content: [{ type: "audio", audio: { data: "", format: "wav" } }] },+ ]),+ true,+ "an audio part with an unusable payload is still private",+ );+ // The complement: a plain typed question is what the lookup exists for.+ assert.equal(+ messagesUsePrivateContent([+ { role: "user", content: [{ type: "text", text: "name three dog breeds" }] },+ ]),+ false,+ "an ordinary text turn must still be eligible",+ );+ // A non-video file part is not media this rule speaks for; the attachment rule below+ // it already decides those on their text.+ assert.equal(+ messagesUsePrivateContent([+ { role: "user", content: [{ type: "file", data: "eA==", mimeType: "application/pdf" }] },+ ]),+ false,+ "the video test is on the mime type, not on being a file part",+ );+});diff --git a/studio/frontend/tests/thread-scoped-settings.test.ts b/studio/frontend/tests/thread-scoped-settings.test.tsindex 3d4e0a67616..1adcdb28ca9 100644--- a/studio/frontend/tests/thread-scoped-settings.test.ts+++ b/studio/frontend/tests/thread-scoped-settings.test.ts@@ -83,6 +83,7 @@ test("settings that describe the installation stay out of the snapshot", () => {"showCanvasMenuItem","collapseHtmlArtifacts","allowArtifactNetworkAccess",+ "searchImages","ragOcrScanned","ragCaptionFigures","researchWebsitePolicy",