AI-native design editor. Open-source Figma alternative.
refactor(desktop): group the shell's modules by domain (#1420)
Danila Poyarkovab2875cc761e
diff --git a/desktop/AGENTS.md b/desktop/AGENTS.mdindex 072176764..d098ff6d6 100644--- a/desktop/AGENTS.md+++ b/desktop/AGENTS.md@@ -11,9 +11,9 @@ Check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.j- The Software Update window is a second webview labelled `updater` that loads `updater.html` (`src/updater.ts`), never the editor's `index.html`; its own capability, `desktop/capabilities/updater.json`, grants only checking, installing, restarting, closing, and opening links. It owns no documents, so before a restart or a Windows install it asks the editor window over `updater:restart-request` to run the Quit approval (`src/app/shell/updater/approvals.ts`, `tests/app/shell/updater/session.test.ts`).- Never click Install in a `tauri dev` build: the updater unpacks the release next to the running binary, which there is `desktop/target/debug`.- `desktop/generated/menu.json` is produced by `bun run generate:tauri-menu` from `src/app/shell/menu/schema.ts`; do not edit or import it directly.-- A menu entry with a `feature` in the schema is built only while the frontend names that feature through `set_native_menu_features` (`src/app/shell/menu/features.ts`); every rebuild keeps the check states the menu had (`desktop/src/menu.rs`).+- A menu entry with a `feature` in the schema is built only while the frontend names that feature through `set_native_menu_features` (`src/app/shell/menu/features.ts`); every rebuild keeps the check states the menu had (`desktop/src/menu/mod.rs`).- Run `bun run generate:icons --target desktop` before direct Cargo checks; native icons are generated, not committed.- `build_fig_file` performs full `.fig` export on desktop at the level it is given, on a blocking thread, since high levels take seconds; saves that patch an opened archive compress in the web worker (`packages/fig/AGENTS.md`).- The embedded WebDriver plugin compiles only with the `native-test` Cargo feature and must never be enabled in development or production binaries. Native tests use `bun run test:native` (`tests/AGENTS.md`).-- The editor opens external links through the `open_external_url` command, which allows only `http`, `https`, and `mailto`; native-test builds record them for `take_native_test_opened_urls` instead of launching a browser (`opener` unit tests, `tests/e2e/native/cloud-links.spec.ts`).-- `openpencil://` links are parsed in `desktop/src/deep_link.rs`: `open` queues files through `take_pending_open`, `join` queues validated room IDs through `take_pending_rooms`, `cloud` queues Cloud invitations and shared links (UUID, hex secret, `http(s)` server) through `take_pending_cloud_links`; second launches forward their link arguments through the single-instance handler (`deep_link` unit tests).+- The editor opens external links through the `open_external_url` command, which allows only `http`, `https`, and `mailto`; native-test builds record them for `take_native_test_opened_urls` instead of launching a browser (`system::opener` unit tests, `tests/e2e/native/cloud-links.spec.ts`).+- `openpencil://` links are parsed in `desktop/src/launch/links.rs` and queued in `desktop/src/launch/mod.rs`: `open` queues files through `take_pending_open`, `join` queues validated room IDs through `take_pending_rooms`, `cloud` queues Cloud invitations and shared links (UUID, hex secret, `http(s)` server) through `take_pending_cloud_links`; second launches forward their link arguments through the single-instance handler (`launch::links` unit tests).diff --git a/desktop/Cargo.lock b/desktop/Cargo.lockindex 26e9d0547..74730a91d 100644--- a/desktop/Cargo.lock+++ b/desktop/Cargo.lock@@ -3258,11 +3258,13 @@ version = "0.16.0"dependencies = ["fix-path-env","fontique",+ "httparse","keyring","objc2-core-foundation","objc2-core-text","reqwest 0.12.28","security-framework",+ "semver","serde","serde_json","tauri",diff --git a/desktop/Cargo.toml b/desktop/Cargo.tomlindex cfaf7f169..9aef8d867 100644--- a/desktop/Cargo.toml+++ b/desktop/Cargo.toml@@ -35,6 +35,7 @@ tauri-plugin-shell = "2"zstd = "0.13"zip = { version = "2", default-features = false }which = "7.0.3"+semver = "1"fontique = "0.11"fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs", branch = "dev" }tauri-plugin-updater = "2"@@ -44,6 +45,7 @@ tauri-plugin-clipboard-manager = "2"tauri-plugin-deep-link = "2"keyring = "4.1.5"url = "2"+httparse = "1"tauri-plugin-wdio-webdriver = { version = "1.3.0", optional = true }[target.'cfg(target_os = "macos")'.dependencies]diff --git a/desktop/src/agents.rs b/desktop/src/agents/lookup.rssimilarity index 96%rename from desktop/src/agents.rsrename to desktop/src/agents/lookup.rsindex 0a86f29e2..887884e7c 100644--- a/desktop/src/agents.rs+++ b/desktop/src/agents/lookup.rs@@ -43,12 +43,7 @@ const VERSION_TIMEOUT: Duration = Duration::from_secs(5);/// The version line a companion prints for `--version`, or `None` for anything else.fn parse_version(output: &str) -> Option<String> {let line = output.lines().next()?.trim();- let mut core = line.split(['-', '+']).next()?.split('.');- let numeric = (0..3).all(|_| {- core.next()- .is_some_and(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))- });- (numeric && core.next().is_none()).then(|| line.to_owned())+ semver::Version::parse(line).ok().map(|_| line.to_owned())}/// Asks one of OpenPencil's own companions for its version. Asking the program reports what@@ -185,7 +180,7 @@ fn lookup_with(pub async fn agent_lookup() -> Result<AgentLookup, String> {tauri::async_runtime::spawn_blocking(|| {let current = std::env::var("PATH").unwrap_or_default();- let search_path = crate::augment_path(¤t, &crate::mcp_candidate_dirs());+ let search_path = super::path::augment_path(¤t, &super::path::candidate_dirs());let cwd = std::env::current_dir().unwrap_or_else(|_| Path::new("/").to_path_buf());lookup_with(search_path.clone(),diff --git a/desktop/src/agents/mcp.rs b/desktop/src/agents/mcp.rsnew file mode 100644index 000000000..9a56413bd--- /dev/null+++ b/desktop/src/agents/mcp.rs@@ -0,0 +1,42 @@+//! Finding the OpenPencil MCP server that agents connect to.++use super::path::search_dirs;++/// Name of the MCP entry point installed by `@open-pencil/mcp`.+const MCP_EXECUTABLE: &str = "openpencil-mcp-http";+/// Bound on the directories reported back to the settings diagnostics.+const MAX_REPORTED_SEARCH_DIRS: usize = 12;++fn push_unique_dir(dirs: &mut Vec<String>, dir: String) {+ if !dirs.contains(&dir) {+ dirs.push(dir);+ }+}++#[derive(serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct McpLookup {+ available: bool,+ path: Option<String>,+ /// Existing directories that were searched, for diagnostics.+ searched: Vec<String>,+}++#[tauri::command]+pub fn mcp_lookup() -> McpLookup {+ let resolved = which::which(MCP_EXECUTABLE).ok();+ let path = resolved.as_ref().map(|p| p.display().to_string());+ let mut searched: Vec<String> = Vec::new();+ if let Some(dir) = resolved.as_ref().and_then(|p| p.parent()) {+ push_unique_dir(&mut searched, dir.display().to_string());+ }+ for dir in search_dirs() {+ push_unique_dir(&mut searched, dir.display().to_string());+ }+ searched.truncate(MAX_REPORTED_SEARCH_DIRS);+ McpLookup {+ available: resolved.is_some(),+ path,+ searched,+ }+}diff --git a/desktop/src/agents/mod.rs b/desktop/src/agents/mod.rsnew file mode 100644index 000000000..ad01953b0--- /dev/null+++ b/desktop/src/agents/mod.rs@@ -0,0 +1,5 @@+//! Coding agents, their companions, and the MCP server they reach OpenPencil through.++pub mod lookup;+pub mod mcp;+pub mod path;diff --git a/desktop/src/agents/path.rs b/desktop/src/agents/path.rsnew file mode 100644index 000000000..0d5ddeb20--- /dev/null+++ b/desktop/src/agents/path.rs@@ -0,0 +1,122 @@+//! The `PATH` agents and companions are found and started with.++use std::path::PathBuf;++/// Directories that commonly hold a globally installed Node/Bun CLI.+///+/// GUI launches inherit launchd's minimal `PATH`, so a package installed by+/// npm, Bun, Volta, or Homebrew can be invisible even though the user's shell+/// finds it. `fix_path_env::fix()` reads the login shell first; these entries+/// cover managers that only modify an interactive rc file.+pub fn candidate_dirs() -> Vec<PathBuf> {+ let mut dirs: Vec<PathBuf> = Vec::new();+ // Bun, Volta, and npm keep their Windows folders under USERPROFILE, which `home_dir` reads+ // there instead of a HOME set by Unix-style tools.+ if let Some(home) = std::env::home_dir() {+ dirs.push(home.join(".bun/bin"));+ dirs.push(home.join(".local/bin"));+ dirs.push(home.join(".npm-global/bin"));+ dirs.push(home.join(".volta/bin"));+ dirs.push(home.join("n/bin"));+ dirs.push(home.join(".local/share/mise/shims"));+ }+ #[cfg(target_os = "macos")]+ {+ dirs.push(PathBuf::from("/opt/homebrew/bin"));+ dirs.push(PathBuf::from("/usr/local/bin"));+ dirs.push(PathBuf::from("/opt/local/bin"));+ }+ #[cfg(target_os = "linux")]+ {+ dirs.push(PathBuf::from("/usr/local/bin"));+ dirs.push(PathBuf::from("/home/linuxbrew/.linuxbrew/bin"));+ }+ #[cfg(windows)]+ {+ if let Some(appdata) = std::env::var_os("APPDATA").map(PathBuf::from) {+ dirs.push(appdata.join("npm"));+ }+ }+ dirs+}++/// Existing candidate directories, most specific first, for diagnostics.+pub fn search_dirs() -> Vec<PathBuf> {+ candidate_dirs()+ .into_iter()+ .filter(|dir| dir.is_dir())+ .collect()+}++/// Append candidate directories that the current process `PATH` is missing.+pub fn augment_path(path: &str, candidates: &[PathBuf]) -> String {+ let mut entries: Vec<PathBuf> = std::env::split_paths(path).collect();+ for candidate in candidates {+ if candidate.is_dir() && !entries.contains(candidate) {+ entries.push(candidate.clone());+ }+ }+ std::env::join_paths(entries)+ .map(|joined| joined.to_string_lossy().into_owned())+ .unwrap_or_else(|_| path.to_string())+}++/// Make globally installed CLIs visible to `which` and to spawned children.+pub fn augment_process_path() {+ let current = std::env::var("PATH").unwrap_or_default();+ let next = augment_path(¤t, &candidate_dirs());+ if next != current {+ std::env::set_var("PATH", next);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn augment_path_appends_missing_candidates_once() {+ let current_dir = std::env::temp_dir();+ let appended_dir = std::env::temp_dir().join("open-pencil-appended");+ std::fs::create_dir_all(&appended_dir).expect("create candidate dir");++ let current =+ std::env::join_paths([PathBuf::from("/open-pencil-first"), current_dir.clone()])+ .expect("join path list");+ let candidates = vec![current_dir.clone(), appended_dir.clone()];+ let entries: Vec<PathBuf> =+ std::env::split_paths(&augment_path(¤t.to_string_lossy(), &candidates)).collect();++ // Existing entries keep their order and the missing candidate is+ // appended once, at the end.+ assert_eq!(+ entries,+ vec![+ PathBuf::from("/open-pencil-first"),+ current_dir,+ appended_dir.clone(),+ ]+ );++ let _ = std::fs::remove_dir(&appended_dir);+ }++ #[test]+ fn augment_path_ignores_candidates_that_do_not_exist() {+ let current =+ std::env::join_paths([PathBuf::from("/open-pencil-only")]).expect("join path list");+ let augmented = augment_path(+ ¤t.to_string_lossy(),+ &[PathBuf::from("/open-pencil-nonexistent")],+ );++ assert!(!augmented.contains("nonexistent"));+ }++ #[test]+ fn augment_path_keeps_an_existing_path_when_nothing_changes() {+ let current = std::env::var("PATH").unwrap_or_default();+ let augmented = augment_path(¤t, &[]);+ assert_eq!(augmented, current);+ }+}diff --git a/desktop/src/fig_container.rs b/desktop/src/files/fig.rssimilarity index 100%rename from desktop/src/fig_container.rsrename to desktop/src/files/fig.rsdiff --git a/desktop/src/files/mod.rs b/desktop/src/files/mod.rsnew file mode 100644index 000000000..1eecec248--- /dev/null+++ b/desktop/src/files/mod.rs@@ -0,0 +1,4 @@+//! Documents on disk: `.fig` export and the recent files list.++pub mod fig;+pub mod recent;diff --git a/desktop/src/files/recent.rs b/desktop/src/files/recent.rsnew file mode 100644index 000000000..280b8e4ad--- /dev/null+++ b/desktop/src/files/recent.rs@@ -0,0 +1,8 @@+//! The recent files the native menu lists.++use crate::menu::update_app_menu;++#[tauri::command]+pub fn set_recent_files(app: tauri::AppHandle, paths: Vec<String>) -> Result<(), String> {+ update_app_menu(&app, |inputs| inputs.recent_files = paths)+}diff --git a/desktop/src/launch/args.rs b/desktop/src/launch/args.rsnew file mode 100644index 000000000..1d6bba5be--- /dev/null+++ b/desktop/src/launch/args.rs@@ -0,0 +1,56 @@+//! Documents and links a launch names in its arguments.++use std::path::{Path, PathBuf};++pub fn file_association_path(path: PathBuf) -> Option<PathBuf> {+ let path = path.canonicalize().ok()?;+ if !path.is_file() {+ return None;+ }+ let ext = path.extension()?.to_string_lossy().to_lowercase();+ matches!(ext.as_str(), "fig" | "pen").then_some(path)+}++fn path_from_arg(arg: String, cwd: &Path) -> Option<PathBuf> {+ if arg.starts_with('-') {+ return None;+ }++ if let Ok(url) = tauri::Url::parse(&arg) {+ if let Ok(path) = url.to_file_path() {+ return Some(path);+ }+ }++ let path = PathBuf::from(arg);+ Some(if path.is_absolute() {+ path+ } else {+ cwd.join(path)+ })+}++pub fn open_paths_from_args(args: Vec<String>, cwd: &Path) -> Vec<PathBuf> {+ args.into_iter()+ .filter_map(|arg| path_from_arg(arg, cwd))+ .filter_map(file_association_path)+ .collect()+}++/// `openpencil://` URLs among a second launch's arguments: Windows and Linux start a new+/// process for a link, and the single-instance plugin hands its arguments to this one.+#[cfg(all(+ any(target_os = "macos", windows, target_os = "linux"),+ not(feature = "native-test")+))]+pub fn deep_links_from_args(args: &[String]) -> Vec<url::Url> {+ args.iter()+ .filter(|arg| arg.starts_with("openpencil://"))+ .filter_map(|arg| url::Url::parse(arg).ok())+ .collect()+}++pub fn startup_open_paths() -> Vec<PathBuf> {+ let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));+ open_paths_from_args(std::env::args().skip(1).collect(), &cwd)+}diff --git a/desktop/src/deep_link.rs b/desktop/src/launch/links.rssimilarity index 60%rename from desktop/src/deep_link.rsrename to desktop/src/launch/links.rsindex 62580cb58..aa8c55449 100644--- a/desktop/src/deep_link.rs+++ b/desktop/src/launch/links.rs@@ -1,4 +1,4 @@-use std::path::{Component, Path, PathBuf};+//! Parsing `openpencil://` links into what the app should open, join, or hand to sign-in.use url::Url;@@ -182,7 +182,7 @@ pub fn parse_open_url(url: &Url) -> Result<DeepLinkOpen, DeepLinkError> {if file.starts_with('/') || file.starts_with('\\') || is_windows_abs {return Err(DeepLinkError::AbsolutePath);}- // `.` is refused here as well as in `path_ends_with_segments`: a link that carried one+ // `.` is refused here as well as in `paths::path_ends_with_segments`: a link that carried one// would be queued and then could never match an open tab or a picked file.if file.split(['/', '\\']).any(|seg| seg == ".." || seg == ".") {return Err(DeepLinkError::ParentSegment);@@ -197,77 +197,6 @@ pub fn parse_open_url(url: &Url) -> Result<DeepLinkOpen, DeepLinkError> {})}-/// Whether `candidate` ends with `suffix` as a whole sequence of path segments.-///-/// The link carries a repository-relative path, the candidate is an absolute path-/// from an open tab or the file picker, and the two may disagree on case: on-/// macOS and Windows the default filesystem is case-insensitive, so `Web/Design`-/// and `web/design` name the same file and a case-sensitive comparison would-/// cancel a link that points at an already open document.-///-/// The rule is per-platform, not per-volume: ASCII-case-insensitive on macOS and-/// Windows, exact on Linux. Deliberately ASCII only — macOS folds the full Unicode-/// case table, matching that here would mean carrying a Unicode fold for a gain-/// nobody links against. A case-sensitive APFS volume is likewise not probed;-/// the cost of being wrong there is a link that focuses a same-named file in a-/// different directory case. Nothing is read and nothing is opened here: the command-/// resolves and compares path strings, never file contents.-///-/// `candidate` is canonicalized so a `..`-laden or symlink-prefixed tab path still-/// compares by its real segments, and the literal path is tried as well: a symlink-/// *inside* the trailing segments (a monorepo `packages/web -> ../apps/web`) makes-/// the two disagree, and the link should match either spelling. A candidate that-/// cannot be canonicalized at all — the file moved, or the volume went away — is-/// compared by its literal segments alone rather than failing the match.-///-/// `async` so `canonicalize` runs off the main thread: it hits the filesystem, and a-/// stale network mount can block for as long as its timeout.-#[tauri::command(async)]-pub fn path_matches_suffix(candidate: String, suffix: String) -> bool {- let literal = PathBuf::from(&candidate);- let canonical = literal.canonicalize().unwrap_or_else(|_| literal.clone());- path_ends_with_segments(&canonical, &suffix) || path_ends_with_segments(&literal, &suffix)-}--fn segment_eq(left: &str, right: &str) -> bool {- if cfg!(any(target_os = "macos", windows)) {- left.eq_ignore_ascii_case(right)- } else {- left == right- }-}--/// A suffix is a *relative* trailing path. `parse_open_url` already refuses an absolute-/// or `..`-bearing `file`, but this is the comparison every caller funnels through, so it-/// refuses them again rather than trusting its caller: an absolute suffix would otherwise-/// match on its segments alone, turning `/etc/hikyo.pen` into a relative lookup.-fn path_ends_with_segments(candidate: &Path, suffix: &str) -> bool {- if suffix.starts_with('/') || suffix.starts_with('\\') || Path::new(suffix).is_absolute() {- return false;- }- let wanted: Vec<&str> = suffix- .split(['/', '\\'])- .filter(|s| !s.is_empty())- .collect();- if wanted.is_empty() || wanted.iter().any(|seg| *seg == ".." || *seg == ".") {- return false;- }- let actual: Vec<String> = candidate- .components()- .filter_map(|component| match component {- Component::Normal(part) => Some(part.to_string_lossy().into_owned()),- _ => None,- })- .collect();- if actual.len() < wanted.len() {- return false;- }- actual[actual.len() - wanted.len()..]- .iter()- .zip(&wanted)- .all(|(have, want)| segment_eq(have, want))-}-#[cfg(test)]mod tests {use super::*;@@ -468,138 +397,4 @@ mod tests {);assert!(parse("openpencil://open?file=a.fig").is_ok());}-- #[test]- fn suffix_matches_whole_trailing_segments() {- assert!(path_ends_with_segments(- Path::new("/r/hikyo/web/design/hikyo.pen"),- "web/design/hikyo.pen"- ));- // A partial segment is not a segment: `redesign` must not satisfy `design`.- assert!(!path_ends_with_segments(- Path::new("/r/redesign/hikyo.pen"),- "design/hikyo.pen"- ));- // A suffix longer than the path cannot match.- assert!(!path_ends_with_segments(- Path::new("/hikyo.pen"),- "design/hikyo.pen"- ));- assert!(!path_ends_with_segments(Path::new("/r/hikyo.pen"), ""));- }-- #[test]- fn suffix_case_rule_follows_the_platform() {- let folded = path_ends_with_segments(- Path::new("/r/hikyo/Web/Design/Hikyo.pen"),- "web/design/hikyo.pen",- );- assert_eq!(folded, cfg!(any(target_os = "macos", windows)));- }-- #[test]- fn suffix_accepts_backslash_separators() {- assert!(path_ends_with_segments(- Path::new("/r/web/design/hikyo.pen"),- "web\\design\\hikyo.pen"- ));- }-- /// A unique directory under the system temp dir, removed by `TempTree::drop`.- /// std only: the crate has no dev-dependency on a tempdir helper and one test- /// does not earn one.- struct TempTree(PathBuf);-- impl TempTree {- fn new(tag: &str) -> Self {- let unique = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .expect("clock before the epoch")- .as_nanos();- let root = std::env::temp_dir().join(format!("openpencil-{tag}-{unique}"));- std::fs::create_dir_all(&root).expect("create the temp tree");- Self(root)- }-- fn file(&self, relative: &str) -> PathBuf {- let path = self.0.join(relative);- std::fs::create_dir_all(path.parent().expect("a parent")).expect("create dirs");- std::fs::write(&path, b"{}").expect("write the fixture");- path- }- }-- impl Drop for TempTree {- fn drop(&mut self) {- let _ = std::fs::remove_dir_all(&self.0);- }- }-- fn matches(candidate: &Path, suffix: &str) -> bool {- path_matches_suffix(candidate.to_string_lossy().into_owned(), suffix.to_string())- }-- #[test]- fn command_matches_a_real_file_by_its_trailing_segments() {- let tree = TempTree::new("exact");- let file = tree.file("web/design/hikyo.pen");-- assert!(matches(&file, "web/design/hikyo.pen"));- assert!(matches(&file, "hikyo.pen"));- assert!(!matches(&file, "design/other.pen"));- assert!(!matches(&file, "app/web/design/hikyo.pen"));- }-- #[test]- fn command_folds_case_only_where_the_filesystem_does() {- let tree = TempTree::new("case");- let file = tree.file("Web/Design/Hikyo.pen");-- assert_eq!(- matches(&file, "web/design/hikyo.pen"),- cfg!(any(target_os = "macos", windows))- );- }-- /// The reason the command compares the literal path as well as the canonical one:- /// a symlink *inside* the trailing segments makes the two spellings disagree, and a- /// link written against either of them must still find the file.- #[cfg(unix)]- #[test]- fn command_matches_a_symlinked_trailing_directory() {- let tree = TempTree::new("symlink");- tree.file("apps/web/hikyo.pen");- std::fs::create_dir_all(tree.0.join("packages")).expect("create packages");- std::os::unix::fs::symlink(tree.0.join("apps/web"), tree.0.join("packages/web"))- .expect("create the symlink");- let through_link = tree.0.join("packages/web/hikyo.pen");-- // Only the literal spelling carries `packages`; `canonicalize` resolves it to `apps`.- assert!(matches(&through_link, "packages/web/hikyo.pen"));- assert!(matches(&through_link, "apps/web/hikyo.pen"));- }-- #[test]- fn command_falls_back_to_the_literal_path_when_the_file_is_gone() {- // Nothing on disk, so `canonicalize` fails: the link must still match an open- // tab whose document moved or whose volume went away.- assert!(matches(- Path::new("/r/hikyo/web/design/hikyo.pen"),- "web/design/hikyo.pen"- ));- }-- #[test]- fn command_refuses_an_absolute_or_dot_dot_suffix() {- let tree = TempTree::new("relative");- let file = tree.file("web/design/hikyo.pen");- let absolute = file.to_string_lossy().into_owned();-- assert!(!matches(&file, &absolute));- assert!(!matches(&file, "/web/design/hikyo.pen"));- assert!(!matches(&file, "../design/hikyo.pen"));- assert!(!matches(&file, "web/../design/hikyo.pen"));- assert!(!matches(&file, "./hikyo.pen"));- assert!(!matches(&file, ""));- }}diff --git a/desktop/src/launch/mod.rs b/desktop/src/launch/mod.rsnew file mode 100644index 000000000..87769fffb--- /dev/null+++ b/desktop/src/launch/mod.rs@@ -0,0 +1,172 @@+//! Everything that asks the app to open something: file associations, launch arguments, and+//! `openpencil://` links, queued until the frontend takes them.++pub mod args;+pub mod links;+pub mod paths;++use std::path::PathBuf;+use std::sync::Mutex;++use tauri::{Emitter, Manager};+use tauri_plugin_fs::FsExt;++#[derive(Clone, serde::Serialize)]+pub struct PendingOpenFile {+ path: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ node: Option<String>,+ /// Which producer queued this entry: a `openpencil://` link (true) or a file+ /// association / argv path (false). The frontend cannot tell them apart from+ /// the path alone — a canonicalized Windows path is verbatim (`\\?\C:\…`).+ #[serde(rename = "deepLink")]+ deep_link: bool,+}++#[derive(Default)]+pub struct PendingOpen(Mutex<Vec<PendingOpenFile>>);++/// Rooms from `openpencil://join` links, waiting for the frontend to open them.+#[derive(Default)]+pub struct PendingRooms(Mutex<Vec<String>>);++/// Cloud invitations and shared links from `openpencil://cloud` links, waiting for the frontend.+#[derive(Default)]+pub struct PendingCloudLinks(Mutex<Vec<links::CloudLink>>);++#[tauri::command]+pub fn take_pending_cloud_links(state: tauri::State<PendingCloudLinks>) -> Vec<links::CloudLink> {+ state+ .0+ .lock()+ .map(|mut pending| pending.drain(..).collect())+ .unwrap_or_default()+}++/// Native-test builds take a link through the same path a launch or an opened URL does.+#[cfg(feature = "native-test")]+#[tauri::command]+pub fn native_test_open_deep_link(app: tauri::AppHandle, url: String) -> Result<(), String> {+ let url = url::Url::parse(&url).map_err(|error| error.to_string())?;+ queue_deep_links(&app, vec![url]);+ Ok(())+}++#[tauri::command]+pub fn take_pending_rooms(state: tauri::State<PendingRooms>) -> Vec<String> {+ state+ .0+ .lock()+ .map(|mut pending| pending.drain(..).collect())+ .unwrap_or_default()+}++#[tauri::command]+pub fn take_pending_open(state: tauri::State<PendingOpen>) -> Vec<PendingOpenFile> {+ state+ .0+ .lock()+ .map(|mut pending| pending.drain(..).collect())+ .unwrap_or_default()+}++fn queue_pending<R: tauri::Runtime>(app: &tauri::AppHandle<R>, files: Vec<PendingOpenFile>) {+ if files.is_empty() {+ return;+ }++ if let Ok(mut pending) = app.state::<PendingOpen>().0.lock() {+ pending.extend(files);+ }++ let _ = app.emit("open-associated-files", ());+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.set_focus();+ }+}++pub fn queue_open_paths<R: tauri::Runtime>(app: &tauri::AppHandle<R>, paths: Vec<PathBuf>) {+ let files = paths+ .into_iter()+ .map(|path| {+ let _ = app.fs_scope().allow_file(&path);+ PendingOpenFile {+ path: path.to_string_lossy().into_owned(),+ node: None,+ deep_link: false,+ }+ })+ .collect::<Vec<_>>();++ queue_pending(app, files);+}++/// The scheme filter is load-bearing: on macOS the plugin forwards every+/// `RunEvent::Opened` URL here, including the `file://` URLs of a double-clicked+/// document, which `queue_open_paths` already handles.+///+/// Relative paths from a link are deliberately not passed through+/// `fs_scope().allow_file`: the frontend resolves them against open tabs or the+/// file picker and allows the resolved absolute path there.+pub fn queue_deep_links<R: tauri::Runtime>(app: &tauri::AppHandle<R>, urls: Vec<url::Url>) {+ let mut files = Vec::new();+ let mut rooms = Vec::new();+ let mut cloud_links = Vec::new();+ for url in urls.iter().filter(|url| url.scheme() == "openpencil") {+ match links::parse_deep_link(url) {+ Ok(links::DeepLink::Open(open)) => files.push(PendingOpenFile {+ path: open.file,+ node: open.node,+ deep_link: true,+ }),+ Ok(links::DeepLink::Join(join)) => rooms.push(join.room),+ Ok(links::DeepLink::Cloud(link)) => cloud_links.push(link),+ // The sign-in that opened the browser is waiting; it checks the state itself.+ Ok(links::DeepLink::OAuth(callback)) => {+ let _ = app.emit("oauth-callback", callback);+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.set_focus();+ }+ }+ // Cloud links carry a secret in the fragment, so a refused link is not echoed.+ Err(error) => eprintln!(+ "[deep-link] refused {}: {error:?}",+ url.host_str().unwrap_or("")+ ),+ }+ }++ queue_pending(app, files);+ queue_rooms(app, rooms);+ queue_cloud_links(app, cloud_links);+}++fn queue_cloud_links<R: tauri::Runtime>(app: &tauri::AppHandle<R>, links: Vec<links::CloudLink>) {+ if links.is_empty() {+ return;+ }++ if let Ok(mut pending) = app.state::<PendingCloudLinks>().0.lock() {+ pending.extend(links);+ }++ let _ = app.emit("open-cloud-links", ());+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.set_focus();+ }+}++fn queue_rooms<R: tauri::Runtime>(app: &tauri::AppHandle<R>, rooms: Vec<String>) {+ if rooms.is_empty() {+ return;+ }++ if let Ok(mut pending) = app.state::<PendingRooms>().0.lock() {+ pending.extend(rooms);+ }++ let _ = app.emit("open-room-links", ());+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.set_focus();+ }+}diff --git a/desktop/src/launch/paths.rs b/desktop/src/launch/paths.rsnew file mode 100644index 000000000..4f2ff961b--- /dev/null+++ b/desktop/src/launch/paths.rs@@ -0,0 +1,213 @@+//! Matching a link's relative path against the absolute paths of open documents.++use std::path::{Component, Path, PathBuf};++/// Whether `candidate` ends with `suffix` as a whole sequence of path segments.+///+/// The link carries a repository-relative path, the candidate is an absolute path+/// from an open tab or the file picker, and the two may disagree on case: on+/// macOS and Windows the default filesystem is case-insensitive, so `Web/Design`+/// and `web/design` name the same file and a case-sensitive comparison would+/// cancel a link that points at an already open document.+///+/// The rule is per-platform, not per-volume: ASCII-case-insensitive on macOS and+/// Windows, exact on Linux. Deliberately ASCII only — macOS folds the full Unicode+/// case table, matching that here would mean carrying a Unicode fold for a gain+/// nobody links against. A case-sensitive APFS volume is likewise not probed;+/// the cost of being wrong there is a link that focuses a same-named file in a+/// different directory case. Nothing is read and nothing is opened here: the command+/// resolves and compares path strings, never file contents.+///+/// `candidate` is canonicalized so a `..`-laden or symlink-prefixed tab path still+/// compares by its real segments, and the literal path is tried as well: a symlink+/// *inside* the trailing segments (a monorepo `packages/web -> ../apps/web`) makes+/// the two disagree, and the link should match either spelling. A candidate that+/// cannot be canonicalized at all — the file moved, or the volume went away — is+/// compared by its literal segments alone rather than failing the match.+///+/// `async` so `canonicalize` runs off the main thread: it hits the filesystem, and a+/// stale network mount can block for as long as its timeout.+#[tauri::command(async)]+pub fn path_matches_suffix(candidate: String, suffix: String) -> bool {+ let literal = PathBuf::from(&candidate);+ let canonical = literal.canonicalize().unwrap_or_else(|_| literal.clone());+ path_ends_with_segments(&canonical, &suffix) || path_ends_with_segments(&literal, &suffix)+}++fn segment_eq(left: &str, right: &str) -> bool {+ if cfg!(any(target_os = "macos", windows)) {+ left.eq_ignore_ascii_case(right)+ } else {+ left == right+ }+}++/// A suffix is a *relative* trailing path. `parse_open_url` already refuses an absolute+/// or `..`-bearing `file`, but this is the comparison every caller funnels through, so it+/// refuses them again rather than trusting its caller: an absolute suffix would otherwise+/// match on its segments alone, turning `/etc/hikyo.pen` into a relative lookup.+fn path_ends_with_segments(candidate: &Path, suffix: &str) -> bool {+ if suffix.starts_with('/') || suffix.starts_with('\\') || Path::new(suffix).is_absolute() {+ return false;+ }+ let wanted: Vec<&str> = suffix+ .split(['/', '\\'])+ .filter(|s| !s.is_empty())+ .collect();+ if wanted.is_empty() || wanted.iter().any(|seg| *seg == ".." || *seg == ".") {+ return false;+ }+ let actual: Vec<String> = candidate+ .components()+ .filter_map(|component| match component {+ Component::Normal(part) => Some(part.to_string_lossy().into_owned()),+ _ => None,+ })+ .collect();+ if actual.len() < wanted.len() {+ return false;+ }+ actual[actual.len() - wanted.len()..]+ .iter()+ .zip(&wanted)+ .all(|(have, want)| segment_eq(have, want))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn suffix_matches_whole_trailing_segments() {+ assert!(path_ends_with_segments(+ Path::new("/r/hikyo/web/design/hikyo.pen"),+ "web/design/hikyo.pen"+ ));+ // A partial segment is not a segment: `redesign` must not satisfy `design`.+ assert!(!path_ends_with_segments(+ Path::new("/r/redesign/hikyo.pen"),+ "design/hikyo.pen"+ ));+ // A suffix longer than the path cannot match.+ assert!(!path_ends_with_segments(+ Path::new("/hikyo.pen"),+ "design/hikyo.pen"+ ));+ assert!(!path_ends_with_segments(Path::new("/r/hikyo.pen"), ""));+ }++ #[test]+ fn suffix_case_rule_follows_the_platform() {+ let folded = path_ends_with_segments(+ Path::new("/r/hikyo/Web/Design/Hikyo.pen"),+ "web/design/hikyo.pen",+ );+ assert_eq!(folded, cfg!(any(target_os = "macos", windows)));+ }++ #[test]+ fn suffix_accepts_backslash_separators() {+ assert!(path_ends_with_segments(+ Path::new("/r/web/design/hikyo.pen"),+ "web\\design\\hikyo.pen"+ ));+ }++ /// A unique directory under the system temp dir, removed by `TempTree::drop`.+ /// std only: the crate has no dev-dependency on a tempdir helper and one test+ /// does not earn one.+ struct TempTree(PathBuf);++ impl TempTree {+ fn new(tag: &str) -> Self {+ let unique = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .expect("clock before the epoch")+ .as_nanos();+ let root = std::env::temp_dir().join(format!("openpencil-{tag}-{unique}"));+ std::fs::create_dir_all(&root).expect("create the temp tree");+ Self(root)+ }++ fn file(&self, relative: &str) -> PathBuf {+ let path = self.0.join(relative);+ std::fs::create_dir_all(path.parent().expect("a parent")).expect("create dirs");+ std::fs::write(&path, b"{}").expect("write the fixture");+ path+ }+ }++ impl Drop for TempTree {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }++ fn matches(candidate: &Path, suffix: &str) -> bool {+ path_matches_suffix(candidate.to_string_lossy().into_owned(), suffix.to_string())+ }++ #[test]+ fn command_matches_a_real_file_by_its_trailing_segments() {+ let tree = TempTree::new("exact");+ let file = tree.file("web/design/hikyo.pen");++ assert!(matches(&file, "web/design/hikyo.pen"));+ assert!(matches(&file, "hikyo.pen"));+ assert!(!matches(&file, "design/other.pen"));+ assert!(!matches(&file, "app/web/design/hikyo.pen"));+ }++ #[test]+ fn command_folds_case_only_where_the_filesystem_does() {+ let tree = TempTree::new("case");+ let file = tree.file("Web/Design/Hikyo.pen");++ assert_eq!(+ matches(&file, "web/design/hikyo.pen"),+ cfg!(any(target_os = "macos", windows))+ );+ }++ /// The reason the command compares the literal path as well as the canonical one:+ /// a symlink *inside* the trailing segments makes the two spellings disagree, and a+ /// link written against either of them must still find the file.+ #[cfg(unix)]+ #[test]+ fn command_matches_a_symlinked_trailing_directory() {+ let tree = TempTree::new("symlink");+ tree.file("apps/web/hikyo.pen");+ std::fs::create_dir_all(tree.0.join("packages")).expect("create packages");+ std::os::unix::fs::symlink(tree.0.join("apps/web"), tree.0.join("packages/web"))+ .expect("create the symlink");+ let through_link = tree.0.join("packages/web/hikyo.pen");++ // Only the literal spelling carries `packages`; `canonicalize` resolves it to `apps`.+ assert!(matches(&through_link, "packages/web/hikyo.pen"));+ assert!(matches(&through_link, "apps/web/hikyo.pen"));+ }++ #[test]+ fn command_falls_back_to_the_literal_path_when_the_file_is_gone() {+ // Nothing on disk, so `canonicalize` fails: the link must still match an open+ // tab whose document moved or whose volume went away.+ assert!(matches(+ Path::new("/r/hikyo/web/design/hikyo.pen"),+ "web/design/hikyo.pen"+ ));+ }++ #[test]+ fn command_refuses_an_absolute_or_dot_dot_suffix() {+ let tree = TempTree::new("relative");+ let file = tree.file("web/design/hikyo.pen");+ let absolute = file.to_string_lossy().into_owned();++ assert!(!matches(&file, &absolute));+ assert!(!matches(&file, "/web/design/hikyo.pen"));+ assert!(!matches(&file, "../design/hikyo.pen"));+ assert!(!matches(&file, "web/../design/hikyo.pen"));+ assert!(!matches(&file, "./hikyo.pen"));+ assert!(!matches(&file, ""));+ }+}diff --git a/desktop/src/lib.rs b/desktop/src/lib.rsindex 1c44eb9a3..dda8cb085 100644--- a/desktop/src/lib.rs+++ b/desktop/src/lib.rs@@ -1,403 +1,40 @@mod agents;mod credentials;-mod deep_link;-mod fig_container;+mod files;mod fonts;+mod launch;mod menu;-mod menu_events;mod network;-mod opener;-#[cfg(target_os = "macos")]-mod window;+mod system;use credentials::{credential_access_paused, credential_read, credential_remove, credential_retry_access,credential_status, credential_store_availability, credential_write,};-use deep_link::path_matches_suffix;-use fig_container::build_fig_file;use fonts::{list_system_fonts, load_system_font};+use launch::args;+use menu::events::handle_menu_event;use menu::{install_app_menu, native_menu_checked, set_native_menu_checked, set_native_menu_features,- update_app_menu, NativeMenuInputs, NativeMenuState,+ NativeMenuInputs, NativeMenuState,};-use menu_events::handle_menu_event;use network::http::{cancel_http_request, proxy_http_request, ProxyHttpRequests};-use std::{- path::{Path, PathBuf},- sync::Mutex,-};-use tauri::{Emitter, Manager};-use tauri_plugin_fs::FsExt;+use std::sync::Mutex;#[cfg(target_os = "macos")]-use window::show_main_window;--#[derive(Clone, serde::Serialize)]-struct PendingOpenFile {- path: String,- #[serde(skip_serializing_if = "Option::is_none")]- node: Option<String>,- /// Which producer queued this entry: a `openpencil://` link (true) or a file- /// association / argv path (false). The frontend cannot tell them apart from- /// the path alone — a canonicalized Windows path is verbatim (`\\?\C:\…`).- #[serde(rename = "deepLink")]- deep_link: bool,-}--struct PendingOpen(Mutex<Vec<PendingOpenFile>>);--/// Rooms from `openpencil://join` links, waiting for the frontend to open them.-struct PendingRooms(Mutex<Vec<String>>);--/// Cloud invitations and shared links from `openpencil://cloud` links, waiting for the frontend.-struct PendingCloudLinks(Mutex<Vec<deep_link::CloudLink>>);--#[tauri::command]-fn take_pending_cloud_links(state: tauri::State<PendingCloudLinks>) -> Vec<deep_link::CloudLink> {- state- .0- .lock()- .map(|mut pending| pending.drain(..).collect())- .unwrap_or_default()-}--/// Native-test builds take a link through the same path a launch or an opened URL does.-#[cfg(feature = "native-test")]-#[tauri::command]-fn native_test_open_deep_link(app: tauri::AppHandle, url: String) -> Result<(), String> {- let url = url::Url::parse(&url).map_err(|error| error.to_string())?;- queue_deep_links(&app, vec![url]);- Ok(())-}--#[tauri::command]-fn take_pending_rooms(state: tauri::State<PendingRooms>) -> Vec<String> {- state- .0- .lock()- .map(|mut pending| pending.drain(..).collect())- .unwrap_or_default()-}--#[tauri::command]-fn take_pending_open(state: tauri::State<PendingOpen>) -> Vec<PendingOpenFile> {- state- .0- .lock()- .map(|mut pending| pending.drain(..).collect())- .unwrap_or_default()-}--/// Version of the system WebView engine the app is rendering in, so the-/// startup support gate can name it when the engine is too old. Uses the-/// WebKit bundle version on macOS, the WebKitGTK version on Linux, and the-/// WebView2 runtime version on Windows; `None` when the runtime cannot report it.-#[tauri::command]-fn webview_version() -> Option<String> {- tauri::webview_version().ok()-}--/// Whether the environment turns off pings and usage stats: `OPENPENCIL_TELEMETRY` set to-/// `0`, `false`, or `no`, or `DO_NOT_TRACK` set to anything but `0` or `false`.-#[tauri::command]-fn sharing_disabled_by_env() -> bool {- let is_off = |name: &str, off: &[&str]| {- std::env::var(name)- .map(|value| off.contains(&value.trim().to_ascii_lowercase().as_str()))- .unwrap_or(false)- };- let do_not_track = std::env::var("DO_NOT_TRACK")- .map(|value| {- !matches!(- value.trim().to_ascii_lowercase().as_str(),- "" | "0" | "false"- )- })- .unwrap_or(false);- is_off("OPENPENCIL_TELEMETRY", &["0", "false", "no"]) || do_not_track-}--#[tauri::command]-fn set_recent_files(app: tauri::AppHandle, paths: Vec<String>) -> Result<(), String> {- update_app_menu(&app, |inputs| inputs.recent_files = paths)-}--/// Name of the MCP entry point installed by `@open-pencil/mcp`.-const MCP_EXECUTABLE: &str = "openpencil-mcp-http";-/// Bound on the directories reported back to the settings diagnostics.-const MAX_REPORTED_SEARCH_DIRS: usize = 12;--/// Directories that commonly hold a globally installed Node/Bun CLI.-///-/// GUI launches inherit launchd's minimal `PATH`, so a package installed by-/// npm, Bun, Volta, or Homebrew can be invisible even though the user's shell-/// finds it. `fix_path_env::fix()` reads the login shell first; these entries-/// cover managers that only modify an interactive rc file.-fn mcp_candidate_dirs() -> Vec<PathBuf> {- let mut dirs: Vec<PathBuf> = Vec::new();- // Bun, Volta, and npm keep their Windows folders under USERPROFILE, which a HOME set by- // Unix-style tools does not always match; HOME remains the fallback there.- let home = if cfg!(windows) {- std::env::var_os("USERPROFILE").or_else(|| std::env::var_os("HOME"))- } else {- std::env::var_os("HOME")- };- if let Some(home) = home.map(PathBuf::from) {- dirs.push(home.join(".bun/bin"));- dirs.push(home.join(".local/bin"));- dirs.push(home.join(".npm-global/bin"));- dirs.push(home.join(".volta/bin"));- dirs.push(home.join("n/bin"));- dirs.push(home.join(".local/share/mise/shims"));- }- #[cfg(target_os = "macos")]- {- dirs.push(PathBuf::from("/opt/homebrew/bin"));- dirs.push(PathBuf::from("/usr/local/bin"));- dirs.push(PathBuf::from("/opt/local/bin"));- }- #[cfg(target_os = "linux")]- {- dirs.push(PathBuf::from("/usr/local/bin"));- dirs.push(PathBuf::from("/home/linuxbrew/.linuxbrew/bin"));- }- #[cfg(windows)]- {- if let Some(appdata) = std::env::var_os("APPDATA").map(PathBuf::from) {- dirs.push(appdata.join("npm"));- }- }- dirs-}--fn push_unique_dir(dirs: &mut Vec<String>, dir: String) {- if !dirs.contains(&dir) {- dirs.push(dir);- }-}--/// Existing candidate directories, most specific first, for diagnostics.-fn mcp_search_dirs() -> Vec<PathBuf> {- mcp_candidate_dirs()- .into_iter()- .filter(|dir| dir.is_dir())- .collect()-}--/// Append candidate directories that the current process `PATH` is missing.-fn augment_path(path: &str, candidates: &[PathBuf]) -> String {- let mut entries: Vec<PathBuf> = std::env::split_paths(path).collect();- for candidate in candidates {- if candidate.is_dir() && !entries.contains(candidate) {- entries.push(candidate.clone());- }- }- std::env::join_paths(entries)- .map(|joined| joined.to_string_lossy().into_owned())- .unwrap_or_else(|_| path.to_string())-}--/// Make globally installed CLIs visible to `which` and to spawned children.-fn augment_mcp_path() {- let current = std::env::var("PATH").unwrap_or_default();- let next = augment_path(¤t, &mcp_candidate_dirs());- if next != current {- std::env::set_var("PATH", next);- }-}--#[derive(serde::Serialize)]-#[serde(rename_all = "camelCase")]-struct McpLookup {- available: bool,- path: Option<String>,- /// Existing directories that were searched, for diagnostics.- searched: Vec<String>,-}--#[tauri::command]-fn mcp_lookup() -> McpLookup {- let resolved = which::which(MCP_EXECUTABLE).ok();- let path = resolved.as_ref().map(|p| p.display().to_string());- let mut searched: Vec<String> = Vec::new();- if let Some(dir) = resolved.as_ref().and_then(|p| p.parent()) {- push_unique_dir(&mut searched, dir.display().to_string());- }- for dir in mcp_search_dirs() {- push_unique_dir(&mut searched, dir.display().to_string());- }- searched.truncate(MAX_REPORTED_SEARCH_DIRS);- McpLookup {- available: resolved.is_some(),- path,- searched,- }-}--fn file_association_path(path: PathBuf) -> Option<PathBuf> {- let path = path.canonicalize().ok()?;- if !path.is_file() {- return None;- }- let ext = path.extension()?.to_string_lossy().to_lowercase();- matches!(ext.as_str(), "fig" | "pen").then_some(path)-}--fn path_from_arg(arg: String, cwd: &Path) -> Option<PathBuf> {- if arg.starts_with('-') {- return None;- }-- if let Ok(url) = tauri::Url::parse(&arg) {- if let Ok(path) = url.to_file_path() {- return Some(path);- }- }-- let path = PathBuf::from(arg);- Some(if path.is_absolute() {- path- } else {- cwd.join(path)- })-}--fn open_paths_from_args(args: Vec<String>, cwd: &Path) -> Vec<PathBuf> {- args.into_iter()- .filter_map(|arg| path_from_arg(arg, cwd))- .filter_map(file_association_path)- .collect()-}--fn queue_pending<R: tauri::Runtime>(app: &tauri::AppHandle<R>, files: Vec<PendingOpenFile>) {- if files.is_empty() {- return;- }-- if let Ok(mut pending) = app.state::<PendingOpen>().0.lock() {- pending.extend(files);- }-- let _ = app.emit("open-associated-files", ());- if let Some(window) = app.get_webview_window("main") {- let _ = window.set_focus();- }-}--fn queue_open_paths<R: tauri::Runtime>(app: &tauri::AppHandle<R>, paths: Vec<PathBuf>) {- let files = paths- .into_iter()- .map(|path| {- let _ = app.fs_scope().allow_file(&path);- PendingOpenFile {- path: path.to_string_lossy().into_owned(),- node: None,- deep_link: false,- }- })- .collect::<Vec<_>>();-- queue_pending(app, files);-}--/// The scheme filter is load-bearing: on macOS the plugin forwards every-/// `RunEvent::Opened` URL here, including the `file://` URLs of a double-clicked-/// document, which `queue_open_paths` already handles.-///-/// Relative paths from a link are deliberately not passed through-/// `fs_scope().allow_file`: the frontend resolves them against open tabs or the-/// file picker and allows the resolved absolute path there.-fn queue_deep_links<R: tauri::Runtime>(app: &tauri::AppHandle<R>, urls: Vec<url::Url>) {- let mut files = Vec::new();- let mut rooms = Vec::new();- let mut cloud_links = Vec::new();- for url in urls.iter().filter(|url| url.scheme() == "openpencil") {- match deep_link::parse_deep_link(url) {- Ok(deep_link::DeepLink::Open(open)) => files.push(PendingOpenFile {- path: open.file,- node: open.node,- deep_link: true,- }),- Ok(deep_link::DeepLink::Join(join)) => rooms.push(join.room),- Ok(deep_link::DeepLink::Cloud(link)) => cloud_links.push(link),- // The sign-in that opened the browser is waiting; it checks the state itself.- Ok(deep_link::DeepLink::OAuth(callback)) => {- let _ = app.emit("oauth-callback", callback);- if let Some(window) = app.get_webview_window("main") {- let _ = window.set_focus();- }- }- // Cloud links carry a secret in the fragment, so a refused link is not echoed.- Err(error) => eprintln!(- "[deep-link] refused {}: {error:?}",- url.host_str().unwrap_or("")- ),- }- }-- queue_pending(app, files);- queue_rooms(app, rooms);- queue_cloud_links(app, cloud_links);-}--fn queue_cloud_links<R: tauri::Runtime>(- app: &tauri::AppHandle<R>,- links: Vec<deep_link::CloudLink>,-) {- if links.is_empty() {- return;- }-- if let Ok(mut pending) = app.state::<PendingCloudLinks>().0.lock() {- pending.extend(links);- }-- let _ = app.emit("open-cloud-links", ());- if let Some(window) = app.get_webview_window("main") {- let _ = window.set_focus();- }-}--fn queue_rooms<R: tauri::Runtime>(app: &tauri::AppHandle<R>, rooms: Vec<String>) {- if rooms.is_empty() {- return;- }-- if let Ok(mut pending) = app.state::<PendingRooms>().0.lock() {- pending.extend(rooms);- }-- let _ = app.emit("open-room-links", ());- if let Some(window) = app.get_webview_window("main") {- let _ = window.set_focus();- }-}--/// `openpencil://` URLs among a second launch's arguments: Windows and Linux start a new-/// process for a link, and the single-instance plugin hands its arguments to this one.-fn deep_links_from_args(args: &[String]) -> Vec<url::Url> {- args.iter()- .filter(|arg| arg.starts_with("openpencil://"))- .filter_map(|arg| url::Url::parse(arg).ok())- .collect()-}--fn startup_open_paths() -> Vec<PathBuf> {- let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));- open_paths_from_args(std::env::args().skip(1).collect(), &cwd)-}+use system::window::show_main_window;+use tauri::{Emitter, Manager};#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {let _ = fix_path_env::fix();- augment_mcp_path();+ agents::path::augment_process_path();let mut builder = tauri::Builder::default();#[cfg(feature = "native-test")]{builder = builder- .manage(opener::OpenedExternalUrls::default())+ .manage(system::opener::OpenedExternalUrls::default()).plugin(tauri_plugin_wdio_webdriver::init());}@@ -407,24 +44,27 @@ pub fn run() {))]{builder = builder.plugin(tauri_plugin_single_instance::init(|app, args, cwd| {- queue_deep_links(app, deep_links_from_args(&args));- queue_open_paths(app, open_paths_from_args(args, Path::new(&cwd)));+ launch::queue_deep_links(app, args::deep_links_from_args(&args));+ launch::queue_open_paths(+ app,+ args::open_paths_from_args(args, std::path::Path::new(&cwd)),+ );}));}builder = builder.plugin(tauri_plugin_deep_link::init());builder- .manage(PendingOpen(Mutex::new(Vec::new())))+ .manage(launch::PendingOpen::default()).manage(ProxyHttpRequests::default()).manage(network::oauth::ChatGPTOAuthLoopback::default())- .manage(PendingRooms(Mutex::new(Vec::new())))+ .manage(launch::PendingRooms::default()).manage(NativeMenuState(Mutex::new(NativeMenuInputs::default())))- .manage(PendingCloudLinks(Mutex::new(Vec::new())))+ .manage(launch::PendingCloudLinks::default()).invoke_handler(tauri::generate_handler![- agents::agent_lookup,- agents::agent_workspace,- build_fig_file,+ agents::lookup::agent_lookup,+ agents::lookup::agent_workspace,+ files::fig::build_fig_file,network::oauth::chatgpt_oauth_listen,network::oauth::chatgpt_oauth_wait,network::oauth::chatgpt_oauth_cancel,@@ -435,26 +75,26 @@ pub fn run() {credential_status,credential_store_availability,credential_write,- mcp_lookup,+ agents::mcp::mcp_lookup,#[cfg(feature = "native-test")]- native_test_open_deep_link,- opener::open_external_url,+ launch::native_test_open_deep_link,+ system::opener::open_external_url,#[cfg(feature = "native-test")]- opener::take_native_test_opened_urls,- path_matches_suffix,+ system::opener::take_native_test_opened_urls,+ launch::paths::path_matches_suffix,list_system_fonts,load_system_font,proxy_http_request,cancel_http_request,- set_recent_files,+ files::recent::set_recent_files,set_native_menu_features,native_menu_checked,set_native_menu_checked,- take_pending_open,- take_pending_rooms,- sharing_disabled_by_env,- take_pending_cloud_links,- webview_version+ launch::take_pending_open,+ launch::take_pending_rooms,+ system::env::sharing_disabled_by_env,+ launch::take_pending_cloud_links,+ system::env::webview_version]).plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_dialog::init())@@ -468,7 +108,7 @@ pub fn run() {handle_menu_event(app, event.id().0.as_str());}).setup(|app| {- queue_open_paths(app.handle(), startup_open_paths());+ launch::queue_open_paths(app.handle(), args::startup_open_paths());use tauri_plugin_deep_link::DeepLinkExt;// On macOS the plugin turns `RunEvent::Opened` into this callback, so every@@ -477,7 +117,7 @@ pub fn run() {// `Opened` arm further down keeps handling file URLs.let handle = app.handle().clone();app.deep_link().on_open_url(move |event| {- queue_deep_links(&handle, event.urls());+ launch::queue_deep_links(&handle, event.urls());});#[cfg(any(windows, target_os = "linux"))]{@@ -501,7 +141,7 @@ pub fn run() {// arrive between the registration above and this read — anything later goes// to `on_open_url` and is no longer in `current` by the time it is read.if let Ok(Some(urls)) = app.deep_link().get_current() {- queue_deep_links(app.handle(), urls);+ launch::queue_deep_links(app.handle(), urls);}Ok(install_app_menu(@@ -524,70 +164,15 @@ pub fn run() {let paths = urls.into_iter().filter_map(|url| url.to_file_path().ok())- .filter_map(file_association_path)+ .filter_map(args::file_association_path).collect();- queue_open_paths(_app, paths);+ launch::queue_open_paths(_app, paths);}#[cfg(target_os = "macos")]tauri::RunEvent::Reopen {- has_visible_windows,+ has_visible_windows: false,..- } => {- if !has_visible_windows {- show_main_window(_app);- }- }+ } => show_main_window(_app),_ => {}});}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn augment_path_appends_missing_candidates_once() {- let current_dir = std::env::temp_dir();- let appended_dir = std::env::temp_dir().join("open-pencil-appended");- std::fs::create_dir_all(&appended_dir).expect("create candidate dir");-- let current =- std::env::join_paths([PathBuf::from("/open-pencil-first"), current_dir.clone()])- .expect("join path list");- let candidates = vec![current_dir.clone(), appended_dir.clone()];- let entries: Vec<PathBuf> =- std::env::split_paths(&augment_path(¤t.to_string_lossy(), &candidates)).collect();-- // Existing entries keep their order and the missing candidate is- // appended once, at the end.- assert_eq!(- entries,- vec![- PathBuf::from("/open-pencil-first"),- current_dir,- appended_dir.clone(),- ]- );-- let _ = std::fs::remove_dir(&appended_dir);- }-- #[test]- fn augment_path_ignores_candidates_that_do_not_exist() {- let current =- std::env::join_paths([PathBuf::from("/open-pencil-only")]).expect("join path list");- let augmented = augment_path(- ¤t.to_string_lossy(),- &[PathBuf::from("/open-pencil-nonexistent")],- );-- assert!(!augmented.contains("nonexistent"));- }-- #[test]- fn augment_path_keeps_an_existing_path_when_nothing_changes() {- let current = std::env::var("PATH").unwrap_or_default();- let augmented = augment_path(¤t, &[]);- assert_eq!(augmented, current);- }-}diff --git a/desktop/src/menu_events.rs b/desktop/src/menu/events.rssimilarity index 100%rename from desktop/src/menu_events.rsrename to desktop/src/menu/events.rsdiff --git a/desktop/src/menu.rs b/desktop/src/menu/mod.rssimilarity index 99%rename from desktop/src/menu.rsrename to desktop/src/menu/mod.rsindex 974b00389..bcac58570 100644--- a/desktop/src/menu.rs+++ b/desktop/src/menu/mod.rs@@ -1,3 +1,5 @@+pub mod events;+use serde::Deserialize;use std::collections::HashMap;use std::path::Path;@@ -67,7 +69,7 @@ struct AppMenuFile {#[cfg(target_os = "macos")]fn app_menu_file() -> tauri::Result<AppMenuFile> {Ok(serde_json::from_str(include_str!(- "../generated/app-menu.json"+ "../../generated/app-menu.json"))?)}@@ -217,7 +219,7 @@ fn build_schema_menus<R: tauri::Runtime>(app: &tauri::AppHandle<R>,build: &MenuBuild,) -> tauri::Result<Vec<Submenu<R>>> {- let groups: Vec<MenuGroup> = serde_json::from_str(include_str!("../generated/menu.json"))?;+ let groups: Vec<MenuGroup> = serde_json::from_str(include_str!("../../generated/menu.json"))?;groups.iter().map(|group| build_submenu(app, &group.label, &group.items, build))diff --git a/desktop/src/network/oauth.rs b/desktop/src/network/oauth.rsindex f710a1873..b751d68df 100644--- a/desktop/src/network/oauth.rs+++ b/desktop/src/network/oauth.rs@@ -93,12 +93,19 @@ fn callback_request(target: &str, state: &str) -> CallbackRequest {}}-/// The target of an HTTP request line such as `GET /auth/callback?code=… HTTP/1.1`.+/// Headers a browser sends with the redirect; more than this reads as noise.+const MAX_REQUEST_HEADERS: usize = 64;++/// The target of a GET request such as `GET /auth/callback?code=… HTTP/1.1`.fn request_target(head: &str) -> Option<&str> {- let mut parts = head.lines().next()?.split(' ');- let method = parts.next()?;- let target = parts.next()?;- (method == "GET").then_some(target)+ let mut headers = [httparse::EMPTY_HEADER; MAX_REQUEST_HEADERS];+ let mut request = httparse::Request::new(&mut headers);+ // A request cut off before its blank line can still fill in the method and path.+ if !request.parse(head.as_bytes()).ok()?.is_complete() {+ return None;+ }+ request.method.filter(|method| *method == "GET")?;+ request.path}fn read_head(stream: &mut TcpStream) -> Option<String> {@@ -366,5 +373,11 @@ mod tests {);assert_eq!(request_target("POST /auth/callback HTTP/1.1\r\n\r\n"), None);assert_eq!(request_target(""), None);+ assert_eq!(request_target("GET /auth/callback?code=a\r\n\r\n"), None);+ assert_eq!(request_target("GET /auth/callback?code=a&state=s1 "), None);+ assert_eq!(+ request_target("GET /auth/callback?code=a HTTP/1.1\r\nHost: localhost\r\n"),+ None+ );}}diff --git a/desktop/src/system/env.rs b/desktop/src/system/env.rsnew file mode 100644index 000000000..0df07e306--- /dev/null+++ b/desktop/src/system/env.rs@@ -0,0 +1,30 @@+//! What the system and environment tell the frontend about where it runs.++/// Version of the system WebView engine the app is rendering in, so the+/// startup support gate can name it when the engine is too old. Uses the+/// WebKit bundle version on macOS, the WebKitGTK version on Linux, and the+/// WebView2 runtime version on Windows; `None` when the runtime cannot report it.+#[tauri::command]+pub fn webview_version() -> Option<String> {+ tauri::webview_version().ok()+}++/// Whether the environment turns off pings and usage stats: `OPENPENCIL_TELEMETRY` set to+/// `0`, `false`, or `no`, or `DO_NOT_TRACK` set to anything but `0` or `false`.+#[tauri::command]+pub fn sharing_disabled_by_env() -> bool {+ let is_off = |name: &str, off: &[&str]| {+ std::env::var(name)+ .map(|value| off.contains(&value.trim().to_ascii_lowercase().as_str()))+ .unwrap_or(false)+ };+ let do_not_track = std::env::var("DO_NOT_TRACK")+ .map(|value| {+ !matches!(+ value.trim().to_ascii_lowercase().as_str(),+ "" | "0" | "false"+ )+ })+ .unwrap_or(false);+ is_off("OPENPENCIL_TELEMETRY", &["0", "false", "no"]) || do_not_track+}diff --git a/desktop/src/system/mod.rs b/desktop/src/system/mod.rsnew file mode 100644index 000000000..77d882b8c--- /dev/null+++ b/desktop/src/system/mod.rs@@ -0,0 +1,7 @@+//! The operating system around the editor window: its WebView, environment, browser, and+//! window.++pub mod env;+pub mod opener;+#[cfg(target_os = "macos")]+pub mod window;diff --git a/desktop/src/opener.rs b/desktop/src/system/opener.rssimilarity index 100%rename from desktop/src/opener.rsrename to desktop/src/system/opener.rsdiff --git a/desktop/src/window.rs b/desktop/src/system/window.rssimilarity index 100%rename from desktop/src/window.rsrename to desktop/src/system/window.rsdiff --git a/packages/cloud/src/contract/links.ts b/packages/cloud/src/contract/links.tsindex ecacf99f8..87e946c19 100644--- a/packages/cloud/src/contract/links.ts+++ b/packages/cloud/src/contract/links.ts@@ -70,7 +70,7 @@ export function cloudDocumentPath(documentId: string): string {/*** The desktop app's form of a Cloud link, `openpencil://cloud/<kind>/<id>?server=…#secret`, which- * `desktop/src/deep_link.rs` validates before the editor sees it.+ * `desktop/src/launch/links.rs` validates before the editor sees it.*/export function cloudDesktopLinkURL(kind: CloudLinkKind,diff --git a/src/app/cloud/links.ts b/src/app/cloud/links.tsindex 5fa81579f..009ba4c3a 100644--- a/src/app/cloud/links.ts+++ b/src/app/cloud/links.ts@@ -26,7 +26,7 @@ export type CloudLink = { kind: CloudLinkKind; id: string; server: string; secreconst CLOUD_LINK_PATH = /^\/cloud\/(invitations|share)\/([^/]+)$/-/** Desktop events and commands for `openpencil://cloud` links (`desktop/src/lib.rs`). */+/** Desktop events and commands for `openpencil://cloud` links (`desktop/src/launch/mod.rs`). */const CLOUD_LINKS_EVENT = 'open-cloud-links'const TAKE_PENDING_CLOUD_LINKS = 'take_pending_cloud_links'diff --git a/src/app/collab/room/links.ts b/src/app/collab/room/links.tsindex fc56a32c0..fa63d9ea2 100644--- a/src/app/collab/room/links.ts+++ b/src/app/collab/room/links.ts@@ -2,7 +2,7 @@ import * as v from 'valibot'import { bindDesktopLinkQueue } from '@/app/tauri/link-queue'-/** Desktop events and commands for `openpencil://join?room=<id>` links (`desktop/src/lib.rs`). */+/** Desktop events and commands for `openpencil://join?room=<id>` links (`desktop/src/launch/mod.rs`). */export const ROOM_LINKS_EVENT = 'open-room-links'const TAKE_PENDING_ROOMS = 'take_pending_rooms'diff --git a/tests/engine/app/document/io/deep-link.test.ts b/tests/engine/app/document/io/deep-link.test.tsindex b4a36d971..c387b4330 100644--- a/tests/engine/app/document/io/deep-link.test.ts+++ b/tests/engine/app/document/io/deep-link.test.ts@@ -5,7 +5,7 @@ import { openDeepLink, resolveDeepLinkFile } from '@/app/document/io/deep-link'/*** Stands in for the `path_matches_suffix` Tauri command. The real comparator asks the* platform (ASCII-case-insensitive on macOS and Windows, exact on Linux); these tests- * cover the resolver's own contract, and the case rule is tested in `deep_link.rs`.+ * cover the resolver's own contract, and the case rule is tested in `desktop/src/launch/paths.rs`.*/const matchesSuffix = async (candidate: string, relative: string): Promise<boolean> => {const a = candidate.replaceAll('\\', '/')