Skip to content

AI-native design editor. Open-source Figma alternative.

feat: open documents and layers from openpencil:// and web links (#708)

Marc Went511bb481ac66
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0d0bdd366..47e07d4fd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -49,6 +49,8 @@
### Added
+- Open documents and jump to a named layer from `openpencil://open?file=&node=` links, resolving the file against open tabs or a one-time file picker. Path segments match the way the filesystem does: case-insensitively on macOS and Windows, exactly on Linux.
+- Open documents and jump to a named layer in the web app from `?file=&node=` links, fetching the file from an `https:` URL without credentials, ignoring the URL fragment, and refusing a document larger than 64 MiB — a ceiling the automation bridge's `openFile` now shares.
- Expose design inspection and undoable layer-property and variable edits to browser agents through experimental WebMCP in supporting browsers, with explicit Off, Inspect, and Edit access controls in Settings.
- Control custom tool exposure independently through `mcp`, `ai`, and `webmcp` exclusions. Tools are included by default, subject to execution support and user permissions.
- Bind Design JSX spacing, sizing, corners, and typography directly to numeric document variables.
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock
index 70d152426..6ef9f2be1 100644
--- a/desktop/Cargo.lock
+++ b/desktop/Cargo.lock
@@ -660,6 +660,26 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "const-random"
+version = "0.1.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"
+dependencies = [
+ "const-random-macro",
+]
+
+[[package]]
+name = "const-random-macro"
+version = "0.1.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"
+dependencies = [
+ "getrandom 0.2.17",
+ "once_cell",
+ "tiny-keccak",
+]
+
[[package]]
name = "cookie"
version = "0.18.2"
@@ -1057,6 +1077,15 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "dlv-list"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f"
+dependencies = [
+ "const-random",
+]
+
[[package]]
name = "dom_query"
version = "0.27.0"
@@ -1924,6 +1953,12 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
+[[package]]
+name = "hashbrown"
+version = "0.14.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
+
[[package]]
name = "hashbrown"
version = "0.15.5"
@@ -3269,6 +3304,7 @@ dependencies = [
"tauri",
"tauri-build",
"tauri-plugin-clipboard-manager",
+ "tauri-plugin-deep-link",
"tauri-plugin-dialog",
"tauri-plugin-fs",
"tauri-plugin-opener",
@@ -3277,6 +3313,7 @@ dependencies = [
"tauri-plugin-single-instance",
"tauri-plugin-updater",
"tauri-plugin-wdio-webdriver",
+ "url",
"which",
"zip 2.4.2",
"zstd",
@@ -3294,6 +3331,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+[[package]]
+name = "ordered-multimap"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79"
+dependencies = [
+ "dlv-list",
+ "hashbrown 0.14.5",
+]
+
[[package]]
name = "ordered-stream"
version = "0.2.0"
@@ -3959,6 +4006,16 @@ dependencies = [
"windows-sys 0.52.0",
]
+[[package]]
+name = "rust-ini"
+version = "0.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7"
+dependencies = [
+ "cfg-if",
+ "ordered-multimap",
+]
+
[[package]]
name = "rustc-hash"
version = "2.1.3"
@@ -4916,6 +4973,27 @@ dependencies = [
"thiserror 2.0.20",
]
+[[package]]
+name = "tauri-plugin-deep-link"
+version = "2.4.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d489b8ecceae1cd09f6e1f7606f2095ac721cc8d54cf2f0e6bb377cc52cff6"
+dependencies = [
+ "dunce",
+ "plist",
+ "rust-ini",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "tauri-utils",
+ "thiserror 2.0.20",
+ "tracing",
+ "url",
+ "windows-registry",
+ "windows-result 0.3.4",
+]
+
[[package]]
name = "tauri-plugin-dialog"
version = "2.7.2"
@@ -5022,6 +5100,7 @@ dependencies = [
"serde",
"serde_json",
"tauri",
+ "tauri-plugin-deep-link",
"thiserror 2.0.20",
"tokio",
"tracing",
@@ -5301,6 +5380,15 @@ dependencies = [
"time-core",
]
+[[package]]
+name = "tiny-keccak"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
+dependencies = [
+ "crunchy",
+]
+
[[package]]
name = "tinystr"
version = "0.8.4"
@@ -6260,6 +6348,17 @@ dependencies = [
"windows-link 0.1.3",
]
+[[package]]
+name = "windows-registry"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e"
+dependencies = [
+ "windows-link 0.1.3",
+ "windows-result 0.3.4",
+ "windows-strings 0.4.2",
+]
+
[[package]]
name = "windows-result"
version = "0.3.4"
diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml
index cab109cc3..6402d5393 100644
--- a/desktop/Cargo.toml
+++ b/desktop/Cargo.toml
@@ -39,12 +39,14 @@ fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs", branch =
tauri-plugin-updater = "2"
tauri-plugin-process = "2"
tauri-plugin-clipboard-manager = "2"
+tauri-plugin-deep-link = "2"
keyring = "4.1.5"
+url = "2"
tauri-plugin-wdio-webdriver = { version = "1.3.0", optional = true }
[target.'cfg(target_os = "macos")'.dependencies]
security-framework = "3"
[target.'cfg(any(target_os = "macos", windows, target_os = "linux"))'.dependencies]
-tauri-plugin-single-instance = "2"
+tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
diff --git a/desktop/capabilities/default.json b/desktop/capabilities/default.json
index 78e1f27cb..0926a3560 100644
--- a/desktop/capabilities/default.json
+++ b/desktop/capabilities/default.json
@@ -68,4 +68,4 @@
"shell:allow-stdin-write",
"shell:allow-kill"
]
-}
+}
\ No newline at end of file
diff --git a/desktop/linux/main.desktop b/desktop/linux/main.desktop
new file mode 100644
index 000000000..d56a80e6d
--- /dev/null
+++ b/desktop/linux/main.desktop
@@ -0,0 +1,14 @@
+[Desktop Entry]
+Categories={{categories}}
+{{#if comment}}
+Comment={{comment}}
+{{/if}}
+Exec={{exec}} %U
+StartupWMClass={{exec}}
+Icon={{icon}}
+Name={{name}}
+Terminal=false
+Type=Application
+{{#if mime_type}}
+MimeType={{mime_type}}
+{{/if}}
diff --git a/desktop/src/deep_link.rs b/desktop/src/deep_link.rs
new file mode 100644
index 000000000..b913dadb9
--- /dev/null
+++ b/desktop/src/deep_link.rs
@@ -0,0 +1,342 @@
+use std::path::{Component, Path, PathBuf};
+
+use url::Url;
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct DeepLinkOpen {
+ pub file: String,
+ pub node: Option<String>,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub enum DeepLinkError {
+ UnknownAction(String),
+ MissingFile,
+ AbsolutePath,
+ ParentSegment,
+ BadExtension,
+}
+
+pub fn parse_open_url(url: &Url) -> Result<DeepLinkOpen, DeepLinkError> {
+ // openpencil://open?… → host is the action.
+ let action = url.host_str().unwrap_or("");
+ if action != "open" {
+ return Err(DeepLinkError::UnknownAction(action.to_string()));
+ }
+ let mut file = None;
+ let mut node = None;
+ for (k, v) in url.query_pairs() {
+ match k.as_ref() {
+ "file" => file = Some(v.into_owned()),
+ "node" => node = Some(v.into_owned()),
+ _ => {}
+ }
+ }
+ let file = file
+ .filter(|f| !f.is_empty())
+ .ok_or(DeepLinkError::MissingFile)?;
+ let is_windows_abs = file.len() > 1 && file.as_bytes()[1] == b':';
+ 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
+ // 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);
+ }
+ let lower = file.to_ascii_lowercase();
+ if !(lower.ends_with(".pen") || lower.ends_with(".fig")) {
+ return Err(DeepLinkError::BadExtension);
+ }
+ Ok(DeepLinkOpen {
+ file,
+ node: node.filter(|n| !n.is_empty()),
+ })
+}
+
+/// 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::*;
+
+ fn parse(s: &str) -> Result<DeepLinkOpen, DeepLinkError> {
+ parse_open_url(&Url::parse(s).unwrap())
+ }
+
+ #[test]
+ fn open_with_file_and_node() {
+ assert_eq!(
+ parse("openpencil://open?file=web%2Fdesign%2Fhikyo.pen&node=Button%2FPrimary"),
+ Ok(DeepLinkOpen {
+ file: "web/design/hikyo.pen".into(),
+ node: Some("Button/Primary".into())
+ })
+ );
+ }
+
+ #[test]
+ fn node_is_optional() {
+ assert_eq!(parse("openpencil://open?file=a.pen").unwrap().node, None);
+ }
+
+ #[test]
+ fn unknown_action() {
+ assert_eq!(
+ parse("openpencil://export?file=a.pen"),
+ Err(DeepLinkError::UnknownAction("export".into()))
+ );
+ }
+
+ #[test]
+ fn missing_file() {
+ assert_eq!(parse("openpencil://open"), Err(DeepLinkError::MissingFile));
+ }
+
+ #[test]
+ fn dot_segment_refused() {
+ // The matcher refuses `.` too, so accepting it here would queue a link that can
+ // never resolve against an open tab or a picked file.
+ assert_eq!(
+ parse("openpencil://open?file=web%2F.%2Fdesign.pen"),
+ Err(DeepLinkError::ParentSegment)
+ );
+ }
+
+ #[test]
+ fn absolute_refused() {
+ assert_eq!(
+ parse("openpencil://open?file=%2FUsers%2Fx%2Fa.pen"),
+ Err(DeepLinkError::AbsolutePath)
+ );
+ assert_eq!(
+ parse("openpencil://open?file=C%3A%5Cx%5Ca.pen"),
+ Err(DeepLinkError::AbsolutePath)
+ );
+ }
+
+ #[test]
+ fn parent_segment_refused() {
+ assert_eq!(
+ parse("openpencil://open?file=..%2Fa.pen"),
+ Err(DeepLinkError::ParentSegment)
+ );
+ // The dots themselves percent-encoded: decoding happens before the check.
+ assert_eq!(
+ parse("openpencil://open?file=%2E%2E%2Fa.pen"),
+ Err(DeepLinkError::ParentSegment)
+ );
+ }
+
+ #[test]
+ fn extension_checked() {
+ assert_eq!(
+ parse("openpencil://open?file=a.txt"),
+ Err(DeepLinkError::BadExtension)
+ );
+ 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/lib.rs b/desktop/src/lib.rs
index 5ebdf198f..39d2d4229 100644
--- a/desktop/src/lib.rs
+++ b/desktop/src/lib.rs
@@ -1,4 +1,5 @@
mod credentials;
+mod deep_link;
mod fig_container;
mod fonts;
mod http;
@@ -11,6 +12,7 @@ use credentials::{
credential_access_paused, credential_retry_access, credential_read, credential_remove, 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 http::proxy_http_request;
@@ -28,6 +30,13 @@ 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>>);
@@ -186,17 +195,7 @@ fn open_paths_from_args(args: Vec<String>, cwd: &Path) -> Vec<PathBuf> {
.collect()
}
-fn queue_open_paths<R: tauri::Runtime>(app: &tauri::AppHandle<R>, paths: Vec<PathBuf>) {
- let files = paths
- .into_iter()
- .filter_map(|path| {
- let _ = app.fs_scope().allow_file(&path);
- Some(PendingOpenFile {
- path: path.to_string_lossy().into_owned(),
- })
- })
- .collect::<Vec<_>>();
-
+fn queue_pending<R: tauri::Runtime>(app: &tauri::AppHandle<R>, files: Vec<PendingOpenFile>) {
if files.is_empty() {
return;
}
@@ -211,6 +210,49 @@ fn queue_open_paths<R: tauri::Runtime>(app: &tauri::AppHandle<R>, paths: Vec<Pat
}
}
+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 files: Vec<PendingOpenFile> = urls
+ .iter()
+ .filter(|url| url.scheme() == "openpencil")
+ .filter_map(|url| match deep_link::parse_open_url(url) {
+ Ok(open) => Some(PendingOpenFile {
+ path: open.file,
+ node: open.node,
+ deep_link: true,
+ }),
+ Err(error) => {
+ eprintln!("[deep-link] refused {url}: {error:?}");
+ None
+ }
+ })
+ .collect();
+
+ queue_pending(app, files);
+}
+
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)
@@ -238,6 +280,8 @@ pub fn run() {
}));
}
+ builder = builder.plugin(tauri_plugin_deep_link::init());
+
builder
.manage(PendingOpen(Mutex::new(Vec::new())))
.invoke_handler(tauri::generate_handler![
@@ -250,6 +294,7 @@ pub fn run() {
credential_store_availability,
credential_write,
mcp_lookup,
+ path_matches_suffix,
list_system_fonts,
load_system_font,
proxy_http_request,
@@ -270,6 +315,41 @@ pub fn run() {
})
.setup(|app| {
queue_open_paths(app.handle(), startup_open_paths());
+
+ use tauri_plugin_deep_link::DeepLinkExt;
+ // On macOS the plugin turns `RunEvent::Opened` into this callback, so every
+ // link that arrives while the app runs is handled here; the cold-start link
+ // arrives before this closure and is drained from `current` below. The
+ // `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());
+ });
+ #[cfg(any(windows, target_os = "linux"))]
+ {
+ if let Err(error) = app.deep_link().register_all() {
+ eprintln!("[deep-link] register_all failed: {error}");
+ }
+ }
+ // Every desktop platform can deliver the launch link before this closure
+ // runs, which means before the listener above exists, and the plugin's
+ // `deep-link://new-url` emit then reaches nobody:
+ //
+ // - Windows / Linux: the link is argv, and the plugin parses it in its own
+ // setup (`handle_cli_arguments`).
+ // - macOS: AppKit delivers the GetURL event *before* the app's setup. Traced
+ // on a cold `open openpencil://…`: `RunEvent::Opened` at T+0.085 s, this
+ // closure at T+0.342 s, and `on_open_url` never fired.
+ //
+ // In all three cases the URL survives only in the plugin's `current`, so it
+ // is read here. No link can be queued twice: `RunEvent::Opened` is dispatched
+ // on the main thread, the same thread this closure runs on, so a link cannot
+ // 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);
+ }
+
Ok(install_app_menu(app.handle(), &[])?)
})
.build(tauri::generate_context!())
diff --git a/desktop/tauri.conf.json b/desktop/tauri.conf.json
index 714742a9b..b3119f60d 100644
--- a/desktop/tauri.conf.json
+++ b/desktop/tauri.conf.json
@@ -51,11 +51,22 @@
"rank": "Alternate"
}
],
+ "linux": {
+ "deb": {
+ "desktopTemplate": "linux/main.desktop"
+ },
+ "rpm": {
+ "desktopTemplate": "linux/main.desktop"
+ }
+ },
"macOS": {
"signingIdentity": "Developer ID Application: Danila Poyarkov (N7D7M3Q3CD)"
}
},
"plugins": {
+ "deep-link": {
+ "desktop": { "schemes": ["openpencil"] }
+ },
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDU4QzBCRjBFNzhFNEVEMDEKUldRQjdlUjREci9BV0hLaEJPeG5tRXdsWkhQWFdEa0VxcEtNR1o1S2VJeGlKU1VDTldQTi9wYncK",
"endpoints": ["https://github.com/open-pencil/open-pencil/releases/latest/download/latest.json"],
diff --git a/packages/docs/programmable/index.md b/packages/docs/programmable/index.md
index 6a49babe3..815db4935 100644
--- a/packages/docs/programmable/index.md
+++ b/packages/docs/programmable/index.md
@@ -58,6 +58,32 @@ Connect Claude Code, Cursor, Windsurf, or any MCP-compatible client to OpenPenci
[MCP Server →](./mcp-server)
+## URL scheme
+
+The desktop app registers `openpencil://`, so a published page — a Storybook story, a design review, a README — can link straight to a layer:
+
+```
+openpencil://open?file=web/design/hikyo.pen&node=Button/Large/Default
+```
+
+`file` is a repository-relative path ending in `.pen` or `.fig`; absolute paths and `.` or `..` segments are refused. `node` is optional. Both values are URL-encoded — path separators may stay literal, but a literal `+` must be sent as `%2B` — and a repeated key takes its last value.
+
+The app matches `file` against the paths of the open tabs as a whole trailing segment sequence, and focuses that tab without re-reading the document, so a file that moved or turned unreadable since it opened still gets its layer selected. The first open tab whose path ends with the requested path wins, which matters when two checkouts have the same file open. Segments are compared the way the platform's filesystem does: ASCII-case-insensitively on macOS and Windows, exactly on Linux, so `Web/Design/hikyo.pen` and `web/design/hikyo.pen` are the same file on a Mac and two different ones on Linux. If no open tab matches, a file picker asks for the file once; the picked file must end with the same relative path, otherwise the link is cancelled. No path is joined onto a root and no filesystem access is granted beyond what the picker returns. A file the link actually opens — the picked one — joins the recent-files list like any other file you open; focusing a tab that was already open does not touch the list, because nothing was opened.
+
+With a node name, the app selects every layer carrying that exact name on the current page and zooms the view to the whole selection. An unknown name shows a notice and leaves the document open. Opening a file and selecting layers is all the scheme can do.
+
+The web app takes the same link from its own address bar:
+
+```
+https://app.openpencil.dev/?file=https://raw.githubusercontent.com/open-pencil/open-pencil/master/tests/fixtures/pencil_button.pen&node=Button/Large/Default
+```
+
+Here `file` is an absolute `https:` URL ending in `.pen` or `.fig` — the web app has no filesystem, so a relative path, an `http:` URL or any other extension is refused with a console warning and nothing else. The extension is read off the URL's path, so a query string on the linked file changes nothing. A fragment is dropped before the fetch: it never reaches the server, so `…/hikyo.pen#a` and `…/hikyo.pen#b` open one tab, not two. `node` behaves exactly as above: the same exact-name selection and zoom, the same notice when no layer carries the name. Both values are URL-encoded, a literal `+` must be sent as `%2B`, and a repeated key takes its last value, as on the desktop. The link is handled on any route, so `/share/<room>?file=…` and `/demo?file=…` work like `/?file=…`.
+
+The browser fetches the file cross-origin, so the host must allow it: `raw.githubusercontent.com` sends `Access-Control-Allow-Origin: *` and works. The request carries no credentials and refuses to follow redirects, which keeps an `https:` link from being bounced to a plaintext one — a `https://github.com/<owner>/<repo>/raw/...` URL redirects to `raw.githubusercontent.com` and is therefore refused, so link to the raw host directly. `file` and `node` are stripped from the address bar through the router as soon as they are read — before the fetch, and also when the link was refused — so a reload does not re-open the document, and neither a copied URL nor a later in-app navigation carries the link payload. A linked document is capped at 64 MiB: the body is counted as it streams in, not trusted from `Content-Length`, and the request is aborted the moment it goes over, with the link reporting that the file exceeds 64 MiB. A deployment that serves the app under a Content-Security-Policy must allow the linked host in `connect-src`, otherwise the fetch is blocked and the link reports that it could not open the file.
+
+On macOS the scheme belongs to the installed app bundle, so links reach an installed build and not a `tauri dev` process. On Windows and Linux the link arrives through the deep-link plugin, including when the app is not running yet: the link is queued at startup and handled once the editor is ready; on Linux the bundled desktop entry passes the link through `%U`.
+
## Why Open?
Figma is a closed platform. Their MCP server is read-only. CDP browser access was killed in version 126. Design files live in a proprietary format on someone else's servers. Plugin development requires a custom runtime with limited APIs.
diff --git a/src/app/automation/bridge/file-handlers.ts b/src/app/automation/bridge/file-handlers.ts
index 700935e2c..2f0db5981 100644
--- a/src/app/automation/bridge/file-handlers.ts
+++ b/src/app/automation/bridge/file-handlers.ts
@@ -4,8 +4,9 @@ import {
type AutomationTarget
} from '@/app/automation/bridge/target'
import { resolveBrowserFileURL } from '@/app/document/io/browser'
+import { openBrowserFileFromURL } from '@/app/shell/menu/files'
import { openFileFromPath } from '@/app/shell/menu/use'
-import { closeTab, createTab, getActiveStore, getTabById, openFileInNewTab } from '@/app/tabs'
+import { closeTab, createTab, getActiveStore, getTabById } from '@/app/tabs'
import { isTauri } from '@/app/tauri/env'
export async function handleSaveFile(target: AutomationTarget, args: unknown): Promise<unknown> {
@@ -58,12 +59,9 @@ export async function handleOpenFile(_target: AutomationTarget, args: unknown):
if (isTauri()) {
await openFileFromPath(path)
} else {
- const resourceURL = resolveBrowserFileURL(path)
- const response = await fetch(resourceURL)
- if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`)
- const name = resourceURL.pathname.split('/').pop() ?? 'file.fig'
- const file = new File([await response.blob()], name)
- await openFileInNewTab(file, undefined, resourceURL.href)
+ // Same fetch, cap and format check as every other browser open: an automation client
+ // is not more trusted than a link.
+ await openBrowserFileFromURL(resolveBrowserFileURL(path))
}
const target = resolveAutomationTarget(getActiveStore(), undefined)
return responseWithTarget({ ok: true, result: { opened: true } }, target)
diff --git a/src/app/document/io/browser.ts b/src/app/document/io/browser.ts
index 3d09761ee..73e69edfe 100644
--- a/src/app/document/io/browser.ts
+++ b/src/app/document/io/browser.ts
@@ -1,5 +1,76 @@
import type { ViewportSize } from '@/app/document/io/types'
+/**
+ * Ceiling on a document fetched from a URL. Both the browser link and the automation
+ * bridge accept an unbounded, caller-supplied URL, and buffering whatever the host
+ * sends would let one response exhaust the tab. Well past any real design file.
+ */
+export const MAX_REMOTE_DOCUMENT_BYTES = 64 * 1024 * 1024
+
+interface BoundedBodyOptions {
+ /** Aborts the underlying request when the body exceeds the cap. */
+ onExceeded?: () => void
+ /** Error message for an oversized body; defaults to the MiB figure. */
+ sizeError?: string
+}
+
+function oversizedBody(maxBytes: number): string {
+ return `exceeds ${Math.floor(maxBytes / (1024 * 1024))} MiB`
+}
+
+/**
+ * Reads a response body, aborting as soon as it exceeds `maxBytes`. The body is counted
+ * chunk by chunk as it streams in: `Content-Length` is the sender's claim, absent on a
+ * chunked response and free to lie on any other, so it is only a cheap early exit and
+ * the cap itself is enforced on the bytes that actually arrive. `onExceeded` cancels the
+ * request instead of draining the rest of an oversized body.
+ */
+export async function readBoundedBody(
+ response: Response,
+ maxBytes: number,
+ { onExceeded, sizeError }: BoundedBodyOptions = {}
+): Promise<Uint8Array<ArrayBuffer>> {
+ const fail = (): never => {
+ onExceeded?.()
+ throw new Error(sizeError ?? oversizedBody(maxBytes))
+ }
+
+ const declared = Number(response.headers.get('content-length'))
+ if (Number.isFinite(declared) && declared > maxBytes) fail()
+
+ if (!response.body) {
+ const bytes = new Uint8Array(await response.arrayBuffer())
+ if (bytes.byteLength > maxBytes) fail()
+ return bytes
+ }
+
+ const reader = response.body.getReader()
+ const chunks: Uint8Array[] = []
+ let totalBytes = 0
+ try {
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ totalBytes += value.byteLength
+ if (totalBytes > maxBytes) fail()
+ chunks.push(value)
+ }
+ } catch (error) {
+ await reader.cancel().catch(() => undefined)
+ throw error
+ } finally {
+ reader.releaseLock()
+ }
+
+ const bytes = new Uint8Array(totalBytes)
+ let offset = 0
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset)
+ offset += chunk.byteLength
+ }
+ return bytes
+}
+
export function resolveBrowserFileURL(path: string): URL {
const url = new URL(path, window.location.href)
url.hash = ''
diff --git a/src/app/document/io/deep-link.ts b/src/app/document/io/deep-link.ts
new file mode 100644
index 000000000..8f9f7e2fa
--- /dev/null
+++ b/src/app/document/io/deep-link.ts
@@ -0,0 +1,107 @@
+// openpencil://open?file=<relative>&node=<name>. The file is resolved against the
+// paths of the open tabs by whole trailing segments, so a one-segment file takes
+// the first open tab whose path ends with it. The segment comparison is the
+// filesystem's, not JavaScript's: the desktop build asks Rust, which folds ASCII
+// case on macOS and Windows and compares exactly on Linux. Otherwise the user picks it once
+// per link and the pick must end with the same relative path. A file the link
+// opens — the picked one — lands in the recent-files list like any other file
+// opened from the app; focusing an already open tab opens nothing and so does
+// not touch the list. No fs
+// scope is widened here: the dialog plugin scopes what it returns, and nothing
+// else is ever read from disk.
+import { notificationMessages } from '@/app/i18n/notifications'
+import { activateTabForPath, chooseTauriOpenPaths, openFileFromPath } from '@/app/shell/menu/files'
+
+export interface DeepLinkTarget {
+ path: string
+ node?: string
+}
+
+export interface DeepLinkActions {
+ /** Absolute paths of the documents currently open in tabs. */
+ openPaths: () => string[]
+ /** Selects the node and zooms to it. False when no node carries that name. */
+ selectByName: (name: string) => boolean
+ notify: (message: string) => void
+}
+
+/** A link is attacker-supplied text; a toast is not a place for 4 KB of it. */
+export function clamp(value: string): string {
+ return value.length > 120 ? `${value.slice(0, 119)}…` : value
+}
+
+/**
+ * Whether `candidate` ends with `relative` as whole path segments, decided by the
+ * `path_matches_suffix` Tauri command: it canonicalizes the candidate and compares
+ * its trailing segments the way the platform's filesystem does. Doing this in JS
+ * would either be case-sensitive (and cancel a link whose case differs on macOS or
+ * Windows) or lowercase everything (and match the wrong file on Linux).
+ */
+export type SuffixMatcher = (candidate: string, relative: string) => Promise<boolean>
+
+const tauriMatchesSuffix: SuffixMatcher = async (candidate, relative) => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ return invoke<boolean>('path_matches_suffix', { candidate, suffix: relative })
+}
+
+export async function resolveDeepLinkFile(
+ file: string,
+ openPaths: string[],
+ matches: SuffixMatcher = tauriMatchesSuffix
+): Promise<string | null> {
+ for (const path of openPaths) {
+ if (await matches(path, file)) return path
+ }
+ return null
+}
+
+/** File-system entry points, injected so tests can drive the picker branch. */
+interface DeepLinkIo {
+ choosePaths: () => Promise<string[]>
+ openPath: (path: string) => Promise<void>
+ /** Focuses the tab already showing `path`. False when no tab holds it. */
+ activateTab: (path: string) => Promise<boolean>
+ matchesSuffix: SuffixMatcher
+}
+
+const tauriIo: DeepLinkIo = {
+ choosePaths: chooseTauriOpenPaths,
+ openPath: openFileFromPath,
+ activateTab: activateTabForPath,
+ matchesSuffix: tauriMatchesSuffix
+}
+
+export async function openDeepLink(
+ target: DeepLinkTarget,
+ actions: DeepLinkActions,
+ io: DeepLinkIo = tauriIo
+): Promise<void> {
+ const messages = notificationMessages.get()
+ const known = await resolveDeepLinkFile(target.path, actions.openPaths(), io.matchesSuffix)
+ if (known) {
+ // An already open document is focused, never re-read from disk: re-reading would
+ // fail the whole link when the file moved or turned unreadable since it opened.
+ // It can also have closed between the snapshot and the activate — open it then.
+ if (!(await io.activateTab(known))) await io.openPath(known)
+ } else {
+ actions.notify(messages.deepLinkLocateFile({ file: clamp(target.path) }))
+ const chosen = await io.choosePaths()
+ // Dismissing the picker is not the same as picking the wrong file, so it gets its
+ // own notice instead of one that talks about a file the user never chose.
+ if (chosen.length === 0) {
+ actions.notify(messages.deepLinkPickerDismissed)
+ return
+ }
+ const picked = await resolveDeepLinkFile(target.path, chosen, io.matchesSuffix)
+ if (!picked) {
+ actions.notify(messages.deepLinkCancelled({ file: clamp(target.path) }))
+ return
+ }
+ await io.openPath(picked)
+ }
+ if (target.node && !actions.selectByName(target.node)) {
+ actions.notify(
+ messages.deepLinkNodeNotFound({ node: clamp(target.node), file: clamp(target.path) })
+ )
+ }
+}
diff --git a/src/app/document/io/pending-open.ts b/src/app/document/io/pending-open.ts
new file mode 100644
index 000000000..dfd74a047
--- /dev/null
+++ b/src/app/document/io/pending-open.ts
@@ -0,0 +1,46 @@
+// The queue the desktop shell fills before the editor exists: a double-clicked
+// document, an `Open With`, an argv path, or an `openpencil://` link. Rust tags each
+// entry with its producer because the frontend cannot tell them apart from the path
+// alone — a link's path is repo-relative, but a canonicalized Windows path is verbatim
+// (`\\?\C:\…`) and an association path can be anything the filesystem allows.
+//
+// This lives outside `WorkspaceView.vue` so the routing — which entry goes to the
+// deep-link resolver and which to the plain opener — is unit-testable without mounting
+// a view.
+import type { DeepLinkActions, DeepLinkTarget } from '@/app/document/io/deep-link'
+import { openDeepLink } from '@/app/document/io/deep-link'
+import { openDesignFileBatch, openFileFromPath } from '@/app/shell/menu/files'
+
+export interface PendingOpenFile extends DeepLinkTarget {
+ /** True when a `openpencil://` link queued this entry, false for a file association. */
+ deepLink: boolean
+}
+
+/** File-system entry points, injected so tests can observe the routing. */
+export interface PendingOpenIo {
+ openPath: (path: string) => Promise<void>
+ openLink: (target: DeepLinkTarget, actions: DeepLinkActions) => Promise<void>
+}
+
+const tauriIo: PendingOpenIo = { openPath: openFileFromPath, openLink: openDeepLink }
+
+function displayName(file: PendingOpenFile): string {
+ return file.path.split(/[/\\]/).pop() ?? file.path
+}
+
+/**
+ * Serialised, but one failing entry must not swallow the rest of the batch:
+ * `openDesignFileBatch` is the per-item catch every other open path already uses, so a
+ * rejection is logged *and* toasted and the drain carries on to the next file.
+ */
+export async function openPendingFiles(
+ files: readonly PendingOpenFile[],
+ actions: DeepLinkActions,
+ io: PendingOpenIo = tauriIo
+): Promise<void> {
+ await openDesignFileBatch(files, displayName, async (file) => {
+ // Only the deep-link resolver may turn a link's relative path into a real one.
+ if (file.deepLink) await io.openLink({ path: file.path, node: file.node }, actions)
+ else await io.openPath(file.path)
+ })
+}
diff --git a/src/app/document/io/web-link.ts b/src/app/document/io/web-link.ts
new file mode 100644
index 000000000..cd16a2097
--- /dev/null
+++ b/src/app/document/io/web-link.ts
@@ -0,0 +1,115 @@
+// https://app.openpencil.dev/?file=<https url>&node=<name> — the browser twin of the
+// desktop `openpencil://open` link. The desktop variant resolves a repo-relative path
+// against open tabs; the web app has no filesystem, so `file` is an absolute `https:`
+// URL the browser fetches cross-origin, without credentials and without following a
+// redirect. Nothing else is reachable: no `http:`, no `file:`, no other extension.
+import { omit } from 'es-toolkit'
+
+import { clamp } from '@/app/document/io/deep-link'
+import { notificationMessages } from '@/app/i18n/notifications'
+import { openBrowserFileFromURL } from '@/app/shell/menu/files'
+
+export interface WebOpenParams {
+ file: URL
+ node?: string
+}
+
+export interface WebLinkActions {
+ /** Selects the node and zooms to it. False when no node carries that name. */
+ selectByName: (name: string) => boolean
+ notify: (message: string, level: 'info' | 'error') => void
+}
+
+/**
+ * Pure parser over a `location.search` string. Returns null when the link carries no
+ * usable `file`; a present-but-refused `file` also warns once so the cause is visible
+ * in the console instead of looking like a silent no-op. A repeated key takes its last
+ * value, matching the desktop parser. The accepted URL carries no fragment.
+ */
+export function parseWebOpenParams(search: string): WebOpenParams | null {
+ const params = new URLSearchParams(search)
+ const file = params.getAll('file').at(-1)
+ if (!file) return null
+ let url: URL
+ try {
+ url = new URL(file)
+ } catch {
+ console.warn('[Web link] refused a file that is not a URL:', clamp(file))
+ return null
+ }
+ if (url.protocol !== 'https:' || !/\.(?:pen|fig)$/i.test(url.pathname)) {
+ console.warn('[Web link] refused file, expected https and .pen or .fig:', clamp(file))
+ return null
+ }
+ // The fragment never reaches the server, so two links that differ only in it name
+ // the same document; keeping it would make the tab identity (an exact `href` compare)
+ // see two documents and open a duplicate tab for each fragment.
+ url.hash = ''
+ return { file: url, node: params.getAll('node').at(-1) || undefined }
+}
+
+/** Fetch entry point, injected so tests can drive the failure branch. */
+export interface WebLinkIo {
+ open: (url: URL) => Promise<void>
+}
+
+const browserIo: WebLinkIo = {
+ // No cookies leave the app for a link-supplied host, and a redirect is refused
+ // rather than followed, so an https URL cannot be bounced to a plaintext one.
+ open: (url) => openBrowserFileFromURL(url, { credentials: 'omit', redirect: 'error' })
+}
+
+export async function openWebLink(
+ target: WebOpenParams,
+ actions: WebLinkActions,
+ io: WebLinkIo = browserIo
+): Promise<void> {
+ const messages = notificationMessages.get()
+ try {
+ await io.open(target.file)
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error)
+ // Host, status text and filename all come from the link: clamp both halves.
+ actions.notify(
+ messages.openFileFailed({ name: clamp(target.file.host), error: clamp(detail) }),
+ 'error'
+ )
+ return
+ }
+ if (target.node && !actions.selectByName(target.node)) {
+ actions.notify(
+ messages.deepLinkNodeNotFound({ node: clamp(target.node), file: clamp(target.file.host) }),
+ 'info'
+ )
+ }
+}
+
+/**
+ * The caller's route query minus the link params, so the strip keeps every other key.
+ * Router-free on purpose: the router types live in the view, this is just the filter.
+ */
+export function withoutWebLinkParams<T>(query: Record<string, T>): Record<string, T> {
+ return omit(query, ['file', 'node'])
+}
+
+/**
+ * Handles the link on the current URL. `strip` removes `file` and `node` from the
+ * address bar and runs before the document is fetched, so a reload does not re-open
+ * and neither a copied nor a later pushed URL carries the payload. It also runs for a
+ * refused link, which opened nothing but would otherwise stay in the next copied URL.
+ * Stripping is injected because it belongs to the router: rewriting `history` directly
+ * leaves the router's own record of the current URL pointing at the un-stripped one,
+ * and the next `router.push` writes the params straight back into the history entry.
+ */
+export async function openWebLinkFromLocation(
+ search: string,
+ strip: () => void,
+ actions: WebLinkActions,
+ io: WebLinkIo = browserIo
+): Promise<void> {
+ const params = new URLSearchParams(search)
+ if (!params.has('file') && !params.has('node')) return
+ const target = parseWebOpenParams(search)
+ strip()
+ if (target) await openWebLink(target, actions, io)
+}
diff --git a/src/app/editor/selection/focus.ts b/src/app/editor/selection/focus.ts
new file mode 100644
index 000000000..c6372b613
--- /dev/null
+++ b/src/app/editor/selection/focus.ts
@@ -0,0 +1,48 @@
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+/** What focusing needs from the editor, so a caller can drive it without a whole store. */
+export interface FocusStore {
+ graph: Pick<SceneGraph, 'getChildren' | 'getNode'>
+ state: { currentPageId: string }
+ select: (ids: string[]) => void
+ zoomToSelection: () => void
+}
+
+/**
+ * Ids of the nodes named exactly `name` on the current page, in document order.
+ *
+ * Exact and case-sensitive on purpose: a link names one layer, where the `find_nodes`
+ * tool offers the forgiving search a person does by hand.
+ */
+export function findNodesByName(
+ graph: FocusStore['graph'],
+ rootId: string,
+ name: string
+): string[] {
+ const matches: string[] = []
+ const walk = (parentId: string) => {
+ for (const child of graph.getChildren(parentId)) {
+ if (child.name === name) matches.push(child.id)
+ walk(child.id)
+ }
+ }
+ walk(rootId)
+ return matches
+}
+
+/**
+ * Selects the nodes and zooms to them. False when none of the ids is in the document,
+ * so a caller holding a stale id can tell that nothing was brought into view.
+ */
+export function focusNodes(store: FocusStore, ids: readonly string[]): boolean {
+ const present = ids.filter((id) => store.graph.getNode(id) !== undefined)
+ if (present.length === 0) return false
+ store.select(present)
+ store.zoomToSelection()
+ return true
+}
+
+/** Focuses every node with that exact name on the current page. */
+export function focusNodesByName(store: FocusStore, name: string): boolean {
+ return focusNodes(store, findNodesByName(store.graph, store.state.currentPageId, name))
+}
diff --git a/src/app/editor/vectorize/providers.ts b/src/app/editor/vectorize/providers.ts
index 8e3720301..081f60d4f 100644
--- a/src/app/editor/vectorize/providers.ts
+++ b/src/app/editor/vectorize/providers.ts
@@ -1,6 +1,7 @@
import { encodeBase64 } from '@open-pencil/core/bytes'
import { IS_TAURI } from '@open-pencil/core/constants'
+import { readBoundedBody } from '@/app/document/io/browser'
import { tauriFetch } from '@/app/tauri/http'
import {
@@ -115,40 +116,7 @@ async function readBoundedResponse(
maxBytes: number,
sizeError: string
): Promise<string> {
- const contentLength = Number(response.headers.get('content-length'))
- if (Number.isFinite(contentLength) && contentLength > maxBytes) {
- throw new Error(sizeError)
- }
- if (!response.body) {
- const bytes = new Uint8Array(await response.arrayBuffer())
- if (bytes.byteLength > maxBytes) throw new Error(sizeError)
- return new TextDecoder().decode(bytes)
- }
-
- const reader = response.body.getReader()
- const chunks: Uint8Array[] = []
- let totalBytes = 0
- try {
- let result = await reader.read()
- while (!result.done) {
- totalBytes += result.value.byteLength
- if (totalBytes > maxBytes) throw new Error(sizeError)
- chunks.push(result.value)
- result = await reader.read()
- }
- } catch (error) {
- await reader.cancel().catch(() => undefined)
- throw error
- } finally {
- reader.releaseLock()
- }
-
- const bytes = new Uint8Array(totalBytes)
- let offset = 0
- for (const chunk of chunks) {
- bytes.set(chunk, offset)
- offset += chunk.byteLength
- }
+ const bytes = await readBoundedBody(response, maxBytes, { sizeError })
return new TextDecoder().decode(bytes)
}
diff --git a/src/app/i18n/notifications/index.ts b/src/app/i18n/notifications/index.ts
index f924b6bfe..76656ce8e 100644
--- a/src/app/i18n/notifications/index.ts
+++ b/src/app/i18n/notifications/index.ts
@@ -27,7 +27,12 @@ export const notificationMessageDefaults = {
vectorizeFailed: params('{provider} could not vectorize this image: {error}'),
operationFailed: params('Operation failed: {error}'),
storageConnected: 'Connected. Storage namespace is ready.',
- storageConnectionFailed: params('Could not connect to storage: {error}')
+ storageConnectionFailed: params('Could not connect to storage: {error}'),
+ deepLinkLocateFile: params('Locate “{file}” to follow this link.'),
+ deepLinkPickerDismissed: 'Link cancelled: no file was chosen.',
+ deepLinkCancelled: params('Link cancelled: expected a file ending in “{file}”.'),
+ deepLinkNodeNotFound: params('Node “{node}” was not found in “{file}”.'),
+ openQueuedFilesFailed: params('Could not open the files handed to OpenPencil: {error}')
} as const
const localeLoaders = {
diff --git a/src/app/i18n/notifications/locales/de.json b/src/app/i18n/notifications/locales/de.json
index 85aee03cf..384a03f4f 100644
--- a/src/app/i18n/notifications/locales/de.json
+++ b/src/app/i18n/notifications/locales/de.json
@@ -21,5 +21,10 @@
"nodeID": "Knoten-ID",
"nodeIDs": "Knoten-IDs",
"xPath": "XPath",
- "xPaths": "XPaths"
+ "xPaths": "XPaths",
+ "deepLinkLocateFile": "Wähle „{file}“, um diesem Link zu folgen.",
+ "deepLinkPickerDismissed": "Link abgebrochen: Es wurde keine Datei ausgewählt.",
+ "deepLinkCancelled": "Link abgebrochen: Erwartet wurde eine Datei mit der Endung „{file}“.",
+ "deepLinkNodeNotFound": "Ebene „{node}“ wurde in „{file}“ nicht gefunden.",
+ "openQueuedFilesFailed": "Die an OpenPencil übergebenen Dateien konnten nicht geöffnet werden: {error}"
}
diff --git a/src/app/i18n/notifications/locales/es.json b/src/app/i18n/notifications/locales/es.json
index 68481ac54..3c117106b 100644
--- a/src/app/i18n/notifications/locales/es.json
+++ b/src/app/i18n/notifications/locales/es.json
@@ -21,5 +21,10 @@
"nodeID": "ID de nodo",
"nodeIDs": "ID de nodos",
"xPath": "XPath",
- "xPaths": "XPaths"
+ "xPaths": "XPaths",
+ "deepLinkLocateFile": "Localiza «{file}» para seguir este enlace.",
+ "deepLinkPickerDismissed": "Enlace cancelado: no se eligió ningún archivo.",
+ "deepLinkCancelled": "Enlace cancelado: se esperaba un archivo que terminara en «{file}».",
+ "deepLinkNodeNotFound": "No se encontró la capa «{node}» en «{file}».",
+ "openQueuedFilesFailed": "No se pudieron abrir los archivos entregados a OpenPencil: {error}"
}
diff --git a/src/app/i18n/notifications/locales/fr.json b/src/app/i18n/notifications/locales/fr.json
index da6cc5990..1c3ea26da 100644
--- a/src/app/i18n/notifications/locales/fr.json
+++ b/src/app/i18n/notifications/locales/fr.json
@@ -21,5 +21,10 @@
"nodeID": "ID de nœud",
"nodeIDs": "ID de nœuds",
"xPath": "XPath",
- "xPaths": "XPaths"
+ "xPaths": "XPaths",
+ "deepLinkLocateFile": "Localisez « {file} » pour suivre ce lien.",
+ "deepLinkPickerDismissed": "Lien annulé : aucun fichier n’a été choisi.",
+ "deepLinkCancelled": "Lien annulé : un fichier se terminant par « {file} » était attendu.",
+ "deepLinkNodeNotFound": "Le calque « {node} » est introuvable dans « {file} ».",
+ "openQueuedFilesFailed": "Impossible d’ouvrir les fichiers transmis à OpenPencil : {error}"
}
diff --git a/src/app/i18n/notifications/locales/it.json b/src/app/i18n/notifications/locales/it.json
index 3ab498cd1..6f886d14a 100644
--- a/src/app/i18n/notifications/locales/it.json
+++ b/src/app/i18n/notifications/locales/it.json
@@ -21,5 +21,10 @@
"nodeID": "ID nodo",
"nodeIDs": "ID nodi",
"xPath": "XPath",
- "xPaths": "XPath"
+ "xPaths": "XPath",
+ "deepLinkLocateFile": "Individua «{file}» per seguire questo link.",
+ "deepLinkPickerDismissed": "Link annullato: non è stato scelto alcun file.",
+ "deepLinkCancelled": "Link annullato: era atteso un file che termina con «{file}».",
+ "deepLinkNodeNotFound": "Il livello «{node}» non è stato trovato in «{file}».",
+ "openQueuedFilesFailed": "Impossibile aprire i file passati a OpenPencil: {error}"
}
diff --git a/src/app/i18n/notifications/locales/ja.json b/src/app/i18n/notifications/locales/ja.json
index 45f22396a..76a66069d 100644
--- a/src/app/i18n/notifications/locales/ja.json
+++ b/src/app/i18n/notifications/locales/ja.json
@@ -21,5 +21,10 @@
"nodeID": "ノード ID",
"nodeIDs": "ノード ID",
"xPath": "XPath",
- "xPaths": "XPath"
+ "xPaths": "XPath",
+ "deepLinkLocateFile": "このリンクを開くには「{file}」を指定してください。",
+ "deepLinkPickerDismissed": "リンクをキャンセルしました。ファイルが選択されていません。",
+ "deepLinkCancelled": "リンクをキャンセルしました。「{file}」で終わるファイルが必要です。",
+ "deepLinkNodeNotFound": "「{file}」にレイヤー「{node}」が見つかりませんでした。",
+ "openQueuedFilesFailed": "OpenPencil に渡されたファイルを開けませんでした: {error}"
}
diff --git a/src/app/i18n/notifications/locales/pl.json b/src/app/i18n/notifications/locales/pl.json
index ae6ea80f7..8a1ed39ec 100644
--- a/src/app/i18n/notifications/locales/pl.json
+++ b/src/app/i18n/notifications/locales/pl.json
@@ -21,5 +21,10 @@
"nodeID": "ID węzła",
"nodeIDs": "ID węzłów",
"xPath": "XPath",
- "xPaths": "XPath"
+ "xPaths": "XPath",
+ "deepLinkLocateFile": "Wskaż „{file}”, aby otworzyć ten link.",
+ "deepLinkPickerDismissed": "Link anulowany: nie wybrano żadnego pliku.",
+ "deepLinkCancelled": "Link anulowany: oczekiwano pliku kończącego się na „{file}”.",
+ "deepLinkNodeNotFound": "Nie znaleziono warstwy „{node}” w „{file}”.",
+ "openQueuedFilesFailed": "Nie udało się otworzyć plików przekazanych do OpenPencil: {error}"
}
diff --git a/src/app/i18n/notifications/locales/ru.json b/src/app/i18n/notifications/locales/ru.json
index 9cbe51832..9d9243cf8 100644
--- a/src/app/i18n/notifications/locales/ru.json
+++ b/src/app/i18n/notifications/locales/ru.json
@@ -21,5 +21,10 @@
"nodeID": "ID узла",
"nodeIDs": "ID узлов",
"xPath": "XPath",
- "xPaths": "XPath"
+ "xPaths": "XPath",
+ "deepLinkLocateFile": "Укажите «{file}», чтобы перейти по этой ссылке.",
+ "deepLinkPickerDismissed": "Ссылка отменена: файл не выбран.",
+ "deepLinkCancelled": "Ссылка отменена: ожидался файл с окончанием «{file}».",
+ "deepLinkNodeNotFound": "Слой «{node}» не найден в «{file}».",
+ "openQueuedFilesFailed": "Не удалось открыть файлы, переданные OpenPencil: {error}"
}
diff --git a/src/app/i18n/notifications/locales/zh-cn.json b/src/app/i18n/notifications/locales/zh-cn.json
index 1716b4b72..0ff48e37c 100644
--- a/src/app/i18n/notifications/locales/zh-cn.json
+++ b/src/app/i18n/notifications/locales/zh-cn.json
@@ -21,5 +21,10 @@
"nodeID": "节点 ID",
"nodeIDs": "节点 ID",
"xPath": "XPath",
- "xPaths": "XPath"
+ "xPaths": "XPath",
+ "deepLinkLocateFile": "请找到“{file}”以打开此链接。",
+ "deepLinkPickerDismissed": "已取消链接:未选择任何文件。",
+ "deepLinkCancelled": "已取消链接:需要以“{file}”结尾的文件。",
+ "deepLinkNodeNotFound": "在“{file}”中未找到图层“{node}”。",
+ "openQueuedFilesFailed": "无法打开传递给 OpenPencil 的文件:{error}"
}
diff --git a/src/app/shell/menu/files.ts b/src/app/shell/menu/files.ts
index 4acb47283..78986c6a2 100644
--- a/src/app/shell/menu/files.ts
+++ b/src/app/shell/menu/files.ts
@@ -3,11 +3,16 @@ import { useFileDialog } from '@vueuse/core'
import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
import { setOpenPencilOpenFileHandler } from '@/app/browser-bridge'
-import { resolveBrowserFileURL } from '@/app/document/io/browser'
+import {
+ resolveBrowserFileURL,
+ MAX_REMOTE_DOCUMENT_BYTES,
+ readBoundedBody
+} from '@/app/document/io/browser'
import { notificationMessages } from '@/app/i18n/notifications'
import { rememberRecentFile } from '@/app/recent-files'
import { toast } from '@/app/shell/ui'
-import { openFileInNewTab } from '@/app/tabs'
+import { getTabsSnapshot, openFileInNewTab, switchTab } from '@/app/tabs'
+import { findTabByFileIdentity } from '@/app/tabs/open/identity'
import { isTauri } from '@/app/tauri/env'
import { IS_BROWSER } from '@/constants'
@@ -43,16 +48,33 @@ fileDialog.onChange((files) => {
if (IS_BROWSER && 'window' in globalThis) {
setOpenPencilOpenFileHandler(async (path: string) => {
- const resourceURL = resolveBrowserFileURL(path)
- const response = await fetch(resourceURL)
- const blob = await response.blob()
- const name = resourceURL.pathname.split('/').pop() ?? 'file.fig'
- assertSupportedDesignFile(name)
- const file = new File([blob], name, { type: 'application/octet-stream' })
- await openFileInNewTab(file, undefined, resourceURL.href)
+ await openBrowserFileFromURL(resolveBrowserFileURL(path))
})
}
+/** Fetches a document over HTTP and opens it in a new tab. Browser builds only. */
+export async function openBrowserFileFromURL(url: URL, init?: RequestInit): Promise<void> {
+ // The cap needs a controller of its own, so a caller's signal is combined with it
+ // rather than replaced: dropping it would leave the caller unable to cancel.
+ const controller = new AbortController()
+ const signal = init?.signal
+ ? AbortSignal.any([init.signal, controller.signal])
+ : controller.signal
+ const response = await fetch(url, { ...init, signal })
+ if (!response.ok)
+ throw new Error(`Failed to fetch file: ${response.status} ${response.statusText}`)
+ const bytes = await readBoundedBody(response, MAX_REMOTE_DOCUMENT_BYTES, {
+ onExceeded: () => controller.abort()
+ })
+ if (bytes.byteLength === 0) {
+ throw new Error('Failed to fetch file: the response carried no body')
+ }
+ const name = url.pathname.split('/').pop() ?? 'file.fig'
+ assertSupportedDesignFile(name)
+ const file = new File([bytes], name, { type: 'application/octet-stream' })
+ await openFileInNewTab(file, undefined, url.href)
+}
+
function isSupportedDesignFile(fileName: string): boolean {
const lowerName = fileName.toLowerCase()
return (
@@ -108,6 +130,20 @@ export async function openFileFromPath(path: string) {
rememberRecentFile(path)
}
+/**
+ * Focuses the tab already showing `path` without touching the disk. False when no tab
+ * holds it, which lets a caller fall back to opening the file. `openFileFromPath` would
+ * also land on the existing tab, but only after re-reading the file, so a document that
+ * moved or lost its permissions since it opened would reject instead of being focused.
+ */
+export async function activateTabForPath(path: string): Promise<boolean> {
+ const tab = await findTabByFileIdentity(getTabsSnapshot(), { handle: null, path })
+ if (!tab) return false
+ // The tab can close while the identity lookup awaits, and `switchTab` then does nothing:
+ // reporting success here would make the caller skip opening the file.
+ return switchTab(tab.id)
+}
+
export async function openFileDialog() {
if (isTauri()) {
const paths = await chooseTauriOpenPaths()
diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.ts
index 2cc7cf854..594f29dca 100644
--- a/src/app/tabs/index.ts
+++ b/src/app/tabs/index.ts
@@ -145,10 +145,12 @@ function activateTab(tab: Tab) {
setOpenPencilStore(tab.store)
}
-export function switchTab(tabId: string) {
+/** Activates the tab. False when no tab carries that id, so callers can tell a no-op apart. */
+export function switchTab(tabId: string): boolean {
const tab = tabsRef.value.find((t) => t.id === tabId)
- if (!tab) return
+ if (!tab) return false
activateTab(tab)
+ return true
}
export async function closeTab(tabId: string): Promise<void> {
diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vue
index 8d75e4248..4c944f2a6 100644
--- a/src/views/WorkspaceView.vue
+++ b/src/views/WorkspaceView.vue
@@ -2,22 +2,29 @@
import { useHead } from '@unhead/vue'
import { useEventListener } from '@vueuse/core'
import { onMounted, onUnmounted, provide, ref } from 'vue'
-import { useRoute } from 'vue-router'
+import { useRoute, useRouter } from 'vue-router'
import { startMCPRuntime, stopMCPRuntime } from '@/app/automation/mcp/runtime'
import { startWebMCP } from '@/app/automation/webmcp/runtime'
import { exposeCollaborationActions } from '@/app/browser-bridge'
import { COLLAB_KEY, useCollab } from '@/app/collab/use'
import { createDemoShapes } from '@/app/demo/document'
+import type { PendingOpenFile } from '@/app/document/io/pending-open'
+import { openPendingFiles } from '@/app/document/io/pending-open'
+import { openWebLinkFromLocation, withoutWebLinkParams } from '@/app/document/io/web-link'
+import { focusNodesByName } from '@/app/editor/selection/focus'
+import { notificationMessages } from '@/app/i18n/notifications'
import { appRuntimeConfig } from '@/app/runtime/config'
import { useKeyboard } from '@/app/shell/keyboard/use'
-import { openFileFromPath, useEditorMenu } from '@/app/shell/menu/use'
+import { useEditorMenu } from '@/app/shell/menu/use'
+import { toast } from '@/app/shell/ui'
import {
activeTab,
createDocumentInCurrentTab,
createHomeTab,
createTab,
getActiveStore,
+ getTabsSnapshot,
tabCount
} from '@/app/tabs'
import { isTauri } from '@/app/tauri/env'
@@ -29,8 +36,10 @@ import FontStatusBanner from '@/components/font-status/FontStatusBanner.vue'
import HomeWorkspace from '@/components/home/HomeWorkspace.vue'
import RenameSelectionDialog from '@/components/selection/RenameSelectionDialog.vue'
import TabBar from '@/components/TabBar.vue'
+import { IS_BROWSER } from '@/constants'
const route = useRoute()
+const router = useRouter()
const createdInitialTab = tabCount() === 0
const shouldCreateHome =
route.path === '/' &&
@@ -63,23 +72,72 @@ useEventListener(
const fileAssociationCleanup = ref<(() => void) | null>(null)
-interface PendingOpenFile {
- path: string
+/**
+ * A drain that fails wholesale — the `take_pending_open` invoke, the event binding —
+ * leaves the user staring at an app that ignored their double-click or their link.
+ * Per-entry failures are already toasted inside `openPendingFiles`; this is the outer
+ * net, and it must be visible, not console-only.
+ */
+function reportOpenFailure(error: unknown): void {
+ console.error('[Open With]', error)
+ toast.error(
+ notificationMessages.get().openQueuedFilesFailed({
+ error: error instanceof Error ? error.message : String(error)
+ })
+ )
+}
+
+function openDocumentPaths(): string[] {
+ return getTabsSnapshot()
+ .map((tab) => tab.store.getSourceIdentity().path)
+ .filter((path): path is string => path !== null)
+}
+
+/**
+ * Drops the link params through the router, not through `history` directly: the router
+ * keeps its own copy of the current URL in `history.state` and re-applies it on the next
+ * navigation, which would put `file` and `node` back into the entry. Route and hash are
+ * preserved, so the link works on `/`, `/share/:id` and `/demo` alike.
+ */
+function stripWebLinkParams(): void {
+ void router.replace({
+ path: route.path,
+ query: withoutWebLinkParams(route.query),
+ hash: route.hash
+ })
+}
+
+/** The action both link handlers take; see `focusNodesByName`. */
+function selectNodeByName(name: string): boolean {
+ return focusNodesByName(getActiveStore(), name)
}
async function openPendingAssociatedFiles(): Promise<void> {
const { invoke } = await import('@tauri-apps/api/core')
const files = await invoke<PendingOpenFile[]>('take_pending_open')
- for (const file of files) await openFileFromPath(file.path)
+ await openPendingFiles(files, {
+ openPaths: openDocumentPaths,
+ selectByName: selectNodeByName,
+ notify: toast.info
+ })
+}
+
+// A deep link can block this drain on a modal file picker, so a second event must
+// queue behind the first: overlapping drains would prompt twice for the same file.
+let pendingOpenDrain: Promise<void> = Promise.resolve()
+
+function drainPendingOpens(): Promise<void> {
+ pendingOpenDrain = pendingOpenDrain.then(openPendingAssociatedFiles).catch(reportOpenFailure)
+ return pendingOpenDrain
}
async function bindAssociatedFileOpen(): Promise<void> {
if (!isTauri()) return
const { listen } = await import('@tauri-apps/api/event')
fileAssociationCleanup.value = await listen('open-associated-files', () => {
- void openPendingAssociatedFiles().catch((error) => console.error('[Open With]', error))
+ void drainPendingOpens()
})
- await openPendingAssociatedFiles()
+ await drainPendingOpens()
}
let stopWebMCP: (() => void) | undefined
@@ -91,7 +149,20 @@ onMounted(async () => {
try {
await bindAssociatedFileOpen()
} catch (error) {
- console.error('[Open With]', error)
+ reportOpenFailure(error)
+ }
+
+ // The browser twin of the deep link: the desktop build takes its links through the
+ // deep-link plugin above, so only a real browser reads them off the address bar.
+ if (IS_BROWSER && !isTauri()) {
+ try {
+ await openWebLinkFromLocation(window.location.search, stripWebLinkParams, {
+ selectByName: selectNodeByName,
+ notify: (message, level) => (level === 'error' ? toast.error : toast.info)(message)
+ })
+ } catch (error) {
+ console.error('[Web link]', error)
+ }
}
})
diff --git a/tests/engine/app/document/io/browser.test.ts b/tests/engine/app/document/io/browser.test.ts
new file mode 100644
index 000000000..5a50d1788
--- /dev/null
+++ b/tests/engine/app/document/io/browser.test.ts
@@ -0,0 +1,81 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test'
+
+import { readBoundedBody } from '@/app/document/io/browser'
+import { openBrowserFileFromURL } from '@/app/shell/menu/files'
+
+const MIB = 1024 * 1024
+const originalFetch = globalThis.fetch
+
+function streamed(chunks: number[]): Response {
+ return new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const size of chunks) controller.enqueue(new Uint8Array(size))
+ controller.close()
+ }
+ })
+ )
+}
+
+afterEach(() => {
+ globalThis.fetch = originalFetch
+})
+
+describe('readBoundedBody', () => {
+ test('buffers a body that stays under the cap', async () => {
+ const onExceeded = mock(() => undefined)
+
+ const bytes = await readBoundedBody(streamed([20, 10]), MIB, { onExceeded })
+
+ expect(bytes.byteLength).toBe(30)
+ expect(onExceeded).not.toHaveBeenCalled()
+ })
+
+ test('aborts the request as soon as the cap is exceeded', async () => {
+ const onExceeded = mock(() => undefined)
+ // The third chunk pushes it over: the read stops there instead of draining the
+ // body, and the notice names the cap the user has to stay under.
+ const body = streamed([MIB / 2, MIB / 2, 1, 64 * MIB])
+
+ await expect(readBoundedBody(body, MIB, { onExceeded })).rejects.toThrow('exceeds 1 MiB')
+ expect(onExceeded).toHaveBeenCalledTimes(1)
+ })
+
+ test('accepts a body of exactly the cap and refuses one byte more', async () => {
+ const onExceeded = mock(() => undefined)
+
+ const exact = await readBoundedBody(streamed([MIB / 2, MIB / 2]), MIB, { onExceeded })
+ expect(exact.byteLength).toBe(MIB)
+ expect(onExceeded).not.toHaveBeenCalled()
+
+ await expect(readBoundedBody(streamed([MIB, 1]), MIB, { onExceeded })).rejects.toThrow(
+ 'exceeds'
+ )
+ expect(onExceeded).toHaveBeenCalledTimes(1)
+ })
+
+ test('counts the bytes that arrive, not a Content-Length claim', async () => {
+ const response = streamed([MIB, MIB])
+ response.headers.set('Content-Length', '1')
+ const onExceeded = mock(() => undefined)
+
+ await expect(readBoundedBody(response, MIB, { onExceeded })).rejects.toThrow('exceeds')
+ expect(onExceeded).toHaveBeenCalledTimes(1)
+ })
+
+ test('lets a caller name its own oversized-body error', async () => {
+ await expect(
+ readBoundedBody(streamed([MIB, 1]), MIB, { sizeError: 'Vectorized SVG is too large' })
+ ).rejects.toThrow('Vectorized SVG is too large')
+ })
+})
+
+describe('openBrowserFileFromURL', () => {
+ test('refuses a response with no body instead of opening an empty document', async () => {
+ globalThis.fetch = mock(async () => new Response(null, { status: 200 })) as typeof fetch
+
+ await expect(openBrowserFileFromURL(new URL('https://example.com/design.pen'))).rejects.toThrow(
+ 'carried no body'
+ )
+ })
+})
diff --git a/tests/engine/app/document/io/deep-link.test.ts b/tests/engine/app/document/io/deep-link.test.ts
new file mode 100644
index 000000000..511fbea9e
--- /dev/null
+++ b/tests/engine/app/document/io/deep-link.test.ts
@@ -0,0 +1,213 @@
+import { describe, expect, mock, test } from 'bun:test'
+
+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`.
+ */
+const matchesSuffix = async (candidate: string, relative: string): Promise<boolean> => {
+ const a = candidate.replaceAll('\\', '/')
+ const r = relative.replaceAll('\\', '/')
+ return a === r || a.endsWith(`/${r}`)
+}
+
+const caseInsensitiveMatches = async (candidate: string, relative: string): Promise<boolean> =>
+ matchesSuffix(candidate.toLowerCase(), relative.toLowerCase())
+
+function io(overrides: Partial<Parameters<typeof openDeepLink>[2]> = {}) {
+ return {
+ choosePaths: mock(async (): Promise<string[]> => []),
+ openPath: mock(async (): Promise<void> => undefined),
+ activateTab: mock(async (): Promise<boolean> => true),
+ matchesSuffix,
+ ...overrides
+ }
+}
+
+describe('resolveDeepLinkFile', () => {
+ test('matches an open tab whose path ends with the relative file', async () => {
+ expect(
+ await resolveDeepLinkFile(
+ 'web/design/hikyo.pen',
+ ['/r/hikyo/web/design/hikyo.pen'],
+ matchesSuffix
+ )
+ ).toBe('/r/hikyo/web/design/hikyo.pen')
+ })
+
+ test('returns null when nothing matches', async () => {
+ expect(
+ await resolveDeepLinkFile('web/design/hikyo.pen', ['/other/x.pen'], matchesSuffix)
+ ).toBeNull()
+ })
+
+ test('does not match a partial segment', async () => {
+ expect(
+ await resolveDeepLinkFile('design/hikyo.pen', ['/r/redesign/hikyo.pen'], matchesSuffix)
+ ).toBeNull()
+ })
+
+ test('accepts backslashes on either side', async () => {
+ expect(
+ await resolveDeepLinkFile(
+ 'web\\design\\hikyo.pen',
+ ['C:\\r\\web\\design\\hikyo.pen'],
+ matchesSuffix
+ )
+ ).toBe('C:\\r\\web\\design\\hikyo.pen')
+ })
+
+ test('takes the comparator verdict, so a case-insensitive filesystem still matches', async () => {
+ const paths = ['/r/hikyo/Web/Design/Hikyo.pen']
+ expect(await resolveDeepLinkFile('web/design/hikyo.pen', paths, matchesSuffix)).toBeNull()
+ expect(await resolveDeepLinkFile('web/design/hikyo.pen', paths, caseInsensitiveMatches)).toBe(
+ '/r/hikyo/Web/Design/Hikyo.pen'
+ )
+ })
+
+ test('returns the first matching open path', async () => {
+ expect(
+ await resolveDeepLinkFile('hikyo.pen', ['/a/hikyo.pen', '/b/hikyo.pen'], matchesSuffix)
+ ).toBe('/a/hikyo.pen')
+ })
+})
+
+describe('openDeepLink', () => {
+ test('activates the tab of an already open file without re-reading it from disk', async () => {
+ const selectByName = mock(() => true)
+ const deps = io()
+ const notices: string[] = []
+
+ await openDeepLink(
+ { path: 'web/design/hikyo.pen', node: 'Button/Large/Default' },
+ {
+ openPaths: () => ['/r/hikyo/web/design/hikyo.pen'],
+ selectByName,
+ notify: (message) => notices.push(message)
+ },
+ deps
+ )
+
+ expect(deps.choosePaths).not.toHaveBeenCalled()
+ // The resolved absolute path, never the link's own string, and never a disk read:
+ // a file that moved since its tab opened must still focus that tab.
+ expect(deps.activateTab).toHaveBeenCalledTimes(1)
+ expect(deps.activateTab).toHaveBeenCalledWith('/r/hikyo/web/design/hikyo.pen')
+ expect(deps.openPath).not.toHaveBeenCalled()
+ expect(selectByName).toHaveBeenCalledWith('Button/Large/Default')
+ expect(notices).toEqual([])
+ })
+
+ test('opens the path when its tab closed between the snapshot and the activate', async () => {
+ const deps = io({ activateTab: mock(async () => false) })
+ const notices: string[] = []
+
+ await openDeepLink(
+ { path: 'web/design/hikyo.pen' },
+ {
+ openPaths: () => ['/r/hikyo/web/design/hikyo.pen'],
+ selectByName: () => true,
+ notify: (message) => notices.push(message)
+ },
+ deps
+ )
+
+ expect(deps.openPath).toHaveBeenCalledWith('/r/hikyo/web/design/hikyo.pen')
+ expect(deps.choosePaths).not.toHaveBeenCalled()
+ expect(notices).toEqual([])
+ })
+
+ test('opens the picked file and selects the node when no tab matches', async () => {
+ const selectByName = mock(() => true)
+ const deps = io({ choosePaths: mock(async () => ['/picked/web/design/hikyo.pen']) })
+ const notices: string[] = []
+
+ await openDeepLink(
+ { path: 'web/design/hikyo.pen', node: 'Button/Large/Default' },
+ {
+ openPaths: () => [],
+ selectByName,
+ notify: (message) => notices.push(message)
+ },
+ deps
+ )
+
+ expect(deps.choosePaths).toHaveBeenCalledTimes(1)
+ // The picker branch reads the file: nothing is open yet, so there is no tab to focus.
+ expect(deps.activateTab).not.toHaveBeenCalled()
+ expect(deps.openPath).toHaveBeenCalledTimes(1)
+ expect(deps.openPath).toHaveBeenCalledWith('/picked/web/design/hikyo.pen')
+ expect(deps.openPath).not.toHaveBeenCalledWith('web/design/hikyo.pen')
+ expect(selectByName).toHaveBeenCalledWith('Button/Large/Default')
+ expect(notices).toHaveLength(1)
+ })
+
+ test('notifies when the node is missing', async () => {
+ const deps = io()
+ const notices: string[] = []
+
+ await openDeepLink(
+ { path: 'web/design/hikyo.pen', node: 'Nope' },
+ {
+ openPaths: () => ['/r/hikyo/web/design/hikyo.pen'],
+ selectByName: () => false,
+ notify: (message) => notices.push(message)
+ },
+ deps
+ )
+
+ expect(deps.activateTab).toHaveBeenCalledWith('/r/hikyo/web/design/hikyo.pen')
+ expect(notices).toHaveLength(1)
+ expect(notices[0]).toContain('Nope')
+ })
+
+ test('reports a dismissed picker as nothing chosen, not a wrong file', async () => {
+ const deps = io({ choosePaths: mock(async () => []) })
+ const notices: string[] = []
+
+ await openDeepLink(
+ { path: 'web/design/hikyo.pen', node: 'Button' },
+ {
+ openPaths: () => [],
+ selectByName: () => true,
+ notify: (message) => notices.push(message)
+ },
+ deps
+ )
+
+ expect(deps.choosePaths).toHaveBeenCalledTimes(1)
+ expect(deps.openPath).not.toHaveBeenCalled()
+ expect(deps.activateTab).not.toHaveBeenCalled()
+ // The locate prompt, then a dismissal notice that does not name an unchosen file.
+ expect(notices).toHaveLength(2)
+ expect(notices[1]).toBe('Link cancelled: no file was chosen.')
+ })
+
+ test('cancels the link when the picked file is not the requested one', async () => {
+ const deps = io({
+ choosePaths: mock(async () => ['/elsewhere/other.pen']),
+ openPath: mock(async (path: string): Promise<void> => {
+ throw new Error(`unexpected open of ${path}`)
+ })
+ })
+ const notices: string[] = []
+
+ await openDeepLink(
+ { path: 'web/design/hikyo.pen', node: 'Button' },
+ {
+ openPaths: () => [],
+ selectByName: () => true,
+ notify: (message) => notices.push(message)
+ },
+ deps
+ )
+
+ expect(deps.choosePaths).toHaveBeenCalledTimes(1)
+ expect(deps.openPath).not.toHaveBeenCalled()
+ expect(deps.activateTab).not.toHaveBeenCalled()
+ expect(notices).toHaveLength(2)
+ expect(notices[1]).toContain('web/design/hikyo.pen')
+ })
+})
diff --git a/tests/engine/app/document/io/pending-open.test.ts b/tests/engine/app/document/io/pending-open.test.ts
new file mode 100644
index 000000000..6943d71dd
--- /dev/null
+++ b/tests/engine/app/document/io/pending-open.test.ts
@@ -0,0 +1,110 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test'
+
+import { localeSetting } from '@open-pencil/vue'
+
+import type { PendingOpenFile } from '@/app/document/io/pending-open'
+import { openPendingFiles } from '@/app/document/io/pending-open'
+import { toast } from '@/app/shell/ui'
+
+afterEach(() => {
+ toast.toasts.value = []
+ localeSetting.set(undefined)
+})
+
+const actions = {
+ openPaths: () => [] as string[],
+ selectByName: () => true,
+ notify: () => undefined
+}
+
+function io() {
+ return {
+ openPath: mock(async (): Promise<void> => undefined),
+ openLink: mock(async (): Promise<void> => undefined)
+ }
+}
+
+describe('openPendingFiles', () => {
+ test('routes a deep-link entry to the deep-link resolver, never to the plain opener', async () => {
+ const deps = io()
+ const file: PendingOpenFile = {
+ path: 'tests/fixtures/pencil_button.pen',
+ node: 'Button/Large/Default',
+ deepLink: true
+ }
+
+ await openPendingFiles([file], actions, deps)
+
+ // The relative link path must never reach `openFileFromPath`: it would be read
+ // relative to the process cwd, or fail, instead of being resolved against tabs.
+ expect(deps.openPath).not.toHaveBeenCalled()
+ expect(deps.openLink).toHaveBeenCalledTimes(1)
+ expect(deps.openLink).toHaveBeenCalledWith(
+ { path: 'tests/fixtures/pencil_button.pen', node: 'Button/Large/Default' },
+ actions
+ )
+ })
+
+ test('routes a file-association entry to the plain opener', async () => {
+ const deps = io()
+
+ await openPendingFiles(
+ [{ path: '/r/hikyo/web/design/hikyo.pen', deepLink: false }],
+ actions,
+ deps
+ )
+
+ expect(deps.openLink).not.toHaveBeenCalled()
+ expect(deps.openPath).toHaveBeenCalledTimes(1)
+ expect(deps.openPath).toHaveBeenCalledWith('/r/hikyo/web/design/hikyo.pen')
+ })
+
+ test('keeps both producers in queue order within one drain', async () => {
+ const seen: string[] = []
+ const deps = {
+ openPath: mock(async (path: string) => {
+ seen.push(`path:${path}`)
+ }),
+ openLink: mock(async (target: { path: string }) => {
+ seen.push(`link:${target.path}`)
+ })
+ }
+
+ await openPendingFiles(
+ [
+ { path: '/a/first.pen', deepLink: false },
+ { path: 'b/second.pen', deepLink: true },
+ { path: '/c/third.pen', deepLink: false }
+ ],
+ actions,
+ deps
+ )
+
+ expect(seen).toEqual(['path:/a/first.pen', 'link:b/second.pen', 'path:/c/third.pen'])
+ })
+
+ test('toasts a failing entry and still drains the rest of the batch', async () => {
+ localeSetting.set('en')
+ const deps = {
+ openPath: mock(async (path: string) => {
+ if (path === '/a/broken.pen') throw new Error('Invalid PEN container')
+ }),
+ openLink: mock(async (): Promise<void> => undefined)
+ }
+
+ await expect(
+ openPendingFiles(
+ [
+ { path: '/a/broken.pen', deepLink: false },
+ { path: 'b/second.pen', deepLink: true }
+ ],
+ actions,
+ deps
+ )
+ ).resolves.toBeUndefined()
+
+ expect(deps.openLink).toHaveBeenCalledTimes(1)
+ expect(toast.toasts.value).toHaveLength(1)
+ expect(toast.toasts.value[0]?.message).toContain('broken.pen')
+ })
+})
diff --git a/tests/engine/app/document/io/web-link.test.ts b/tests/engine/app/document/io/web-link.test.ts
new file mode 100644
index 000000000..53863f618
--- /dev/null
+++ b/tests/engine/app/document/io/web-link.test.ts
@@ -0,0 +1,194 @@
+import { describe, expect, mock, test } from 'bun:test'
+
+import {
+ openWebLink,
+ openWebLinkFromLocation,
+ parseWebOpenParams,
+ withoutWebLinkParams
+} from '@/app/document/io/web-link'
+
+const RAW = 'https://raw.githubusercontent.com/o/r/master/design/hikyo.pen'
+
+describe('parseWebOpenParams', () => {
+ test('accepts an https .pen URL with a node', () => {
+ const target = parseWebOpenParams(
+ `?file=${encodeURIComponent(RAW)}&node=Button%2FLarge%2FDefault`
+ )
+ expect(target?.file.href).toBe(RAW)
+ expect(target?.node).toBe('Button/Large/Default')
+ })
+
+ test('accepts a .fig URL without a node', () => {
+ const target = parseWebOpenParams('?file=https%3A%2F%2Fexample.com%2Fa%2Fb.FIG')
+ expect(target?.file.href).toBe('https://example.com/a/b.FIG')
+ expect(target?.node).toBeUndefined()
+ })
+
+ test('drops the fragment, so two links to one file do not open two tabs', () => {
+ // The tab identity compares the source URL exactly; a fragment never reaches the
+ // server, so keeping it would duplicate the document once per fragment.
+ const first = parseWebOpenParams(`?file=${encodeURIComponent(`${RAW}#Button`)}`)
+ const second = parseWebOpenParams(`?file=${encodeURIComponent(`${RAW}#Card`)}`)
+ expect(first?.file.href).toBe(RAW)
+ expect(first?.file.href).toBe(second?.file.href)
+ })
+
+ test('keeps the query string, which the server does see', () => {
+ const target = parseWebOpenParams(`?file=${encodeURIComponent(`${RAW}?v=2#x`)}`)
+ expect(target?.file.href).toBe(`${RAW}?v=2`)
+ })
+
+ test('refuses http', () => {
+ expect(parseWebOpenParams('?file=http%3A%2F%2Fexample.com%2Fa.pen')).toBeNull()
+ })
+
+ test('refuses file URLs', () => {
+ expect(parseWebOpenParams('?file=file%3A%2F%2F%2Fetc%2Fpasswd.pen')).toBeNull()
+ })
+
+ test('refuses another extension', () => {
+ expect(parseWebOpenParams('?file=https%3A%2F%2Fexample.com%2Fa.svg')).toBeNull()
+ })
+
+ test('refuses a relative path, which has no protocol of its own', () => {
+ expect(parseWebOpenParams('?file=design%2Fhikyo.pen')).toBeNull()
+ })
+
+ test('returns null without a file', () => {
+ expect(parseWebOpenParams('?node=Button')).toBeNull()
+ expect(parseWebOpenParams('')).toBeNull()
+ expect(parseWebOpenParams('?file=&node=Button')).toBeNull()
+ })
+
+ test('reads the extension off the path, not the query', () => {
+ expect(parseWebOpenParams('?file=https%3A%2F%2Fh%2Fa.svg%3Fx%3D.pen')).toBeNull()
+ expect(parseWebOpenParams('?file=https%3A%2F%2Fh%2Fa.pen%3Fv%3D1')?.file.href).toBe(
+ 'https://h/a.pen?v=1'
+ )
+ })
+
+ test('accepts an uppercase extension, which the reader registry lowercases anyway', () => {
+ expect(parseWebOpenParams('?file=https%3A%2F%2Fh%2Fa.PEN')?.file.href).toBe('https://h/a.PEN')
+ })
+
+ test('takes the last value of a repeated key, like the desktop parser', () => {
+ const target = parseWebOpenParams(
+ '?file=https%3A%2F%2Fh%2Fa.pen&file=https%3A%2F%2Fh%2Fb.pen&node=A&node=B'
+ )
+ expect(target?.file.href).toBe('https://h/b.pen')
+ expect(target?.node).toBe('B')
+ })
+
+ test('ignores an empty node', () => {
+ expect(parseWebOpenParams(`?file=${encodeURIComponent(RAW)}&node=`)?.node).toBeUndefined()
+ })
+})
+
+describe('openWebLink', () => {
+ const target = { file: new URL(RAW), node: 'Button/Large/Default' }
+
+ test('selects the node after the document opens', async () => {
+ const open = mock(async (): Promise<void> => undefined)
+ const selectByName = mock(() => true)
+ const notices: string[] = []
+
+ await openWebLink(target, { selectByName, notify: (m) => notices.push(m) }, { open })
+
+ expect(open).toHaveBeenCalledWith(target.file)
+ expect(selectByName).toHaveBeenCalledWith('Button/Large/Default')
+ expect(notices).toEqual([])
+ })
+
+ test('notifies with the host, not the whole link, when the fetch fails', async () => {
+ const open = mock(async (): Promise<void> => {
+ throw new Error('Failed to fetch')
+ })
+ const selectByName = mock(() => true)
+ const notices: string[] = []
+
+ await openWebLink(target, { selectByName, notify: (m) => notices.push(m) }, { open })
+
+ expect(selectByName).not.toHaveBeenCalled()
+ expect(notices).toHaveLength(1)
+ expect(notices[0]).toContain('raw.githubusercontent.com')
+ })
+
+ test('notifies when the node is missing', async () => {
+ const open = mock(async (): Promise<void> => undefined)
+ const notices: string[] = []
+
+ await openWebLink(
+ target,
+ { selectByName: () => false, notify: (m) => notices.push(m) },
+ { open }
+ )
+
+ expect(notices).toHaveLength(1)
+ expect(notices[0]).toContain('Button/Large/Default')
+ })
+})
+
+describe('openWebLinkFromLocation', () => {
+ const link = `?tab=2&file=${encodeURIComponent(RAW)}&node=Button%2FLarge%2FDefault#frag`
+
+ test('strips the params before the document is fetched', async () => {
+ const order: string[] = []
+ const open = mock(async (): Promise<void> => {
+ order.push('open')
+ })
+
+ await openWebLinkFromLocation(
+ link,
+ () => order.push('strip'),
+ { selectByName: () => true, notify: () => undefined },
+ { open }
+ )
+
+ expect(order).toEqual(['strip', 'open'])
+ })
+
+ test('strips a refused link too, and opens nothing', async () => {
+ const open = mock(async (): Promise<void> => undefined)
+ const strip = mock(() => undefined)
+
+ await openWebLinkFromLocation(
+ '?file=http%3A%2F%2Fexample.com%2Fa.pen&node=X',
+ strip,
+ { selectByName: () => true, notify: () => undefined },
+ { open }
+ )
+
+ expect(strip).toHaveBeenCalledTimes(1)
+ expect(open).not.toHaveBeenCalled()
+ })
+
+ test('does nothing at all when neither param is present', async () => {
+ const open = mock(async (): Promise<void> => undefined)
+ const strip = mock(() => undefined)
+
+ await openWebLinkFromLocation(
+ '?tab=2',
+ strip,
+ { selectByName: () => true, notify: () => undefined },
+ { open }
+ )
+
+ expect(strip).not.toHaveBeenCalled()
+ expect(open).not.toHaveBeenCalled()
+ })
+})
+
+describe('withoutWebLinkParams', () => {
+ test('removes both link params and keeps everything else', () => {
+ expect(
+ withoutWebLinkParams({ file: 'https://h/a.pen', node: 'A', tab: '2', test: '' })
+ ).toEqual({
+ tab: '2',
+ test: ''
+ })
+ })
+
+ test('leaves a query with no link params untouched', () => {
+ expect(withoutWebLinkParams({ renderer: 'tiled' })).toEqual({ renderer: 'tiled' })
+ })
+})
diff --git a/tests/engine/app/editor/selection/focus.test.ts b/tests/engine/app/editor/selection/focus.test.ts
new file mode 100644
index 000000000..fe2843557
--- /dev/null
+++ b/tests/engine/app/editor/selection/focus.test.ts
@@ -0,0 +1,82 @@
+import { expect, test } from 'bun:test'
+
+import {
+ findNodesByName,
+ focusNodes,
+ focusNodesByName,
+ type FocusStore
+} from '@/app/editor/selection/focus'
+
+import { firstPageId, makeSceneGraph } from '#tests/helpers/scene'
+
+function harness() {
+ const graph = makeSceneGraph()
+ const pageId = firstPageId(graph)
+ const selected: string[][] = []
+ let zooms = 0
+ const store: FocusStore = {
+ graph,
+ state: { currentPageId: pageId },
+ select: (ids) => void selected.push(ids),
+ zoomToSelection: () => void zooms++
+ }
+ return {
+ graph,
+ pageId,
+ store,
+ selected,
+ get zooms() {
+ return zooms
+ }
+ }
+}
+
+test('finds every node with the exact name and nothing else', () => {
+ const { graph, pageId } = harness()
+ const frame = graph.createNode('FRAME', pageId, { name: 'Card' })
+ const exact = graph.createNode('RECTANGLE', frame.id, { name: 'Button' })
+ graph.createNode('RECTANGLE', frame.id, { name: 'Button/Primary' })
+ graph.createNode('TEXT', frame.id, { name: 'button' })
+
+ expect(findNodesByName(graph, pageId, 'Button')).toEqual([exact.id])
+ expect(findNodesByName(graph, pageId, 'Missing')).toEqual([])
+})
+
+test('walks nested groups rather than only the first level', () => {
+ const { graph, pageId } = harness()
+ const outer = graph.createNode('FRAME', pageId, { name: 'Outer' })
+ const inner = graph.createNode('GROUP', outer.id, { name: 'Inner' })
+ const leaf = graph.createNode('RECTANGLE', inner.id, { name: 'Deep' })
+
+ expect(findNodesByName(graph, pageId, 'Deep')).toEqual([leaf.id])
+})
+
+test('focuses every match by name and zooms once', () => {
+ const { graph, pageId, store, selected } = harness()
+ const frame = graph.createNode('FRAME', pageId, { name: 'Card' })
+ const first = graph.createNode('RECTANGLE', frame.id, { name: 'Button' })
+ const second = graph.createNode('RECTANGLE', frame.id, { name: 'Button' })
+
+ expect(focusNodesByName(store, 'Button')).toBe(true)
+ expect(selected).toEqual([[first.id, second.id]])
+})
+
+test('does nothing for a name the page does not carry', () => {
+ const { store, selected } = harness()
+
+ expect(focusNodesByName(store, 'Missing')).toBe(false)
+ expect(selected).toEqual([])
+})
+
+test('ignores ids that are no longer in the document', () => {
+ const { graph, pageId, store, selected } = harness()
+ const stale = graph.createNode('RECTANGLE', pageId, { name: 'Gone' })
+ const live = graph.createNode('RECTANGLE', pageId, { name: 'Here' })
+ graph.deleteNode(stale.id)
+
+ // A share or awareness reference can outlive the node it points at.
+ expect(focusNodes(store, [stale.id])).toBe(false)
+ expect(selected).toEqual([])
+ expect(focusNodes(store, [stale.id, live.id])).toBe(true)
+ expect(selected).toEqual([[live.id]])
+})