Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-tools): render screenshot via app webview, gate tool to desktop
Akarshan Biswasc2c0ee44aa6f
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 706197d6e..28dd60106 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -4462,10 +4462,17 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"dependencies = ["bitflags 2.13.0","block2",+ "libc","objc2",+ "objc2-cloud-kit",+ "objc2-core-data","objc2-core-foundation","objc2-core-graphics",+ "objc2-core-image",+ "objc2-core-text",+ "objc2-core-video","objc2-foundation",+ "objc2-quartz-core",][[package]]@@ -4485,6 +4492,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"dependencies = [+ "bitflags 2.13.0","objc2","objc2-foundation",]@@ -4545,6 +4553,19 @@ dependencies = ["objc2-core-graphics",]+[[package]]+name = "objc2-core-video"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"+dependencies = [+ "bitflags 2.13.0",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-io-surface",+]+[[package]]name = "objc2-encode"version = "4.1.0"@@ -4584,6 +4605,16 @@ dependencies = ["objc2-core-foundation",]+[[package]]+name = "objc2-javascript-core"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a1e6550c4caed348956ce3370c9ffeca70bb1dbed4fa96112e7c6170e074586"+dependencies = [+ "objc2",+ "objc2-core-foundation",+]+[[package]]name = "objc2-osa-kit"version = "0.3.2"@@ -4608,6 +4639,17 @@ dependencies = ["objc2-foundation",]+[[package]]+name = "objc2-security"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a"+dependencies = [+ "bitflags 2.13.0",+ "objc2",+ "objc2-core-foundation",+]+[[package]]name = "objc2-ui-kit"version = "0.3.2"@@ -4651,6 +4693,8 @@ dependencies = ["objc2-app-kit","objc2-core-foundation","objc2-foundation",+ "objc2-javascript-core",+ "objc2-security",][[package]]@@ -7440,10 +7484,19 @@ name = "tauri-plugin-agent-tools"version = "0.8.3"dependencies = ["base64 0.22.1",+ "block2",+ "cairo-rs",+ "gio",+ "glib","glob","ignore","nix 0.30.1",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "objc2-web-kit","percent-encoding",+ "png 0.17.16","regex","serde","serde_json",@@ -7454,6 +7507,9 @@ dependencies = ["tauri-plugin-websearch","thiserror 2.0.18","tokio",+ "webkit2gtk",+ "webview2-com",+ "windows 0.61.3","windows-sys 0.60.2",]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.tomlindex efce8d4a5..6fe53c581 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml@@ -15,10 +15,37 @@ links = "tauri-plugin-agent-tools"# keep the whole GUI stack out of the graph.[features]default = ["tauri"]-tauri = ["dep:tauri", "dep:tauri-plugin"]+# The Linux GUI crates back the webview `screenshot` renderer and only exist on+# that target, so they are enabled by the `tauri` feature but stay absent from+# the CLI graph (which never turns `tauri` on).+tauri = [+ "dep:tauri",+ "dep:tauri-plugin",+ # `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.+ "tauri/wry",+ # Linux screenshot backend (webkit2gtk snapshot -> cairo -> PNG).+ "dep:webkit2gtk",+ "dep:cairo-rs",+ "dep:gio",+ "dep:glib",+ # macOS screenshot backend (WKWebView snapshot -> NSImage -> PNG).+ "dep:objc2",+ "dep:objc2-web-kit",+ "dep:objc2-app-kit",+ "dep:objc2-foundation",+ "dep:block2",+ # Windows screenshot backend (WebView2 CapturePreview -> IStream PNG).+ "dep:webview2-com",+ "dep:windows",+][dependencies]base64 = "0.22"+# Pure Rust, no GUI linkage; used by the webview screenshot path and harmless in+# the CLI graph.+png = "0.17"glob = "0.3"percent-encoding = "2"ignore = "0.4"@@ -40,6 +67,52 @@ tauri-plugin = { version = "2.3.1", features = ["build"], optional = true }[target.'cfg(unix)'.dependencies]nix = { version = "=0.30.1", features = ["signal", "process"] }+# Webview `screenshot` backend (see `webview_shot.rs`). All optional and enabled+# by the `tauri` feature, so the headless CLI never pulls a GUI stack in.+[target.'cfg(target_os = "linux")'.dependencies]+webkit2gtk = { version = "2.0", features = ["v2_8"], optional = true }+cairo-rs = { version = "0.18", optional = true }+gio = { version = "0.18", optional = true }+glib = { version = "0.18", optional = true }++# macOS webview `screenshot` backend. Versions pinned to the workspace lockfile+# so linkage does not duplicate the objc2 stack tauri/wry already pulls.+[target.'cfg(target_os = "macos")'.dependencies]+objc2 = { version = "0.6", optional = true }+objc2-web-kit = { version = "0.3", features = [+ "WKWebView",+ "WKSnapshotConfiguration",+ "block2",+ "objc2-app-kit",+ "objc2-core-foundation",+], optional = true }+objc2-app-kit = { version = "0.3", features = [+ "NSImage",+ "NSImageRep",+ "NSBitmapImageRep",+], optional = true }+objc2-foundation = { version = "0.3", features = [+ "NSData",+ "NSDictionary",+ "NSError",+ "NSGeometry",+ "NSString",+ "NSValue",+], optional = true }+block2 = { version = "0.6", optional = true }++# Windows webview `screenshot` backend. `windows` (0.61) matches the version+# `webview2-com` / `tauri-runtime-wry` resolve to, so the `IStream` handed to+# `CapturePreview` is the same type. Separate from the `windows-sys` crate used+# by the bash sandbox below.+[target.'cfg(target_os = "windows")'.dependencies]+webview2-com = { version = "0.38", optional = true }+windows = { version = "0.61", features = [+ "Win32_Foundation",+ "Win32_System_Com",+ "Win32_UI_Shell",+], optional = true }+# AppContainer confinement for the `bash` tool: profile creation, workspace ACLs# and the `STARTUPINFOEX` spawn that carries the lowbox token.[target.'cfg(windows)'.dependencies]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex b0de4b729..006db7680 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -687,7 +687,8 @@ fn resolve_workspace_root(// here rather than trusted: an unusable one is an error, never a silent drop,// or the agent would work against a folder it believes is attached and is not.#[allow(clippy::too_many_arguments)]-pub async fn execute_tool(+pub async fn execute_tool<R: tauri::Runtime>(+ app: tauri::AppHandle<R>,data_folder: String,thread_id: String,project: Option<String>,@@ -701,6 +702,7 @@ pub async fn execute_tool(call_id: Option<String>,) -> Result<ToolResult, AgentToolsError> {execute_tool_inner(+ screenshot_backend(&app),data_folder,thread_id,project,@@ -717,6 +719,28 @@ pub async fn execute_tool(.await}+/// The webview-backed `screenshot` renderer on the desktop (Linux, macOS,+/// Windows); `None` everywhere else, keeping the Chrome fallback.+#[cfg(all(+ feature = "tauri",+ any(target_os = "linux", target_os = "macos", target_os = "windows")+))]+fn screenshot_backend<R: tauri::Runtime>(+ app: &tauri::AppHandle<R>,+) -> Option<crate::tools::ScreenshotBackend> {+ Some(crate::webview_shot::make_backend(app))+}++#[cfg(not(all(+ feature = "tauri",+ any(target_os = "linux", target_os = "macos", target_os = "windows")+)))]+fn screenshot_backend<R: tauri::Runtime>(+ _app: &tauri::AppHandle<R>,+) -> Option<crate::tools::ScreenshotBackend> {+ None+}+/// `execute_tool`, plus a channel that receives the tool's output as it is/// produced. A separate command rather than an optional argument because/// `tauri::ipc::Channel` is a `CommandArg`, not a `Deserialize`, so it cannot be@@ -724,7 +748,8 @@ pub async fn execute_tool(#[cfg(feature = "tauri")]#[tauri::command]#[allow(clippy::too_many_arguments)]-pub async fn execute_tool_streaming(+pub async fn execute_tool_streaming<R: tauri::Runtime>(+ app: tauri::AppHandle<R>,data_folder: String,thread_id: String,project: Option<String>,@@ -740,6 +765,7 @@ pub async fn execute_tool_streaming() -> Result<ToolResult, AgentToolsError> {let sink = output_sink(on_output, call_id.clone());execute_tool_inner(+ screenshot_backend(&app),data_folder,thread_id,project,@@ -758,6 +784,7 @@ pub async fn execute_tool_streaming(#[allow(clippy::too_many_arguments)]async fn execute_tool_inner(+ screenshot_backend: Option<crate::tools::ScreenshotBackend>,data_folder: String,thread_id: String,project: Option<String>,@@ -905,7 +932,8 @@ async fn execute_tool_inner(.with_scratch_root(&scratch).with_read_roots(&read_roots).with_write_roots(&write_roots)- .with_thread_id(Some(&thread_id));+ .with_thread_id(Some(&thread_id))+ .with_screenshot_backend(screenshot_backend);if let Some(sp) = skill_project.as_deref() {ctx = ctx.with_skill_project_root(sp);}@@ -1049,6 +1077,41 @@ mod tests {dir}+ /// Test shim: `execute_tool` is now a generic Tauri command taking an+ /// `AppHandle`, which the tests have no runtime to build. This drives the+ /// same path with no webview backend (Chrome only) and no output sink.+ #[allow(clippy::too_many_arguments)]+ async fn execute_tool(+ data_folder: String,+ thread_id: String,+ project: Option<String>,+ name: String,+ args: serde_json::Value,+ enabled_skills: Option<Vec<String>>,+ allow_network: Option<bool>,+ read_only_project: Option<String>,+ project_writable: Option<bool>,+ scope: Option<WorkspaceScope>,+ call_id: Option<String>,+ ) -> Result<ToolResult, AgentToolsError> {+ execute_tool_inner(+ None,+ data_folder,+ thread_id,+ project,+ name,+ args,+ enabled_skills,+ allow_network,+ read_only_project,+ project_writable,+ scope,+ call_id,+ None,+ )+ .await+ }+const T1: &str = "thread-one";/// Own thread ids: the session scratch is keyed by thread id and lives in/// the shared host temp dir, so reusing one couples these tests to everydiff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rsindex 933f9cd3c..7b9864bb6 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs@@ -19,6 +19,14 @@ pub mod workspace;#[cfg(feature = "tauri")]mod commands;+/// Webview-backed `screenshot` renderer, so the tool works without Chrome, on+/// all three desktop platforms; other targets keep the Chrome path.+#[cfg(all(+ feature = "tauri",+ any(target_os = "linux", target_os = "macos", target_os = "windows")+))]+mod webview_shot;+/// Runs the confined-spawn helper and exits, when this process was re-exec'd as/// one by the Windows sandbox backend. A no-op on every other platform and on a/// normal launch, but it must be called before anything else in `main`: thediff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex a8bbb2dfc..cf8b091fb 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -19,7 +19,7 @@ use crate::tools::sandbox::{escapes_write_roots, in_scratch, is_hidden_jan_path, lexical_normalize, resolve_path,scratch_display_path, symlink_escapes_any_root,};-use crate::tools::{BuiltinTool, ImageContentPart, ToolContext};+use crate::tools::{BuiltinTool, ImageContentPart, ScreenshotBackend, ToolContext};const MAX_BYTES: usize = 64 * 1024;const MAX_LINES: usize = 2000;@@ -144,7 +144,17 @@ pub async fn execute_builtin(let scratch = ctx.scratch_root;let (content, images) = match tool.name {"read" => read(args, project_root, scratch, ctx.read_roots).await,- "screenshot" => screenshot(args, project_root, scratch, ctx.read_roots).await,+ #[cfg(feature = "tauri")]+ "screenshot" => {+ screenshot(+ args,+ project_root,+ scratch,+ ctx.read_roots,+ ctx.screenshot_backend.as_ref(),+ )+ .await+ }_ => (execute_text(tool, args, ctx).await, None),};(content, images)@@ -1241,22 +1251,22 @@ fn chrome_binary() -> Option<PathBuf> {.map(PathBuf::from)}-/// Render a local HTML/SVG file to PNG bytes with headless Chrome.+/// Render a local HTML/SVG file to PNG bytes.///-/// Shared by the model-facing `screenshot` tool and the `agent_render_preview`-/// command the annotation overlay calls, so both agree on Chrome discovery,-/// viewport clamping and the output cap. `width`/`height` are the viewport in-/// CSS pixels; the caller picks them (the overlay passes its own stage size so-/// the PNG lines up pixel-for-pixel with what the user drew on).+/// `backend`, when present, renders through the desktop's own webview (no Chrome+/// needed); on any backend failure this falls back to headless Chrome so nothing+/// regresses. `None` goes straight to Chrome. Either way the viewport clamping+/// and output cap are identical.///-/// `scale` is the device pixel ratio: the PNG comes out `width*scale` pixels-/// wide with the layout unchanged. The overlay passes the webview's own ratio-/// so a HiDPI screen doesn't composite crisp marks over an upscaled blur.+/// `width`/`height` are the viewport in CSS pixels; `scale` is the device pixel+/// ratio, so the PNG comes out `width*scale` pixels wide with the layout+/// unchanged.pub async fn render_html_png(target: &Path,width: u64,height: u64,scale: f64,+ backend: Option<&ScreenshotBackend>,) -> Result<Vec<u8>, String> {let ext = target.extension()@@ -1272,12 +1282,6 @@ pub async fn render_html_png(return Err(format!("file not found: {}", target.display()));}- let Some(chrome) = chrome_binary() else {- return Err(- "no Chrome/Chromium binary found (set CHROME_PATH to point at one)".to_string(),- );- };-let width = width.clamp(320, 4096);let height = height.clamp(240, 4096);let scale = if scale.is_finite() {@@ -1285,6 +1289,23 @@ pub async fn render_html_png(} else {1.0};++ // Try the injected backend (the desktop's webview capture) first, so the tool+ // works without Chrome; on any failure fall through to Chrome so nothing+ // regresses.+ if let Some(backend) = backend {+ match backend(target.to_path_buf(), width, height, scale).await {+ Ok(png) => return finalize_screenshot_png(png),+ Err(_) => { /* fall through to Chrome */ }+ }+ }++ let Some(chrome) = chrome_binary() else {+ return Err(+ "no Chrome/Chromium binary found (set CHROME_PATH to point at one)".to_string(),+ );+ };+// A per-call profile (pid + nanos) keeps headless Chrome from colliding// with a running browser or a leftover from a previous call; `--screenshot`// exits after writing, but the wait below is bounded in case it lingers.@@ -1351,8 +1372,13 @@ pub async fn render_html_png(};let _ = tokio::fs::remove_file(&shot).await;+ finalize_screenshot_png(png)+}++/// Shared empty-check and size cap for a rendered PNG, whatever produced it.+fn finalize_screenshot_png(png: Vec<u8>) -> Result<Vec<u8>, String> {if png.is_empty() {- return Err("Chrome produced an empty screenshot (page may be blank)".to_string());+ return Err("screenshot came out empty (page may be blank)".to_string());}if png.len() > SCREENSHOT_MAX_PNG_BYTES {return Err(format!(@@ -1369,11 +1395,17 @@ pub async fn render_html_png(/// Returns an `ImageContentPart` rather than a data URL pasted into the text,/// matching what `read` does for images: that is the form a vision model/// actually consumes, and it keeps a megabyte of base64 out of the transcript.+///+/// Desktop-only (`feature = "tauri"`): the headless CLI has no webview to render+/// through and no window to show a Chrome fallback, so `screenshot` is not+/// advertised there. See `BUILTIN_TOOLS` and `builtin_tool_schemas`.+#[cfg(feature = "tauri")]async fn screenshot(args: &serde_json::Value,root: &Path,scratch: Option<&Path>,read_roots: &[PathBuf],+ backend: Option<&ScreenshotBackend>,) -> (String, Option<Vec<ImageContentPart>>) {let Some(path) = arg_str(args, "path") else {return ("ERROR: missing required argument 'path'".to_string(), None);@@ -1387,7 +1419,7 @@ async fn screenshot(None,);}- let png = match render_html_png(&target, width, height, 1.0).await {+ let png = match render_html_png(&target, width, height, 1.0, backend).await {Ok(b) => b,Err(e) => return (format!("ERROR: {e}"), None),};@@ -3521,37 +3553,41 @@ mod tests {/// Two headless Chromes racing for the same profile dir collide, so the/// tests that actually launch one are serialised. An async mutex so the test/// can hold it across the awaited screenshot without `await_holding_lock`.+ #[cfg(feature = "tauri")]static CHROME_TEST_LOCK: std::sync::LazyLock<tokio::sync::Mutex<()>> =std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));+ #[cfg(feature = "tauri")]#[tokio::test]async fn screenshot_rejects_a_non_html_file() {let root = unique_root();std::fs::write(root.join("a.txt"), b"nope").unwrap();- let (out, images) = screenshot(&json!({"path": "a.txt"}), &root, None, &[]).await;+ let (out, images) = screenshot(&json!({"path": "a.txt"}), &root, None, &[], None).await;assert!(out.contains("only renders"), "{out}");assert!(images.is_none());let _ = std::fs::remove_dir_all(&root);}+ #[cfg(feature = "tauri")]#[tokio::test]async fn screenshot_rejects_a_missing_file() {let root = unique_root();- let (out, images) = screenshot(&json!({"path": "gone.html"}), &root, None, &[]).await;+ let (out, images) = screenshot(&json!({"path": "gone.html"}), &root, None, &[], None).await;assert!(out.contains("file not found"), "{out}");assert!(images.is_none());let _ = std::fs::remove_dir_all(&root);}+ #[cfg(feature = "tauri")]#[tokio::test]async fn screenshot_requires_a_path() {let root = unique_root();- let (out, _) = screenshot(&json!({}), &root, None, &[]).await;+ let (out, _) = screenshot(&json!({}), &root, None, &[], None).await;assert!(out.contains("missing required argument"), "{out}");let _ = std::fs::remove_dir_all(&root);}- #[cfg(unix)]+ #[cfg(all(unix, feature = "tauri"))]#[tokio::test]async fn screenshot_refuses_a_symlink_out_of_the_workspace() {let root = unique_root();@@ -3561,7 +3597,7 @@ mod tests {let link = root.join("innocent.html");std::os::unix::fs::symlink(&secret, &link).unwrap();- let (out, images) = screenshot(&json!({"path": "innocent.html"}), &root, None, &[]).await;+ let (out, images) = screenshot(&json!({"path": "innocent.html"}), &root, None, &[], None).await;assert!(out.contains("symlink"), "{out}");assert!(images.is_none());let _ = std::fs::remove_dir_all(&root);@@ -3570,6 +3606,7 @@ mod tests {/// Renders for real when a browser is present, and returns an image part/// rather than a data URL buried in the text.+ #[cfg(feature = "tauri")]#[tokio::test]#[allow(clippy::await_holding_lock)]async fn screenshot_returns_an_image_part_when_chrome_is_present() {@@ -3589,6 +3626,7 @@ mod tests {&root,None,&[],+ None,).await;assert!(!out.starts_with("ERROR"), "{out}");diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex 44340bffa..496626903 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -144,6 +144,10 @@ pub struct ToolContext<'a> {/// `[tools].env_set`. Applied after `env_passthrough` and winning per key;/// the one way to inject a secret-named variable on purpose.pub env_set: &'a [(String, String)],+ /// Renders HTML/SVG to PNG for the `screenshot` tool. `None` falls back to+ /// headless Chrome; the desktop injects a webview-backed renderer. See+ /// [`ScreenshotBackend`].+ pub screenshot_backend: Option<ScreenshotBackend>,}impl std::fmt::Debug for ToolContext<'_> {@@ -168,6 +172,7 @@ impl std::fmt::Debug for ToolContext<'_> {.field("thread_id", &self.thread_id).field("env_passthrough", &self.env_passthrough).field("env_set", &self.env_set)+ .field("screenshot_backend", &self.screenshot_backend.is_some()).finish()}}@@ -176,6 +181,24 @@ impl std::fmt::Debug for ToolContext<'_> {/// Chunks are raw fragments, not lines -- a caller that wants lines buffers them.pub type OutputSink = std::sync::Arc<dyn Fn(String) + Send + Sync>;+/// Renders a local HTML/SVG file (path, width, height, scale) to PNG bytes.+///+/// Injected by the desktop so `screenshot` can capture through the app's own+/// webview instead of shelling out to Chrome. A boxed closure so this module+/// stays Tauri-free: the webview implementation lives behind the `tauri` feature+/// (`crate::webview_shot`). `None` keeps the Chrome-only path.+pub type ScreenshotBackend = std::sync::Arc<+ dyn Fn(+ std::path::PathBuf,+ u64,+ u64,+ f64,+ ) -> std::pin::Pin<+ Box<dyn std::future::Future<Output = Result<Vec<u8>, String>> + Send>,+ > + Send+ + Sync,+>;+impl<'a> ToolContext<'a> {pub fn new(project_root: &'a Path, store_root: &'a Path, enabled_skills: &'a [String]) -> Self {Self {@@ -196,9 +219,16 @@ impl<'a> ToolContext<'a> {thread_id: None,env_passthrough: &[],env_set: &[],+ screenshot_backend: None,}}+ /// Inject the `screenshot` PNG renderer. See [`Self::screenshot_backend`].+ pub fn with_screenshot_backend(mut self, backend: Option<ScreenshotBackend>) -> Self {+ self.screenshot_backend = backend;+ self+ }+/// The session (thread) this call belongs to. See [`Self::thread_id`].pub fn with_thread_id(mut self, thread_id: Option<&'a str>) -> Self {self.thread_id = thread_id;@@ -359,6 +389,9 @@ pub const BUILTIN_TOOLS: &[BuiltinTool] = &[path_args: &["path"],},// Read: it renders a file that is already reachable and writes nothing back.+ // Desktop-only: the headless CLI has no webview/window, so it is not built+ // with `feature = "tauri"` and never advertises or dispatches `screenshot`.+ #[cfg(feature = "tauri")]BuiltinTool {name: "screenshot",capability: Capability::Read,@@ -477,7 +510,10 @@ mod tests {#[test]fn builtin_count_matches_expected() {// 8 coding tools + 6 dedicated skill/memory tools + 2 native web tools.- assert_eq!(BUILTIN_TOOLS.len(), 16);+ // `screenshot` (one of the coding tools) is desktop-only, so the headless+ // CLI build (`feature = "tauri"` off) has one fewer.+ let expected = if cfg!(feature = "tauri") { 16 } else { 15 };+ assert_eq!(BUILTIN_TOOLS.len(), expected);}#[test]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rsindex 343113a03..7591786ad 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs@@ -4,9 +4,11 @@use serde_json::{json, Value};-/// OpenAI function schemas for the 7 built-in tools.+/// OpenAI function schemas for the built-in tools, one per `BUILTIN_TOOLS`+/// entry. `screenshot` is desktop-only (`feature = "tauri"`), so the headless+/// CLI advertises one fewer.pub fn builtin_tool_schemas() -> Vec<Value> {- vec![+ [json!({"type": "function","function": {@@ -74,6 +76,7 @@ pub fn builtin_tool_schemas() -> Vec<Value> {}}}),+ #[cfg(feature = "tauri")]json!({"type": "function","function": {@@ -251,6 +254,7 @@ pub fn builtin_tool_schemas() -> Vec<Value> {}}),]+ .to_vec()}#[cfg(test)]@@ -261,7 +265,8 @@ mod tests {#[test]fn schemas_match_builtin_tools() {let schemas = builtin_tool_schemas();- assert_eq!(schemas.len(), 16);+ let expected_len = if cfg!(feature = "tauri") { 16 } else { 15 };+ assert_eq!(schemas.len(), expected_len);for schema in &schemas {assert_eq!(schema["type"], "function");}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/webview_shot.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/webview_shot.rsnew file mode 100644index 000000000..05e4be849--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/webview_shot.rs@@ -0,0 +1,404 @@+//! Webview-backed `screenshot` renderer for the desktop.+//!+//! Renders a local HTML/SVG file to PNG using the app's own platform webview, so+//! `screenshot` works without a Chrome/Chromium binary. The window-build,+//! page-load, settle and destroy orchestration is cross-platform; only the+//! snapshot itself is per-OS (`take_snapshot`):+//!+//! - Linux: `webkit2gtk` `WebView::snapshot` (`FullDocument`) -> cairo surface -> PNG.+//! - macOS: `WKWebView takeSnapshotWithConfiguration:` -> `NSImage` -> PNG (viewport).+//! - Windows: WebView2 `ICoreWebView2::CapturePreview` -> PNG bytes (viewport).+//!+//! Everything that touches a GUI stack lives here, behind `feature = "tauri"` and+//! the desktop targets, so the Tauri-free core and the headless CLI never pull it+//! into their graph. The Chrome path stays the fallback everywhere.++use std::path::PathBuf;+use std::sync::{Arc, Mutex};+use std::time::Duration;++use tauri::webview::PageLoadEvent;+use tauri::{Runtime, WebviewUrl, WebviewWindowBuilder};+use tokio::sync::oneshot;++use crate::tools::ScreenshotBackend;++const LOAD_TIMEOUT: Duration = Duration::from_secs(30);+const SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(30);+/// Settle window for async assets (fonts, images) after `load` fires.+const SETTLE: Duration = Duration::from_millis(150);++/// One-shot delivery slot for the completed snapshot, shared with whatever+/// platform callback produces the PNG bytes.+type SnapshotSlot = Arc<Mutex<Option<oneshot::Sender<Result<Vec<u8>, String>>>>>;++fn deliver(slot: &SnapshotSlot, value: Result<Vec<u8>, String>) {+ if let Ok(mut guard) = slot.lock() {+ if let Some(tx) = guard.take() {+ let _ = tx.send(value);+ }+ }+}++/// Build a [`ScreenshotBackend`] that captures through the app's webview.+pub fn make_backend<R: Runtime>(app: &tauri::AppHandle<R>) -> ScreenshotBackend {+ let app = app.clone();+ Arc::new(move |target, width, height, scale| {+ let app = app.clone();+ Box::pin(capture(app, target, width, height, scale))+ })+}++async fn capture<R: Runtime>(+ app: tauri::AppHandle<R>,+ target: PathBuf,+ width: u64,+ height: u64,+ // The platform snapshots at the display's own backing scale; there is no+ // viewport DPR knob to honor here, so `scale` is accepted for signature+ // parity and left unapplied. The tool only ever passes 1.0.+ _scale: f64,+) -> Result<Vec<u8>, String> {+ let url = tauri::Url::from_file_path(&target)+ .map_err(|_| format!("cannot build file URL for {}", target.display()))?;+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ let label = format!("jan-shot-{}-{nanos}", std::process::id());++ let (load_tx, load_rx) = oneshot::channel::<()>();+ let load_signal = Arc::new(Mutex::new(Some(load_tx)));+ let (win_tx, win_rx) = oneshot::channel::<Result<tauri::WebviewWindow<R>, String>>();++ // Window creation and page-load registration happen on the main thread (the+ // GUI toolkit owns the widget). The window is built visible but far+ // off-screen: a webview that is never mapped can snapshot blank, so it must+ // be realized, and off-screen keeps it from flashing on the user's display.+ let build_app = app.clone();+ let build = move || {+ let signal = load_signal.clone();+ let res = WebviewWindowBuilder::new(&build_app, &label, WebviewUrl::External(url))+ .title("")+ .inner_size(width as f64, height as f64)+ .position(-10000.0, -10000.0)+ .decorations(false)+ .skip_taskbar(true)+ .visible(true)+ .on_page_load(move |_window, payload| {+ if payload.event() == PageLoadEvent::Finished {+ if let Ok(mut guard) = signal.lock() {+ if let Some(tx) = guard.take() {+ let _ = tx.send(());+ }+ }+ }+ })+ .build()+ .map_err(|e| format!("failed to create capture window: {e}"));+ let _ = win_tx.send(res);+ };+ app.run_on_main_thread(build)+ .map_err(|e| format!("failed to schedule capture window: {e}"))?;++ let window = win_rx+ .await+ .map_err(|_| "capture window builder dropped".to_string())??;++ let result = capture_loaded(&window, load_rx, width, height).await;+ let _ = window.destroy();+ result+}++async fn capture_loaded<R: Runtime>(+ window: &tauri::WebviewWindow<R>,+ load_rx: oneshot::Receiver<()>,+ width: u64,+ height: u64,+) -> Result<Vec<u8>, String> {+ match tokio::time::timeout(LOAD_TIMEOUT, load_rx).await {+ Ok(Ok(())) => {}+ Ok(Err(_)) => return Err("capture window closed before load".to_string()),+ Err(_) => return Err("webview screenshot timed out waiting for page load".to_string()),+ }+ tokio::time::sleep(SETTLE).await;++ let (png_tx, png_rx) = oneshot::channel::<Result<Vec<u8>, String>>();+ let slot: SnapshotSlot = Arc::new(Mutex::new(Some(png_tx)));+ let cb_slot = slot.clone();+ window+ .with_webview(move |platform| {+ take_snapshot(&platform, width, height, cb_slot);+ })+ .map_err(|e| format!("failed to reach platform webview: {e}"))?;++ match tokio::time::timeout(SNAPSHOT_TIMEOUT, png_rx).await {+ Ok(Ok(res)) => res,+ Ok(Err(_)) => Err("webview snapshot callback dropped".to_string()),+ Err(_) => Err("webview screenshot timed out waiting for snapshot".to_string()),+ }+}++// ---------------------------------------------------------------------------+// Linux: webkit2gtk snapshot -> cairo surface -> PNG.+// ---------------------------------------------------------------------------++#[cfg(target_os = "linux")]+fn take_snapshot(+ platform: &tauri::webview::PlatformWebview,+ _width: u64,+ _height: u64,+ slot: SnapshotSlot,+) {+ use webkit2gtk::{SnapshotOptions, SnapshotRegion, WebViewExt};++ let webview = platform.inner();+ webview.snapshot(+ SnapshotRegion::FullDocument,+ SnapshotOptions::NONE,+ None::<&webkit2gtk::gio::Cancellable>,+ move |result| {+ let png = result+ .map_err(|e| format!("webkit snapshot failed: {e}"))+ .and_then(surface_to_png);+ deliver(&slot, png);+ },+ );+}++/// Encode a cairo `ARgb32` surface (BGRA, premultiplied on little-endian) as a+/// straight-alpha RGBA PNG.+#[cfg(target_os = "linux")]+fn surface_to_png(surface: cairo::Surface) -> Result<Vec<u8>, String> {+ let mut image = cairo::ImageSurface::try_from(surface)+ .map_err(|_| "snapshot surface is not an image surface".to_string())?;+ if image.format() != cairo::Format::ARgb32 {+ return Err(format!("unexpected snapshot format {:?}", image.format()));+ }+ let width = image.width();+ let height = image.height();+ if width <= 0 || height <= 0 {+ return Err("snapshot has empty dimensions".to_string());+ }+ let stride = image.stride() as usize;+ let data = image+ .data()+ .map_err(|e| format!("cannot read snapshot pixels: {e}"))?;++ let w = width as usize;+ let h = height as usize;+ let mut rgba = Vec::with_capacity(w * h * 4);+ for row in 0..h {+ let start = row * stride;+ for col in 0..w {+ let px = &data[start + col * 4..start + col * 4 + 4];+ let (b, g, r, a) = (px[0], px[1], px[2], px[3]);+ let straight = |c: u8| -> u8 {+ if a == 0 {+ 0+ } else {+ ((c as u16 * 255 + a as u16 / 2) / a as u16) as u8+ }+ };+ rgba.extend_from_slice(&[straight(r), straight(g), straight(b), a]);+ }+ }+ drop(data);++ encode_rgba_png(&rgba, width as u32, height as u32)+}++#[cfg(target_os = "linux")]+fn encode_rgba_png(rgba: &[u8], width: u32, height: u32) -> Result<Vec<u8>, String> {+ let mut out = Vec::new();+ {+ let mut encoder = png::Encoder::new(&mut out, width, height);+ encoder.set_color(png::ColorType::Rgba);+ encoder.set_depth(png::BitDepth::Eight);+ let mut writer = encoder+ .write_header()+ .map_err(|e| format!("PNG header failed: {e}"))?;+ writer+ .write_image_data(rgba)+ .map_err(|e| format!("PNG encode failed: {e}"))?;+ }+ Ok(out)+}++// ---------------------------------------------------------------------------+// macOS: WKWebView snapshot -> NSImage -> PNG.+//+// WKWebView captures the viewport, not the full scrollable document: full-page+// capture there is unreliable, so this snapshots the window's inner size+// (`width` x `height`). That is a deliberate difference from Linux's+// `FullDocument`.+// ---------------------------------------------------------------------------++#[cfg(target_os = "macos")]+fn take_snapshot(+ platform: &tauri::webview::PlatformWebview,+ width: u64,+ height: u64,+ slot: SnapshotSlot,+) {+ use objc2::MainThreadMarker;+ use objc2_app_kit::NSImage;+ use objc2_foundation::{NSError, NSPoint, NSRect, NSSize};+ use objc2_web_kit::{WKSnapshotConfiguration, WKWebView};++ let ptr: *mut WKWebView = platform.inner().cast();+ if ptr.is_null() {+ deliver(&slot, Err("null WKWebView handle".to_string()));+ return;+ }+ // The webview is owned by the window we keep alive until `destroy()`, so a+ // borrow for the duration of the (synchronous) `takeSnapshot` call is sound;+ // WebKit retains what it needs for the async completion itself.+ let webview: &WKWebView = unsafe { &*ptr };++ let mtm = match MainThreadMarker::new() {+ Some(m) => m,+ None => {+ deliver(&slot, Err("webview snapshot not on main thread".to_string()));+ return;+ }+ };++ let config = unsafe { WKSnapshotConfiguration::new(mtm) };+ let rect = NSRect::new(+ NSPoint::new(0.0, 0.0),+ NSSize::new(width as f64, height as f64),+ );+ unsafe { config.setRect(rect) };++ let cb_slot = slot.clone();+ let handler = block2::RcBlock::new(move |image: *mut NSImage, error: *mut NSError| {+ deliver(&cb_slot, nsimage_to_png(image, error));+ });++ unsafe {+ webview.takeSnapshotWithConfiguration_completionHandler(Some(&*config), &handler);+ }+}++/// Convert the `NSImage` handed to the snapshot completion handler into PNG+/// bytes, routing through a TIFF representation so no CoreGraphics dependency is+/// needed. Both pointers come straight from WebKit; exactly one is non-null.+#[cfg(target_os = "macos")]+fn nsimage_to_png(+ image: *mut objc2_app_kit::NSImage,+ error: *mut objc2_foundation::NSError,+) -> Result<Vec<u8>, String> {+ use objc2::runtime::AnyObject;+ use objc2_app_kit::{NSBitmapImageFileType, NSBitmapImageRep, NSBitmapImageRepPropertyKey};+ use objc2_foundation::NSDictionary;++ if image.is_null() {+ let detail = if error.is_null() {+ "no image and no error".to_string()+ } else {+ unsafe { (*error).localizedDescription() }.to_string()+ };+ return Err(format!("WKWebView snapshot failed: {detail}"));+ }++ let image: &objc2_app_kit::NSImage = unsafe { &*image };+ let tiff = unsafe { image.TIFFRepresentation() }+ .ok_or_else(|| "snapshot has no TIFF representation".to_string())?;+ let rep = NSBitmapImageRep::imageRepWithData(&tiff)+ .ok_or_else(|| "cannot build bitmap rep from snapshot".to_string())?;+ let props: objc2::rc::Retained<NSDictionary<NSBitmapImageRepPropertyKey, AnyObject>> =+ NSDictionary::new();+ let data = unsafe { rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &props) }+ .ok_or_else(|| "PNG encode of snapshot failed".to_string())?;+ Ok(data.to_vec())+}++// ---------------------------------------------------------------------------+// Windows: WebView2 CapturePreview -> in-memory IStream (already PNG).+//+// CapturePreview captures the viewport at the webview's current size, so this+// matches macOS's viewport capture rather than Linux's `FullDocument`.+// ---------------------------------------------------------------------------++#[cfg(target_os = "windows")]+fn take_snapshot(+ platform: &tauri::webview::PlatformWebview,+ _width: u64,+ _height: u64,+ slot: SnapshotSlot,+) {+ use webview2_com::Microsoft::Web::WebView2::Win32::COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_PNG;+ use webview2_com::CapturePreviewCompletedHandler;+ use windows::Win32::UI::Shell::SHCreateMemStream;++ let controller = platform.controller();+ let setup = (|| -> Result<(), String> {+ let webview = unsafe { controller.CoreWebView2() }+ .map_err(|e| format!("cannot reach CoreWebView2: {e}"))?;+ let stream = unsafe { SHCreateMemStream(None) }+ .ok_or_else(|| "failed to allocate capture stream".to_string())?;+ let cb_stream = stream.clone();+ let cb_slot = slot.clone();+ let handler = CapturePreviewCompletedHandler::create(Box::new(move |result| {+ let png = result+ .map_err(|e| format!("CapturePreview failed: {e}"))+ .and_then(|()| unsafe { read_stream(&cb_stream) });+ deliver(&cb_slot, png);+ Ok(())+ }));+ unsafe {+ webview.CapturePreview(+ COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_PNG,+ &stream,+ &handler,+ )+ }+ .map_err(|e| format!("CapturePreview call failed: {e}"))?;+ Ok(())+ })();+ if let Err(e) = setup {+ deliver(&slot, Err(e));+ }+}++/// Drain an in-memory `IStream` that WebView2 filled with PNG bytes.+#[cfg(target_os = "windows")]+unsafe fn read_stream(+ stream: &windows::Win32::System::Com::IStream,+) -> Result<Vec<u8>, String> {+ use windows::Win32::System::Com::{STATFLAG_NONAME, STATSTG, STREAM_SEEK_SET};++ stream+ .Seek(0, STREAM_SEEK_SET, None)+ .map_err(|e| format!("capture stream seek failed: {e}"))?;++ let mut stat = STATSTG::default();+ stream+ .Stat(&mut stat, STATFLAG_NONAME)+ .map_err(|e| format!("capture stream stat failed: {e}"))?;+ let size = stat.cbSize as usize;+ if size == 0 {+ return Err("capture stream is empty".to_string());+ }++ let mut buf = vec![0u8; size];+ let mut total = 0usize;+ while total < size {+ let mut read = 0u32;+ let remaining = (size - total) as u32;+ let hr = stream.Read(+ buf.as_mut_ptr().add(total) as *mut core::ffi::c_void,+ remaining,+ Some(&mut read),+ );+ hr.ok()+ .map_err(|e| format!("capture stream read failed: {e}"))?;+ if read == 0 {+ break;+ }+ total += read as usize;+ }+ buf.truncate(total);+ Ok(buf)+}