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.

[Bug] Unsloth Studio: let fenced HTML canvases honor the canvas network-access setting (#8098)

Leo Borcherding2c8d5a622c43
diff --git a/studio/backend/tests/test_artifact_preview_frame_csp.py b/studio/backend/tests/test_artifact_preview_frame_csp.py
new file mode 100644
index 00000000000..9ede57ecba9
--- /dev/null
+++ b/studio/backend/tests/test_artifact_preview_frame_csp.py
@@ -0,0 +1,46 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The preview shell picks its CSP from ``allow_network`` and nothing else, so
+both directions of that switch are worth pinning: the permissive variant must
+require the flag, and its absence must land on the strict one. Every canvas
+reaches this route now, fenced HTML included, not just approved render_html
+output."""
+
+import asyncio
+
+import routes.inference as inf_mod
+
+
+def _csp(*args) -> str:
+ response = asyncio.run(inf_mod.artifact_preview_frame(*args))
+ return response.headers["content-security-policy"]
+
+
+def test_omitting_the_flag_serves_the_strict_csp():
+ # The fail-closed direction: a caller that says nothing gets no network.
+ csp = _csp()
+ assert "default-src 'none';" in csp
+ assert "script-src 'unsafe-inline';" in csp
+ assert "connect-src 'none';" in csp
+ assert "http:" not in csp.split("frame-ancestors")[0]
+
+
+def test_allow_network_serves_the_permissive_csp():
+ csp = _csp(True)
+ assert "script-src-elem 'unsafe-inline' http: https:" in csp
+ assert "connect-src http: https: ws: wss:" in csp
+
+
+def test_the_flag_is_what_changes_the_policy():
+ assert _csp(True) != _csp(False)
+
+
+def test_the_sandbox_holds_in_both_variants():
+ # Network access widens what the canvas may fetch, never how it is isolated.
+ for csp in (_csp(False), _csp(True)):
+ assert "sandbox allow-scripts" in csp
+ assert "object-src 'none';" in csp
+ assert "base-uri 'none';" in csp
+ assert "form-action 'none';" in csp
+ assert "frame-ancestors 'self'" in csp
diff --git a/studio/frontend/src/features/chat/artifacts/artifact-surface.tsx b/studio/frontend/src/features/chat/artifacts/artifact-surface.tsx
index d9f7fca62ea..92719a09c06 100644
--- a/studio/frontend/src/features/chat/artifacts/artifact-surface.tsx
+++ b/studio/frontend/src/features/chat/artifacts/artifact-surface.tsx
@@ -331,8 +331,6 @@ export function ArtifactSurface({
code={artifact.code}
title={artifact.title}
fill={true}
- // Network mode only for tool-rendered canvases, never fences.
- allowNetworkAccess={artifact.source === "tool"}
className="h-full"
/>
) : (
diff --git a/studio/frontend/src/features/chat/artifacts/html-frame.tsx b/studio/frontend/src/features/chat/artifacts/html-frame.tsx
index 36e3ed8a5b3..d0e41768aee 100644
--- a/studio/frontend/src/features/chat/artifacts/html-frame.tsx
+++ b/studio/frontend/src/features/chat/artifacts/html-frame.tsx
@@ -35,16 +35,14 @@ export function ArtifactHtmlFrame({
title = "HTML canvas preview",
className,
fill = false,
- // Tool-rendered canvases only; default off so fences never get network.
- allowNetworkAccess = false,
}: {
code: string;
title?: string;
className?: string;
fill?: boolean;
- allowNetworkAccess?: boolean;
}) {
const iframeRef = useRef<HTMLIFrameElement>(null);
+ // Every canvas honors this, fence or tool. Off by default, and the only gate.
const networkAccessEnabled = useChatRuntimeStore(
(state) => state.allowArtifactNetworkAccess,
);
@@ -53,11 +51,11 @@ export function ArtifactHtmlFrame({
const src = useMemo(() => {
const query = new URLSearchParams({ v: hashArtifactCode(code) });
// Never put the auth token in the URL: in-frame code can read location.href.
- if (allowNetworkAccess && networkAccessEnabled) {
+ if (networkAccessEnabled) {
query.set("allow_network", "1");
}
return apiUrl(`/api/inference/artifact-preview-frame?${query.toString()}`);
- }, [allowNetworkAccess, networkAccessEnabled, code]);
+ }, [networkAccessEnabled, code]);
// Feed only parent-initiated loads, so a self-navigated frame can't self-upgrade.
const pendingPostRef = useRef(false);
useEffect(() => {
diff --git a/studio/frontend/tests/artifact-frame-network-access.test.ts b/studio/frontend/tests/artifact-frame-network-access.test.ts
new file mode 100644
index 00000000000..de9cafa2cfb
--- /dev/null
+++ b/studio/frontend/tests/artifact-frame-network-access.test.ts
@@ -0,0 +1,88 @@
+// 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 { openingTag } from "./helpers/tsx-ast.ts";
+
+// No DOM renderer here and the frame pulls in React plus the runtime store, so
+// assert the wiring in the source the way artifact-source-key.test.ts does.
+const sourceFile = (relative: string): ts.SourceFile => {
+ const path = fileURLToPath(new URL(relative, import.meta.url));
+ return ts.createSourceFile(
+ path,
+ readFileSync(path, "utf8"),
+ ts.ScriptTarget.ESNext,
+ true,
+ ts.ScriptKind.TSX,
+ );
+};
+
+const SURFACE = "../src/features/chat/artifacts/artifact-surface.tsx";
+const FRAME = "../src/features/chat/artifacts/html-frame.tsx";
+
+/** Every `<ArtifactHtmlFrame>` opening tag in the artifact surface. */
+function readFrameOpeningTags(): string[] {
+ const source = sourceFile(SURFACE);
+ const tags: string[] = [];
+ const visit = (node: ts.Node): void => {
+ const opening = openingTag(node);
+ if (opening?.tagName.getText() === "ArtifactHtmlFrame") {
+ tags.push(opening.getText());
+ }
+ node.forEachChild(visit);
+ };
+ source.forEachChild(visit);
+ return tags;
+}
+
+// The bug: a fenced html block is source "fence", so gating on "tool" left every
+// fenced canvas on the strict CSP and a CDN import (three.js) silently died.
+// Every call site is checked, so a source-gated one cannot hide behind an
+// ungated one that happens to be visited later.
+test("no canvas preview is gated on the artifact source", () => {
+ const tags = readFrameOpeningTags();
+ assert.ok(
+ tags.length > 0,
+ "<ArtifactHtmlFrame> not found in the artifact surface",
+ );
+ for (const tag of tags) {
+ assert.doesNotMatch(
+ tag,
+ /\bsource\b/,
+ "the preview frame must not discriminate on artifact.source",
+ );
+ }
+});
+
+/** Every condition guarding an `allow_network` query flag in the frame. */
+function readAllowNetworkGuards(): string[] {
+ const source = sourceFile(FRAME);
+ const conditions: string[] = [];
+ const visit = (node: ts.Node): void => {
+ if (
+ ts.isIfStatement(node) &&
+ node.thenStatement.getText().includes("allow_network")
+ ) {
+ conditions.push(node.expression.getText());
+ }
+ node.forEachChild(visit);
+ };
+ source.forEachChild(visit);
+ return conditions;
+}
+
+// The permissive CSP is opt-in, and that setting is the whole gate. Asserting the
+// condition exactly is the point: a second operand is how the gate gets defeated
+// (an || that short-circuits past it, or a source check smuggled back in), and
+// there is no legitimate reason for one here.
+test("the permissive CSP is gated on the user's network setting alone", () => {
+ const conditions = readAllowNetworkGuards();
+ assert.equal(conditions.length, 1, "expected exactly one allow_network guard");
+ assert.equal(conditions[0], "networkAccessEnabled");
+});
diff --git a/studio/frontend/tests/artifact-source-key.test.ts b/studio/frontend/tests/artifact-source-key.test.ts
index e90037e603c..f8e394102f3 100644
--- a/studio/frontend/tests/artifact-source-key.test.ts
+++ b/studio/frontend/tests/artifact-source-key.test.ts
@@ -14,6 +14,7 @@ import {
createChatArtifact,
hashArtifactCode,
} from "../src/features/chat/artifacts/types.ts";
+import { openingTag } from "./helpers/tsx-ast.ts";
// The shipped helper the component keys on, not a copy of it.
const sourceKey = buildArtifactSourceKey;
@@ -86,13 +87,6 @@ const SURFACE_PATH = fileURLToPath(
),
);
-/** The opening tag of `node`, for both `<x>` and `<x />`. */
-const openingTag = (node: ts.Node): ts.JsxOpeningLikeElement | null => {
- if (ts.isJsxSelfClosingElement(node)) return node;
- if (ts.isJsxElement(node)) return node.openingElement;
- return null;
-};
-
/** The `key` expression on the source view's Streamdown, or null if unkeyed. */
function readStreamdownKey(): string | null {
const source = ts.createSourceFile(
diff --git a/studio/frontend/tests/helpers/tsx-ast.ts b/studio/frontend/tests/helpers/tsx-ast.ts
new file mode 100644
index 00000000000..abfca99e506
--- /dev/null
+++ b/studio/frontend/tests/helpers/tsx-ast.ts
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Kept out of kit.ts on purpose: 24 test files import that, and only the handful
+// asserting JSX wiring should pay for loading the TypeScript compiler.
+
+import ts from "typescript";
+
+/** The opening tag of `node`, for both `<x>` and `<x />`. */
+export const openingTag = (node: ts.Node): ts.JsxOpeningLikeElement | null => {
+ if (ts.isJsxSelfClosingElement(node)) return node;
+ if (ts.isJsxElement(node)) return node.openingElement;
+ return null;
+};