diff --git a/Cargo.lock b/Cargo.lock index 9df0f37..45f9abc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1001,6 +1001,7 @@ dependencies = [ "form_urlencoded", "idna", "percent-encoding", + "serde", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index b47e32e..21a3776 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,7 +45,7 @@ rusqlite = { version = "=0.31.0", features = ["bundled", "hooks"] } tungstenite = { version = "=0.21.0", default-features = false, features = ["handshake"] } # Keep the transitive URL parser compatible with the project's Rust 1.75 MSRV. # Newer url 2.5.x releases pull in edition-2024 IDNA crates. -url = "=2.4.1" +url = { version = "=2.4.1", features = ["serde"] } # Ratatui's compatible range otherwise resolves to a release requiring Rust 1.85. unicode-segmentation = "=1.12.0" vt100 = "=0.15.2" diff --git a/docs/work-view.md b/docs/work-view.md index 4ec9a8c..b9c0d6c 100644 --- a/docs/work-view.md +++ b/docs/work-view.md @@ -55,7 +55,30 @@ command globally. No BetterAgentView companion app or Hammerspoon is needed. This example uses **F8** (Fn+F8 on keyboards whose top row controls media). Choose another binding if you already use it. Press it while a browser or another app has focus: BetterAgentView switches in the background without typing into that app. -Press it again to switch back. It doesn't hide the other app or its windows. +Press it again to switch back. It leaves other apps and unmanaged browser tabs alone. If your dashboard uses a custom `XDG_STATE_HOME`, set the same value in the shortcut's shell command so both use the same saved mode. + +## Private HTML artifacts on macOS + +An OpenCode shell wrapper can pass local HTML or SVG artifact paths to + + betteragentview open-artifact -- /path/to/artifact.html + +Use the existing session environment, including `OPENCODE_SESSION_ID`. The command +looks up the originating project, not the artifact's output folder. If the +command prints `work`, continue with the usual open behavior. If it prints +`private`, BetterAgentView handled the open. If it fails, report the error rather +than opening the file in an unmanaged tab. Add `--background` before `--` to avoid +explicitly activating Chrome. + +Private artifacts open in their own Chrome windows. Work-only closes only the +tabs BetterAgentView created, and restores them from disk when you return to All +Sessions. An artifact requested during Work-only opens when you switch back. The +page reloads; live page state is not preserved. + +macOS may ask for permission to automate Google Chrome. Tabs opened outside the +wrapper, moved to other windows, navigated away, or restored by Chrome after a +restart are not tracked. Existing tabs at the same URL are untouched. This is +a screen presentation feature, not a way to hide browser history or erase files. diff --git a/src/adapters/opencode_db.rs b/src/adapters/opencode_db.rs index ad73e22..6fa9f13 100644 --- a/src/adapters/opencode_db.rs +++ b/src/adapters/opencode_db.rs @@ -17,6 +17,36 @@ use rusqlite::{Connection, OpenFlags, OptionalExtension}; use crate::perf; use crate::process::{CommandOutput, CommandRequest, CommandRunner}; +/// Use the originating session's directory, not shell cwd or artifact location. +#[cfg(target_os = "macos")] +pub(crate) fn artifact_session_directory(program: &str, id: &str) -> Result { + let runner = DirectDbRunner::new(Arc::new(crate::process::ProcessRunner), program.to_owned()); + let path = runner + .path() + .ok_or_else(|| anyhow!("OpenCode database not found"))?; + let db = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?; + db.busy_timeout(Duration::from_secs(1))?; + for (table, query) in [ + ("session_v2", "SELECT directory FROM session_v2 WHERE id=?1"), + ("session", "SELECT directory FROM session WHERE id=?1"), + ] { + let exists: bool = db.query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1)", + [table], + |row| row.get(0), + )?; + if exists { + if let Some(directory) = db + .query_row(query, [id], |row| row.get::<_, String>(0)) + .optional()? + { + return Ok(PathBuf::from(directory)); + } + } + } + bail!("originating OpenCode session was not found") +} + pub(super) struct DirectDbRunner { inner: Arc, program: String, diff --git a/src/lib.rs b/src/lib.rs index f502360..f3d17b8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,6 +27,8 @@ pub mod order; pub mod paused; pub mod perf_log; pub mod pi_supervisor; +#[cfg(target_os = "macos")] +pub mod private_artifacts; pub mod proc_info; pub mod process; pub mod queue; diff --git a/src/main.rs b/src/main.rs index cc71965..7e06582 100644 --- a/src/main.rs +++ b/src/main.rs @@ -84,6 +84,13 @@ enum Commands { #[arg(value_enum)] mode: ScopeMode, }, + /// Route a local OpenCode HTML or SVG artifact from a shell open wrapper. + #[cfg(target_os = "macos")] + OpenArtifact { + #[arg(long)] + background: bool, + path: PathBuf, + }, /// Private mobile history sync and queued replies. Disabled until explicitly paired. Bridge { #[arg(long, value_name = "PATH")] @@ -654,6 +661,16 @@ fn main() -> Result<()> { match command { Commands::View { mode } => { let store = agentview::work_view::WorkViewStore::load_default()?; + #[cfg(target_os = "macos")] + let enabled = agentview::private_artifacts::set_mode( + &store, + match mode { + ScopeMode::Toggle => None, + ScopeMode::Work => Some(true), + ScopeMode::All => Some(false), + }, + )?; + #[cfg(not(target_os = "macos"))] let enabled = match mode { ScopeMode::Toggle => store.toggle()?, ScopeMode::Work => { @@ -667,6 +684,18 @@ fn main() -> Result<()> { }; println!("{}", if enabled { "Work only" } else { "All sessions" }); } + #[cfg(target_os = "macos")] + Commands::OpenArtifact { background, path } => { + let session = std::env::var("OPENCODE_SESSION_ID") + .context("open-artifact needs the originating OPENCODE_SESSION_ID")?; + let handled = agentview::private_artifacts::open( + &cli.opencode_bin, + &session, + path, + !background, + )?; + println!("{}", if handled { "private" } else { "work" }); + } Commands::Bridge { state_dir, command } => { let dir = state_dir .clone() diff --git a/src/private_artifacts.applescript b/src/private_artifacts.applescript new file mode 100644 index 0000000..0c412ac --- /dev/null +++ b/src/private_artifacts.applescript @@ -0,0 +1,67 @@ +use framework "AppKit" +use scripting additions + +on launchIdentity() + set instances to current application's NSRunningApplication's runningApplicationsWithBundleIdentifier:"com.google.Chrome" + if (instances's |count|() as integer) is 0 then return "" + if (instances's |count|() as integer) is not 1 then error "More than one Chrome instance is running" + set browserApp to instances's firstObject() + return (browserApp's processIdentifier() as text) & ":" & ((browserApp's launchDate()'s timeIntervalSince1970()) as text) +end launchIdentity + +on run argv + set operation to item 1 of argv + set epoch to my launchIdentity() + if operation is "create" then + if epoch is "" then + tell application id "com.google.Chrome" to launch + set epoch to my launchIdentity() + if epoch is "" then error "Chrome did not start" + end if + tell application id "com.google.Chrome" + set ownedWindow to make new window + return epoch & " " & (id of ownedWindow) & " " & (id of active tab of ownedWindow) + end tell + end if + if epoch is "" or epoch is not (item 2 of argv) then return "gone" + set windowKey to item 3 of argv + set tabKey to item 4 of argv + set expectedURL to item 5 of argv + set bringForward to (item 6 of argv) is "yes" + tell application id "com.google.Chrome" + try + set ownedWindow to window id windowKey + if (mode of ownedWindow) is not "normal" then return "gone" + set ownedTab to tab id tabKey of ownedWindow + set actualURL to URL of ownedTab + on error messageText number errorCode + if errorCode is -1728 or errorCode is -1719 then return "gone" + error messageText number errorCode + end try + if epoch is not (my launchIdentity()) then return "gone" + set isEmptyTab to (actualURL is "chrome://newtab/" or actualURL is "about:blank" or actualURL is "") + considering case + set sameURL to actualURL is expectedURL + end considering + if operation is "navigate" or operation is "reload" then + if operation is "reload" and sameURL then + reload ownedTab + else if operation is "navigate" and isEmptyTab then + set URL of ownedTab to expectedURL + else + return "gone" + end if + if bringForward then + if (count of tabs of ownedWindow) is 1 then set index of ownedWindow to 1 + activate + end if + else if operation is "close" then + if not sameURL then return "gone" + close ownedTab + if exists (tab id tabKey of window id windowKey) then error "Chrome did not close the private tab" + else + error "Unknown artifact operation" + end if + return "ok" + end tell +end run diff --git a/src/private_artifacts.rs b/src/private_artifacts.rs new file mode 100644 index 0000000..6493862 --- /dev/null +++ b/src/private_artifacts.rs @@ -0,0 +1,380 @@ +//! Local macOS presentation only. Never enumerates Chrome tabs or adopts one. +use crate::process::{CommandRequest, CommandRunner, ProcessRunner}; +use crate::work_view::{WorkRoots, WorkViewStore}; +use anyhow::{bail, Context, Result}; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; +use std::time::Duration; +use url::Url; + +#[derive(Clone, Debug, Deserialize, Serialize)] +struct Tab { + launch: String, + window: String, + id: String, +} + +#[derive(Deserialize, Serialize)] +struct Artifact { + session: String, + url: Url, + tab: Option, // None means defer the next open until All Sessions. +} + +struct Registry { + path: PathBuf, + entries: Vec, +} + +trait Browser { + fn create(&self) -> Result; + fn open(&self, tab: &Tab, url: &Url, foreground: bool, new_tab: bool) -> Result; + fn close(&self, tab: &Tab, url: &Url) -> Result; +} + +struct Chrome; + +impl Chrome { + fn run(&self, action: &str, args: &[&str]) -> Result { + let mut request = CommandRequest::new( + "/usr/bin/osascript", + [ + "-e", + include_str!("private_artifacts.applescript"), + "--", + action, + ] + .into_iter() + .chain(args.iter().copied()) + .map(str::to_owned) + .collect(), + ); + request.timeout = Duration::from_secs(8); + let output = ProcessRunner + .run(&request) + .context("Chrome Automation failed")?; + if output.status != 0 { + bail!("Chrome Automation failed: {}", output.stderr_lossy()); + } + Ok(output.stdout_text()?.trim().to_owned()) + } + + fn act(&self, action: &str, tab: &Tab, url: &Url, foreground: bool) -> Result { + let flag = if foreground { "yes" } else { "no" }; + match self + .run( + action, + &[&tab.launch, &tab.window, &tab.id, url.as_str(), flag], + )? + .as_str() + { + "ok" => Ok(true), + "gone" => Ok(false), + _ => bail!("unexpected Chrome Automation reply"), + } + } +} + +impl Browser for Chrome { + fn create(&self) -> Result { + let reply = self.run("create", &[])?; + let fields: Vec<_> = reply.split_whitespace().collect(); + let [launch, window, id] = fields.as_slice() else { + bail!("Chrome did not return the managed tab identity"); + }; + Ok(Tab { + launch: (*launch).into(), + window: (*window).into(), + id: (*id).into(), + }) + } + + fn open(&self, tab: &Tab, url: &Url, foreground: bool, new_tab: bool) -> Result { + self.act( + if new_tab { "navigate" } else { "reload" }, + tab, + url, + foreground, + ) + } + + fn close(&self, tab: &Tab, url: &Url) -> Result { + self.act("close", tab, url, false) + } +} + +impl Registry { + fn load(store: &WorkViewStore) -> Result { + let path = store.0.with_file_name("private-artifacts.json"); + let entries = match std::fs::read(&path) { + Ok(bytes) => { + serde_json::from_slice(&bytes).context("invalid private artifact registry")? + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(), + Err(error) => return Err(error.into()), + }; + Ok(Self { path, entries }) + } + + fn save(&self) -> Result<()> { + crate::fs_util::write_private_json(&self.path, &self.entries) + } + + fn request( + &mut self, + browser: &impl Browser, + session: &str, + url: Url, + work_only: bool, + foreground: bool, + ) -> Result<()> { + let index = match self + .entries + .iter() + .position(|entry| entry.session == session && entry.url == url) + { + Some(index) => index, + None => { + self.entries.push(Artifact { + session: session.to_owned(), + url, + tab: None, + }); + self.save()?; + self.entries.len() - 1 + } + }; + if work_only { + // A prior failed toggle may have left a live tab. Retry that close. + if let Some(tab) = &self.entries[index].tab { + browser.close(tab, &self.entries[index].url)?; + self.entries[index].tab = None; + self.save()?; + } + return Ok(()); + } + self.show(browser, index, foreground) + } + + fn show(&mut self, browser: &impl Browser, index: usize, foreground: bool) -> Result<()> { + let entry = &self.entries[index]; + if let Some(tab) = &entry.tab { + if browser.open(tab, &entry.url, foreground, false)? { + return Ok(()); + } + } + // Persist ownership before exposing the file in Chrome. If the write + // fails, the new tab stays blank and no private page can escape tracking. + let tab = browser.create()?; + self.entries[index].tab = Some(tab.clone()); + self.save()?; + if !browser.open(&tab, &self.entries[index].url, foreground, true)? { + self.entries[index].tab = None; + self.save()?; + bail!("the new Chrome tab disappeared before the artifact opened"); + } + Ok(()) + } + + fn apply(&mut self, browser: &impl Browser, work_only: bool) -> Result<()> { + let mut first_error = None; + let mut index = 0; + while index < self.entries.len() { + let entry = &self.entries[index]; + let result = match (work_only, &entry.tab) { + (true, Some(tab)) => match browser.close(tab, &entry.url) { + Ok(true) => { + self.entries[index].tab = None; + self.save() + } + Ok(false) => { + // Already closed, navigated away, or from a past Chrome + // launch. Toggling back should not resurrect that tab. + self.entries.remove(index); + self.save()?; + continue; + } + Err(error) => Err(error), + }, + (false, None) => self.show(browser, index, false), + _ => Ok(()), + }; + if let Err(error) = result { + first_error.get_or_insert(error); + } + index += 1; + } + first_error.map_or(Ok(()), Err) + } +} + +fn local_url(path: &Path) -> Result { + let path = path + .canonicalize() + .context("artifact file does not exist")?; + if !path.is_file() + || !path + .extension() + .and_then(|ext| ext.to_str()) + .is_some_and(|ext| { + ["html", "htm", "svg"] + .iter() + .any(|allowed| ext.eq_ignore_ascii_case(allowed)) + }) + { + bail!("expected a local HTML or SVG file"); + } + Url::from_file_path(path).map_err(|_| anyhow::anyhow!("invalid local artifact path")) +} + +/// Return false to let the caller's existing open behavior handle work files. +pub fn open(opencode: &str, session: &str, path: &Path, foreground: bool) -> Result { + let directory = crate::adapters::opencode_db::artifact_session_directory(opencode, session)?; + if WorkRoots::load_default()?.contains(&directory) { + return Ok(false); + } + let url = local_url(path)?; + let store = WorkViewStore::load_default()?; + store.with_lock(|| { + Registry::load(&store)?.request(&Chrome, session, url, store.read()?, foreground) + })?; + Ok(true) +} + +/// Serialize global mode changes with opening private artifacts, so an open +/// racing the toggle is either closed by it or never shown in the first place. +pub fn set_mode(store: &WorkViewStore, requested: Option) -> Result { + store.with_lock(|| { + let enabled = match requested { + Some(enabled) => enabled, + None => !store.read()?, + }; + store.set(enabled)?; + Registry::load(store)?.apply(&Chrome, enabled).context( + "desktop mode changed, but Chrome artifacts did not all update; rerun 'view work' or 'view all' to retry", + )?; + Ok(enabled) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::{Cell, RefCell}; + use std::collections::BTreeMap; + + #[derive(Default)] + struct FakeChrome { + sequence: Cell, + tabs: RefCell>>, + blocked: Cell, + } + + impl Browser for FakeChrome { + fn create(&self) -> Result { + self.sequence.set(self.sequence.get() + 1); + let id = self.sequence.get().to_string(); + self.tabs.borrow_mut().insert(id.clone(), None); + Ok(Tab { + launch: "launch".into(), + window: id.clone(), + id, + }) + } + + fn open(&self, tab: &Tab, url: &Url, _foreground: bool, new_tab: bool) -> Result { + let mut tabs = self.tabs.borrow_mut(); + let Some(current) = tabs.get_mut(&tab.id) else { + return Ok(false); + }; + if !(current.as_ref() == Some(url) || new_tab && current.is_none()) { + return Ok(false); + } + *current = Some(url.clone()); + Ok(true) + } + + fn close(&self, tab: &Tab, url: &Url) -> Result { + if self.blocked.get() { + bail!("Automation refused"); + } + let mut tabs = self.tabs.borrow_mut(); + if tabs.get(&tab.id) != Some(&Some(url.clone())) { + return Ok(false); + } + tabs.remove(&tab.id); + Ok(true) + } + } + + #[test] + fn defers_dedupes_and_restores_without_touching_unrelated_tabs() { + let dir = tempfile::tempdir().unwrap(); + let store = WorkViewStore(dir.path().join("work.json")); + let path = dir.path().join("My #1?.HtMl"); + std::fs::write(&path, "synthetic").unwrap(); + let url = local_url(&path).unwrap(); + assert!(url.as_str().ends_with("My%20%231%3F.HtMl")); + let browser = FakeChrome::default(); + browser + .tabs + .borrow_mut() + .insert("unrelated".into(), Some(url.clone())); + + let mut registry = Registry::load(&store).unwrap(); + registry + .request(&browser, "ses_private", url.clone(), true, true) + .unwrap(); + registry + .request(&browser, "ses_private", url.clone(), true, true) + .unwrap(); + assert_eq!(browser.sequence.get(), 0); + let mut registry = Registry::load(&store).unwrap(); + registry.apply(&browser, false).unwrap(); + registry + .request(&browser, "ses_private", url.clone(), false, true) + .unwrap(); + assert_eq!(browser.sequence.get(), 1); + + browser.blocked.set(true); + assert!(registry.apply(&browser, true).is_err()); + assert!(Registry::load(&store).unwrap().entries[0].tab.is_some()); + browser.blocked.set(false); + registry.apply(&browser, true).unwrap(); + assert_eq!( + *browser.tabs.borrow(), + BTreeMap::from([("unrelated".into(), Some(url))]) + ); + registry.apply(&browser, false).unwrap(); + assert_eq!(browser.tabs.borrow().len(), 2); + assert_eq!(browser.sequence.get(), 2); + } + + #[test] + fn does_not_reopen_tabs_that_were_navigated_away_or_manually_closed() { + let dir = tempfile::tempdir().unwrap(); + let store = WorkViewStore(dir.path().join("work.json")); + let mut registry = Registry::load(&store).unwrap(); + let browser = FakeChrome::default(); + let url = Url::parse("file:///private.html").unwrap(); + registry + .request(&browser, "ses_one", url.clone(), false, false) + .unwrap(); + registry + .request(&browser, "ses_two", url, false, false) + .unwrap(); + let unrelated = Url::parse("https://example.invalid").unwrap(); + browser + .tabs + .borrow_mut() + .insert("1".into(), Some(unrelated.clone())); + browser.tabs.borrow_mut().remove("2"); + registry.apply(&browser, true).unwrap(); + registry.apply(&browser, false).unwrap(); + assert!(registry.entries.is_empty()); + assert_eq!( + *browser.tabs.borrow(), + BTreeMap::from([("1".into(), Some(unrelated))]) + ); + } +} diff --git a/src/work_view.rs b/src/work_view.rs index f6ecde2..25b3621 100644 --- a/src/work_view.rs +++ b/src/work_view.rs @@ -44,6 +44,14 @@ impl WorkViewStore { /// Serialize concurrent global-hotkey invocations on Unix. The lock is /// released by the kernel even if a caller crashes. pub fn toggle(&self) -> Result { + self.with_lock(|| { + let enabled = !self.read()?; + self.set(enabled)?; + Ok(enabled) + }) + } + + pub fn with_lock(&self, action: impl FnOnce() -> Result) -> Result { let parent = self.0.parent().context("state path has no parent")?; if !parent.exists() { fs::create_dir_all(parent)?; @@ -68,10 +76,9 @@ impl WorkViewStore { return Err(std::io::Error::last_os_error().into()); } } - let enabled = !self.read()?; - self.set(enabled)?; + let result = action(); drop(lock); - Ok(enabled) + result } pub fn watch_native(&self, enabled: bool) { diff --git a/tests/private_artifact_open.rs b/tests/private_artifact_open.rs new file mode 100644 index 0000000..5b70c1d --- /dev/null +++ b/tests/private_artifact_open.rs @@ -0,0 +1,92 @@ +#![cfg(target_os = "macos")] + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::process::Command; + +#[test] +fn wrapper_classifies_origin_not_artifact_path_and_defers_private_opens() { + let fixture = tempfile::tempdir().unwrap(); + let work = fixture.path().join("work"); + let private = fixture.path().join("private"); + fs::create_dir(&work).unwrap(); + fs::create_dir(&private).unwrap(); + let config = fixture.path().join("config"); + let state = fixture.path().join("state"); + fs::create_dir_all(config.join("agentview")).unwrap(); + fs::write( + config.join("agentview/work-roots.json"), + serde_json::json!({"roots": [&work]}).to_string(), + ) + .unwrap(); + let db_path = fixture.path().join("history.db"); + let db = rusqlite::Connection::open(&db_path).unwrap(); + db.execute_batch("CREATE TABLE session_v2 (id TEXT PRIMARY KEY, directory TEXT NOT NULL);") + .unwrap(); + for (id, directory) in [("ses_work", &work), ("ses_private", &private)] { + db.execute( + "INSERT INTO session_v2 VALUES (?1, ?2)", + [id, directory.to_str().unwrap()], + ) + .unwrap(); + } + let opencode = fixture.path().join("opencode"); + fs::write( + &opencode, + r#"#!/bin/sh +[ "$1 $2 $3" = 'debug paths db' ] || exit 2 +echo "$FIXTURE_DB" +"#, + ) + .unwrap(); + fs::set_permissions(&opencode, fs::Permissions::from_mode(0o700)).unwrap(); + + let cli = || { + let mut command = Command::new(env!("CARGO_BIN_EXE_betteragentview")); + command + .env("XDG_CONFIG_HOME", &config) + .env("XDG_STATE_HOME", &state) + .env("XDG_CACHE_HOME", fixture.path().join("cache")) + .env("FIXTURE_DB", &db_path) + .args(["--opencode-bin", opencode.to_str().unwrap()]); + command + }; + assert!(cli() + .args(["view", "work"]) + .output() + .unwrap() + .status + .success()); + // A shared output folder need not be under either project's directory. + let artifact = fixture.path().join("example #1.html"); + fs::write(&artifact, "synthetic").unwrap(); + let open = |session| { + cli() + .env("OPENCODE_SESSION_ID", session) + .args(["open-artifact", "--", artifact.to_str().unwrap()]) + .output() + .unwrap() + }; + let route = |session| { + let output = open(session); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap().trim().to_owned() + }; + let registry = state.join("agentview/private-artifacts.json"); + assert_eq!(route("ses_work"), "work"); + assert!(!registry.exists()); + assert!(!open("ses_unknown").status.success()); + assert!(!registry.exists()); + assert_eq!(route("ses_private"), "private"); + let entries: serde_json::Value = serde_json::from_slice(&fs::read(registry).unwrap()).unwrap(); + assert_eq!(entries[0]["session"], "ses_private"); + assert!(entries[0]["tab"].is_null()); + assert!(entries[0]["url"] + .as_str() + .unwrap() + .ends_with("example%20%231.html")); +}