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: Ask about this page on every page, desktop included (#12926)
Michael Han115777de2d63
diff --git a/studio/frontend/src/features/browser/annotate-layer.tsx b/studio/frontend/src/features/browser/annotate-layer.tsxindex 3e6dd2d74fe..050c0cb7c16 100644--- a/studio/frontend/src/features/browser/annotate-layer.tsx+++ b/studio/frontend/src/features/browser/annotate-layer.tsx@@ -21,11 +21,14 @@ import {useRef,useState,} from "react";+import { flushSync } from "react-dom";import { annotateScript } from "./api";import { canScreenshot } from "./screenshot-support";import { screenshotPage } from "./capture";import { type AnnotateEvent, type AnnotateRect, MAX_MARKS } from "./frame-message";-import { frameRect, onFrameAnnotate, sendFrameCommand } from "./page-frame";+import { startNativeAnnotate } from "./native-annotate";+import { focusPanel, nativeViewBounds } from "./native-view";+import { type FrameCommand, frameRect, onFrameAnnotate, sendFrameCommand } from "./page-frame";import { useBrowserPrefsStore } from "./prefs-store";import { useBrowserStore } from "./store";@@ -206,11 +209,12 @@ const sameRanges = (a: Range[] | null, b: Range[] | null) =>range.endOffset === b[index]?.endOffset,);-/** Request edits on a file: click marks a block, drag marks an area; Send posts all as one message. */+/** Request edits on a file or a Studio page: click marks a block, drag marks an area; Send posts all as one message. */export function AnnotateLayer({page,fileName,-}: { page: HTMLElement; fileName: string }) {+ url,+}: { page: HTMLElement; fileName: string; url?: string }) {const t = useT();const layerRef = useRef<HTMLDivElement | null>(null);const cursorRef = useRef<HTMLDivElement | null>(null);@@ -256,7 +260,7 @@ export function AnnotateLayer({setSending(true);const files = await annotationScreenshot(page);const sent = await sendAnnotations(- { file: fileName, items: outgoing.map(({ quote, request }) => ({ quote, request })) },+ { file: fileName, url, items: outgoing.map(({ quote, request }) => ({ quote, request })) },files,).finally(() => setSending(false));if (sent) exit();@@ -619,6 +623,7 @@ function CommentForm({<formdata-annotate-ui=""data-annotate-chrome=""+ data-native-cover=""onSubmit={(event) => {event.preventDefault();onSave();@@ -675,12 +680,15 @@ function AnnotateBar({sendDisabled,onSend,onExit,+ besidePage = false,}: {count: number;canSend: boolean;sendDisabled: boolean;onSend: () => void;onExit: () => void;+ /** Over a native view: the page ends above the bar, so it only slides sideways. */+ besidePage?: boolean;}) {const t = useT();const [offset, setOffset] = useState({ x: 0, y: 0 });@@ -704,7 +712,7 @@ function AnnotateBar({const minY = -(bounds.height - height - 20 - 8);setOffset({x: Math.min(maxX, Math.max(-maxX, event.clientX - start.x)),- y: Math.min(12, Math.max(minY, event.clientY - start.y)),+ y: besidePage ? 0 : Math.min(12, Math.max(minY, event.clientY - start.y)),});};const endDrag = (event: ReactPointerEvent<HTMLButtonElement>) => {@@ -715,6 +723,7 @@ function AnnotateBar({ref={barRef}data-annotate-ui=""data-annotate-chrome=""+ data-native-inset={besidePage ? "" : undefined}className={cn("pointer-events-auto absolute bottom-5 left-1/2 flex h-12 items-center gap-1 rounded-2xl pr-1.5 pl-2.5 text-ui-15",SURFACE,@@ -777,13 +786,15 @@ function accentColor(): string {return `rgb(${r}, ${g}, ${b})`;}-/** Ask about a web page: the page's own script tracks the pointer and draws marks (`annotation` in routes/browser.py); this layer holds the comments and the bar. */+/** Ask about a web page: the page's own script tracks the pointer and draws marks (`annotation` in routes/browser.py); this layer holds the comments and the bar.+ * Framed pages are driven through their shell, native views through `startNativeAnnotate`. */export function WebAnnotateLayer({tabId,title,url,page,-}: { tabId: string; title: string; url: string; page: HTMLElement | null }) {+ native = false,+}: { tabId: string; title: string; url: string; page: HTMLElement | null; native?: boolean }) {const t = useT();const layerRef = useRef<HTMLDivElement | null>(null);const inputRef = useRef<HTMLInputElement | null>(null);@@ -795,17 +806,21 @@ export function WebAnnotateLayer({const [draft, setDraft] = useState("");const [sending, setSending] = useState(false);const [, setLayout] = useState(0);+ const zoom = useBrowserStore((state) => state.tabs.find((tab) => tab.id === tabId)?.zoom ?? 1);const { setAnnotating, sendAnnotations } = useBrowserStore.getState();+ const nativeSend = useRef<((command: FrameCommand) => void) | null>(null);const exit = () => setAnnotating(null);- const forget = (id: number) => sendFrameCommand(tabId, { command: "annotateForget", id });+ const command = (next: FrameCommand) =>+ native ? nativeSend.current?.(next) : sendFrameCommand(tabId, next);+ const forget = (id: number) => command({ command: "annotateForget", id });// The page gets the annotate code only now (each document once; repeats are ignored there).const start = () =>void annotateScript().then((code) => {if (liveTab.current !== tabId) return;- sendFrameCommand(tabId, { command: "annotateInstall", code });- sendFrameCommand(tabId, { command: "annotate", on: true, color: accentColor() });+ command({ command: "annotateInstall", code });+ command({ command: "annotate", on: true, color: accentColor() });},() => liveTab.current === tabId && exit(),);@@ -842,6 +857,10 @@ export function WebAnnotateLayer({if (outgoing.length === 0 || !sendAnnotations || sending) return;// One at a time: a second click while staging would add the annotations twice.setSending(true);+ // Keep the open comment and close its form, so a native view shows again for the screenshot.+ setItems(outgoing);+ setPending(null);+ setDraft("");const files = await annotationScreenshot(page);const sent = await sendAnnotations({ file: title || url, url, items: outgoing.map(({ quote, request }) => ({ quote, request })) },@@ -850,10 +869,20 @@ export function WebAnnotateLayer({if (sent) exit();};+ // A press in a native view keeps key focus there: move it back to the comment.+ const takeKeys = () => {+ if (native) void focusPanel(tabId).then(() => inputRef.current?.focus());+ };+// Read on each report, so one always sees this render's state.const handle = (event: AnnotateEvent) => {switch (event.kind) {case "ready":+ // New document (a native view navigated in place): drop the old marks.+ setItems([]);+ setPending(null);+ setDraft("");+ setRects(new Map());start();break;case "up":@@ -868,6 +897,7 @@ export function WebAnnotateLayer({if (!item) break;setPending({ id: item.id, quote: item.quote, saved: true });setDraft(item.request);+ takeKeys();break;}case "mark": {@@ -887,6 +917,7 @@ export function WebAnnotateLayer({setRects((current) => new Map(current).set(event.id, event.rect));setPending({ id: event.id, quote, saved: false });setDraft("");+ takeKeys();break;}case "rects":@@ -900,16 +931,31 @@ export function WebAnnotateLayer({startRef.current = start;useEffect(() => {- const stop = onFrameAnnotate(tabId, (event) => handleRef.current(event));+ const listener = (event: AnnotateEvent) => handleRef.current(event);+ let stop: () => void;+ if (native) {+ // One poll can carry several reports: render between them so each sees the last one's state.+ const channel = startNativeAnnotate(tabId, (event) => flushSync(() => listener(event)));+ nativeSend.current = channel.send;+ stop = () => {+ nativeSend.current = null;+ channel.stop();+ };+ } else {+ const unlisten = onFrameAnnotate(tabId, listener);+ stop = () => {+ unlisten();+ sendFrameCommand(tabId, { command: "annotate", on: false });+ };+ }liveTab.current = tabId;// Now, for a page already loaded; a page still loading asks with "ready".startRef.current();return () => {liveTab.current = null;stop();- sendFrameCommand(tabId, { command: "annotate", on: false });};- }, [tabId]);+ }, [tabId, native]);useEffect(() => {const layer = layerRef.current;@@ -937,18 +983,21 @@ export function WebAnnotateLayer({useEffect(() => {const numbers: Array<[number, number]> = items.map((item, index) => [item.id, index + 1]);if (pending && !pending.saved) numbers.push([pending.id, items.length + 1]);- sendFrameCommand(tabId, { command: "annotateNumbers", numbers });+ command({ command: "annotateNumbers", numbers });}, [tabId, items, pending]);const origin = layerRef.current?.getBoundingClientRect() ?? new DOMRect();- const frame = frameRect(tabId) ?? origin;+ // Native views report CSS pixels; scale by their zoom.+ const bounds = native ? nativeViewBounds(tabId) : null;+ const frame = bounds ? { left: bounds.x, top: bounds.y } : (frameRect(tabId) ?? origin);+ const scale = bounds ? zoom : 1;const rect = pending ? rects.get(pending.id) : null;const pendingBox: Box | null = rect? {- left: rect.left + frame.left - origin.left,- top: rect.top + frame.top - origin.top,- width: rect.width,- height: rect.height,+ left: rect.left * scale + frame.left - origin.left,+ top: rect.top * scale + frame.top - origin.top,+ width: rect.width * scale,+ height: rect.height * scale,}: null;const count = items.length;@@ -957,6 +1006,16 @@ export function WebAnnotateLayer({return (<div ref={layerRef} className="pointer-events-none absolute inset-0 z-10 overflow-hidden">+ {native && pending ? (+ // The page is a snapshot while commenting; a press on it saves, as on a live page.+ <div+ data-annotate-ui=""+ data-native-cover=""+ aria-hidden={true}+ className="pointer-events-auto absolute inset-0"+ onPointerDown={save}+ />+ ) : null}{pending && pendingBox ? (<CommentFormkey={pending.id}@@ -976,6 +1035,7 @@ export function WebAnnotateLayer({sendDisabled={!sendAnnotations || sending}onSend={send}onExit={exit}+ besidePage={native}/>) : null}</div>diff --git a/studio/frontend/src/features/browser/browser-panel.tsx b/studio/frontend/src/features/browser/browser-panel.tsxindex 9a36c4de0f1..341be6e08b0 100644--- a/studio/frontend/src/features/browser/browser-panel.tsx+++ b/studio/frontend/src/features/browser/browser-panel.tsx@@ -1360,16 +1360,28 @@ function nativePage(tab: BrowserTab | undefined): boolean {return Boolean(tab && currentEntry(tab).kind === "web" && hasNativeView(tab.id));}-/** Ask about the page, as with a file's Request edits. Native views can't be drawn over. */+/** How a tab is annotated: a framed page, a native view, or Studio's own markup (new tab,+ * internal pages, documents, errors). Null while loading. Files use Request edits. */+function annotateMode(tab: BrowserTab | undefined, native: boolean): "frame" | "native" | "dom" | null {+ if (!tab) return null;+ const entry = currentEntry(tab);+ if (entry.kind === "newtab" || entry.kind === "internal") return "dom";+ if (entry.kind !== "web" || tab.loading) return null;+ if (native) return tab.nativeError ? "dom" : "native";+ return tab.documentType || tab.pageError ? "dom" : "frame";+}++/** Ask about the page, as with a file's Request edits. */function AnnotatePageButton({ tab }: { tab: BrowserTab | undefined }) {const t = useT();const canAnnotate = useBrowserStore((state) => state.sendAnnotations !== null);const annotating = useBrowserStore((state) => tab !== undefined && state.annotateTabId === tab.id);- if (!canAnnotate || nativePage(tab)) return null;+ const native = useNativeBrowser((state) => state.enabled);+ if (!canAnnotate) return null;return (<IconButtonlabel={t("browser.annotate.page")}- disabled={!tab || !showsWebPage(tab)}+ disabled={annotateMode(tab, native) === null}onClick={() => tab && useBrowserStore.getState().setAnnotating(annotating ? null : tab.id)}className={cn(ANNOTATE_BUTTON,@@ -2117,6 +2129,7 @@ export const BrowserPanel = memo(function BrowserPanel({ active = true }: { acticonst activeTabId = useBrowserStore((state) => state.activeTabId);const device = useBrowserStore((state) => state.device);const annotateTabId = useBrowserStore((state) => state.annotateTabId);+ const tabTitle = useTabTitle();const [pageElement, setPageElement] = useState<HTMLDivElement | null>(null);const sectionRef = useRef<HTMLElement>(null);// Zoom keys, Ctrl+wheel and the View menu zoom the page, not the interface, while focus or the pointer is here.@@ -2159,6 +2172,7 @@ export const BrowserPanel = memo(function BrowserPanel({ active = true }: { actidevice !== "off" && activeEntry?.kind === "web"? DEVICE_WIDTHS[device]: null;+ const pageAnnotating = activeTab && annotateTabId === activeTab.id ? annotateMode(activeTab, native) : null;return (<section@@ -2257,17 +2271,23 @@ export const BrowserPanel = memo(function BrowserPanel({ active = true }: { actifileName={activeEntry.name}/>) : null}- {activeTab &&- annotateTabId === activeTab.id &&- showsWebPage(activeTab) &&- !nativePage(activeTab) ? (+ {activeTab && activeEntry && (pageAnnotating === "frame" || pageAnnotating === "native") ? (// A new page, a reload or a replacement starts over: its marks were the last page's.<WebAnnotateLayer- key={`${activeTab.id}:${entryKey(currentEntry(activeTab))}:${activeTab.reloadKey}`}+ key={`${activeTab.id}:${entryKey(activeEntry)}:${activeTab.reloadKey}:${pageAnnotating}`}tabId={activeTab.id}title={activeTab.title}url={webAddress(activeTab) ?? ""}page={pageElement}+ native={pageAnnotating === "native"}+ />+ ) : null}+ {activeTab && activeEntry && pageAnnotating === "dom" && pageElement ? (+ <AnnotateLayer+ key={`${activeTab.id}:${entryKey(activeEntry)}:${activeTab.reloadKey}`}+ page={pageElement}+ fileName={tabTitle(activeTab, activeEntry)}+ url={webAddress(activeTab) ?? undefined}/>) : null}</div>diff --git a/studio/frontend/src/features/browser/native-annotate.ts b/studio/frontend/src/features/browser/native-annotate.tsnew file mode 100644index 00000000000..2cd985a54a3--- /dev/null+++ b/studio/frontend/src/features/browser/native-annotate.ts@@ -0,0 +1,136 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Annotate in a desktop native view: commands go through `browser_view_annotate`+ * (src-tauri/src/browser_webview.rs) and reports are polled, since the view can't message back. */++import { type AnnotateEvent, parseFrameMessage } from "./frame-message";+import { callNative } from "./native-support";+import type { FrameCommand } from "./page-frame";++// Hover outlines draw in the page; this only paces marks and scrolled rects.+const POLL_MS = 80;++type NativeCommand =+ | { command: "install"; code: string }+ | { command: "start"; color: string }+ | { command: "stop" }+ | { command: "forget"; id: number }+ | { command: "number"; numbers: Array<[number, number]> }+ | { command: "poll" };++type Answer = { installed: boolean; events: unknown[] };++function nativeCommand(command: FrameCommand): NativeCommand | null {+ switch (command.command) {+ case "annotateInstall":+ return { command: "install", code: command.code };+ case "annotate":+ return command.on ? { command: "start", color: command.color ?? "" } : { command: "stop" };+ case "annotateForget":+ return { command: "forget", id: command.id };+ case "annotateNumbers":+ return { command: "number", numbers: command.numbers };+ default:+ return null;+ }+}++function answerOf(value: unknown): Answer | null {+ if (!value || typeof value !== "object") return null;+ const { installed, events } = value as Record<string, unknown>;+ return typeof installed === "boolean" && Array.isArray(events) ? { installed, events } : null;+}++// One queue per tab across channels, so a closing channel's stop can't land after a new one's start.+const tabQueues = new Map<string, Promise<void>>();++/** Drives `tabId`'s page until `stop`. Reports `ready` when a navigation drops the code, so the layer reinstalls it. */+export function startNativeAnnotate(+ tabId: string,+ listener: (event: AnnotateEvent) => void,+): { send: (command: FrameCommand) => void; stop: () => void } {+ let live = true;+ // Null until the first answer; `ready` fires on installed -> not installed.+ let installed: boolean | null = null;+ // Install or start calls that failed or found no code, replayed after the next answer.+ const failed = new Map<"install" | "start", NativeCommand>();++ const deliver = (answer: Answer) => {+ if (!live) return;+ if (installed === true && !answer.installed) listener({ kind: "ready" });+ installed = answer.installed;+ // The page can write to the queue too, so validate like frame messages.+ for (const event of answer.events) {+ if (!live) return;+ const data = event && typeof event === "object" ? { ...event, source: "unsloth-browser" } : null;+ const message = parseFrameMessage(data);+ if (message?.type === "annotate") listener(message.event);+ }+ };++ const run = (command: NativeCommand): Promise<void> => {+ const call = () =>+ callNative<unknown>("browser_view_annotate", { tabId, command }).then(+ (value) => {+ const answer = answerOf(value);+ if (answer) deliver(answer);+ // A start that found no code (its install failed) goes again behind the install.+ if (live && command.command === "start" && answer && !answer.installed) failed.set("start", command);+ replay();+ },+ () => {+ if (live && (command.command === "install" || command.command === "start")) {+ failed.set(command.command, command);+ }+ },+ );+ // Serial, so install lands before start. A closed channel only sends its stop.+ const next = (tabQueues.get(tabId) ?? Promise.resolve()).then(() =>+ live || command.command === "stop" ? call() : undefined,+ );+ tabQueues.set(tabId, next);+ void next.finally(() => {+ if (tabQueues.get(tabId) === next) tabQueues.delete(tabId);+ });+ return next;+ };++ const replay = () => {+ if (!live) return;+ const install = failed.get("install");+ const start = failed.get("start");+ if (install) {+ failed.delete("install");+ void run(install);+ }+ // Start only behind its install or once the code is in, so a navigating page can't loop it.+ if (start && (install || installed)) {+ failed.delete("start");+ void run(start);+ }+ };++ let polling = false;+ const timer = window.setInterval(() => {+ if (polling) return;+ polling = true;+ void run({ command: "poll" }).finally(() => {+ polling = false;+ });+ }, POLL_MS);++ return {+ send: (command) => {+ const native = nativeCommand(command);+ if (!native) return;+ if (native.command === "stop") failed.delete("start");+ void run(native);+ },+ stop: () => {+ window.clearInterval(timer);+ void run({ command: "stop" });+ live = false;+ },+ };+}diff --git a/studio/frontend/src/features/browser/native-view.ts b/studio/frontend/src/features/browser/native-view.tsindex c1425a0ac2c..4be3a8c03db 100644--- a/studio/frontend/src/features/browser/native-view.ts+++ b/studio/frontend/src/features/browser/native-view.ts@@ -91,6 +91,7 @@ function keepReachedPage(tabId: string): void {function closeView(tabId: string): void {keepReachedPage(tabId);views.delete(tabId);+ viewBounds.delete(tabId);zooms.delete(tabId);icons.delete(tabId);pages.delete(tabId);@@ -225,6 +226,12 @@ export function nativeAction(tabId: string, action: "back" | "forward" | "reloadvoid call("browser_view_action", { tabId, action }).catch(() => undefined);}+/** Gives key focus back to the panel's webview. */+export function focusPanel(tabId: string): Promise<void> {+ if (!views.has(tabId)) return Promise.resolve();+ return call("browser_view_action", { tabId, action: "blur" }).catch(() => undefined);+}+export function returnToNativePage(tabId: string): boolean {const shown = pages.get(tabId);const store = useBrowserStore.getState();@@ -241,14 +248,20 @@ export function hasNativeView(tabId: string): boolean {return views.has(tabId);}+/** Last shown bounds of `tabId`'s view, in window coordinates. */+export function nativeViewBounds(tabId: string): Bounds | null {+ return viewBounds.get(tabId) ?? null;+}+export async function nativeFind(tabId: string, query: string, backwards: boolean): Promise<boolean> {if (!views.has(tabId)) return false;return call<boolean>("browser_view_find", { tabId, query, backwards }).catch(() => false);}// exclude upward-opening tooltips to avoid hiding the native page on every hover; overlapping toasts still cover it.+// `data-native-cover`: panel UI over the page, e.g. an annotation comment.const OVERLAY_SELECTOR =- '[data-radix-popper-content-wrapper], [role="dialog"], [role="alertdialog"], [data-slot$="-overlay"], [data-sonner-toast]';+ '[data-radix-popper-content-wrapper], [role="dialog"], [role="alertdialog"], [data-slot$="-overlay"], [data-sonner-toast], [data-native-cover]';function intersects(a: DOMRect, b: DOMRect): boolean {return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;@@ -274,7 +287,10 @@ function visibleRect(element: HTMLElement): DOMRect | null {}if (rect.width < 2 || rect.height < 2) return null;let bottom = rect.bottom;- for (const dock of document.querySelectorAll<HTMLElement>(".chat-full-view-dock, .chat-full-view-dock-minimized")) {+ // `data-native-inset`: panel UI below the page, e.g. the annotate bar.+ for (const dock of document.querySelectorAll<HTMLElement>(+ ".chat-full-view-dock, .chat-full-view-dock-minimized, [data-native-inset]",+ )) {const box = dock.getBoundingClientRect();if (box.height > 0 && intersects(box, rect)) bottom = Math.min(bottom, box.top - DOCK_GAP);}@@ -379,6 +395,7 @@ export function whenNativeViewShown(tabId: string, timeoutMs = 1500): Promise<bo// keep the last frame on the placeholder so overlays do not leave the panel blank.let snapshot: { tabId: string; element: HTMLElement; url: string } | null = null;let shownBounds: Bounds | null = null;+const viewBounds = new Map<string, Bounds>();function clearSnapshot(): void {if (!snapshot) return;@@ -434,6 +451,7 @@ async function applyView(desired: Desired): Promise<void> {if (stale()) return;clearSnapshot();shownBounds = bounds;+ viewBounds.set(tabId, bounds);setShownView(tabId);// record the entry after navigation succeeds so failures remain retryable.if (existed && loaded !== entry) {@@ -485,6 +503,7 @@ onNativeViewsClosed(() => {for (const tabId of [...views.keys()]) keepReachedPage(tabId);setShownView(null);views.clear();+ viewBounds.clear();zooms.clear();icons.clear();pages.clear();diff --git a/studio/frontend/src/features/browser/store.ts b/studio/frontend/src/features/browser/store.tsindex 8b7afb985b0..84ba9ff20f8 100644--- a/studio/frontend/src/features/browser/store.ts+++ b/studio/frontend/src/features/browser/store.ts@@ -67,6 +67,8 @@ export type BrowserTab = {zoom: number;nativeHistory: { back: boolean; forward: boolean } | null;nativeError: string | null;+ /** The proxied page failed to load, so an error shows instead of its frame. */+ pageError?: boolean;/** The name the reader gave the tab; kept as it navigates. */customTitle: string | null;muted: boolean;@@ -297,7 +299,7 @@ type BrowserState = {patch: Partial<Pick<BrowserTab,- "title" | "favicon" | "documentType" | "displayUrl" | "loading" | "nativeHistory" | "nativeError"+ "title" | "favicon" | "documentType" | "displayUrl" | "loading" | "nativeHistory" | "nativeError" | "pageError">>,) => void;@@ -348,6 +350,7 @@ function pushEntry(tab: BrowserTab, entry: BrowserEntry, replace = false): Browsloading: entry.kind === "web",openKey: null,nativeError: null,+ pageError: false,zoom,};}@@ -365,6 +368,7 @@ function moveTo(tab: BrowserTab, index: number): BrowserTab {loading: entry.kind === "web",openKey: entry.kind === "file" ? (entry.openKey ?? null) : null,nativeError: null,+ pageError: false,};}diff --git a/studio/frontend/src/features/browser/tab-view.tsx b/studio/frontend/src/features/browser/tab-view.tsxindex eccf5df53eb..dfbc07a8cb1 100644--- a/studio/frontend/src/features/browser/tab-view.tsx+++ b/studio/frontend/src/features/browser/tab-view.tsx@@ -242,11 +242,21 @@ function WebPage({const name = page.fileName ?? fileNameFromUrl(page.url);setPageDownload(tab.id, { blob: page.blob, name, contentType: page.contentType });fitZoomToPage(tab.id, true);- updateTab(tab.id, { loading: false, title: name, displayUrl: page.url, documentType: page.contentType });+ updateTab(tab.id, {+ loading: false,+ title: name,+ displayUrl: page.url,+ documentType: page.contentType,+ pageError: false,+ });if (method !== "POST") useBrowserHistoryStore.getState().recordVisit(page.url, name);} else {fitZoomToPage(tab.id, false);- updateTab(tab.id, { title: hostOf(page.url), displayUrl: page.url === url ? null : page.url });+ updateTab(tab.id, {+ title: hostOf(page.url),+ displayUrl: page.url === url ? null : page.url,+ pageError: false,+ });}};const cached = cachedPage(entry);@@ -255,7 +265,7 @@ function WebPage({return () => setPageDownload(tab.id, null);}if (blocked) {- updateTab(tab.id, { loading: false, title: hostOf(url) });+ updateTab(tab.id, { loading: false, title: hostOf(url), pageError: true });return;}if (method === "POST") {@@ -277,7 +287,7 @@ function WebPage({message: error instanceof Error ? error.message : String(error),botCheck: error instanceof BrowserFetchError && error.botCheck,});- updateTab(tab.id, { loading: false, title: hostOf(url) });+ updateTab(tab.id, { loading: false, title: hostOf(url), pageError: true });});return () => {controller.abort();diff --git a/studio/frontend/tests/browser-native-annotate.test.ts b/studio/frontend/tests/browser-native-annotate.test.tsnew file mode 100644index 00000000000..454f49650bd--- /dev/null+++ b/studio/frontend/tests/browser-native-annotate.test.ts@@ -0,0 +1,174 @@+// 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 { register } from "node:module";+import { test } from "node:test";++Object.assign(globalThis, { window: globalThis });++type Answer = { installed: boolean; events: unknown[] };+type Call = { command: Record<string, unknown>; answer: (value: Answer) => void; fail: () => void };+const calls: Call[] = [];+(globalThis as { nativeViewCall?: unknown }).nativeViewCall = (+ _name: string,+ args: { command: Record<string, unknown> },+) =>+ new Promise<Answer>((answer, reject) =>+ calls.push({ command: args.command, answer, fail: () => reject(new Error("no such tab")) }),+ );++register("./helpers/browser-store-resolver.mjs", import.meta.url);+register("./helpers/native-view-resolver.mjs", import.meta.url);+const { startNativeAnnotate } = await import("../src/features/browser/native-annotate.ts");++const settle = () => new Promise((resolve) => setTimeout(resolve, 5));+const sent = () => calls.map(({ command }) => command.command);++test("commands reach the page one at a time, in order, and only checked reports come back", async () => {+ calls.length = 0;+ const events: unknown[] = [];+ const channel = startNativeAnnotate("t1", (event) => events.push(event));+ try {+ channel.send({ command: "annotateInstall", code: "return {}" });+ channel.send({ command: "annotate", on: true, color: "#fff" });+ await settle();+ // Start waits for install.+ assert.deepEqual(sent(), ["install"]);+ calls[0]?.answer({ installed: true, events: [] });+ await settle();+ assert.deepEqual(sent(), ["install", "start"]);+ assert.deepEqual(calls[1]?.command, { command: "start", color: "#fff" });+ calls[1]?.answer({+ installed: true,+ events: [+ { type: "annotate", event: "up" },+ { type: "annotate", event: "mark", id: 1, rect: { left: 1, top: 2, width: 3, height: 4 }, quote: "Hi" },+ // Forged by the page: dropped.+ { type: "annotate", event: "mark", id: "x" },+ { type: "navigate", url: "https://example.com" },+ "junk",+ ],+ });+ await settle();+ assert.deepEqual(events, [+ { kind: "up" },+ { kind: "mark", id: 1, rect: { left: 1, top: 2, width: 3, height: 4 }, quote: "Hi", image: false, alt: "", area: false },+ ]);+ } finally {+ channel.stop();+ }+});++test("a page that loses the code (it navigated) asks for it again, once", async () => {+ calls.length = 0;+ const events: unknown[] = [];+ const channel = startNativeAnnotate("t4", (event) => events.push(event));+ const answerNext = async (installed: boolean) => {+ for (let wait = 0; wait < 100 && calls.length === 0; wait++) await settle();+ const call = calls.shift();+ call?.answer({ installed, events: [] });+ await settle();+ };+ try {+ // Never installed yet: no ready.+ await answerNext(false);+ assert.deepEqual(events, []);+ await answerNext(true);+ await answerNext(false);+ await answerNext(false);+ assert.deepEqual(events, [{ kind: "ready" }]);+ } finally {+ channel.stop();+ await settle();+ }+ assert.ok(calls.some(({ command }) => command.command === "stop"), "stopping turns the page's annotate off");+});++test("a closing channel's stop runs before a new channel's commands for the tab", async () => {+ calls.length = 0;+ const old = startNativeAnnotate("t2", () => undefined);+ await new Promise((resolve) => setTimeout(resolve, 100));+ // A poll hangs (the page is navigating) while the layer remounts.+ assert.deepEqual(sent(), ["poll"]);+ old.stop();+ const fresh = startNativeAnnotate("t2", () => undefined);+ try {+ fresh.send({ command: "annotateInstall", code: "return {}" });+ fresh.send({ command: "annotate", on: true, color: "#fff" });+ for (let at = 0; at < 3; at++) {+ calls[at]?.answer({ installed: at > 0, events: [] });+ await settle();+ }+ assert.deepEqual(sent().slice(0, 4), ["poll", "stop", "install", "start"]);+ } finally {+ fresh.stop();+ await settle();+ }+});++test("an install or start that failed is sent again after the next answer", async () => {+ calls.length = 0;+ const channel = startNativeAnnotate("t3", () => undefined);+ try {+ channel.send({ command: "annotateInstall", code: "return {}" });+ channel.send({ command: "annotate", on: true, color: "#fff" });+ await settle();+ calls[0]?.fail();+ await settle();+ calls[1]?.fail();+ // The next poll answers: both go again, in order.+ for (let wait = 0; wait < 100 && calls.length < 3; wait++) await settle();+ calls[2]?.answer({ installed: false, events: [] });+ await settle();+ calls[3]?.answer({ installed: true, events: [] });+ await settle();+ assert.deepEqual(sent().slice(0, 5), ["install", "start", "poll", "install", "start"]);+ } finally {+ channel.stop();+ await settle();+ }+});++test("a start that reaches the page after its install failed goes again behind the install", async () => {+ calls.length = 0;+ const channel = startNativeAnnotate("t5", () => undefined);+ try {+ channel.send({ command: "annotateInstall", code: "return {}" });+ channel.send({ command: "annotate", on: true, color: "#fff" });+ await settle();+ calls[0]?.fail();+ await settle();+ // The view now exists, but without the code: the start does nothing there.+ calls[1]?.answer({ installed: false, events: [] });+ await settle();+ calls[2]?.answer({ installed: true, events: [] });+ await settle();+ assert.deepEqual(sent().slice(0, 4), ["install", "start", "install", "start"]);+ } finally {+ channel.stop();+ await settle();+ }+});++test("a start that finds no code is not resent until the code is in", async () => {+ calls.length = 0;+ const channel = startNativeAnnotate("t6", () => undefined);+ try {+ channel.send({ command: "annotate", on: true, color: "#fff" });+ await settle();+ calls[0]?.answer({ installed: false, events: [] });+ // Polls only: no tight loop of starts while the page has no code.+ for (let wait = 0; wait < 100 && calls.length < 2; wait++) await settle();+ calls[1]?.answer({ installed: false, events: [] });+ for (let wait = 0; wait < 100 && calls.length < 3; wait++) await settle();+ assert.deepEqual(sent().slice(0, 3), ["start", "poll", "poll"]);+ // Once a poll finds the code, the start goes again.+ calls[2]?.answer({ installed: true, events: [] });+ await settle();+ assert.equal(sent()[3], "start");+ } finally {+ channel.stop();+ await settle();+ }+});diff --git a/studio/src-tauri/src/browser_webview.rs b/studio/src-tauri/src/browser_webview.rsindex c9c8ccedb17..795be9434be 100644--- a/studio/src-tauri/src/browser_webview.rs+++ b/studio/src-tauri/src/browser_webview.rs@@ -1315,6 +1315,8 @@ pub fn browser_view_action<R: Runtime>("reload" => page.reload(),"stop" => page.eval("window.stop()"),"focus" => page.set_focus(),+ // Key focus back to the panel, e.g. for an annotation comment.+ "blur" => webview.set_focus(),_ => return Err("unknown action".into()),};result.map_err(|error| error.to_string())@@ -1366,6 +1368,117 @@ pub async fn browser_view_find<R: Runtime>(.unwrap_or(false))}+// Same cap as the page shell's `install` (routes/browser.py).+const MAX_ANNOTATE_CODE: usize = 262_144;+const MAX_ANNOTATE_NUMBERS: usize = 500;++/// Commands for a page's annotate code (`_ANNOTATE_JS` in routes/browser.py).+#[derive(Debug, Deserialize)]+#[serde(tag = "command", rename_all = "camelCase")]+pub enum AnnotateCommand {+ Install { code: String },+ Start { color: String },+ Stop,+ Forget { id: u32 },+ Number { numbers: Vec<(u32, u32)> },+ Poll,+}++// Installs the annotate code under a non-enumerable key. `post` queues reports for the panel to+// poll, keeping only the latest `rects`. Each call returns whether the code is installed (a+// navigation drops it) and the reports since the last call.+const ANNOTATE_SCRIPT: &str = r#"(() => {+ const key = Symbol.for("unsloth.annotate");+ const command = __COMMAND__;+ let shell = window[key];+ if (!shell && command.command === "install") {+ const queue = [];+ const post = (message) => {+ if (!message || message.type !== "annotate") return;+ if (message.event === "rects") {+ const at = queue.findIndex((queued) => queued.event === "rects");+ if (at !== -1) queue.splice(at, 1);+ }+ if (queue.length < 200) queue.push(message);+ };+ try {+ shell = { queue, annotation: (function (post) {+__CODE__+ })(post) };+ Object.defineProperty(window, key, { value: shell, configurable: true });+ } catch { shell = null; }+ }+ if (!shell) return JSON.stringify({ installed: false, events: [] });+ const { annotation, queue } = shell;+ if (command.command === "start") annotation.start(command.color);+ else if (command.command === "stop") annotation.stop();+ else if (command.command === "forget") annotation.forget(command.id);+ else if (command.command === "number") annotation.number(command.numbers);+ return JSON.stringify({ installed: true, events: queue.splice(0) });+})()"#;++fn annotate_script(command: &AnnotateCommand) -> Result<String, String> {+ let (args, code) = match command {+ AnnotateCommand::Install { code } => {+ if code.len() > MAX_ANNOTATE_CODE {+ return Err("annotate code too large".into());+ }+ (serde_json::json!({ "command": "install" }), code.as_str())+ }+ AnnotateCommand::Start { color } => (+ serde_json::json!({ "command": "start", "color": color.chars().take(64).collect::<String>() }),+ "",+ ),+ AnnotateCommand::Stop => (serde_json::json!({ "command": "stop" }), ""),+ AnnotateCommand::Forget { id } => {+ (serde_json::json!({ "command": "forget", "id": id }), "")+ }+ AnnotateCommand::Number { numbers } => {+ let numbers: Vec<_> = numbers.iter().take(MAX_ANNOTATE_NUMBERS).collect();+ (+ serde_json::json!({ "command": "number", "numbers": numbers }),+ "",+ )+ }+ AnnotateCommand::Poll => (serde_json::json!({ "command": "poll" }), ""),+ };+ // Spliced in, not compiled in the page, so a CSP without 'unsafe-eval' can't block it.+ // Single pass, so neither part can inject the other's placeholder.+ let (head, rest) = ANNOTATE_SCRIPT+ .split_once("__COMMAND__")+ .ok_or("bad annotate script")?;+ let (middle, tail) = rest.split_once("__CODE__").ok_or("bad annotate script")?;+ Ok(format!("{head}{args}{middle}{code}{tail}"))+}++/// Runs an annotate command in a tab's page and returns `{ installed, events }`. The panel+/// validates events like frame messages, since the page can write to the queue.+#[tauri::command]+pub async fn browser_view_annotate<R: Runtime>(+ webview: Webview<R>,+ tab_id: String,+ command: AnnotateCommand,+) -> Result<serde_json::Value, String> {+ require_main(&webview)?;+ let page = view(webview.app_handle(), &tab_id)?;+ let script = annotate_script(&command)?;+ let (tx, rx) = tokio::sync::oneshot::channel();+ let tx = Mutex::new(Some(tx));+ page.eval_with_callback(script, move |result| {+ if let Some(tx) = tx.lock().unwrap().take() {+ let _ = tx.send(result);+ }+ })+ .map_err(|error| error.to_string())?;+ let result = tokio::time::timeout(Duration::from_secs(5), rx)+ .await+ .map_err(|_| "page did not answer".to_string())?+ .map_err(|error| error.to_string())?;+ // The script returns a JSON string, which the engine JSON-encodes again.+ let inner = serde_json::from_str::<String>(&result).map_err(|error| error.to_string())?;+ serde_json::from_str(&inner).map_err(|error| error.to_string())+}+/// Mute or unmute a tab's page. Windows mutes the whole view (Web Audio too) and keeps it muted/// across loads; macOS mutes the page's media, and each page it loads after (see `MUTE_SCRIPT`).#[tauri::command]@@ -1823,6 +1936,42 @@ mod tests {assert_eq!(bounds.viewport_width, 5.0);}+ #[test]+ fn annotate_commands_match_the_panel() {+ let parse = |value| serde_json::from_value::<AnnotateCommand>(value).unwrap();+ assert!(matches!(+ parse(serde_json::json!({ "command": "number", "numbers": [[3, 1]] })),+ AnnotateCommand::Number { numbers } if numbers == vec![(3, 1)]+ ));+ assert!(matches!(+ parse(serde_json::json!({ "command": "poll" })),+ AnnotateCommand::Poll+ ));+ assert!(serde_json::from_value::<AnnotateCommand>(+ serde_json::json!({ "command": "eval" })+ )+ .is_err());+ }++ #[test]+ fn annotate_code_is_spliced_once() {+ let script = annotate_script(&AnnotateCommand::Install {+ code: "return __COMMAND__;".into(),+ })+ .unwrap();+ assert!(script.contains(r#"const command = {"command":"install"};"#));+ assert!(script.contains("return __COMMAND__;"));+ let start = annotate_script(&AnnotateCommand::Start {+ color: "__CODE__".into(),+ })+ .unwrap();+ assert!(start.contains(r#""color":"__CODE__""#));+ assert!(annotate_script(&AnnotateCommand::Install {+ code: "x".repeat(MAX_ANNOTATE_CODE + 1)+ })+ .is_err());+ }+#[test]fn titles_are_bounded() {assert_eq!(diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 2446993eebf..25c3fdc730b 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -2251,6 +2251,7 @@ fn main() {browser_webview::browser_view_action,browser_webview::browser_view_zoom,browser_webview::browser_view_find,+ browser_webview::browser_view_annotate,browser_webview::browser_view_close,browser_webview::browser_view_clear_data,browser_webview::browser_view_mute,