Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cowork): unsandboxed preview served from a scoped preview:// scheme
Akarshan Biswas9bafc055dc20
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex cdd2bd01d..da2530f60 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -7443,6 +7443,7 @@ dependencies = ["glob","ignore","nix 0.30.1",+ "percent-encoding","regex","serde","serde_json",diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.tomlindex 77bafcc46..efce8d4a5 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml@@ -20,6 +20,7 @@ tauri = ["dep:tauri", "dep:tauri-plugin"][dependencies]base64 = "0.22"glob = "0.3"+percent-encoding = "2"ignore = "0.4"regex = "1"similar = "2.6"diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rsindex 2f69679cb..21583b02d 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs@@ -26,6 +26,8 @@ const COMMANDS: &[&str] = &["stop_monitor","list_monitors","stop_session_monitors",+ "preview_register_root",+ "preview_unregister_root",];fn main() {diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.tsindex 72e1f47f7..cf65c9151 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts@@ -81,6 +81,25 @@ export async function threadWorkspaceSweep(}/** The Cowork session sandbox, created if absent. */+/**+ * Let the `preview://` scheme serve files under `root` to the unsandboxed+ * preview frame. `allowNetwork` becomes the served page's CSP; registering+ * again replaces it. Unregister when the frame goes away.+ */+export async function previewRegisterRoot(+ root: string,+ allowNetwork: boolean+): Promise<void> {+ await invoke('plugin:agent-tools|preview_register_root', {+ root,+ allowNetwork,+ })+}++export async function previewUnregisterRoot(root: string): Promise<void> {+ await invoke('plugin:agent-tools|preview_unregister_root', { root })+}+export async function sessionWorkspacePath(dataFolder: string,sessionId: stringdiff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.tomlindex 1848bf042..b918a623f 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml@@ -28,4 +28,6 @@ permissions = ["allow-stop-monitor","allow-list-monitors","allow-stop-session-monitors",+ "allow-preview-register-root",+ "allow-preview-unregister-root",]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.jsonindex 1e612d425..01ad2c7a4 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json@@ -643,10 +643,10 @@"markdownDescription": "Denies the workspace_path command without any pre-configured scope."},{- "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`",+ "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`","type": "string","const": "default",- "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`"+ "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`"}]}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex 4749adc6e..d370f4d9b 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -37,6 +37,7 @@ use serde::Serialize;use crate::memory;use crate::permissions::ToolPermissions;+use crate::preview::{self, PreviewRoots};use crate::skills::{self, SkillMeta};use crate::tools::gate::{self, Decision, PromptKind, SessionGrants};use crate::tools::jail;@@ -837,6 +838,55 @@ async fn execute_tool_inner(})}+/// Let the `preview://` scheme serve files under `root`, with `allow_network`+/// as the page policy. Re-registering the same root replaces the flag.+#[tauri::command]+pub fn preview_register_root(+ roots: tauri::State<'_, PreviewRoots>,+ root: String,+ allow_network: bool,+) -> Result<(), AgentToolsError> {+ roots.register(Path::new(&root), allow_network)?;+ Ok(())+}++#[tauri::command]+pub fn preview_unregister_root(roots: tauri::State<'_, PreviewRoots>, root: String) {+ roots.unregister(Path::new(&root));+}++/// One `preview://` request. Anything not resolvable to a file under a+/// registered root is a 404 with no detail: the requester is model markup.+pub fn preview_response<R: tauri::Runtime>(+ app: &tauri::AppHandle<R>,+ request_path: &str,+) -> tauri::http::Response<Vec<u8>> {+ use tauri::http::{header, Response, StatusCode};+ use tauri::Manager;+ let not_found = || {+ Response::builder()+ .status(StatusCode::NOT_FOUND)+ .body(Vec::new())+ .expect("static response")+ };+ let Some(served) = app.state::<PreviewRoots>().resolve(request_path) else {+ return not_found();+ };+ let Ok(body) = std::fs::read(&served.path) else {+ return not_found();+ };+ Response::builder()+ .status(StatusCode::OK)+ .header(header::CONTENT_TYPE, preview::mime_for(&served.path))+ .header(+ header::CONTENT_SECURITY_POLICY,+ preview::csp(served.allow_network),+ )+ .header(header::CACHE_CONTROL, "no-store")+ .body(body)+ .unwrap_or_else(|_| not_found())+}+/// Build the live-output sink.////// `OutputSink` is `Fn`, not `FnMut`, so the sequence counter and the bytediff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rsindex 64b841200..00fcbd0b2 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs@@ -11,6 +11,7 @@pub mod memory;pub mod permissions;+pub mod preview;pub mod skills;pub mod tools;pub mod workspace;@@ -59,8 +60,22 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {commands::start_monitor,commands::stop_monitor,commands::list_monitors,- commands::stop_session_monitors+ commands::stop_session_monitors,+ commands::preview_register_root,+ commands::preview_unregister_root])+ .setup(|app, _api| {+ use tauri::Manager;+ app.manage(preview::PreviewRoots::default());+ Ok(())+ })+ .register_asynchronous_uri_scheme_protocol("preview", |ctx, request, responder| {+ let app = ctx.app_handle().clone();+ // Off the webview thread: canonicalize and read touch the disk.+ std::thread::spawn(move || {+ responder.respond(commands::preview_response(&app, request.uri().path()));+ });+ }).build()}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/preview.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/preview.rsnew file mode 100644index 000000000..fab45a5c7--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/preview.rs@@ -0,0 +1,263 @@+//! The `preview://` scheme: serves artifact files to the Cowork preview pane+//! from a real origin, so a page keeps `localStorage` and resolves relative+//! assets, neither of which an opaque-origin `srcdoc` frame can do.+//!+//! The origin is shared with nothing else in the app, and what it can serve is+//! bounded by [`PreviewRoots`]: a request resolves only to a file under a root+//! the pane registered, so model markup cannot link its way to the rest of the+//! disk even though the asset protocol's own scope is `**/*`. Each root carries+//! the network flag the pane chose, emitted as a CSP header on every response;+//! the page cannot change it because it never sees the registration.+//!+//! Tauri-free: the scheme wiring lives in `lib.rs`, the commands in `commands.rs`.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::Mutex;++#[derive(Default)]+pub struct PreviewRoots {+ roots: Mutex<HashMap<PathBuf, bool>>,+}++/// A file the scheme may serve, with the network flag of the root it sits in.+pub struct Served {+ pub path: PathBuf,+ pub allow_network: bool,+}++impl PreviewRoots {+ pub fn register(&self, root: &Path, allow_network: bool) -> Result<(), String> {+ let canon = std::fs::canonicalize(root).map_err(|e| format!("ERROR: {e}"))?;+ if !canon.is_dir() {+ return Err(format!("ERROR: not a directory: {}", root.display()));+ }+ self.lock().insert(canon, allow_network);+ Ok(())+ }++ pub fn unregister(&self, root: &Path) {+ let Ok(canon) = std::fs::canonicalize(root) else {+ return;+ };+ self.lock().remove(&canon);+ }++ /// The file a request path names, or `None` when it is not a regular file+ /// under a registered root. Canonicalized first, so `..` segments and+ /// symlinks are judged by where they land, not how they are spelled.+ pub fn resolve(&self, request_path: &str) -> Option<Served> {+ let decoded = percent_encoding::percent_decode_str(request_path)+ .decode_utf8()+ .ok()?;+ let canon = std::fs::canonicalize(fs_path(&decoded)).ok()?;+ if !canon.is_file() {+ return None;+ }+ let roots = self.lock();+ let (_, allow_network) = roots.iter().find(|(root, _)| canon.starts_with(root))?;+ Some(Served {+ path: canon,+ allow_network: *allow_network,+ })+ }++ fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<PathBuf, bool>> {+ self.roots.lock().unwrap_or_else(|p| p.into_inner())+ }+}++/// The URL path is the absolute filesystem path with real slashes (so relative+/// references resolve against the file's directory). On Windows that puts a+/// `/` in front of the drive letter, which is not part of the path.+fn fs_path(decoded: &str) -> PathBuf {+ if cfg!(windows) {+ let bytes = decoded.as_bytes();+ if bytes.len() >= 3+ && bytes[0] == b'/'+ && bytes[1].is_ascii_alphabetic()+ && bytes[2] == b':'+ {+ return PathBuf::from(&decoded[1..]);+ }+ }+ PathBuf::from(decoded)+}++/// The document policy for a served page. `'self'` is what lets the page load+/// its own css/js/images from beside itself; `https:` joins only when the pane's+/// network toggle is on. Mirrors `htmlSandbox.ts` for the srcdoc frame.+pub fn csp(allow_network: bool) -> String {+ let net = if allow_network { " https:" } else { "" };+ [+ "default-src 'none'".to_string(),+ format!("script-src 'self' 'unsafe-inline' blob:{net}"),+ format!("style-src 'self' 'unsafe-inline'{net}"),+ format!("img-src 'self' data: blob:{net}"),+ format!("font-src 'self' data:{net}"),+ format!("media-src 'self' data: blob:{net}"),+ "worker-src 'self' blob:".to_string(),+ format!("connect-src 'self'{net}"),+ ]+ .join("; ")+}++pub fn mime_for(path: &Path) -> &'static str {+ let ext = path+ .extension()+ .and_then(|e| e.to_str())+ .map(|e| e.to_ascii_lowercase())+ .unwrap_or_default();+ match ext.as_str() {+ "html" | "htm" => "text/html; charset=utf-8",+ "css" => "text/css; charset=utf-8",+ "js" | "mjs" => "text/javascript; charset=utf-8",+ "json" | "map" => "application/json",+ "wasm" => "application/wasm",+ "svg" => "image/svg+xml",+ "png" => "image/png",+ "jpg" | "jpeg" => "image/jpeg",+ "gif" => "image/gif",+ "webp" => "image/webp",+ "ico" => "image/x-icon",+ "mp3" => "audio/mpeg",+ "wav" => "audio/wav",+ "ogg" => "audio/ogg",+ "mp4" | "m4v" => "video/mp4",+ "webm" => "video/webm",+ "woff" => "font/woff",+ "woff2" => "font/woff2",+ "ttf" => "font/ttf",+ "txt" | "md" | "csv" => "text/plain; charset=utf-8",+ _ => "application/octet-stream",+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn temp_root(tag: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "jan-preview-{tag}-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ));+ std::fs::create_dir_all(dir.join("assets")).unwrap();+ std::fs::write(dir.join("index.html"), "<canvas></canvas>").unwrap();+ std::fs::write(dir.join("assets/a b.png"), b"png").unwrap();+ dir+ }++ fn url_path(p: &Path) -> String {+ let s = p.to_string_lossy().replace('\\', "/");+ let s = s.replace(' ', "%20");+ if s.starts_with('/') {+ s+ } else {+ format!("/{s}")+ }+ }++ #[test]+ fn serves_files_under_a_registered_root_only() {+ let root = temp_root("in");+ let roots = PreviewRoots::default();+ assert!(roots.resolve(&url_path(&root.join("index.html"))).is_none());+ roots.register(&root, false).unwrap();+ let served = roots.resolve(&url_path(&root.join("index.html"))).unwrap();+ assert!(served.path.ends_with("index.html"));+ assert!(!served.allow_network);+ // Percent-decoded, so a space in a name is found.+ assert!(roots+ .resolve(&url_path(&root.join("assets/a b.png")))+ .is_some());+ // A directory is not a file to serve.+ assert!(roots.resolve(&url_path(&root.join("assets"))).is_none());+ }++ #[test]+ fn a_path_outside_every_root_is_refused_however_spelled() {+ let root = temp_root("out");+ let other = temp_root("other");+ let roots = PreviewRoots::default();+ roots.register(&root, true).unwrap();+ assert!(roots+ .resolve(&url_path(&other.join("index.html")))+ .is_none());+ let traversal = format!(+ "{}/../{}/index.html",+ url_path(&root),+ other.file_name().unwrap().to_string_lossy()+ );+ assert!(roots.resolve(&traversal).is_none());+ }++ #[cfg(unix)]+ #[test]+ fn a_symlink_out_of_the_root_is_refused() {+ let root = temp_root("link");+ let other = temp_root("target");+ std::os::unix::fs::symlink(other.join("index.html"), root.join("leak.html")).unwrap();+ let roots = PreviewRoots::default();+ roots.register(&root, false).unwrap();+ assert!(roots.resolve(&url_path(&root.join("leak.html"))).is_none());+ }++ #[test]+ fn network_flag_follows_the_root_and_unregister_closes_it() {+ let root = temp_root("net");+ let roots = PreviewRoots::default();+ roots.register(&root, true).unwrap();+ assert!(+ roots+ .resolve(&url_path(&root.join("index.html")))+ .unwrap()+ .allow_network+ );+ roots.register(&root, false).unwrap();+ assert!(+ !roots+ .resolve(&url_path(&root.join("index.html")))+ .unwrap()+ .allow_network+ );+ roots.unregister(&root);+ assert!(roots.resolve(&url_path(&root.join("index.html"))).is_none());+ }++ #[test]+ fn registering_a_missing_root_errors() {+ let roots = PreviewRoots::default();+ assert!(roots+ .register(Path::new("/definitely/not/here"), false)+ .is_err());+ }++ #[test]+ fn csp_opens_https_only_with_network() {+ let closed = csp(false);+ assert!(closed.contains("script-src 'self' 'unsafe-inline' blob:;"));+ assert!(!closed.contains("https:"));+ assert!(closed.contains("connect-src 'self'"));+ let open = csp(true);+ assert!(open.contains("connect-src 'self' https:"));+ assert!(open.contains("script-src 'self' 'unsafe-inline' blob: https:"));+ }++ #[test]+ fn mime_by_extension() {+ assert_eq!(+ mime_for(Path::new("a/index.HTML")),+ "text/html; charset=utf-8"+ );+ assert_eq!(+ mime_for(Path::new("game.js")),+ "text/javascript; charset=utf-8"+ );+ assert_eq!(mime_for(Path::new("x.bin")), "application/octet-stream");+ }+}diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex e6140645c..f0136883c 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -28,6 +28,7 @@],"img-src": "'self' asset: http://asset.localhost blob: data: https:","media-src": "'self' asset: http://asset.localhost blob: data: https:",+ "frame-src": "'self' preview: http://preview.localhost","style-src": "'unsafe-inline' 'self' https://fonts.googleapis.com","script-src": "'self' 'unsafe-eval' asset: $APPDATA/**.* http://asset.localhost https://eu-assets.i.posthog.com https://posthog.com"},diff --git a/web-app/src/containers/CoworkPreviewPanel.tsx b/web-app/src/containers/CoworkPreviewPanel.tsxindex 8d11c2dab..298a95d41 100644--- a/web-app/src/containers/CoworkPreviewPanel.tsx+++ b/web-app/src/containers/CoworkPreviewPanel.tsx@@ -1,5 +1,11 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { FolderOpen, Globe, RotateCw, SquareArrowOutUpRight } from 'lucide-react'+import {+ FolderOpen,+ Globe,+ RotateCw,+ ShieldOff,+ SquareArrowOutUpRight,+} from 'lucide-react'import { Button } from '@/components/ui/button'import {Tooltip,@@ -12,6 +18,11 @@ import { getServiceHub, useServiceHub } from '@/hooks/useServiceHub'import { useTranslation } from '@/i18n/react-i18next-compat'import { buildSrcDoc } from '@/lib/htmlSandbox'import { previewShimError } from '@/lib/previewShim'+import {+ previewUrl,+ registerPreviewRoot,+ unregisterPreviewRoot,+} from '@/lib/previewProtocol'import { cn } from '@/lib/utils'import {MAX_PREVIEW_BYTES,@@ -51,6 +62,9 @@ export function CoworkPreviewPanel({ root, path, onClose }: Props) {// mid-interaction in a document or a running page.const [nonce, setNonce] = useState(0)const [allowNetwork, setAllowNetwork] = useState(false)+ // Off by default: the srcdoc sandbox is the safe path. On, the page is served+ // from `preview://` with an origin of its own (see previewProtocol.ts).+ const [unsandboxed, setUnsandboxed] = useState(false)const abs = useMemo(() => (root ? resolveInRoot(root, path) : null),@@ -111,6 +125,19 @@ export function CoworkPreviewPanel({ root, path, onClose }: Props) {const reload = useCallback(() => setNonce((n) => n + 1), [])+ // The scheme serves nothing until the root is registered, and the network+ // flag rides on the registration, so a toggle re-registers. Closing the+ // panel or leaving the mode withdraws the root.+ const live = unsandboxed && kind === 'html' && !!root+ useEffect(() => {+ if (!live || !root) return+ void registerPreviewRoot(root, allowNetwork).catch(() => {+ // A failed registration leaves the frame 404ing; the reload button+ // retries it by re-running this effect.+ })+ return () => void unregisterPreviewRoot(root).catch(() => {})+ }, [live, root, allowNetwork, nonce])+const iconButton = (label: string,Icon: typeof RotateCw,@@ -143,13 +170,23 @@ export function CoworkPreviewPanel({ root, path, onClose }: Props) {onClose={onClose}summary={<div className="flex shrink-0 items-center gap-0.5">- {state.status === 'ready' && state.kind === 'html' &&- iconButton(- t('common:preview.allowNetwork'),- Globe,- () => setAllowNetwork((v) => !v),- allowNetwork- )}+ {state.status === 'ready' && state.kind === 'html' && (+ <>+ {iconButton(+ t('common:preview.allowNetwork'),+ Globe,+ () => setAllowNetwork((v) => !v),+ allowNetwork+ )}+ {root &&+ iconButton(+ t('common:preview.unsandboxed'),+ ShieldOff,+ () => setUnsandboxed((v) => !v),+ unsandboxed+ )}+ </>+ )}{iconButton(t('common:preview.reload'), RotateCw, reload)}{abs && (<>@@ -168,7 +205,11 @@ export function CoworkPreviewPanel({ root, path, onClose }: Props) {</div>}>- <PreviewBody state={state} allowNetwork={allowNetwork} />+ <PreviewBody+ state={state}+ allowNetwork={allowNetwork}+ liveUrl={live && abs ? previewUrl(abs) : null}+ /></CoworkSidePanel>)}@@ -179,9 +220,11 @@ const MAX_REPORTED_ERRORS = 5function HtmlFrame({state,allowNetwork,+ liveUrl,}: {state: Extract<PreviewState, { status: 'ready' }>allowNetwork: boolean+ liveUrl: string | null}) {const { t } = useTranslation()const frame = useRef<HTMLIFrameElement>(null)@@ -214,9 +257,11 @@ function HtmlFrame({const blocked = allowNetwork ? 0 : (state.externalRefs ?? 0)const notice = 'border-b bg-muted/40 px-3 py-2 text-xs text-muted-foreground'+ const frameClass = 'min-h-0 w-full flex-1 border-0 bg-white'return (<div className="flex h-full flex-col">- {(state.unresolvedRefs ?? 0) > 0 && (+ {/* Served by URL, relative refs resolve; served inline, they cannot. */}+ {!liveUrl && (state.unresolvedRefs ?? 0) > 0 && (<p className={notice}>{t('common:preview.unresolvedRefs', { count: state.unresolvedRefs })}</p>@@ -234,13 +279,25 @@ function HtmlFrame({})}</p>)}- <iframe- ref={frame}- title={state.path}- srcDoc={srcDoc}- sandbox={scripts ? 'allow-scripts' : ''}- className="min-h-0 w-full flex-1 border-0 bg-white"- />+ {liveUrl ? (+ // `allow-same-origin` is safe here because the origin is the scheme's,+ // not the app's; it is what makes storage and relative assets work.+ <iframe+ key={liveUrl}+ title={state.path}+ src={liveUrl}+ sandbox="allow-scripts allow-same-origin allow-pointer-lock allow-modals"+ className={frameClass}+ />+ ) : (+ <iframe+ ref={frame}+ title={state.path}+ srcDoc={srcDoc}+ sandbox={scripts ? 'allow-scripts' : ''}+ className={frameClass}+ />+ )}</div>)}@@ -256,9 +313,12 @@ function Notice({ children }: { children: React.ReactNode }) {function PreviewBody({state,allowNetwork,+ liveUrl,}: {state: PreviewStateallowNetwork: boolean+ /** Set when the page is served unsandboxed from `preview://`. */+ liveUrl: string | null}) {const { t } = useTranslation()@@ -280,7 +340,9 @@ function PreviewBody({switch (state.kind) {case 'html':case 'svg':- return <HtmlFrame state={state} allowNetwork={allowNetwork} />+ return (+ <HtmlFrame state={state} allowNetwork={allowNetwork} liveUrl={liveUrl} />+ )case 'markdown':return (<div className="h-full overflow-auto px-4 py-3">diff --git a/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx b/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsxindex 9be6407a7..e073eb9b8 100644--- a/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx+++ b/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx@@ -8,7 +8,15 @@ vi.mock('@/i18n/react-i18next-compat', () => ({}),}))-const convertFileSrc = vi.fn((p: string) => `asset://${p}`)+const convertFileSrc = vi.fn((p: string, protocol?: string) =>+ protocol ? `${protocol}://localhost${p}` : `asset://${p}`+)+const previewRegisterRoot = vi.fn(async () => {})+const previewUnregisterRoot = vi.fn(async () => {})+vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({+ previewRegisterRoot: (...a: unknown[]) => previewRegisterRoot(...a),+ previewUnregisterRoot: (...a: unknown[]) => previewUnregisterRoot(...a),+}))const openPath = vi.fn()const revealItemInDir = vi.fn()const hub = {@@ -48,6 +56,8 @@ const view = (path: string) =>describe('CoworkPreviewPanel', () => {beforeEach(() => {convertFileSrc.mockClear()+ previewRegisterRoot.mockClear()+ previewUnregisterRoot.mockClear()vi.unstubAllGlobals()})@@ -172,6 +182,43 @@ describe('CoworkPreviewPanel', () => {expect(screen.queryByRole('alert')).toBeNull()})+ // The unsandboxed mode trades the srcdoc sandbox for the scheme's own+ // origin. The scheme serves nothing until the pane registers the root, the+ // network flag travels with that registration, and closing withdraws it.+ it('serves the page from preview:// with its own origin when unsandboxed', async () => {+ respondWith('<canvas></canvas><script>run()</script>')+ const { unmount } = view('game.html')+ await screen.findByTitle('game.html')++ fireEvent.click(screen.getByLabelText('common:preview.unsandboxed'))+ const frame = (await waitFor(() => {+ const f = screen.getByTitle('game.html') as HTMLIFrameElement+ expect(f.getAttribute('src')).toBeTruthy()+ return f+ })) as HTMLIFrameElement+ expect(frame.getAttribute('src')).toBe(`preview://localhost${ROOT}/game.html`)+ expect(frame.getAttribute('sandbox')).toContain('allow-same-origin')+ expect(frame.srcdoc).toBe('')+ await waitFor(() =>+ expect(previewRegisterRoot).toHaveBeenLastCalledWith(ROOT, false)+ )++ fireEvent.click(screen.getByLabelText('common:preview.allowNetwork'))+ await waitFor(() =>+ expect(previewRegisterRoot).toHaveBeenLastCalledWith(ROOT, true)+ )++ unmount()+ expect(previewUnregisterRoot).toHaveBeenCalledWith(ROOT)+ })++ it('registers nothing while the sandbox is in use', async () => {+ respondWith('<p>ok</p>')+ view('page.html')+ await screen.findByTitle('page.html')+ expect(previewRegisterRoot).not.toHaveBeenCalled()+ })+it('renders markdown through the shared renderer', async () => {respondWith('# Title')view('notes.md')diff --git a/web-app/src/lib/__tests__/coworkPreview.test.ts b/web-app/src/lib/__tests__/coworkPreview.test.tsindex 93708b363..45b4f0c83 100644--- a/web-app/src/lib/__tests__/coworkPreview.test.ts+++ b/web-app/src/lib/__tests__/coworkPreview.test.ts@@ -6,6 +6,7 @@ import {isAssetKind,unresolvedRefs,externalRefs,+ previewUrlFor,resolveInRoot,} from '@/lib/coworkPreview'@@ -97,6 +98,23 @@ describe('externalRefs', () => {})})+describe('previewUrlFor', () => {+ it('keeps the directory structure so relative assets resolve', () => {+ expect(+ previewUrlFor('/home/me/proj/index.html', 'http://preview.localhost/%2F')+ ).toBe('http://preview.localhost/home/me/proj/index.html')+ expect(previewUrlFor('/a/b.html', 'preview://localhost/%2F')).toBe(+ 'preview://localhost/a/b.html'+ )+ })++ it('encodes segments and normalizes a windows path', () => {+ expect(+ previewUrlFor('C:\\Users\\me\\my game\\index.html', 'http://preview.localhost/x')+ ).toBe('http://preview.localhost/C%3A/Users/me/my%20game/index.html')+ })+})+describe('resolveInRoot', () => {const root = '/Users/me/proj'diff --git a/web-app/src/lib/coworkPreview.ts b/web-app/src/lib/coworkPreview.tsindex f0379761e..28bbdf019 100644--- a/web-app/src/lib/coworkPreview.ts+++ b/web-app/src/lib/coworkPreview.ts@@ -148,5 +148,23 @@ export function resolveInRoot(root: string, path: string): string | null {return inRoot ? abs : null}+/**+ * The `preview://` URL for `abs`. `sampleUrl` is what `convertFileSrc` produced+ * for any path under that scheme, which is how the platform's spelling of the+ * origin (`preview://localhost` on macOS, `http://preview.localhost` elsewhere)+ * is learned without hard-coding it.+ *+ * Deliberately not `convertFileSrc(abs, 'preview')`: that encodes the whole+ * path as one segment, so a relative `assets/a.png` in the page would resolve+ * against the scheme root and miss. Real slashes keep the file's directory as+ * the base URL. A Windows drive path gets a leading slash; `preview.rs` strips+ * it back off.+ */+export function previewUrlFor(abs: string, sampleUrl: string): string {+ const origin = /^[a-z][a-z0-9+.-]*:\/\/[^/]*/i.exec(sampleUrl)?.[0] ?? ''+ const path = abs.replace(/\\/g, '/').replace(/^\/+/, '')+ return `${origin}/${path.split('/').map(encodeURIComponent).join('/')}`+}+/** Guard before reading, so an oversized file fails fast instead of hanging. */export const MAX_PREVIEW_BYTES = 2 * 1024 * 1024diff --git a/web-app/src/lib/previewProtocol.ts b/web-app/src/lib/previewProtocol.tsnew file mode 100644index 000000000..d999ac03a--- /dev/null+++ b/web-app/src/lib/previewProtocol.ts@@ -0,0 +1,23 @@+import {+ previewRegisterRoot,+ previewUnregisterRoot,+} from '@janhq/tauri-plugin-agent-tools-api'+import { getServiceHub } from '@/hooks/useServiceHub'+import { previewUrlFor } from '@/lib/coworkPreview'++/**+ * The unsandboxed preview: the page is loaded by URL from the `preview://`+ * scheme instead of inlined into a `srcDoc`, so it gets an origin of its own+ * (storage works, relative assets resolve) that is still not the app's. The+ * scheme serves only roots registered here; see `preview.rs`.+ */+export const registerPreviewRoot = (root: string, allowNetwork: boolean) =>+ previewRegisterRoot(root, allowNetwork)++export const unregisterPreviewRoot = (root: string) =>+ previewUnregisterRoot(root)++/** The `preview://` URL for an absolute file path, on this platform. */+export function previewUrl(abs: string): string {+ return previewUrlFor(abs, getServiceHub().core().convertFileSrc('/', 'preview'))+}diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 16c860241..e6d0114cb 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -144,6 +144,7 @@"tooLarge": "Too big to preview. Open it to see it in another app.","reload": "Reload","allowNetwork": "Allow network",+ "unsandboxed": "Run unsandboxed: saved data and local files work","unresolvedRefs_one": "1 file this page links to can't load in the preview. Open it to see it in a browser.","unresolvedRefs_other": "{{count}} files this page links to can't load in the preview. Open it to see it in a browser.","externalRefs_one": "1 resource this page loads from the web is blocked. Turn on \"Allow network\" to load it.",