Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(cowork): check the file itself before Open hands it to another app
James Damb1e39908b08f
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 7bb17e250..aca7f746a 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -7820,6 +7820,7 @@ dependencies = ["similar","tauri","tauri-plugin",+ "tauri-plugin-opener","tauri-plugin-websearch","thiserror 2.0.18","tokio",diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.tomlindex 1814d632f..499f50ee9 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml@@ -21,6 +21,8 @@ default = ["tauri"]tauri = ["dep:tauri","dep:tauri-plugin",+ # `open_artifact` hands the checked file to the OS default app.+ "dep:tauri-plugin-opener",# `wry` gives `WebviewWindow::with_webview`, which the screenshot renderer needs# to reach the platform webview. The desktop enables it anyway; the CLI never# turns on `tauri`, so this stays out of the CLI graph.@@ -60,6 +62,7 @@ serde_yaml = "0.9.34"thiserror = "2.0.12"tokio = { version = "1", features = ["full"] }tauri = { version = "2.8.5", default-features = false, optional = true }+tauri-plugin-opener = { version = "2.2.7", optional = true }# `provider` only; `default-features = false` keeps `tauri` out of the graph so# the headless CLI can use the web tools.tauri-plugin-websearch = { path = "../tauri-plugin-websearch", default-features = false }diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rsindex 179e45531..91479eefa 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs@@ -32,6 +32,7 @@ const COMMANDS: &[&str] = &["cancel_thread_bash","preview_register_root","preview_unregister_root",+ "open_artifact",];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 ab43eee26..72f35a57c 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@@ -100,6 +100,19 @@ export async function previewUnregisterRoot(root: string): Promise<void> {await invoke('plugin:agent-tools|preview_unregister_root', { root })}+/**+ * Open an agent-written file in its OS default app. The host checks the file+ * itself and rejects a link, a file outside `roots` (the session's sandbox and+ * attached folder), a type the OS would run, or an executable.+ */+export async function openArtifact(+ dataFolder: string,+ roots: string[],+ path: string+): Promise<void> {+ await invoke('plugin:agent-tools|open_artifact', { dataFolder, roots, path })+}+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 277c04754..7908cb41f 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml@@ -34,4 +34,5 @@ permissions = ["allow-cancel-thread-bash","allow-preview-register-root","allow-preview-unregister-root",+ "allow-open-artifact",]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 09612084a..5858705c4 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@@ -426,6 +426,18 @@"const": "deny-memory-write","markdownDescription": "Denies the memory_write command without any pre-configured scope."},+ {+ "description": "Enables the open_artifact command without any pre-configured scope.",+ "type": "string",+ "const": "allow-open-artifact",+ "markdownDescription": "Enables the open_artifact command without any pre-configured scope."+ },+ {+ "description": "Denies the open_artifact command without any pre-configured scope.",+ "type": "string",+ "const": "deny-open-artifact",+ "markdownDescription": "Denies the open_artifact command without any pre-configured scope."+ },{"description": "Enables the preview_register_root command without any pre-configured scope.","type": "string",@@ -691,10 +703,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-skill-invoke`\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-blackboard-write`\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-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`",+ "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-skill-invoke`\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-blackboard-write`\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-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`\n- `allow-open-artifact`","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-skill-invoke`\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-blackboard-write`\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-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`"+ "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-skill-invoke`\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-blackboard-write`\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-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`\n- `allow-open-artifact`"}]}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/artifact.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/artifact.rsnew file mode 100644index 000000000..ed7fd50d7--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/artifact.rs@@ -0,0 +1,190 @@+//! What Cowork's "Open" may hand to the OS default app.+//!+//! The file was written by the agent, and the sandboxed shell can make any+//! name it likes: `report.pdf` may be a link to a program, or a program+//! itself. Opening runs whatever the OS associates with the file it lands on,+//! so the decision rests on the file, not on the name the frontend saw.+//!+//! Tauri-free: the command that opens the checked file lives in `commands.rs`.++use std::path::{Path, PathBuf};++use crate::workspace;++/// Extensions "Open" may hand to the default app: documents, media and plain+/// text. Mirrors `OPENS_IN_DEFAULT_APP` in the web app's `coworkPreview.ts`,+/// which skips the round trip for anything else.+const OPENS_IN_DEFAULT_APP: &[&str] = &[+ "pdf", "png", "jpg", "jpeg", "gif", "webp", "bmp", "svg", "txt", "md", "markdown", "csv",+ "tsv", "json", "html", "htm", "rtf", "docx", "xlsx", "pptx", "odt", "ods", "odp", "mp3", "wav",+ "ogg", "flac", "m4a", "aac", "opus", "mp4", "webm", "mov", "mkv", "avi", "m4v",+];++/// The roots "Open" may reach, from the ones the frontend names: anything+/// inside the Cowork sessions' sandboxes, or a folder that passes the checks a+/// writable attach does. Any other root is dropped, so a file under it is+/// refused.+pub fn open_roots(data_folder: &Path, requested: &[String]) -> Vec<PathBuf> {+ let sessions = workspace::sessions_dir(data_folder);+ let sessions = sessions.canonicalize().unwrap_or(sessions);+ let home = workspace::user_home();+ requested+ .iter()+ .filter_map(|root| {+ let canon = Path::new(root).canonicalize().ok()?;+ if workspace::is_within(&canon, &sessions) {+ return Some(canon);+ }+ let canon = workspace::validate_read_root(&canon, &sessions, Some(data_folder)).ok()?;+ workspace::validate_write_root(&canon, home.as_deref(), data_folder).ok()?;+ Some(canon)+ })+ .collect()+}++/// The file at `path`, canonicalized, if "Open" may hand it to its default+/// app: not itself a link, a regular file inside one of `roots`, of an+/// allowed type where it really lives, and (on Unix) not executable.+pub fn checked_artifact(path: &Path, roots: &[PathBuf]) -> Result<PathBuf, String> {+ let link = std::fs::symlink_metadata(path)+ .map_err(|e| format!("cannot open {}: {e}", path.display()))?;+ if link.file_type().is_symlink() {+ return Err(format!("{} is a link and is not opened", path.display()));+ }+ let canon = path+ .canonicalize()+ .map_err(|e| format!("cannot open {}: {e}", path.display()))?;+ let meta =+ std::fs::metadata(&canon).map_err(|e| format!("cannot open {}: {e}", path.display()))?;+ if !meta.is_file() {+ return Err(format!("{} is not a file", path.display()));+ }+ if !roots.iter().any(|root| workspace::is_within(&canon, root)) {+ return Err(format!(+ "{} is outside the session's folders",+ path.display()+ ));+ }+ let allowed = canon+ .extension()+ .and_then(|e| e.to_str())+ .is_some_and(|e| OPENS_IN_DEFAULT_APP.contains(&e.to_ascii_lowercase().as_str()));+ if !allowed {+ return Err(format!(+ "{} is not a type that opens in another app",+ path.display()+ ));+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if meta.permissions().mode() & 0o111 != 0 {+ return Err(format!(+ "{} is executable and is not opened",+ path.display()+ ));+ }+ }+ Ok(canon)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn temp_root(tag: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "jan-artifact-{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).unwrap();+ dir.canonicalize().unwrap()+ }++ #[test]+ fn an_allowed_document_inside_a_root_opens() {+ let root = temp_root("doc");+ std::fs::write(root.join("Report.PDF"), b"%PDF-1.7").unwrap();+ let got = checked_artifact(&root.join("Report.PDF"), &[root.clone()]).unwrap();+ assert_eq!(got, root.join("Report.PDF"));+ }++ #[test]+ fn a_file_outside_every_root_is_refused() {+ let root = temp_root("root");+ let other = temp_root("other");+ std::fs::write(other.join("report.pdf"), b"%PDF").unwrap();+ let err = checked_artifact(&other.join("report.pdf"), &[root.clone()]).unwrap_err();+ assert!(err.contains("outside"), "{err}");+ // Climbing out by `..` is judged by where it lands.+ let climbed = root+ .join("..")+ .join(other.file_name().unwrap())+ .join("report.pdf");+ assert!(checked_artifact(&climbed, &[root]).is_err());+ }++ #[test]+ fn a_type_the_os_would_run_is_refused() {+ let root = temp_root("type");+ for name in ["run.command", "setup.exe", "x.sh", "noext"] {+ std::fs::write(root.join(name), b"x").unwrap();+ assert!(+ checked_artifact(&root.join(name), &[root.clone()]).is_err(),+ "{name}"+ );+ }+ }++ #[cfg(unix)]+ #[test]+ fn a_link_is_refused_even_to_an_allowed_type() {+ let root = temp_root("link");+ let prog = root.join("prog");+ std::fs::write(&prog, b"#!/bin/sh\n").unwrap();+ std::os::unix::fs::symlink(&prog, root.join("report.pdf")).unwrap();+ std::fs::write(root.join("real.pdf"), b"%PDF").unwrap();+ std::os::unix::fs::symlink(root.join("real.pdf"), root.join("alias.pdf")).unwrap();+ for name in ["report.pdf", "alias.pdf"] {+ let err = checked_artifact(&root.join(name), &[root.clone()]).unwrap_err();+ assert!(err.contains("link"), "{name}: {err}");+ }+ }++ #[cfg(unix)]+ #[test]+ fn an_executable_file_is_refused_whatever_its_name() {+ use std::os::unix::fs::PermissionsExt;+ let root = temp_root("exec");+ let file = root.join("report.pdf");+ std::fs::write(&file, b"\x7fELF").unwrap();+ std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o755)).unwrap();+ let err = checked_artifact(&file, &[root]).unwrap_err();+ assert!(err.contains("executable"), "{err}");+ }++ #[test]+ fn only_session_sandboxes_and_attachable_folders_are_roots() {+ let data = temp_root("data");+ let session = workspace::sessions_dir(&data).join("s1");+ std::fs::create_dir_all(&session).unwrap();+ let folder = temp_root("folder");+ let roots = open_roots(+ &data,+ &[+ session.to_string_lossy().into_owned(),+ folder.to_string_lossy().into_owned(),+ // The data folder itself holds settings and keys; the+ // filesystem root has no outside; a missing folder is nothing.+ data.to_string_lossy().into_owned(),+ "/".to_string(),+ data.join("missing").to_string_lossy().into_owned(),+ ],+ );+ assert_eq!(roots, vec![session.canonicalize().unwrap(), folder]);+ }+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex 006dd7c52..24dcfc175 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -35,6 +35,7 @@ use std::path::{Path, PathBuf};use serde::Serialize;+use crate::artifact;use crate::memory;use crate::permissions::ToolPermissions;use crate::preview::{self, PreviewRoots};@@ -1073,6 +1074,29 @@ pub fn preview_unregister_root(roots: tauri::State<'_, PreviewRoots>, root: Striroots.unregister(Path::new(&root));}+/// Cowork's "Open": hand an agent-written file to its OS default app, once+/// [`artifact::checked_artifact`] has checked the file itself, not just its+/// name, against the session's folders in `roots`. A refusal is an error the+/// frontend answers by revealing the file instead.+#[tauri::command]+pub async fn open_artifact<R: tauri::Runtime>(+ app: tauri::AppHandle<R>,+ data_folder: String,+ roots: Vec<String>,+ path: String,+) -> Result<(), AgentToolsError> {+ use tauri_plugin_opener::OpenerExt;+ let data_folder = workspace::host_data_folder(&data_folder);+ let roots = artifact::open_roots(&data_folder, &roots);+ let file = artifact::checked_artifact(Path::new(&path), &roots)?;+ // The canonical path, so what opens is what was checked; without the+ // `\\?\` prefix `canonicalize` adds on Windows, which not every handler accepts.+ let file = crate::tools::proc::without_verbatim_prefix(&file);+ app.opener()+ .open_path(file.to_string_lossy(), None::<&str>)+ .map_err(|e| AgentToolsError::from(e.to_string()))+}+/// 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>(diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rsindex 194523468..e9e85f972 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs@@ -9,6 +9,7 @@//! available in both configurations; only `init()` and the IPC shims in//! `commands` are gated.+pub mod artifact;pub mod memory;pub mod permissions;pub mod preview;@@ -79,7 +80,8 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {commands::stop_session_monitors,commands::cancel_thread_bash,commands::preview_register_root,- commands::preview_unregister_root+ commands::preview_unregister_root,+ commands::open_artifact]).setup(|app, _api| {use tauri::Manager;diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rsindex 5fdfdaa68..931db886f 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs@@ -269,7 +269,7 @@ fn strip_data_volume_prefix(key: &str) -> &str {}}-fn is_within(inner: &Path, outer: &Path) -> bool {+pub(crate) fn is_within(inner: &Path, outer: &Path) -> bool {let (inner, outer) = (containment_key(inner), containment_key(outer));inner == outer || inner.starts_with(&format!("{}/", outer.trim_end_matches('/')))}diff --git a/web-app/src/containers/CoworkArtifactCard.tsx b/web-app/src/containers/CoworkArtifactCard.tsxindex 4f902b2b5..f36329584 100644--- a/web-app/src/containers/CoworkArtifactCard.tsx+++ b/web-app/src/containers/CoworkArtifactCard.tsx@@ -15,6 +15,7 @@ import {resolveInRoots,} from '@/lib/coworkPreview'import { ARTIFACT_ICON, type CoworkArtifact } from '@/lib/coworkArtifacts'+import { artifactOpener } from '@/lib/previewProtocol'import { cn } from '@/lib/utils'/** One accent per artifact family, so a transcript full of cards scans by@@ -128,7 +129,7 @@ export function CoworkArtifactCard({<div className="flex shrink-0 items-center overflow-hidden rounded-md border"><buttontype="button"- onClick={() => void openOrReveal(serviceHub.opener(), abs)}+ onClick={() => void openOrReveal(artifactOpener(), roots, abs)}title={t('common:artifactOpenExternal')}className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium hover:bg-accent">@@ -154,7 +155,7 @@ export function CoworkArtifactCard({</DropdownMenuItem><DropdownMenuSeparator /><DropdownMenuItem- onClick={() => void openOrReveal(serviceHub.opener(), abs)}+ onClick={() => void openOrReveal(artifactOpener(), roots, abs)}><SquareArrowOutUpRight size={14} />{t('common:artifactOpenExternal')}diff --git a/web-app/src/containers/CoworkPreviewPanel.tsx b/web-app/src/containers/CoworkPreviewPanel.tsxindex db4f5ffbd..f3ea587ea 100644--- a/web-app/src/containers/CoworkPreviewPanel.tsx+++ b/web-app/src/containers/CoworkPreviewPanel.tsx@@ -19,6 +19,7 @@ import { useTranslation } from '@/i18n/react-i18next-compat'import { buildSrcDoc } from '@/lib/htmlSandbox'import { previewShimError } from '@/lib/previewShim'import {+ artifactOpener,previewUrl,registerPreviewRoot,unregisterPreviewRoot,@@ -212,7 +213,7 @@ export function CoworkPreviewPanel({ roots, path, onClose }: Props) {{iconButton(t('common:artifactOpenExternal'),SquareArrowOutUpRight,- () => void openOrReveal(serviceHub.opener(), abs)+ () => void openOrReveal(artifactOpener(), roots, abs))}{iconButton(t('common:artifactShowInFolder'),diff --git a/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx b/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsxindex b1f5ab0a7..45baaaba7 100644--- a/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx+++ b/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx@@ -13,13 +13,16 @@ const convertFileSrc = vi.fn((p: string, protocol?: string) =>)const previewRegisterRoot = vi.fn(async () => {})const previewUnregisterRoot = vi.fn(async () => {})+const openArtifact = vi.fn(async () => {})vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({previewRegisterRoot: (...a: unknown[]) => previewRegisterRoot(...a),previewUnregisterRoot: (...a: unknown[]) => previewUnregisterRoot(...a),+ openArtifact: (...a: unknown[]) => openArtifact(...a),}))const openPath = vi.fn()const revealItemInDir = vi.fn()const hub = {+ app: () => ({ getJanDataFolder: async () => '/data' }),core: () => ({ convertFileSrc }),opener: () => ({ openPath, revealItemInDir }),}@@ -254,6 +257,28 @@ describe('CoworkPreviewPanel', () => {expect(previewRegisterRoot).not.toHaveBeenCalled()})+ // "Open" goes through the host, which checks the file and not just its+ // name; a refusal shows the file in its folder instead.+ it('opens through the host check and reveals what it refuses', async () => {+ respondWith('<p>ok</p>')+ view('page.html')+ await screen.findByTitle('page.html')++ fireEvent.click(screen.getByLabelText('common:artifactOpenExternal'))+ await waitFor(() =>+ expect(openArtifact).toHaveBeenCalledWith('/data', [ROOT], `${ROOT}/page.html`)+ )+ expect(openPath).not.toHaveBeenCalled()+ expect(revealItemInDir).not.toHaveBeenCalled()++ openArtifact.mockRejectedValueOnce(new Error('is a link'))+ fireEvent.click(screen.getByLabelText('common:artifactOpenExternal'))+ await waitFor(() =>+ expect(revealItemInDir).toHaveBeenCalledWith(`${ROOT}/page.html`)+ )+ expect(openPath).not.toHaveBeenCalled()+ })+it('registers nothing while the sandbox is in use', async () => {respondWith('<p>ok</p>')view('page.html')diff --git a/web-app/src/lib/__tests__/coworkPreview.test.ts b/web-app/src/lib/__tests__/coworkPreview.test.tsindex caa9c2fc9..15d3e41d4 100644--- a/web-app/src/lib/__tests__/coworkPreview.test.ts+++ b/web-app/src/lib/__tests__/coworkPreview.test.ts@@ -236,21 +236,29 @@ describe('opensInDefaultApp', () => {describe('openOrReveal', () => {const opener = () => ({- openPath: vi.fn().mockResolvedValue(undefined),+ openArtifact: vi.fn().mockResolvedValue(undefined),revealItemInDir: vi.fn().mockResolvedValue(undefined),})- it('opens an allowed type', async () => {+ it('opens an allowed type through the host check, with the session roots', async () => {const o = opener()- await openOrReveal(o, '/w/report.pdf')- expect(o.openPath).toHaveBeenCalledWith('/w/report.pdf')+ await openOrReveal(o, [null, '/w'], '/w/report.pdf')+ expect(o.openArtifact).toHaveBeenCalledWith(['/w'], '/w/report.pdf')expect(o.revealItemInDir).not.toHaveBeenCalled()})+ // The name passed, but the file did not (e.g. a link to a program).+ it('reveals a file the host refuses to open', async () => {+ const o = opener()+ o.openArtifact.mockRejectedValueOnce(new Error('is a link'))+ await openOrReveal(o, ['/w'], '/w/report.pdf')+ expect(o.revealItemInDir).toHaveBeenCalledWith('/w/report.pdf')+ })+it('reveals anything else instead of opening it', async () => {const o = opener()- await openOrReveal(o, '/w/run.command')+ await openOrReveal(o, ['/w'], '/w/run.command')expect(o.revealItemInDir).toHaveBeenCalledWith('/w/run.command')- expect(o.openPath).not.toHaveBeenCalled()+ expect(o.openArtifact).not.toHaveBeenCalled()})})diff --git a/web-app/src/lib/coworkPreview.ts b/web-app/src/lib/coworkPreview.tsindex 803e7f9b6..0c1ba5512 100644--- a/web-app/src/lib/coworkPreview.ts+++ b/web-app/src/lib/coworkPreview.ts@@ -112,17 +112,29 @@ export function opensInDefaultApp(path: string): boolean {}/** "Open" for an agent-written file: the default app for a document or media- * type, the file manager (file selected) for anything else. */-export function openOrReveal(+ * type, the file manager (file selected) for anything else. The name is only a+ * first cut: `openArtifact` checks the file itself (a `report.pdf` can be a+ * link to a program), and whatever it refuses is revealed instead. */+export async function openOrReveal(opener: {- openPath(path: string): Promise<void>+ openArtifact(roots: string[], path: string): Promise<void>revealItemInDir(path: string): Promise<void>},+ roots: Array<string | null>,abs: string): Promise<void> {- return opensInDefaultApp(abs)- ? opener.openPath(abs)- : opener.revealItemInDir(abs)+ if (opensInDefaultApp(abs)) {+ try {+ await opener.openArtifact(+ roots.filter((r): r is string => !!r),+ abs+ )+ return+ } catch {+ // Refused or failed: fall through to showing it in its folder.+ }+ }+ await opener.revealItemInDir(abs)}export function basenameOf(path: string): string {diff --git a/web-app/src/lib/previewProtocol.ts b/web-app/src/lib/previewProtocol.tsindex d999ac03a..cc0778a29 100644--- a/web-app/src/lib/previewProtocol.ts+++ b/web-app/src/lib/previewProtocol.ts@@ -1,4 +1,5 @@import {+ openArtifact,previewRegisterRoot,previewUnregisterRoot,} from '@janhq/tauri-plugin-agent-tools-api'@@ -21,3 +22,16 @@ export const unregisterPreviewRoot = (root: string) =>export function previewUrl(abs: string): string {return previewUrlFor(abs, getServiceHub().core().convertFileSrc('/', 'preview'))}++/** What `openOrReveal` opens and reveals with: "Open" goes through the host,+ * which checks the file itself rather than its name (`open_artifact`). */+export function artifactOpener() {+ return {+ openArtifact: async (roots: string[], abs: string) => {+ const dataFolder = await getServiceHub().app().getJanDataFolder()+ await openArtifact(dataFolder ?? '', roots, abs)+ },+ revealItemInDir: (abs: string) =>+ getServiceHub().opener().revealItemInDir(abs),+ }+}