Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(chat): preview HTML the model writes, in its own walled-off page (B29)

purplea9df1376005d
diff --git a/src-tauri/src/html_preview.rs b/src-tauri/src/html_preview.rs
new file mode 100644
index 00000000..4bcdceba
--- /dev/null
+++ b/src-tauri/src/html_preview.rs
@@ -0,0 +1,212 @@
+//! The page behind the chat's HTML preview (B29, 3.0.9).
+//!
+//! Why a scheme of its own and not `srcdoc`: an `about:srcdoc` frame inherits
+//! the policy of the page that holds it, and the app's policy says
+//! `script-src 'self'`. The model's inline script was therefore never run in
+//! the shipped app, only in the browser build without that policy. A document
+//! served from `luprev://` has its own response and so its own policy, the one
+//! [`preview_csp`] writes, and nothing of the app's.
+//!
+//! What keeps the preview away from the app, in layers:
+//!
+//! * The frame is sandboxed without `allow-same-origin` (frontend, tested in
+//! `html-preview.test.ts`), and the response says the same once more with
+//! the CSP `sandbox` directive, so even a top-level load of the URL gets an
+//! opaque origin.
+//! * The policy has no `connect-src`, no `frame-src`, no `form-action`, no
+//! worker and no remote source of any kind. Network only when the user
+//! allowed it for this one preview, and then `https:` alone: never
+//! `http://localhost`, so Ollama, the engine and the app's own ports stay
+//! out of reach either way.
+//! * The page does not exist until the user clicks Preview: the frontend puts
+//! the document here at that moment ([`html_preview_put`]) and gets a fresh
+//! random id back. Opening a chat runs nothing.
+//! * The store keeps the last [`KEEP`] documents and nothing on disk.
+use std::borrow::Cow;
+use std::collections::VecDeque;
+use std::sync::{LazyLock, Mutex};
+
+use tauri::http::{header, Request, Response, StatusCode};
+
+/// The scheme name. On Windows and Android Tauri serves it as
+/// `http://luprev.localhost/`, elsewhere as `luprev://localhost/`; the
+/// frontend builds the URL with `convertFileSrc(id, 'luprev')`.
+pub const SCHEME: &str = "luprev";
+
+/// How many previews stay servable. A reload asks for a new id, so this only
+/// has to cover the frames that are open at the same time.
+const KEEP: usize = 16;
+
+/// The biggest document the preview takes. A model answer is far below.
+pub const MAX_BYTES: usize = 2 * 1024 * 1024;
+
+struct Entry {
+ id: String,
+ doc: String,
+ allow_network: bool,
+}
+
+static STORE: LazyLock<Mutex<VecDeque<Entry>>> = LazyLock::new(|| Mutex::new(VecDeque::new()));
+
+/// The policy of a preview page.
+///
+/// Inline script and style are what a generated page consists of, so they are
+/// in; `eval` too, because small canvas demos and libraries pasted inline use
+/// it, and it reaches nothing the inline script could not. Pictures, fonts
+/// and media only as `data:` and `blob:` unless the user opened the network.
+pub fn preview_csp(allow_network: bool) -> String {
+ let net = if allow_network { " https:" } else { "" };
+ [
+ "default-src 'none'".to_string(),
+ format!("script-src 'unsafe-inline' 'unsafe-eval'{net}"),
+ format!("style-src 'unsafe-inline'{net}"),
+ format!("img-src data: blob:{net}"),
+ format!("font-src data:{net}"),
+ format!("media-src data: blob:{net}"),
+ if allow_network { "connect-src https:".to_string() } else { "connect-src 'none'".to_string() },
+ "frame-src 'none'".to_string(),
+ "worker-src 'none'".to_string(),
+ "object-src 'none'".to_string(),
+ "form-action 'none'".to_string(),
+ "base-uri 'none'".to_string(),
+ "sandbox allow-scripts".to_string(),
+ ]
+ .join("; ")
+}
+
+fn new_id() -> String {
+ use rand::RngCore;
+ let mut b = [0u8; 16];
+ rand::thread_rng().fill_bytes(&mut b);
+ b.iter().map(|x| format!("{x:02x}")).collect()
+}
+
+/// Keep `doc` for one preview and hand back its id.
+pub fn put(doc: String, allow_network: bool) -> Result<String, String> {
+ if doc.len() > MAX_BYTES {
+ return Err("This page is too large to preview.".into());
+ }
+ let id = new_id();
+ let mut store = STORE.lock().map_err(|_| "preview store poisoned".to_string())?;
+ store.push_back(Entry { id: id.clone(), doc, allow_network });
+ while store.len() > KEEP {
+ store.pop_front();
+ }
+ Ok(id)
+}
+
+/// The id from a request path: `/<32 hex>`, nothing else.
+fn id_of(path: &str) -> Option<&str> {
+ let id = path.strip_prefix('/')?;
+ (id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit())).then_some(id)
+}
+
+/// Answer one request on the scheme.
+pub fn respond(path: &str) -> Response<Cow<'static, [u8]>> {
+ let hit = id_of(path).and_then(|id| {
+ let store = STORE.lock().ok()?;
+ store.iter().find(|e| e.id == id).map(|e| (e.doc.clone(), e.allow_network))
+ });
+ let Some((doc, allow_network)) = hit else {
+ return Response::builder()
+ .status(StatusCode::NOT_FOUND)
+ .header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
+ .header(header::CONTENT_SECURITY_POLICY, preview_csp(false))
+ .body(Cow::Borrowed(&b"not found"[..]))
+ .expect("static response");
+ };
+ Response::builder()
+ .status(StatusCode::OK)
+ .header(header::CONTENT_TYPE, "text/html; charset=utf-8")
+ .header(header::CONTENT_SECURITY_POLICY, preview_csp(allow_network))
+ .header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
+ .header(header::REFERRER_POLICY, "no-referrer")
+ .header(header::CACHE_CONTROL, "no-store")
+ .body(Cow::Owned(doc.into_bytes()))
+ .expect("preview response")
+}
+
+/// The scheme handler Tauri calls.
+pub fn handle(request: Request<Vec<u8>>) -> Response<Cow<'static, [u8]>> {
+ respond(request.uri().path())
+}
+
+/// Put a document up for preview. Called on the user's click, never on load.
+#[tauri::command]
+pub fn html_preview_put(doc: String, allow_network: bool) -> Result<String, String> {
+ put(doc, allow_network)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The store is one per process; the eviction test fills it, so the
+ /// tests take turns instead of racing each other's ids out.
+ static TURN: Mutex<()> = Mutex::new(());
+
+ fn csp_of(r: &Response<Cow<'static, [u8]>>) -> String {
+ r.headers().get(header::CONTENT_SECURITY_POLICY).unwrap().to_str().unwrap().to_string()
+ }
+
+ #[test]
+ fn served_page_has_its_own_closed_policy() {
+ let _turn = TURN.lock().unwrap_or_else(|e| e.into_inner());
+ let id = put("<script>1</script>".into(), false).unwrap();
+ let r = respond(&format!("/{id}"));
+ assert_eq!(r.status(), StatusCode::OK);
+ let csp = csp_of(&r);
+ assert!(csp.contains("default-src 'none'"));
+ assert!(csp.contains("connect-src 'none'"));
+ assert!(csp.contains("frame-src 'none'"));
+ assert!(csp.contains("form-action 'none'"));
+ assert!(csp.contains("sandbox allow-scripts"));
+ assert!(!csp.contains("allow-same-origin"));
+ assert!(!csp.contains("http:"), "no plain http source, so no localhost: {csp}");
+ assert!(!csp.contains("https:"), "no network without the user's yes: {csp}");
+ assert!(!csp.contains("'self'"));
+ assert_eq!(&r.body()[..], b"<script>1</script>");
+ }
+
+ #[test]
+ fn network_only_https_and_only_when_allowed() {
+ let _turn = TURN.lock().unwrap_or_else(|e| e.into_inner());
+ let id = put("x".into(), true).unwrap();
+ let csp = csp_of(&respond(&format!("/{id}")));
+ assert!(csp.contains("connect-src https:"));
+ assert!(!csp.contains("http:"));
+ assert!(!csp.contains("localhost"));
+ assert!(!csp.contains("ws:"));
+ assert!(csp.contains("sandbox allow-scripts"));
+ }
+
+ #[test]
+ fn unknown_or_malformed_ids_are_not_found() {
+ let _turn = TURN.lock().unwrap_or_else(|e| e.into_inner());
+ assert_eq!(respond("/").status(), StatusCode::NOT_FOUND);
+ assert_eq!(respond("/../etc/passwd").status(), StatusCode::NOT_FOUND);
+ assert_eq!(respond(&format!("/{}", "a".repeat(32))).status(), StatusCode::NOT_FOUND);
+ let id = put("x".into(), false).unwrap();
+ assert_eq!(respond(&format!("/{id}/x")).status(), StatusCode::NOT_FOUND);
+ }
+
+ #[test]
+ fn ids_are_fresh_and_old_pages_drop_out() {
+ let _turn = TURN.lock().unwrap_or_else(|e| e.into_inner());
+ let first = put("first".into(), false).unwrap();
+ let mut ids = vec![first.clone()];
+ for i in 0..KEEP {
+ ids.push(put(format!("p{i}"), false).unwrap());
+ }
+ let unique: std::collections::HashSet<_> = ids.iter().collect();
+ assert_eq!(unique.len(), ids.len());
+ assert_eq!(respond(&format!("/{first}")).status(), StatusCode::NOT_FOUND);
+ assert_eq!(respond(&format!("/{}", ids.last().unwrap())).status(), StatusCode::OK);
+ }
+
+ #[test]
+ fn oversized_documents_are_refused() {
+ let _turn = TURN.lock().unwrap_or_else(|e| e.into_inner());
+ assert!(put("a".repeat(MAX_BYTES + 1), false).is_err());
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index ea2b59c1..67859cad 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -18,6 +18,7 @@ mod android_entry;
#[cfg(target_os = "linux")]
mod linux_media;
mod app_identity;
+mod html_preview;
mod cancel_registry;
mod commands;
mod crash_report;
@@ -649,6 +650,9 @@ pub fn run() {
use commands::mobile_guard::GuardExt as _;
builder
.manage(app_state)
+ // The chat's HTML preview: its own scheme so its page carries its own
+ // closed policy instead of inheriting the app's (html_preview.rs).
+ .register_uri_scheme_protocol(html_preview::SCHEME, |_ctx, request| html_preview::handle(request))
.manage(commands::oauth::OauthPending::default())
// Entries marked `#[cfg(desktop)]` are not registered on a phone:
// ComfyUI's websocket, every installer, the character trainer, the
@@ -661,6 +665,7 @@ pub fn run() {
// commands/mobile_guard.rs), on the desktop it does nothing.
.mobile_guard()
.invoke_handler(tauri::generate_handler![
+ html_preview::html_preview_put,
// Hugging Face "Use this model": the page takes the waiting link
#[cfg(desktop)]
hf_link::hf_link_take,
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index f6e209f7..641f140c 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -25,7 +25,7 @@
}
],
"security": {
- "csp": "default-src 'self' http://ipc.localhost; connect-src 'self' blob: http://ipc.localhost http://tauri.localhost http://localhost:* http://127.0.0.1:* https://lu-labs.ai https://lrrhheztdytyfpizvuup.supabase.co https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com https://openrouter.ai https://api.openai.com https://api.groq.com https://api.together.xyz https://api.deepseek.com https://api.mistral.ai https://api.anthropic.com ws://localhost:* ws://127.0.0.1:*; img-src 'self' data: blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://*.civitai.com https://*.githubusercontent.com; media-src 'self' blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://lu-labs.ai; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'wasm-unsafe-eval'"
+ "csp": "default-src 'self' http://ipc.localhost; connect-src 'self' blob: http://ipc.localhost http://tauri.localhost http://localhost:* http://127.0.0.1:* https://lu-labs.ai https://lrrhheztdytyfpizvuup.supabase.co https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com https://openrouter.ai https://api.openai.com https://api.groq.com https://api.together.xyz https://api.deepseek.com https://api.mistral.ai https://api.anthropic.com ws://localhost:* ws://127.0.0.1:*; img-src 'self' data: blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://*.civitai.com https://*.githubusercontent.com; media-src 'self' blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://lu-labs.ai; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'wasm-unsafe-eval'; frame-src 'self' luprev: http://luprev.localhost"
}
},
"plugins": {
diff --git a/src/components/chat/CodeBlock.tsx b/src/components/chat/CodeBlock.tsx
index 37f0a79e..774a466c 100644
--- a/src/components/chat/CodeBlock.tsx
+++ b/src/components/chat/CodeBlock.tsx
@@ -1,4 +1,4 @@
-import { useState } from 'react'
+import { lazy, Suspense, useState } from 'react'
// PrismLight, NOT the `Prism` barrel. The barrel pulls refractor's ~300
// grammars into the boot chunk (~570 kB of a 2.61 MB App chunk) for a
// highlighter that realistically sees a dozen languages. PrismLight ships the
@@ -6,7 +6,11 @@ import { useState } from 'react'
import SyntaxHighlighter from 'react-syntax-highlighter/dist/esm/prism-light'
// Deep path on purpose: `styles/prism` is a barrel over 46 themes.
import oneDark from 'react-syntax-highlighter/dist/esm/styles/prism/one-dark'
-import { Copy, Check, ChevronDown } from 'lucide-react'
+import { Copy, Check, ChevronDown, Play } from 'lucide-react'
+
+// Loaded on the first Preview click only: most chats never open one.
+const HtmlPreviewPanel = lazy(() => import('./HtmlPreviewPanel').then((m) => ({ default: m.HtmlPreviewPanel })))
+const HtmlPreviewModal = lazy(() => import('./HtmlPreviewModal').then((m) => ({ default: m.HtmlPreviewModal })))
// ── Grammars ───────────────────────────────────────────────────────────────
//
@@ -171,6 +175,10 @@ export function CodeBlock({ code, language }: Props) {
const lineCount = code.split('\n').length
const isLong = lineCount > COLLAPSE_THRESHOLD
const [expanded, setExpanded] = useState(!isLong)
+ // B29: the preview exists only after the user asks for it. It is component
+ // state, never stored, so reopening a chat shows code and runs nothing.
+ const canPreview = isHtmlSnippet(code, language)
+ const [preview, setPreview] = useState<'off' | 'inline' | 'large'>('off')
const handleCopy = () => {
navigator.clipboard.writeText(code)
@@ -184,41 +192,76 @@ export function CodeBlock({ code, language }: Props) {
<div className="relative group rounded-lg overflow-hidden my-1.5 border border-gray-200 dark:border-white/5">
<div className="flex items-center justify-between px-3 py-1 bg-gray-50 dark:bg-white/5 border-b border-gray-200 dark:border-white/5">
<span className="t-micro text-gray-400 font-mono">{language || 'code'}</span>
- <button
- onClick={handleCopy}
- className="flex items-center gap-1 t-micro text-gray-400 hover:text-gray-700 dark:hover:text-white transition-colors"
- aria-label="Copy code"
- >
- {copied ? <Check size={11} /> : <Copy size={11} />}
- {copied ? 'Copied' : 'Copy'}
- </button>
+ <div className="flex items-center gap-3">
+ {canPreview && (
+ <button
+ onClick={() => setPreview(preview === 'off' ? 'inline' : 'off')}
+ className="flex items-center gap-1 t-micro text-gray-400 hover:text-gray-700 dark:hover:text-white transition-colors"
+ aria-pressed={preview !== 'off'}
+ data-testid="code-preview-button"
+ >
+ <Play size={11} />
+ {preview === 'off' ? 'Preview' : 'Code'}
+ </button>
+ )}
+ <button
+ onClick={handleCopy}
+ className="flex items-center gap-1 t-micro text-gray-400 hover:text-gray-700 dark:hover:text-white transition-colors"
+ aria-label="Copy code"
+ >
+ {copied ? <Check size={11} /> : <Copy size={11} />}
+ {copied ? 'Copied' : 'Copy'}
+ </button>
+ </div>
</div>
- <SyntaxHighlighter
- // The RAW tag stays in the header label above; only the highlighter
- // gets the normalised one, so an unknown fence still shows what the
- // model called it while rendering as plain text.
- language={highlightLanguageFor(language)}
- style={oneDark}
- customStyle={{
- margin: 0,
- padding: '0.75rem',
- background: 'rgba(0, 0, 0, 0.3)',
- fontSize: '0.75rem',
- }}
- // The theme gives the inner <code> its own background. It is an
- // inline element, so that colour showed as a band behind every line.
- codeTagProps={{ style: { background: 'transparent' } }}
- >
- {displayCode}
- </SyntaxHighlighter>
- {isLong && (
- <button
- onClick={() => setExpanded(!expanded)}
- className="w-full flex items-center justify-center gap-1 py-1 bg-gray-50 dark:bg-white/5 text-[0.55rem] text-gray-400 hover:text-gray-700 dark:hover:text-white border-t border-gray-200 dark:border-white/5 transition-colors"
- >
- <ChevronDown size={9} className={`transition-transform ${expanded ? 'rotate-180' : ''}`} />
- {expanded ? 'Collapse' : `Show all ${lineCount} lines`}
- </button>
+ {preview !== 'off' && (
+ <Suspense fallback={null}>
+ {preview === 'inline' && (
+ <div className="h-[360px]">
+ <HtmlPreviewPanel
+ code={code}
+ language={language}
+ variant="inline"
+ onClose={() => setPreview('off')}
+ onExpand={() => setPreview('large')}
+ />
+ </div>
+ )}
+ {preview === 'large' && (
+ <HtmlPreviewModal code={code} language={language} onClose={() => setPreview('inline')} />
+ )}
+ </Suspense>
+ )}
+ {preview === 'off' && (
+ <>
+ <SyntaxHighlighter
+ // The RAW tag stays in the header label above; only the highlighter
+ // gets the normalised one, so an unknown fence still shows what the
+ // model called it while rendering as plain text.
+ language={highlightLanguageFor(language)}
+ style={oneDark}
+ customStyle={{
+ margin: 0,
+ padding: '0.75rem',
+ background: 'rgba(0, 0, 0, 0.3)',
+ fontSize: '0.75rem',
+ }}
+ // The theme gives the inner <code> its own background. It is an
+ // inline element, so that colour showed as a band behind every line.
+ codeTagProps={{ style: { background: 'transparent' } }}
+ >
+ {displayCode}
+ </SyntaxHighlighter>
+ {isLong && (
+ <button
+ onClick={() => setExpanded(!expanded)}
+ className="w-full flex items-center justify-center gap-1 py-1 bg-gray-50 dark:bg-white/5 text-[0.55rem] text-gray-400 hover:text-gray-700 dark:hover:text-white border-t border-gray-200 dark:border-white/5 transition-colors"
+ >
+ <ChevronDown size={9} className={`transition-transform ${expanded ? 'rotate-180' : ''}`} />
+ {expanded ? 'Collapse' : `Show all ${lineCount} lines`}
+ </button>
+ )}
+ </>
)}
</div>
)
diff --git a/src/components/chat/HtmlPreviewFrame.tsx b/src/components/chat/HtmlPreviewFrame.tsx
index 55dbee9b..54d90be3 100644
--- a/src/components/chat/HtmlPreviewFrame.tsx
+++ b/src/components/chat/HtmlPreviewFrame.tsx
@@ -14,7 +14,11 @@ import { VIEWPORTS, type Viewport } from '../../lib/html-preview'
import { sandboxAttr } from '../../lib/file-preview'
interface FrameProps {
- doc: string
+ /** The page as text, loaded as srcdoc. Ignored when `src` is given. */
+ doc?: string
+ /** The page on the `luprev` scheme (chat snippets in the app, B29). It
+ * carries its own policy instead of inheriting the app's. */
+ src?: string
viewport: Viewport
allowScripts: boolean
/** Bumping this remounts the iframe, which is how "reload" works. */
@@ -25,6 +29,7 @@ interface FrameProps {
export function HtmlPreviewFrame({
doc,
+ src,
viewport,
allowScripts,
reloadKey = 0,
@@ -35,7 +40,7 @@ export function HtmlPreviewFrame({
return (
<iframe
key={reloadKey}
- srcDoc={doc}
+ {...(src ? { src } : { srcDoc: doc ?? '' })}
sandbox={sandboxAttr(allowScripts)}
referrerPolicy="no-referrer"
title={title}
diff --git a/src/components/chat/HtmlPreviewModal.tsx b/src/components/chat/HtmlPreviewModal.tsx
index de88df56..5142e750 100644
--- a/src/components/chat/HtmlPreviewModal.tsx
+++ b/src/components/chat/HtmlPreviewModal.tsx
@@ -1,9 +1,6 @@
-import { useEffect, useMemo, useState } from 'react'
+import { useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
-import { X, ExternalLink, RotateCw } from 'lucide-react'
-import { openExternal } from '../../api/backend'
-import { buildDocument, type Viewport } from '../../lib/html-preview'
-import { HtmlPreviewFrame, ViewportSwitcher } from './HtmlPreviewFrame'
+import { HtmlPreviewPanel } from './HtmlPreviewPanel'
import { MOTION_S } from '../ui/motion'
interface Props {
@@ -13,19 +10,14 @@ interface Props {
}
/**
- * Preview for a snippet the MODEL produced. It keeps `allow-scripts` on (the
- * user asked for that code to exist, and a generated page without its script
- * is not a preview); the Explorer panel's file preview deliberately does not,
- * see file-preview.ts. Neither ever gets `allow-same-origin`, so the markup
- * lives in an opaque origin and cannot reach the app.
+ * The large view of a snippet the MODEL produced (B29). The page and its
+ * rules are the inline panel's (HtmlPreviewPanel): scripts run, never with
+ * `allow-same-origin`, on the `luprev` scheme with its own closed policy.
*
- * The document shell lives in lib/html-preview.ts, shared with the panel.
+ * The old "open in browser" button is gone: it handed a data: URL to
+ * openExternal, which refuses data: URLs, so it never did anything.
*/
export function HtmlPreviewModal({ code, language, onClose }: Props) {
- const [viewport, setViewport] = useState<Viewport>('desktop')
- const [reloadKey, setReloadKey] = useState(0)
- const doc = useMemo(() => buildDocument(code, language), [code, language])
-
// Esc closes, matching every other overlay in the app.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
@@ -35,13 +27,6 @@ export function HtmlPreviewModal({ code, language, onClose }: Props) {
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
- const openInBrowser = () => {
- // Hand the data URL to the host browser. data: URLs work in modern
- // browsers; users can then save / share / inspect with full devtools.
- const dataUrl = `data:text/html;charset=utf-8;base64,${btoa(unescape(encodeURIComponent(doc)))}`
- openExternal(dataUrl)
- }
-
return (
<AnimatePresence>
<motion.div
@@ -58,52 +43,10 @@ export function HtmlPreviewModal({ code, language, onClose }: Props) {
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.96, opacity: 0 }}
transition={{ duration: MOTION_S.base }}
+ role="dialog"
+ aria-label={`HTML preview (${language || 'html'})`}
>
- {/* Header */}
- <div className="flex items-center justify-between gap-3 px-4 py-2.5 border-b border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.02]">
- <div className="flex items-center gap-2">
- <span className="text-xs font-semibold tracking-wider uppercase text-gray-500 dark:text-gray-400">
- HTML Preview
- </span>
- <span className="t-micro text-gray-400 dark:text-gray-500 font-mono">
- {language || 'html'}
- </span>
- </div>
-
- <ViewportSwitcher viewport={viewport} onChange={setViewport} />
-
- <div className="flex items-center gap-1">
- <button
- onClick={() => setReloadKey((k) => k + 1)}
- className="p-1.5 rounded-md text-gray-500 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-white/[0.06] hover:text-gray-700 dark:hover:text-white transition-colors"
- aria-label="Reload preview"
- title="Reload preview"
- >
- <RotateCw size={14} />
- </button>
- <button
- onClick={openInBrowser}
- className="p-1.5 rounded-md text-gray-500 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-white/[0.06] hover:text-gray-700 dark:hover:text-white transition-colors"
- aria-label="Open in browser"
- title="Open in browser"
- >
- <ExternalLink size={14} />
- </button>
- <button
- onClick={onClose}
- className="p-1.5 rounded-md text-gray-500 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-white/[0.06] hover:text-gray-700 dark:hover:text-white transition-colors"
- aria-label="Close"
- title="Close (Esc)"
- >
- <X size={14} />
- </button>
- </div>
- </div>
-
- {/* Frame area, checkered background to make the rendered surface obvious */}
- <div className="flex-1 overflow-auto bg-[length:24px_24px] bg-[linear-gradient(45deg,rgba(0,0,0,0.04)_25%,transparent_25%,transparent_75%,rgba(0,0,0,0.04)_75%),linear-gradient(45deg,rgba(0,0,0,0.04)_25%,transparent_25%,transparent_75%,rgba(0,0,0,0.04)_75%)] bg-[position:0_0,12px_12px] dark:bg-[length:24px_24px] dark:bg-[linear-gradient(45deg,rgba(255,255,255,0.03)_25%,transparent_25%,transparent_75%,rgba(255,255,255,0.03)_75%),linear-gradient(45deg,rgba(255,255,255,0.03)_25%,transparent_25%,transparent_75%,rgba(255,255,255,0.03)_75%)] flex items-center justify-center p-4">
- <HtmlPreviewFrame doc={doc} viewport={viewport} allowScripts reloadKey={reloadKey} />
- </div>
+ <HtmlPreviewPanel code={code} language={language} variant="modal" onClose={onClose} />
</motion.div>
</motion.div>
</AnimatePresence>
diff --git a/src/components/chat/HtmlPreviewPanel.tsx b/src/components/chat/HtmlPreviewPanel.tsx
new file mode 100644
index 00000000..acb0c0a5
--- /dev/null
+++ b/src/components/chat/HtmlPreviewPanel.tsx
@@ -0,0 +1,95 @@
+import { useState } from 'react'
+import { RotateCw, Maximize2, X, Globe } from 'lucide-react'
+import type { Viewport } from '../../lib/html-preview'
+import { HtmlPreviewFrame, ViewportSwitcher } from './HtmlPreviewFrame'
+import { usePreviewSource } from './usePreviewSource'
+
+interface Props {
+ code: string
+ language?: string
+ /** Inline under the code block, or filling the modal. */
+ variant: 'inline' | 'modal'
+ onClose: () => void
+ onExpand?: () => void
+}
+
+const ICON_BTN =
+ 'p-1 rounded-md text-gray-500 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-white/[0.06] hover:text-gray-700 dark:hover:text-white transition-colors'
+
+/**
+ * A page the model wrote, shown like an artifact (B29). It only exists after
+ * the user pressed Preview. The page runs its own scripts in a sandbox with an
+ * opaque origin and no network; the globe switch opens https for this one page
+ * after a second, explicit yes, and closing the preview forgets it.
+ */
+export function HtmlPreviewPanel({ code, language, variant, onClose, onExpand }: Props) {
+ const [viewport, setViewport] = useState<Viewport>('desktop')
+ const [reloadKey, setReloadKey] = useState(0)
+ const [allowNetwork, setAllowNetwork] = useState(false)
+ const [askingNetwork, setAskingNetwork] = useState(false)
+ const state = usePreviewSource(code, language, allowNetwork, reloadKey)
+
+ const toggleNetwork = () => {
+ if (allowNetwork) setAllowNetwork(false)
+ else setAskingNetwork(true)
+ }
+
+ return (
+ <div className="flex flex-col min-h-0 h-full" data-testid="html-preview-panel" data-network={allowNetwork ? 'on' : 'off'}>
+ <div className="flex items-center justify-between gap-2 px-2 py-1 border-b border-gray-200 dark:border-white/5 bg-gray-50 dark:bg-white/[0.03]">
+ <ViewportSwitcher viewport={viewport} onChange={setViewport} compact={variant === 'inline'} />
+ <div className="flex items-center gap-0.5">
+ <button
+ onClick={toggleNetwork}
+ className={`${ICON_BTN} flex items-center gap-1 t-micro ${allowNetwork ? 'text-amber-500 dark:text-amber-400' : ''}`}
+ aria-pressed={allowNetwork}
+ title={allowNetwork ? 'This page may load from the internet (https). Click to turn off.' : 'This page cannot reach the internet. Click to allow it.'}
+ data-testid="html-preview-network"
+ >
+ <Globe size={12} />
+ {allowNetwork ? 'Online' : 'Offline'}
+ </button>
+ <button onClick={() => setReloadKey((k) => k + 1)} className={ICON_BTN} aria-label="Reload preview" title="Reload preview">
+ <RotateCw size={12} />
+ </button>
+ {onExpand && (
+ <button onClick={onExpand} className={ICON_BTN} aria-label="Open large" title="Open large">
+ <Maximize2 size={12} />
+ </button>
+ )}
+ <button onClick={onClose} className={ICON_BTN} aria-label="Close preview" title={variant === 'modal' ? 'Close (Esc)' : 'Close preview'}>
+ <X size={12} />
+ </button>
+ </div>
+ </div>
+ {askingNetwork && (
+ <div className="flex flex-wrap items-center gap-2 px-3 py-2 t-label text-gray-600 dark:text-gray-300 bg-amber-50 dark:bg-amber-500/10 border-b border-amber-200 dark:border-amber-500/20" data-testid="html-preview-network-ask">
+ <span className="flex-1 min-w-[12rem]">
+ Let this page load from the internet? It can then fetch scripts and pictures over https and send what it contains to any website. Your computer, LU and local servers stay closed to it.
+ </span>
+ <button className="px-2 py-0.5 rounded-md border border-amber-300 dark:border-amber-500/30 hover:bg-amber-100 dark:hover:bg-amber-500/20" onClick={() => { setAllowNetwork(true); setAskingNetwork(false) }}>
+ Allow for this page
+ </button>
+ <button className="px-2 py-0.5 rounded-md hover:bg-gray-100 dark:hover:bg-white/10" onClick={() => setAskingNetwork(false)}>
+ Keep offline
+ </button>
+ </div>
+ )}
+ <div className="flex-1 min-h-0 overflow-auto flex items-center justify-center bg-gray-100 dark:bg-black/20 p-2">
+ {state.status === 'ready' ? (
+ <HtmlPreviewFrame
+ src={state.source.kind === 'src' ? state.source.src : undefined}
+ doc={state.source.kind === 'doc' ? state.source.doc : undefined}
+ viewport={viewport}
+ allowScripts
+ reloadKey={reloadKey}
+ />
+ ) : state.status === 'error' ? (
+ <p className="t-label text-red-500">The preview could not start: {state.message}</p>
+ ) : (
+ <p className="t-label text-gray-400">Starting preview…</p>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/chat/__tests__/html-preview-b29.test.tsx b/src/components/chat/__tests__/html-preview-b29.test.tsx
new file mode 100644
index 00000000..1c7a5a45
--- /dev/null
+++ b/src/components/chat/__tests__/html-preview-b29.test.tsx
@@ -0,0 +1,128 @@
+// @vitest-environment jsdom
+/**
+ * B29 (3.0.9): a page the model writes can be previewed in the chat, like an
+ * artifact, and the preview is walled off from the app.
+ *
+ * - nothing runs when a chat is shown: no frame until the user clicks Preview;
+ * - the frame is sandboxed with scripts but never with same-origin;
+ * - in the app the page comes from the `luprev` scheme, whose response has
+ * its own closed policy (Rust tests in src-tauri/src/html_preview.rs), not
+ * as srcdoc, which inherits the app policy and ran no script at all;
+ * - the network is off and opens only after a second, explicit yes, for
+ * that one page;
+ * - the app's own policy is not loosened for it: it only allows the frame.
+ *
+ * Run: npx vitest run src/components/chat/__tests__/html-preview-b29.test.tsx
+ */
+import { describe, it, expect, afterEach, vi, beforeEach } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+
+const tauri = vi.hoisted(() => ({ on: false, calls: [] as Array<{ cmd: string; args?: Record<string, unknown> }> }))
+vi.mock('../../../api/backend', async (orig) => ({
+ ...(await orig<typeof import('../../../api/backend')>()),
+ isTauri: () => tauri.on,
+ backendCall: async (cmd: string, args?: Record<string, unknown>) => {
+ tauri.calls.push({ cmd, args })
+ return 'ab'.repeat(16)
+ },
+}))
+vi.mock('@tauri-apps/api/core', () => ({
+ convertFileSrc: (path: string, protocol: string) => `${protocol}://localhost/${path}`,
+}))
+
+import { CodeBlock } from '../CodeBlock'
+import { putPreviewDocument } from '../../../lib/html-preview-source'
+
+const PAGE = '<!doctype html><html><body><h1 id="t">x</h1><script>document.getElementById("t").textContent="ran"</script></body></html>'
+const root = resolve(__dirname, '../../../..')
+
+beforeEach(() => { tauri.on = false; tauri.calls = [] })
+afterEach(cleanup)
+
+describe('B29: preview only on the user\'s click', () => {
+ it('an html block offers Preview and shows no frame until it is clicked', () => {
+ const { container } = render(<CodeBlock code={PAGE} language="html" />)
+ expect(screen.getByTestId('code-preview-button').textContent).toBe('Preview')
+ expect(container.querySelector('iframe')).toBeNull()
+ })
+
+ it('code that is not a page gets no Preview', () => {
+ render(<CodeBlock code={'const x = 1'} language="js" />)
+ expect(screen.queryByTestId('code-preview-button')).toBeNull()
+ })
+
+ it('the click mounts a sandboxed frame: scripts yes, same origin never', async () => {
+ const { container } = render(<CodeBlock code={PAGE} language="html" />)
+ fireEvent.click(screen.getByTestId('code-preview-button'))
+ await waitFor(() => expect(container.querySelector('iframe')).not.toBeNull())
+ const frame = container.querySelector('iframe')!
+ expect(frame.getAttribute('sandbox')).toBe('allow-scripts')
+ expect(frame.getAttribute('referrerpolicy')).toBe('no-referrer')
+ // Back to code takes the frame away again.
+ fireEvent.click(screen.getByTestId('code-preview-button'))
+ expect(container.querySelector('iframe')).toBeNull()
+ })
+})
+
+describe('B29: in the app the page comes from the luprev scheme', () => {
+ it('the frame loads luprev://, not srcdoc, and the page went up with the network off', async () => {
+ tauri.on = true
+ const { container } = render(<CodeBlock code={PAGE} language="html" />)
+ fireEvent.click(screen.getByTestId('code-preview-button'))
+ await waitFor(() => expect(container.querySelector('iframe')).not.toBeNull())
+ const frame = container.querySelector('iframe')!
+ expect(frame.getAttribute('src')).toBe(`luprev://localhost/${'ab'.repeat(16)}`)
+ expect(frame.hasAttribute('srcdoc')).toBe(false)
+ expect(tauri.calls).toEqual([{ cmd: 'html_preview_put', args: { doc: PAGE, allowNetwork: false } }])
+ })
+
+ it('the network needs a second yes and goes up as a new page', async () => {
+ tauri.on = true
+ render(<CodeBlock code={PAGE} language="html" />)
+ fireEvent.click(screen.getByTestId('code-preview-button'))
+ await waitFor(() => expect(tauri.calls).toHaveLength(1))
+ fireEvent.click(screen.getByTestId('html-preview-network'))
+ // One click only asks.
+ expect(screen.getByTestId('html-preview-network-ask')).toBeTruthy()
+ expect(screen.getByTestId('html-preview-panel').dataset.network).toBe('off')
+ fireEvent.click(screen.getByText('Keep offline'))
+ expect(screen.queryByTestId('html-preview-network-ask')).toBeNull()
+ expect(tauri.calls).toHaveLength(1)
+ fireEvent.click(screen.getByTestId('html-preview-network'))
+ fireEvent.click(screen.getByText('Allow for this page'))
+ await waitFor(() => expect(tauri.calls).toHaveLength(2))
+ expect(tauri.calls[1].args).toEqual({ doc: PAGE, allowNetwork: true })
+ expect(screen.getByTestId('html-preview-panel').dataset.network).toBe('on')
+ })
+
+ it('in the browser build the page goes in as srcdoc with the closed policy first', async () => {
+ const src = await putPreviewDocument(PAGE, true)
+ expect(src.kind).toBe('doc')
+ const doc = src.kind === 'doc' ? src.doc : ''
+ expect(doc.indexOf('Content-Security-Policy')).toBeLessThan(doc.indexOf('<script>'))
+ expect(doc).toMatch(/default-src 'none'/)
+ expect(doc).not.toMatch(/connect-src/)
+ })
+})
+
+describe('B29: the app policy is not loosened for the preview', () => {
+ const conf = JSON.parse(readFileSync(resolve(root, 'src-tauri/tauri.conf.json'), 'utf8'))
+ const csp: string = conf.app.security.csp
+ const directive = (name: string) => (csp.split(';').map((d) => d.trim()).find((d) => d.startsWith(name + ' ')) ?? '')
+
+ it('frames may come from luprev, and from nowhere new besides', () => {
+ expect(directive('frame-src').split(/\s+/).slice(1).sort()).toEqual(["'self'", 'http://luprev.localhost', 'luprev:'].sort())
+ })
+
+ it('the app itself still runs no inline script', () => {
+ expect(directive('script-src')).not.toMatch(/unsafe-inline|luprev/)
+ })
+
+ it('the scheme is registered and its command is in the handler list', () => {
+ const lib = readFileSync(resolve(root, 'src-tauri/src/lib.rs'), 'utf8')
+ expect(lib).toMatch(/register_uri_scheme_protocol\(html_preview::SCHEME/)
+ expect(lib).toMatch(/html_preview::html_preview_put,/)
+ })
+})
diff --git a/src/components/chat/usePreviewSource.ts b/src/components/chat/usePreviewSource.ts
new file mode 100644
index 00000000..ebf299c3
--- /dev/null
+++ b/src/components/chat/usePreviewSource.ts
@@ -0,0 +1,31 @@
+import { useEffect, useState } from 'react'
+import { buildDocument } from '../../lib/html-preview'
+import { putPreviewDocument, type PreviewSource } from '../../lib/html-preview-source'
+
+export type PreviewState =
+ | { status: 'loading' }
+ | { status: 'ready'; source: PreviewSource }
+ | { status: 'error'; message: string }
+
+/**
+ * The page for a model snippet, put up when the preview mounts. A component
+ * that uses this only mounts on the user's click, so loading a chat runs
+ * nothing. Every reload and every change of the network switch asks for a new
+ * page, so a page never keeps a permission it was not shown with.
+ */
+export function usePreviewSource(code: string, language: string | undefined, allowNetwork: boolean, reloadKey: number): PreviewState {
+ const [state, setState] = useState<{ key: string; value: PreviewState } | null>(null)
+ const key = `${reloadKey}:${allowNetwork ? 1 : 0}`
+ useEffect(() => {
+ let live = true
+ putPreviewDocument(buildDocument(code, language), allowNetwork).then(
+ (source) => { if (live) setState({ key, value: { status: 'ready', source } }) },
+ (err) => { if (live) setState({ key, value: { status: 'error', message: String(err instanceof Error ? err.message : err) } }) },
+ )
+ return () => { live = false }
+ // The code is read at the moment of the click and of every reload, not
+ // followed while a reply is still streaming in.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [key])
+ return state && state.key === key ? state.value : { status: 'loading' }
+}
diff --git a/src/lib/__tests__/explorer-preview.test.ts b/src/lib/__tests__/explorer-preview.test.ts
index 21473c7c..5aec53c3 100644
--- a/src/lib/__tests__/explorer-preview.test.ts
+++ b/src/lib/__tests__/explorer-preview.test.ts
@@ -129,7 +129,10 @@ describe('scripts are off in the Explorer preview', () => {
})
it('counter-test: the model-snippet modal keeps running scripts', () => {
- const src = code('../../components/chat/HtmlPreviewModal.tsx')
+ // Since B29 (3.0.9) the modal shows the chat's preview panel, which
+ // owns the frame.
+ expect(code('../../components/chat/HtmlPreviewModal.tsx')).toMatch(/<HtmlPreviewPanel/)
+ const src = code('../../components/chat/HtmlPreviewPanel.tsx')
expect(src).toMatch(/<HtmlPreviewFrame[^>]*allowScripts/)
})
diff --git a/src/lib/html-preview-source.ts b/src/lib/html-preview-source.ts
new file mode 100644
index 00000000..95369de7
--- /dev/null
+++ b/src/lib/html-preview-source.ts
@@ -0,0 +1,37 @@
+/**
+ * Where a chat HTML preview gets its page from (B29, 3.0.9).
+ *
+ * In the app the page is put up on the `luprev` scheme (src-tauri/src/
+ * html_preview.rs) and the frame loads it by URL. That response carries its
+ * own closed policy; a srcdoc frame would inherit the app's, which allows no
+ * inline script, so a generated page never ran in the installed app.
+ *
+ * In the browser build there is no scheme. The page goes in as srcdoc with the
+ * closed policy as its first tag (the same one the phone preview uses); the
+ * network switch cannot open anything there, which errs on the safe side.
+ *
+ * Nothing here runs on its own: the caller asks on the user's click.
+ */
+import { isTauri, backendCall } from '../api/backend'
+import { withPolicyOnly } from '../mobile/screens/agent/parts/preview-doc'
+
+/** The scheme the Rust side registers. */
+export const PREVIEW_SCHEME = 'luprev'
+
+export type PreviewSource =
+ | { kind: 'src'; src: string }
+ | { kind: 'doc'; doc: string }
+
+/** The URL of a stored page: `luprev://localhost/<id>` on macOS and Linux,
+ * `http://luprev.localhost/<id>` on Windows and Android (Tauri's own rule). */
+export async function previewUrl(id: string): Promise<string> {
+ const { convertFileSrc } = await import('@tauri-apps/api/core')
+ return convertFileSrc(id, PREVIEW_SCHEME)
+}
+
+/** Put the document up for one preview and say how the frame loads it. */
+export async function putPreviewDocument(doc: string, allowNetwork: boolean): Promise<PreviewSource> {
+ if (!isTauri()) return { kind: 'doc', doc: withPolicyOnly(doc) }
+ const id = await backendCall<string>('html_preview_put', { doc, allowNetwork })
+ return { kind: 'src', src: await previewUrl(id) }
+}