Skip to content

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.

Keep HTML previews visible when requesting edits (#14810)

Nilay7aab2d79efdd
diff --git a/studio/backend/routes/browser.py b/studio/backend/routes/browser.py
index 3644e1d1246..5e57a18b8f5 100644
--- a/studio/backend/routes/browser.py
+++ b/studio/backend/routes/browser.py
@@ -1327,18 +1327,36 @@ _ANNOTATE_JS = r"""
display, left: box.left + "px", top: box.top + "px", width: box.width + "px", height: box.height + "px",
});
};
+ // Constructed sheets keep the annotation UI visible under a page's style CSP.
+ const addStyle = (target, css) => {
+ if ("adoptedStyleSheets" in target) {
+ const sheet = new CSSStyleSheet();
+ sheet.replaceSync(css);
+ target.adoptedStyleSheets = [...target.adoptedStyleSheets, sheet];
+ return () => { target.adoptedStyleSheets = target.adoptedStyleSheets.filter((item) => item !== sheet); };
+ }
+ const style = document.createElement("style");
+ style.textContent = css;
+ (target.head || target.documentElement || target).appendChild(style);
+ return () => style.remove();
+ };
const build = () => {
overlay = document.createElement("unsloth-annotate");
overlay.style.cssText = "all: initial; position: fixed; inset: 0; pointer-events: none; z-index: 2147483647;";
root = overlay.attachShadow({ mode: "closed" });
- root.innerHTML = `<style>
+ for (const name of ["hover", "area"]) {
+ const element = document.createElement("div");
+ element.className = name;
+ root.appendChild(element);
+ }
+ addStyle(root, `
:host { --c: ${color}; }
div { position: fixed; box-sizing: border-box; border-radius: 6px; display: none; }
.hover { border: 1.5px solid color-mix(in srgb, var(--c) 75%, transparent); transition: left .08s, top .08s, width .08s, height .08s; }
.area, .mark { border: 1.5px dashed color-mix(in srgb, var(--c) 70%, transparent); background: color-mix(in srgb, var(--c) 6%, transparent); }
.pin { width: ${PIN}px; height: ${PIN}px; border-radius: 50% 50% 50% 4px; background: var(--c); box-shadow: 0 0 0 2px #fff, 0 1px 4px rgb(0 0 0 / .3);
align-items: center; justify-content: center; color: #fff; font: 600 12px/1 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; font-variant-numeric: tabular-nums; }
- </style><div class="hover"></div><div class="area"></div>`;
+ `);
outline = root.querySelector(".hover");
area = root.querySelector(".area");
};
@@ -1476,7 +1494,7 @@ _ANNOTATE_JS = r"""
swallow(event);
send("escape");
};
- const style = document.createElement("style");
+ let removeStyle = null;
const cursor = () => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30"><path d="M3 27V15A12 12 0 1 1 15 27Z" fill="${color}" stroke="white" stroke-width="2"/></svg>`;
return `url("data:image/svg+xml,${encodeURIComponent(svg)}") 3 27, crosshair`;
@@ -1492,12 +1510,11 @@ _ANNOTATE_JS = r"""
if (on) return;
on = true;
build();
- style.textContent = `*, *::before, *::after { cursor: ${cursor()} !important; user-select: none !important; -webkit-user-select: none !important; }`;
+ removeStyle = addStyle(document, `*, *::before, *::after { cursor: ${cursor()} !important; user-select: none !important; -webkit-user-select: none !important; }`);
for (const [type, listener] of listeners) window.addEventListener(type, listener, true);
document.addEventListener("mouseout", onLeave, true);
window.addEventListener("scroll", redraw, true);
window.addEventListener("resize", redraw);
- (document.head || document.documentElement).appendChild(style);
document.documentElement.appendChild(overlay);
redraw();
};
@@ -1508,7 +1525,8 @@ _ANNOTATE_JS = r"""
document.removeEventListener("mouseout", onLeave, true);
window.removeEventListener("scroll", redraw, true);
window.removeEventListener("resize", redraw);
- style.remove();
+ removeStyle?.();
+ removeStyle = null;
overlay?.remove();
cancelAnimationFrame(frame);
if (pending) cancelAnimationFrame(pending);
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 099f93f089f..8e3a5adaf70 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -4359,6 +4359,9 @@ _ARTIFACT_PREVIEW_FRAME_HTML = """<!doctype html>
};
}
};
+ const annotationFactory = (post) => {
+ /* ANNOTATE_JS */
+ };
// Named for canvasStack() in the frontend, which trims from this frame down.
const unslothRenderArtifact = (html) => {
installStorageFallbacks();
@@ -4370,6 +4373,22 @@ _ARTIFACT_PREVIEW_FRAME_HTML = """<!doctype html>
captureConsole();
document.write(html);
document.close();
+ // Instantiate only on a parent command; the factory predates the page's meta CSP.
+ let annotation = null;
+ const postAnnotation = (message) => parent.postMessage({ source: "unsloth-browser", ...message }, "*");
+ window.addEventListener("message", (event) => {
+ if (event.source !== parent) return;
+ const data = event.data;
+ if (!data || data.type !== "unsloth:browser-command") return;
+ if (data.command === "annotateInstall") {
+ if (!annotation) annotation = annotationFactory(postAnnotation);
+ } else if (data.command === "annotate") {
+ if (data.on === true) annotation?.start(data.color);
+ else annotation?.stop();
+ } else if (data.command === "annotateForget") annotation?.forget(Number(data.id));
+ else if (data.command === "annotateNumbers") annotation?.number(data.numbers);
+ });
+ postAnnotation({ type: "annotate", event: "ready" });
// document.open() drops listeners bound before it, so rebind here.
document.addEventListener("securitypolicyviolation", reportBlocked, true);
};
@@ -4389,6 +4408,12 @@ _ARTIFACT_PREVIEW_FRAME_HTML = """<!doctype html>
</html>"""
+def _artifact_preview_frame_html() -> str:
+ # Imported at request time: browser also uses the frame-ancestors policy from this module.
+ from routes.browser import _ANNOTATE_JS
+ return _ARTIFACT_PREVIEW_FRAME_HTML.replace("/* ANNOTATE_JS */", _ANNOTATE_JS, 1)
+
+
async def _authenticate_header_or_query(request: Request, token: Optional[str]) -> str:
"""Resolve the bearer token from the Authorization header or the ``?token=``
query param (needed for <img src> / <iframe>, which can't send custom
@@ -4413,7 +4438,7 @@ async def artifact_preview_frame(allow_network: bool = False):
_ARTIFACT_PREVIEW_FRAME_NETWORK_CSP if allow_network else _ARTIFACT_PREVIEW_FRAME_STRICT_CSP
)
return Response(
- content = _ARTIFACT_PREVIEW_FRAME_HTML,
+ content = _artifact_preview_frame_html(),
media_type = "text/html; charset=utf-8",
headers = {
"Cache-Control": "no-store",
@@ -4631,7 +4656,7 @@ async def mcp_app_frame(
_mcp_app_domains(base_uri, local_schemes = False),
)
return Response(
- content = _ARTIFACT_PREVIEW_FRAME_HTML,
+ content = _artifact_preview_frame_html(),
media_type = "text/html; charset=utf-8",
headers = {
"Cache-Control": "no-store",
diff --git a/studio/backend/tests/test_artifact_preview_frame_csp.py b/studio/backend/tests/test_artifact_preview_frame_csp.py
index d8cd0a14eb3..a556fa24c74 100644
--- a/studio/backend/tests/test_artifact_preview_frame_csp.py
+++ b/studio/backend/tests/test_artifact_preview_frame_csp.py
@@ -199,3 +199,15 @@ def test_the_strict_csp_is_exactly_the_reviewed_policy():
"http://localhost:* http://127.0.0.1:*; "
"sandbox allow-scripts"
)
+
+
+def test_annotation_factory_is_served_before_the_document_can_add_a_meta_csp():
+ from routes.browser import _ANNOTATE_JS
+
+ response = asyncio.run(inf_mod.artifact_preview_frame())
+ shell = response.body.decode()
+ assert _ANNOTATE_JS in shell
+ assert "/* ANNOTATE_JS */" not in shell
+ assert shell.index("const annotationFactory") < shell.index("document.write(html)")
+ assert "annotation = annotationFactory(postAnnotation)" in shell
+ assert "__unslothInstallAnnotation" not in shell
diff --git a/studio/frontend/src/features/browser/annotate-layer.tsx b/studio/frontend/src/features/browser/annotate-layer.tsx
index 11b0d640d4a..a51675de405 100644
--- a/studio/frontend/src/features/browser/annotate-layer.tsx
+++ b/studio/frontend/src/features/browser/annotate-layer.tsx
@@ -28,7 +28,7 @@ import { screenshotPage } from "./capture";
import { type AnnotateEvent, type AnnotateRect, MAX_MARKS } from "./frame-message";
import { startNativeAnnotate } from "./native-annotate";
import { focusPanel, nativeViewBounds } from "./native-view";
-import { type FrameCommand, frameRect, onFrameAnnotate, sendFrameCommand } from "./page-frame";
+import { type FrameCommand, frameRect, frameScale, onFrameAnnotate, sendFrameCommand } from "./page-frame";
import { useBrowserPrefsStore } from "./prefs-store";
import { useBrowserStore } from "./store";
@@ -1032,7 +1032,7 @@ export function WebAnnotateLayer({
url,
page,
native = false,
-}: { tabId: string; title: string; url: string; page: HTMLElement | null; native?: boolean }) {
+}: { 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);
@@ -1101,7 +1101,7 @@ export function WebAnnotateLayer({
setDraft("");
const files = await annotationScreenshot(page);
const sent = await sendAnnotations(
- { file: title || url, url, items: outgoing.map(({ quote, request }) => ({ quote, request })) },
+ { file: title || url || "", url, items: outgoing.map(({ quote, request }) => ({ quote, request })) },
files,
).finally(() => setSending(false));
if (sent) exit();
@@ -1228,7 +1228,7 @@ export function WebAnnotateLayer({
// 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 scale = bounds ? zoom : frameScale(tabId);
const rect = pending ? rects.get(pending.id) : null;
const pendingBox: Box | null = rect
? {
diff --git a/studio/frontend/src/features/browser/browser-panel.tsx b/studio/frontend/src/features/browser/browser-panel.tsx
index 02117beaae9..51101d500d7 100644
--- a/studio/frontend/src/features/browser/browser-panel.tsx
+++ b/studio/frontend/src/features/browser/browser-panel.tsx
@@ -170,7 +170,7 @@ import {
pageDownload,
useBrowserStore,
} from "./store";
-import { sendFrameCommand } from "./page-frame";
+import { sendFrameCommand, useFrameAvailable } from "./page-frame";
import { TabView } from "./tab-view";
import { ZOOM_STEPS, canZoom, homeZoom, stepZoom, zoomTab } from "./zoom";
import { useShallow } from "zustand/shallow";
@@ -1535,14 +1535,8 @@ function BrowserFileToolbar({
const showsSource = kind === "code" || kind === "text" || (hasSource && view.mode === "source");
const htmlPreview = kind === "html" && view.mode === "preview";
const setView = (patch: Partial<FileViewState>) => useBrowserStore.getState().setFileView(tab.id, patch);
- // The preview is a frame the annotation layer can't select in, so marks go on the source.
- useEffect(() => {
- if (annotating && htmlPreview) useBrowserStore.getState().setAnnotating(null);
- }, [annotating, htmlPreview]);
- const toggleAnnotating = () => {
- if (!annotating && htmlPreview) setView({ mode: "source" });
+ const toggleAnnotating = () =>
useBrowserStore.getState().setAnnotating(annotating ? null : tab.id);
- };
const copyContents = () => {
if (!blob) return;
void copyToClipboardFrom(() => blob.text()).then((ok) => {
@@ -1800,14 +1794,8 @@ function FloatingFileToolbar({
const showsSource = kind === "code" || kind === "text" || (hasSource && view.mode === "source");
const htmlPreview = kind === "html" && view.mode === "preview";
const setView = (patch: Partial<FileViewState>) => useBrowserStore.getState().setFileView(tab.id, patch);
- // The preview is a frame the annotation layer can't select in, so marks go on the source.
- useEffect(() => {
- if (annotating && htmlPreview) useBrowserStore.getState().setAnnotating(null);
- }, [annotating, htmlPreview]);
- const toggleAnnotating = () => {
- if (!annotating && htmlPreview) setView({ mode: "source" });
+ const toggleAnnotating = () =>
useBrowserStore.getState().setAnnotating(annotating ? null : tab.id);
- };
const copyContents = () => {
if (!blob) return;
void copyToClipboardFrom(() => blob.text()).then((ok) => {
@@ -2450,6 +2438,7 @@ export const BrowserPanel = memo(function BrowserPanel({ active = true }: { acti
const activeTabId = useBrowserStore((state) => state.activeTabId);
const device = useBrowserStore((state) => state.device);
const annotateTabId = useBrowserStore((state) => state.annotateTabId);
+ const fileMode = useBrowserStore((state) => state.fileViews[state.activeTabId ?? ""]?.mode) ?? DEFAULT_FILE_VIEW.mode;
const tabTitle = useTabTitle();
const [pageElement, setPageElement] = useState<HTMLDivElement | null>(null);
const sectionRef = useRef<HTMLElement>(null);
@@ -2497,6 +2486,9 @@ export const BrowserPanel = memo(function BrowserPanel({ active = true }: { acti
device !== "off" && activeEntry?.kind === "web"
? DEVICE_WIDTHS[device]
: null;
+ const frameAvailable = useFrameAvailable(activeTabId);
+ const htmlAnnotating = frameAvailable && activeEntry?.kind === "file" &&
+ fileBarKind(activeEntry.name, activeEntry.contentType, activeEntry.plainText) === "html" && fileMode === "preview";
const pageAnnotating = activeTab && annotateTabId === activeTab.id ? annotateMode(activeTab, native) : null;
return (
@@ -2613,12 +2605,21 @@ export const BrowserPanel = memo(function BrowserPanel({ active = true }: { acti
annotateTabId === activeTab.id &&
pageElement ? (
// Refreshed bytes are a new document: the marks were on the old one.
- <AnnotateLayer
- key={`${activeTab.id}:${activeEntry.fileId}`}
- page={pageElement}
- fileName={activeEntry.name}
- zoom={activeTab.zoom}
- />
+ htmlAnnotating ? (
+ <WebAnnotateLayer
+ key={`${activeTab.id}:${activeEntry.fileId}:${activeTab.reloadKey}`}
+ tabId={activeTab.id}
+ title={activeEntry.name}
+ page={pageElement}
+ />
+ ) : (
+ <AnnotateLayer
+ key={`${activeTab.id}:${activeEntry.fileId}`}
+ page={pageElement}
+ fileName={activeEntry.name}
+ zoom={activeTab.zoom}
+ />
+ )
) : null}
{activeTab && activeEntry && (pageAnnotating === "frame" || pageAnnotating === "native") ? (
// A new page, a reload or a replacement starts over: its marks were the last page's.
diff --git a/studio/frontend/src/features/browser/file-view.tsx b/studio/frontend/src/features/browser/file-view.tsx
index 893d2fa4342..1aed7294db9 100644
--- a/studio/frontend/src/features/browser/file-view.tsx
+++ b/studio/frontend/src/features/browser/file-view.tsx
@@ -16,6 +16,7 @@ import { MAX_HIGHLIGHT_CHARS } from "@/lib/markdown-plugins";
import { cn } from "@/lib/utils";
import { useCallback, useEffect, useMemo, useState } from "react";
import { canShowFile, mediaKind, textFileKind } from "./file-kind";
+import { registerArtifactFrame } from "./page-frame";
import { stageEditsPrompt } from "./stage-edits";
import { DEFAULT_FILE_VIEW, useBrowserStore } from "./store";
import { VideoFile } from "./video-file";
@@ -96,6 +97,10 @@ function TextFile({
({ errors }: { errors: number }) => tabId && useBrowserStore.getState().setFileView(tabId, { errorCount: errors }),
[tabId],
);
+ const onFrameReady = useCallback(
+ (frame: HTMLIFrameElement) => tabId ? registerArtifactFrame(tabId, frame) : undefined,
+ [tabId],
+ );
const language = useMemo(() => {
if (!text || text.length > MAX_HIGHLIGHT_CHARS) return null;
if (kind === "html") return "html";
@@ -126,6 +131,7 @@ function TextFile({
{previewed ? (
<div className={cn("size-full overflow-auto", source && "hidden")} style={{ zoom: scale }}>
<ReactPreview
+ onFrameReady={onFrameReady}
source={text}
lang={/\.jsx$/i.test(name) ? "jsx" : "tsx"}
title={name}
@@ -150,6 +156,7 @@ function TextFile({
<div className={cn("size-full overflow-auto", source && "hidden")} style={{ zoom: scale }}>
<ArtifactHtmlFrame
code={text}
+ onFrameReady={onFrameReady}
title={name}
fill={true}
reloadNonce={reloadNonce}
diff --git a/studio/frontend/src/features/browser/page-frame.tsx b/studio/frontend/src/features/browser/page-frame.tsx
index 3dc6b78dd26..f908d83a8c0 100644
--- a/studio/frontend/src/features/browser/page-frame.tsx
+++ b/studio/frontend/src/features/browser/page-frame.tsx
@@ -1,7 +1,7 @@
// 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 { useEffect, useRef, useState } from "react";
+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { browserFrameUrl, type PageResponse, requestForPage } from "./api";
import { type AnnotateEvent, type FrameMessage, parseFrameMessage, userActionGate } from "./frame-message";
import { pageRequests } from "./page-requests";
@@ -20,6 +20,15 @@ export type { FrameMessage };
let loadCounter = 0;
const frames = new Map<string, HTMLIFrameElement>();
+const frameListeners = new Set<() => void>();
+const subscribeFrames = (listener: () => void) => {
+ frameListeners.add(listener);
+ return () => { frameListeners.delete(listener); };
+};
+
+export function useFrameAvailable(tabId: string | null): boolean {
+ return useSyncExternalStore(subscribeFrames, () => !!tabId && frames.has(tabId), () => false);
+}
export type FrameCommand =
| { command: "find"; query: string }
@@ -80,6 +89,31 @@ export function onFrameAnnotate(tabId: string, listener: (event: AnnotateEvent)
};
}
+/** Register an artifact's opaque-origin frame for annotation commands only. */
+export function registerArtifactFrame(tabId: string, frame: HTMLIFrameElement): () => void {
+ frames.set(tabId, frame);
+ for (const notify of frameListeners) notify();
+ const listener = (event: MessageEvent) => {
+ if (event.source !== frame.contentWindow || event.origin !== "null") return;
+ const message = parseFrameMessage(event.data);
+ if (message?.type === "annotate") annotateListeners.get(tabId)?.(message.event);
+ };
+ window.addEventListener("message", listener);
+ return () => {
+ window.removeEventListener("message", listener);
+ if (frames.get(tabId) === frame) {
+ frames.delete(tabId);
+ for (const notify of frameListeners) notify();
+ }
+ };
+}
+
+/** CSS zoom on a file preview scales the frame as well as its annotation coordinates. */
+export function frameScale(tabId: string): number {
+ const frame = frames.get(tabId);
+ return frame?.offsetWidth ? frame.getBoundingClientRect().width / frame.offsetWidth : 1;
+}
+
const snapshotRequests = new Map<string, (html: string | null) => void>();
/** The page's markup as it is now (see `snapshot` in routes/browser.py); null if it can't say. */
@@ -261,8 +295,12 @@ export function PageFrame({
const frame = frameRef.current;
if (!frame) return;
frames.set(tabId, frame);
+ for (const notify of frameListeners) notify();
return () => {
- if (frames.get(tabId) === frame) frames.delete(tabId);
+ if (frames.get(tabId) === frame) {
+ frames.delete(tabId);
+ for (const notify of frameListeners) notify();
+ }
};
}, [tabId]);
diff --git a/studio/frontend/src/features/chat/artifacts/html-frame.tsx b/studio/frontend/src/features/chat/artifacts/html-frame.tsx
index 36177b8368a..7ce004c8fda 100644
--- a/studio/frontend/src/features/chat/artifacts/html-frame.tsx
+++ b/studio/frontend/src/features/chat/artifacts/html-frame.tsx
@@ -147,6 +147,7 @@ export function ArtifactHtmlFrame({
onConsoleOpenChange,
onOutputCountChange,
onFixWithModel,
+ onFrameReady,
kind = "html",
}: {
code: string;
@@ -162,6 +163,7 @@ export function ArtifactHtmlFrame({
onFixWithModel?: (prompt: string) => void;
// A React preview runs compiled code, so its runtime line numbers aren't shown.
kind?: "html" | "react";
+ onFrameReady?: (frame: HTMLIFrameElement) => (() => void) | undefined;
}) {
const t = useT();
const locale = useLocale();
@@ -277,6 +279,9 @@ export function ArtifactHtmlFrame({
}
return apiUrl(`/api/inference/artifact-preview-frame?${query.toString()}`);
}, [networkAllowed, loadVersion]);
+ useEffect(() => {
+ if (iframeRef.current) return onFrameReady?.(iframeRef.current);
+ }, [onFrameReady, src]);
// Feed only parent-initiated loads, so a self-navigated frame can't self-upgrade.
const pendingPostRef = useRef(false);
useEffect(() => {
diff --git a/studio/frontend/src/features/chat/artifacts/react-preview/react-preview.tsx b/studio/frontend/src/features/chat/artifacts/react-preview/react-preview.tsx
index 828b87a840f..c35d466f8cd 100644
--- a/studio/frontend/src/features/chat/artifacts/react-preview/react-preview.tsx
+++ b/studio/frontend/src/features/chat/artifacts/react-preview/react-preview.tsx
@@ -59,6 +59,7 @@ export function ReactPreview({
onConsoleOpenChange,
onOutputCountChange,
onFixWithModel,
+ onFrameReady,
}: {
source: string;
lang: "jsx" | "tsx";
@@ -68,6 +69,7 @@ export function ReactPreview({
onConsoleOpenChange?: (open: boolean) => void;
onOutputCountChange?: (counts: { errors: number; total: number }) => void;
onFixWithModel?: (prompt: string) => void;
+ onFrameReady?: (frame: HTMLIFrameElement) => (() => void) | undefined;
}) {
const t = useT();
const key = `${lang}\u0000${source}`;
@@ -124,6 +126,7 @@ export function ReactPreview({
onConsoleOpenChange={onConsoleOpenChange}
onOutputCountChange={onOutputCountChange}
onFixWithModel={onFixWithModel}
+ onFrameReady={onFrameReady}
/>
);
}
diff --git a/studio/frontend/tests/annotation-styles.test.ts b/studio/frontend/tests/annotation-styles.test.ts
new file mode 100644
index 00000000000..11d81345589
--- /dev/null
+++ b/studio/frontend/tests/annotation-styles.test.ts
@@ -0,0 +1,62 @@
+// 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 vm from "node:vm";
+
+const backend = readFileSync(new URL("../../backend/routes/browser.py", import.meta.url), "utf8");
+const annotation = backend.slice(backend.indexOf('_ANNOTATE_JS = r"""'));
+const helper = annotation.slice(annotation.indexOf("const addStyle ="), annotation.indexOf("const build ="));
+
+test("annotation sheets work without inserting inline styles and preserve existing sheets", () => {
+ class Sheet {
+ css = "";
+ replaceSync(css: string) { this.css = css; }
+ }
+ const addStyle = vm.runInNewContext(`${helper}; addStyle`, {
+ CSSStyleSheet: Sheet,
+ document: { createElement: () => { throw new Error("Inline styles blocked by CSP"); } },
+ });
+ const existing = new Sheet();
+ const target = { adoptedStyleSheets: [existing] };
+ const remove = addStyle(target, ".mark { position: fixed; border: 1px dashed blue; }");
+ assert.equal(target.adoptedStyleSheets[0], existing);
+ assert.equal(target.adoptedStyleSheets[1]!.css, ".mark { position: fixed; border: 1px dashed blue; }");
+ const other = new Sheet();
+ target.adoptedStyleSheets.push(other);
+ remove();
+ assert.deepEqual([...target.adoptedStyleSheets], [existing, other]);
+});
+
+test("older webviews retain their inline-style path", () => {
+ const inserted: unknown[] = [];
+ let removed = false;
+ const style = { textContent: "", remove: () => { removed = true; } };
+ const addStyle = vm.runInNewContext(`${helper}; addStyle`, { document: { createElement: () => style } });
+ const remove = addStyle({ head: { appendChild: (value: unknown) => inserted.push(value) } }, ".pin { display: flex; }");
+ assert.equal(style.textContent, ".pin { display: flex; }");
+ assert.deepEqual(inserted, [style]);
+ remove();
+ assert.equal(removed, true);
+});
+
+
+test("annotation controls can be built when Trusted Types rejects HTML sinks", () => {
+ const children: Array<{ className: string }> = [];
+ const root = {
+ set innerHTML(_value: string) { throw new TypeError("TrustedHTML required"); },
+ appendChild: (element: { className: string }) => children.push(element),
+ querySelector: (selector: string) => children.find((element) => `.${element.className}` === selector),
+ };
+ const overlay = { style: {}, attachShadow: () => root };
+ const buildSource = annotation.slice(annotation.indexOf("const build ="), annotation.indexOf("const pinBox ="));
+ const build = vm.runInNewContext(`${buildSource}; build`, {
+ root: null, overlay: null, outline: null, area: null,
+ document: { createElement: (tag: string) => tag === "unsloth-annotate" ? overlay : { className: "" } },
+ color: "#123456", PIN: 28, addStyle: () => {},
+ });
+ build();
+ assert.deepEqual(children.map((element) => element.className), ["hover", "area"]);
+});
diff --git a/studio/frontend/tests/artifact-frame-annotations.test.ts b/studio/frontend/tests/artifact-frame-annotations.test.ts
new file mode 100644
index 00000000000..16d1c762b2c
--- /dev/null
+++ b/studio/frontend/tests/artifact-frame-annotations.test.ts
@@ -0,0 +1,91 @@
+// 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 vm from "node:vm";
+
+const backend = readFileSync(new URL("../../backend/routes/inference.py", import.meta.url), "utf8");
+// Decode the Python string's escaped quotes/backslashes without importing the GPU backend.
+const shell = backend.match(/_ARTIFACT_PREVIEW_FRAME_HTML = """([\s\S]*?)"""/)![1]!
+ .replace(/\\(["\\])/g, "$1");
+const script = shell.match(/<script>([\s\S]*?)<\/script>/)![1]!;
+
+function preview() {
+ const listeners = new Map<string, Array<(event: unknown) => void>>();
+ const reports: Array<Record<string, unknown>> = [];
+ const calls: unknown[] = [];
+ let writes = 0;
+ const parent = { postMessage: (value: Record<string, unknown>) => reports.push(value) };
+ const context = vm.createContext({
+ parent, URLSearchParams, location: { search: "?v=test" }, calls,
+ console: Object.fromEntries(["error", "warn", "info", "log", "debug"].map((level) => [level, () => {}])),
+ addEventListener: (type: string, listener: (event: unknown) => void) => {
+ listeners.set(type, [...(listeners.get(type) ?? []), listener]);
+ },
+ document: {
+ // A document meta CSP may prohibit new scripts after the HTML is written.
+ createElement: () => { throw new Error("Inline scripts blocked by document CSP"); },
+ open: () => listeners.clear(),
+ write: () => writes++, close: () => {}, addEventListener: () => {},
+ },
+ });
+ context.window = context;
+ vm.runInContext(script.replace("/* ANNOTATE_JS */", code), context);
+ const message = (data: unknown, source: unknown = parent) => {
+ for (const listener of [...(listeners.get("message") ?? [])]) listener({ source, data });
+ };
+ message({ type: "unsloth:artifact-html", html: "<h1>Coffee</h1>" });
+ return { context, message, reports, calls, writes: () => writes, installs: () => calls.filter((call) => Array.isArray(call) && call[0] === "install").length };
+}
+
+const code = `calls.push(["install"]); return {
+ start: (color) => { calls.push(["start", color]); post({ type: "annotate", event: "mark", quote: "Coffee" }); },
+ stop: () => calls.push(["stop"]),
+ forget: (id) => calls.push(["forget", id]),
+ number: (numbers) => calls.push(["numbers", numbers])
+};`;
+const command = (command: string, fields = {}) => ({ type: "unsloth:browser-command", command, ...fields });
+
+test("the rendered artifact accepts annotations without rewriting its document", () => {
+ const frame = preview();
+ assert.ok(frame.reports.some((report) => report.event === "ready"));
+ assert.equal(frame.installs(), 0, "the predeclared factory stays idle until requested");
+ frame.message(command("annotateInstall", { code }));
+ frame.message(command("annotate", { on: true, color: "#123456" }));
+ frame.message(command("annotateForget", { id: 2 }));
+ frame.message(command("annotateNumbers", { numbers: [[3, 1]] }));
+ frame.message(command("annotate", { on: false }));
+ assert.equal(frame.writes(), 1, "annotation must preserve the live preview");
+ assert.equal(frame.installs(), 1);
+ assert.deepEqual(JSON.parse(JSON.stringify(frame.calls)), [
+ ["install"], ["start", "#123456"], ["forget", 2], ["numbers", [[3, 1]]], ["stop"],
+ ]);
+ assert.ok(frame.reports.some((report) => report.source === "unsloth-browser" && report.quote === "Coffee"));
+ assert.equal(frame.context.__unslothInstallAnnotation, undefined);
+});
+
+test("a canvas cannot install or toggle annotations by messaging itself", () => {
+ const frame = preview();
+ frame.message(command("annotateInstall", { code }), frame.context);
+ frame.message(command("annotate", { on: true }), frame.context);
+ assert.equal(frame.installs(), 0);
+ assert.deepEqual(frame.calls, []);
+ frame.message(command("annotateInstall", { code }));
+ frame.message(command("annotateInstall", { code }));
+ assert.equal(frame.installs(), 1, "reentering annotation reuses the engine");
+});
+
+test("Request edits preserves the selected file view", () => {
+ const panel = readFileSync(new URL("../src/features/browser/browser-panel.tsx", import.meta.url), "utf8");
+ assert.doesNotMatch(panel, /if \(!annotating && htmlPreview\) setView/);
+ assert.doesNotMatch(panel, /if \(annotating && htmlPreview\).*setAnnotating\(null\)/);
+ assert.match(panel, /htmlAnnotating \? \(\s*<WebAnnotateLayer/);
+});
+
+test("switching a file's view keeps its saved annotations", () => {
+ const panel = readFileSync(new URL("../src/features/browser/browser-panel.tsx", import.meta.url), "utf8");
+ // A view in the key remounts the layer, dropping saved comments on a Markdown Preview/Source switch.
+ assert.match(panel, /<AnnotateLayer\s+key=\{`\$\{activeTab\.id\}:\$\{activeEntry\.fileId\}`\}/);
+});
diff --git a/studio/frontend/tests/react-preview-annotations.test.ts b/studio/frontend/tests/react-preview-annotations.test.ts
new file mode 100644
index 00000000000..210c43bf4ef
--- /dev/null
+++ b/studio/frontend/tests/react-preview-annotations.test.ts
@@ -0,0 +1,91 @@
+// 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 vm from "node:vm";
+import React from "react";
+import ts from "@typescript/typescript6";
+
+const read = (path: string) => readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");
+function component(source: string, context: Record<string, unknown>) {
+ const js = ts.transpileModule(`(${source})`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
+ }).outputText;
+ return vm.runInNewContext(js, { React, useEffect: () => {}, ...context });
+}
+
+test("a rendered React file registers its artifact iframe and returns the cleanup", () => {
+ const source = read("features/browser/file-view.tsx");
+ const cleanup = () => {};
+ const frame = {} as HTMLIFrameElement;
+ const registered: unknown[][] = [];
+ const ReactPreview = () => null;
+ const TextFile = component(source.slice(source.indexOf("function TextFile("), source.indexOf("export function FileView(")), {
+ useState: (initial: unknown) => [initial === null ? "demo" : initial],
+ useBrowserStore: (select: (state: unknown) => unknown) => select({ fileViews: { tab1: { mode: "preview" } } }),
+ textFileKind: () => "react",
+ useCallback: (callback: unknown) => callback,
+ useMemo: (callback: () => unknown) => callback(),
+ MAX_HIGHLIGHT_CHARS: 1000,
+ truncateAttachmentPreviewText: (text: string) => ({ text }),
+ attachmentTextLanguage: () => null,
+ cn: () => "",
+ stageEditsPrompt: () => {},
+ ReactPreview,
+ registerArtifactFrame: (...args: unknown[]) => { registered.push(args); return cleanup; },
+ });
+ const tree = TextFile({ blob: {}, name: "Demo.tsx", tabId: "tab1", scale: 1, reloadNonce: 0 });
+ const preview = tree.props.children[0].props.children;
+ assert.equal(preview.type, ReactPreview);
+ assert.equal(preview.props.onFrameReady(frame), cleanup);
+ assert.deepEqual(registered, [["tab1", frame]]);
+});
+
+test("ReactPreview passes frame registration through to ArtifactHtmlFrame", () => {
+ const source = read("features/chat/artifacts/react-preview/react-preview.tsx");
+ const ArtifactHtmlFrame = () => null;
+ const onFrameReady = () => () => {};
+ const ReactPreview = component(source.slice(source.indexOf("export function ReactPreview")).replace("export function", "function"), {
+ useT: () => () => "",
+ useState: () => [{ key: "tsx\u0000demo", prepared: { status: "ready", html: "<h1>Demo</h1>" } }],
+ ArtifactHtmlFrame,
+ });
+ const frame = ReactPreview({ source: "demo", lang: "tsx", title: "Demo", onFrameReady });
+ assert.equal(frame.type, ArtifactHtmlFrame);
+ assert.equal(frame.props.onFrameReady, onFrameReady);
+});
+
+test("artifact frame availability follows registration and cleanup", () => {
+ const source = read("features/browser/page-frame.tsx");
+ const fragment = source.slice(source.indexOf("const frames ="), source.indexOf("const snapshotRequests =")).replace(/^export /gm, "");
+ const observed: boolean[] = [];
+ const registry = component(`function () { ${fragment} return { registerArtifactFrame, useFrameAvailable }; }`, {
+ window: { addEventListener: () => {}, removeEventListener: () => {} },
+ useSyncExternalStore: (subscribe: (notify: () => void) => void, snapshot: () => boolean) => {
+ subscribe(() => observed.push(snapshot()));
+ observed.push(snapshot());
+ return snapshot();
+ },
+ })();
+ assert.equal(registry.useFrameAvailable("tab1"), false);
+ const cleanup = registry.registerArtifactFrame("tab1", {});
+ cleanup();
+ assert.deepEqual(observed, [false, true, false]);
+});
+
+test("an unavailable React preview uses DOM annotation instead of an absent frame", () => {
+ const source = read("features/browser/browser-panel.tsx");
+ const start = source.indexOf(" const htmlAnnotating =");
+ const declaration = source.slice(start, source.indexOf(";", start) + 1);
+ for (const available of [false, true]) {
+ const htmlAnnotating = vm.runInNewContext(`(() => { ${declaration} return htmlAnnotating; })()`, {
+ frameAvailable: available,
+ activeEntry: { kind: "file", name: "Demo.tsx", contentType: "application/x-unsloth-react-preview" },
+ fileBarKind: () => "html",
+ fileMode: "preview",
+ });
+ assert.equal(htmlAnnotating, available);
+ }
+});