diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ae5d9497..4929d1857 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ from the section of its version (`scripts/releases/notes.ts`); a release without one fails. At tag time, rename `[Unreleased]` to the version and date, like `## [0.4.16] - 2026-10-24`. +## [Unreleased] + +### Changed + +- Desktop: Open folder… uses the native OS folder picker for this app's paired computer, then confirms the folder with the existing checks and Add as project. Other devices keep the in-app browser; cancelling keeps the current folder, and a native dialog failure opens the in-app browser with an explanation. + ## [0.4.104] - 2026-11-19 ### Fixed diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 741b8a66a..49d8a805e 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -360,7 +360,7 @@ Production dependencies, direct and transitive, of the hub (`packages/core`, `pa | zustand | 5.0.15 | MIT | https://github.com/pmndrs/zustand | web | | zwitch | 2.0.4 | MIT | https://github.com/wooorm/zwitch | web | -## Rust crates (562) +## Rust crates (565) From `packages/daemon-rs/Cargo.lock` (daemon) and `packages/desktop/src-tauri/Cargo.lock` (desktop app). @@ -692,6 +692,7 @@ From `packages/daemon-rs/Cargo.lock` (daemon) and `packages/desktop/src-tauri/Ca | regex-automata | 0.4.18 | see crate | https://crates.io/crates/regex-automata/0.4.18 | daemon, desktop | | regex-syntax | 0.8.11 | see crate | https://crates.io/crates/regex-syntax/0.8.11 | daemon, desktop | | reqwest | 0.13.5 | see crate | https://crates.io/crates/reqwest/0.13.5 | desktop | +| rfd | 0.17.2 | see crate | https://crates.io/crates/rfd/0.17.2 | desktop | | ring | 0.17.14 | see crate | https://crates.io/crates/ring/0.17.14 | daemon, desktop | | rust-ini | 0.21.1 | see crate | https://crates.io/crates/rust-ini/0.21.1 | desktop | | rustc_version | 0.4.1 | see crate | https://crates.io/crates/rustc_version/0.4.1 | desktop | @@ -771,6 +772,8 @@ From `packages/daemon-rs/Cargo.lock` (daemon) and `packages/desktop/src-tauri/Ca | tauri-plugin | 2.7.2 | see crate | https://crates.io/crates/tauri-plugin/2.7.2 | desktop | | tauri-plugin-autostart | 2.7.0 | see crate | https://crates.io/crates/tauri-plugin-autostart/2.7.0 | desktop | | tauri-plugin-deep-link | 2.6.2 | see crate | https://crates.io/crates/tauri-plugin-deep-link/2.6.2 | desktop | +| tauri-plugin-dialog | 2.8.4 | see crate | https://crates.io/crates/tauri-plugin-dialog/2.8.4 | desktop | +| tauri-plugin-fs | 2.7.1 | see crate | https://crates.io/crates/tauri-plugin-fs/2.7.1 | desktop | | tauri-plugin-global-shortcut | 2.4.1 | see crate | https://crates.io/crates/tauri-plugin-global-shortcut/2.4.1 | desktop | | tauri-plugin-notification | 2.7.0 | see crate | https://crates.io/crates/tauri-plugin-notification/2.7.0 | desktop | | tauri-plugin-opener | 2.7.2 | see crate | https://crates.io/crates/tauri-plugin-opener/2.7.2 | desktop | diff --git a/packages/desktop/src-tauri/Cargo.lock b/packages/desktop/src-tauri/Cargo.lock index ecd7f79f5..d66f006fa 100644 --- a/packages/desktop/src-tauri/Cargo.lock +++ b/packages/desktop/src-tauri/Cargo.lock @@ -560,6 +560,7 @@ dependencies = [ "tauri-nspanel", "tauri-plugin-autostart", "tauri-plugin-deep-link", + "tauri-plugin-dialog", "tauri-plugin-global-shortcut", "tauri-plugin-notification", "tauri-plugin-opener", @@ -3568,6 +3569,32 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2", + "dispatch2", + "glib-sys", + "gobject-sys", + "gtk-sys", + "js-sys", + "libc", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "percent-encoding", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.61.2", +] + [[package]] name = "ring" version = "0.17.14" @@ -4589,6 +4616,48 @@ dependencies = [ "windows-result", ] +[[package]] +name = "tauri-plugin-dialog" +version = "2.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce0fb9c2b6d34a9720627ed930ebc8af26f61e648695aecaeb03d5c33c5896f5" +dependencies = [ + "log", + "raw-window-handle", + "rfd", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "tauri-plugin-fs", + "thiserror 2.0.21", + "url", +] + +[[package]] +name = "tauri-plugin-fs" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d58eb1d4984e535f47a642ffec09a2da6f5c18a12b5902d12126cb7626d628b" +dependencies = [ + "anyhow", + "dunce", + "glob", + "log", + "objc2-foundation", + "percent-encoding", + "schemars 0.8.22", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "tauri-utils", + "thiserror 2.0.21", + "toml 1.1.8+spec-1.1.0", + "url", +] + [[package]] name = "tauri-plugin-global-shortcut" version = "2.4.1" diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml index 2cd5eedea..6a2f875ee 100644 --- a/packages/desktop/src-tauri/Cargo.toml +++ b/packages/desktop/src-tauri/Cargo.toml @@ -18,6 +18,9 @@ tauri-plugin-deep-link = "2.6" tauri-plugin-global-shortcut = "2.4" tauri-plugin-notification = "2.7" tauri-plugin-opener = "2.7" +# the native folder picker for this computer's own device (main.rs pick_folder), called from +# Rust only: no dialog:* permission is granted to any page +tauri-plugin-dialog = "2.8" # Updates from the signed latest.json on the public releases (src/update.rs, docs/DESIGN.md, Updates) tauri-plugin-updater = "2" tauri-plugin-single-instance = { version = "2.5", features = ["deep-link"] } diff --git a/packages/desktop/src-tauri/build.rs b/packages/desktop/src-tauri/build.rs index 6a541eebc..59e2dfd8c 100644 --- a/packages/desktop/src-tauri/build.rs +++ b/packages/desktop/src-tauri/build.rs @@ -2,7 +2,8 @@ fn main() { // Listing the app commands makes them deny-by-default, so only the bundled // connection page (see capabilities/default.json) can call them. The hub's // remote page never gets them, except computer_status, computer_restart, open_settings, - // update_status and update_install (grant_hub_ipc in src/main.rs). The + // update_status, update_install, native_folder_device, pick_folder and the others + // grant_hub_ipc in src/main.rs lists. The // local_hub_* commands start and stop a hub on this computer, so they are // the bundled page's only. tauri_build::try_build(tauri_build::Attributes::new().app_manifest( @@ -46,6 +47,9 @@ fn main() { "open_download", // Dock bounce / taskbar flash and badge while an approval waits (main.rs attention) "attention", + // the native folder picker, only for this computer's own device (main.rs pick_folder) + "native_folder_device", + "pick_folder", // meeting mode: open and status for the hub page, the rest only for the overlay window "meeting_open", "meeting_enabled", diff --git a/packages/desktop/src-tauri/src/computer.rs b/packages/desktop/src-tauri/src/computer.rs index 6ee858c0e..a58a4a5b4 100644 --- a/packages/desktop/src-tauri/src/computer.rs +++ b/packages/desktop/src-tauri/src/computer.rs @@ -213,6 +213,14 @@ pub fn parse_status(stdout: &str) -> Result { serde_json::from_str(json_line(stdout)).map_err(|e| format!("Unexpected reply from the daemon: {e}")) } +/// This computer's device id on the hub the app uses: the daemon says it is paired, with an id, +/// to the same hub (both sides normalized). None otherwise, so a page never gets a guessed id. +pub fn own_device(local: &LocalStatus, app_hub: Option<&str>) -> Option { + let same = |a: &str, b: &str| matches!((crate::hub::normalize(a), crate::hub::normalize(b)), (Ok(a), Ok(b)) if a == b); + let id = local.device_id.as_deref().map(str::trim).filter(|id| !id.is_empty())?; + (local.paired && same(local.hub.as_deref()?, app_hub?)).then(|| id.to_string()) +} + pub fn status(bin: &Path) -> Result { let out = run(bin, &["status", "--json"], None, Duration::from_secs(15))?; if !out.ok { @@ -436,6 +444,27 @@ mod tests { assert!(parse_status("Error: nope").is_err()); } + #[test] + fn proves_its_own_device_only_on_the_same_hub() { + let local = |paired: bool, hub: Option<&str>, id: Option<&str>| LocalStatus { paired, hub: hub.map(Into::into), device_id: id.map(Into::into), ..Default::default() }; + let ok = local(true, Some("http://box:7717"), Some("dev_1")); + assert_eq!(own_device(&ok, Some("http://box:7717/")).as_deref(), Some("dev_1")); + // normalized on both sides: scheme added, trailing slash, query and fragment dropped + assert_eq!(own_device(&ok, Some("box:7717")).as_deref(), Some("dev_1")); + assert_eq!(own_device(&local(true, Some("https://h.example/c"), Some("dev_2")), Some("https://h.example/c/#token=x")).as_deref(), Some("dev_2")); + // another hub, port, scheme or path prefix: not this hub's device + for other in ["http://box:7718", "https://box:7717", "http://other:7717", "http://box:7717/sub"] { + assert_eq!(own_device(&ok, Some(other)), None, "{other}"); + } + // no app hub, not paired, no hub or no id: nothing proven + assert_eq!(own_device(&ok, None), None); + assert_eq!(own_device(&ok, Some("")), None); + assert_eq!(own_device(&local(false, Some("http://box:7717"), Some("dev_1")), Some("http://box:7717")), None); + assert_eq!(own_device(&local(true, None, Some("dev_1")), Some("http://box:7717")), None); + assert_eq!(own_device(&local(true, Some("http://box:7717"), None), Some("http://box:7717")), None); + assert_eq!(own_device(&local(true, Some("http://box:7717"), Some(" ")), Some("http://box:7717")), None); + } + #[test] fn says_what_turning_it_off_did() { let u = parse_uninstalled(r#"{"removed":true,"unpaired":true,"removedOnHub":true,"name":"arch","deviceId":"dev_1","error":null}"#); diff --git a/packages/desktop/src-tauri/src/main.rs b/packages/desktop/src-tauri/src/main.rs index 478280511..d1331fa9f 100644 --- a/packages/desktop/src-tauri/src/main.rs +++ b/packages/desktop/src-tauri/src/main.rs @@ -49,6 +49,7 @@ use tauri::{ }; use tauri_plugin_autostart::{MacosLauncher, ManagerExt as _}; use tauri_plugin_deep_link::DeepLinkExt; +use tauri_plugin_dialog::DialogExt; use tauri_plugin_global_shortcut::ShortcutState; use tauri_plugin_opener::OpenerExt; @@ -260,6 +261,10 @@ fn grant_hub_ipc(app: &AppHandle, base: &Url) -> Result<(), String> { .permission("allow-open-download") // Dock bounce / taskbar flash and badge while an approval waits (attention) .permission("allow-attention") + // the native folder picker, only for this computer's own device and a focused window + // (pick_folder); never a dialog:* permission, so the page cannot open dialogs itself + .permission("allow-native-folder-device") + .permission("allow-pick-folder") // the hub page may open the meeting overlay, never start capture (MEETING-MODE.md 2.1.1) .permission("allow-meeting-open") .permission("allow-meeting-status") @@ -515,6 +520,107 @@ fn attention(app: AppHandle, on: bool, count: u32) { let _ = win.set_badge_count((count > 0).then_some(i64::from(count))); } +/// This computer's device id on the hub the app uses, proven by the daemon's own status +/// (computer::own_device). None when the daemon is missing, unpaired or paired elsewhere. +fn own_device(app: &AppHandle) -> Option { + let hub_url = state(app).settings.lock().unwrap().hub_url.clone(); + let stable = stable_copy(app).ok().filter(|s| s.exists())?; + computer::own_device(&computer::status(&stable.bin).ok()?, hub_url.as_deref()) +} + +/// A page at `page` is the hub the app uses now. Capabilities stay granted to earlier hub +/// origins (grant_hub_ipc), so a window still on an old hub must not reach the folder commands. +fn on_current_hub(base: Option<&Url>, page: &Url) -> bool { + base.is_some_and(|b| b.origin() == page.origin()) +} + +/// The main or quick ask window, showing the current hub. +fn hub_window(window: &WebviewWindow) -> bool { + matches!(window.label(), MAIN | QUICK) && window.url().is_ok_and(|u| on_current_hub(hub_base(window.app_handle()).as_ref(), &u)) +} + +/// The device id the hub page may open the native folder picker for (web FolderPicker), or null. +#[tauri::command] +async fn native_folder_device(window: WebviewWindow) -> Option { + if !hub_window(&window) { + return None; + } + let app = window.app_handle().clone(); + let id = tauri::async_runtime::spawn_blocking(move || own_device(&app)).await.ok().flatten(); + // the hub may have changed during the daemon check + id.filter(|_| hub_window(&window)) +} + +/// Where the picker opens: `start` when it is an absolute folder here, else the home folder. +/// Only a local disk path on Windows: a \\server\share start would make Windows sign in to that server. +fn start_dir(start: Option<&str>, home: Option) -> Option { + let disk = |p: &Path| !cfg!(windows) || matches!(p.components().next(), Some(std::path::Component::Prefix(x)) if matches!(x.kind(), std::path::Prefix::Disk(_))); + start.map(PathBuf::from).filter(|p| p.is_absolute() && disk(p) && p.is_dir()).or(home) +} + +/// The picked folder as text, None for Cancel. +fn folder_text(picked: Option) -> Result, String> { + let Some(picked) = picked else { return Ok(None) }; + let path = picked.simplified().into_path().map_err(|_| "The picked folder has no path on this computer.".to_string())?; + path.into_os_string().into_string().map(Some).map_err(|_| "The picked folder's path is not valid text.".to_string()) +} + +/// One picker at a time: a page cannot stack dialogs. +static PICKING: AtomicBool = AtomicBool::new(false); + +/// The native folder picker for the hub page's Open folder. Only for `device` = this computer's +/// own proven device (own_device), from the focused main or quick ask window. Returns the folder, +/// null for Cancel, an error when the picker could not open. Reads nothing: the page gets only +/// the path the owner picked. +#[tauri::command] +async fn pick_folder(window: WebviewWindow, device: String, start: Option) -> Result, String> { + let ready = |window: &WebviewWindow| { + if !hub_window(window) { + return Err("Pick a folder from the Conclave window on the current hub.".to_string()); + } + if !window.is_focused().unwrap_or(false) { + return Err("Click Browse in the window first.".to_string()); + } + Ok(()) + }; + ready(&window)?; + let app = window.app_handle().clone(); + let proven = { + let app = app.clone(); + tauri::async_runtime::spawn_blocking(move || own_device(&app)).await.map_err(|e| e.to_string())? + }; + if proven.as_deref() != Some(device.as_str()) { + return Err("The folder picker opens only for this computer's own device.".into()); + } + // again after the daemon check: the window may have moved to another hub or lost focus + ready(&window)?; + if PICKING.swap(true, Ordering::SeqCst) { + return Err("A folder picker is open already.".into()); + } + let mut dialog = app.dialog().file().set_title("Choose a folder").set_parent(&window); + if let Some(dir) = start_dir(start.as_deref(), app.path().home_dir().ok()) { + dialog = dialog.set_directory(dir); + } + let (tx, rx) = std::sync::mpsc::channel(); + // the plugin's callback form: the dialog runs on the main thread, this thread waits. + // None is Cancel, but rfd also returns None for some backend failures (no GTK dialog, + // portal errors), so those read as Cancel too. Only a callback dropped unsent (the main + // thread could not take the dialog) is reported as an error. + dialog.pick_folder(move |picked| { + let _ = tx.send(picked); + }); + let picked = tauri::async_runtime::spawn_blocking(move || rx.recv()).await; + PICKING.store(false, Ordering::SeqCst); + // the path goes only to the hub page that asked, not one the window moved to meanwhile + if !hub_window(&window) { + return Err("The window left the hub while the picker was open.".into()); + } + match picked { + Ok(Ok(picked)) => folder_text(picked), + _ => Err("The folder picker did not open.".into()), + } +} + fn focus(win: &WebviewWindow) { let _ = win.show(); let _ = win.unminimize(); @@ -1944,6 +2050,9 @@ fn main() { // no click hook: its open_url call is not granted to the hub page, so it // swallowed target="_blank" links; new_window opens them instead .plugin(tauri_plugin_opener::Builder::new().open_js_links_on_click(false).build()) + // for pick_folder only; no page is granted a dialog:* permission. Its init script turns + // window.alert/confirm into plugin calls, which the pages do not use (they would be denied) + .plugin(tauri_plugin_dialog::init()) .plugin(panel_plugin()) .plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, Some(vec![HIDDEN_ARG]))) // the app's own updates, checked against the built-in key (update.rs) @@ -1994,7 +2103,9 @@ fn main() { save_download, reveal_download, open_download, - attention + attention, + native_folder_device, + pick_folder ]) .on_window_event(|window, event| { // Closing a window hides it. Quit lives in the tray menu. @@ -2170,6 +2281,79 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn the_folder_picker_starts_in_an_existing_absolute_folder_else_home() { + let dir = std::env::temp_dir().join(format!("conclave-pick-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("f.txt"); + std::fs::write(&file, b"x").unwrap(); + let home = Some(PathBuf::from("/home/me")); + assert_eq!(start_dir(dir.to_str(), home.clone()), Some(dir.clone())); + // a file, a missing folder, a relative path or nothing: home + for bad in [file.to_str(), dir.join("gone").to_str(), Some("relative/dir"), Some(""), None] { + assert_eq!(start_dir(bad, home.clone()), home, "{bad:?}"); + } + assert_eq!(start_dir(Some("relative"), None), None); + #[cfg(windows)] + assert_eq!(start_dir(Some(r"\\attacker\share"), home.clone()), home); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn the_picker_returns_the_folder_null_for_cancel() { + use tauri_plugin_dialog::FilePath; + assert_eq!(folder_text(None), Ok(None)); + let p = std::env::temp_dir(); + assert_eq!(folder_text(Some(FilePath::Path(p.clone()))), Ok(Some(p.to_string_lossy().into_owned()))); + // a URL that is not a local file has no path to hand over + assert!(folder_text(Some(FilePath::Url(Url::parse("https://example.com/x").unwrap()))).is_err()); + } + + #[test] + fn only_the_two_folder_commands_reach_the_hub_page_never_dialog_or_fs_permissions() { + let main = include_str!("main.rs"); + let grant = &main[main.find("fn grant_hub_ipc").unwrap()..main.find("fn hub_page(").unwrap()]; + assert!(grant.contains(".permission(\"allow-native-folder-device\")")); + assert!(grant.contains(".permission(\"allow-pick-folder\")")); + let capability = include_str!("../capabilities/default.json"); + for text in [grant, capability] { + assert!(!text.contains("\"dialog:") && !text.contains("\"fs:"), "{text}"); + } + // deny-by-default app commands, and the fs plugin is never registered + let build = include_str!("../build.rs"); + assert!(build.contains("\"native_folder_device\"") && build.contains("\"pick_folder\"")); + assert!(!main.contains(concat!("tauri_plugin_fs", "::init"))); + // the command checks the current hub window and focus, the proven device, then both again, before any dialog + let pick = &main[main.find("async fn pick_folder").unwrap()..]; + let dialog_at = pick.find(".dialog()").unwrap(); + let device_at = pick.find("proven.as_deref() != Some(device.as_str())").unwrap(); + assert!(pick.find("hub_window(window)").is_some_and(|i| i < device_at)); + assert!(pick.find("is_focused()").is_some_and(|i| i < device_at)); + assert!(pick[device_at..dialog_at].contains("ready(&window)?")); + // and the window is still on the hub when the path goes back + assert!(pick[dialog_at..].find("hub_window(&window)").is_some_and(|i| i < pick[dialog_at..].find("folder_text(picked)").unwrap())); + let device = &main[main.find("async fn native_folder_device").unwrap()..main.find("fn start_dir").unwrap()]; + assert!(device.starts_with("async fn native_folder_device(window: WebviewWindow) -> Option")); + assert!(device.matches("hub_window(&window)").count() == 2); + } + + #[test] + fn the_folder_commands_answer_only_a_page_on_the_current_hub() { + let url = |s: &str| Url::parse(s).unwrap(); + let now = url("https://new.example/"); + assert!(on_current_hub(Some(&now), &url("https://new.example/s/ses_1?quick=1#token=x"))); + // a window still on the hub the app used before (its capability stays), another port or scheme + for page in ["https://old.trycloudflare.com/", "https://new.example:8443/", "http://new.example/", "https://evil.example/"] { + assert!(!on_current_hub(Some(&now), &url(page)), "{page}"); + } + // the bundled pages and no hub at all + assert!(!on_current_hub(Some(&now), &url("tauri://localhost/index.html"))); + assert!(!on_current_hub(Some(&url("tauri://localhost/")), &url("tauri://localhost/index.html"))); + assert!(!on_current_hub(None, &now)); + // a hub under a path: same origin counts, as allow_navigation does + assert!(on_current_hub(Some(&url("https://box.example/conclave/")), &url("https://box.example/conclave/s/1"))); + } + #[test] fn an_open_window_holds_the_automatic_update_even_without_focus() { assert!(on_screen(true, false)); diff --git a/packages/desktop/test/native-folder.test.js b/packages/desktop/test/native-folder.test.js new file mode 100644 index 000000000..8bfa075ed --- /dev/null +++ b/packages/desktop/test/native-folder.test.js @@ -0,0 +1,68 @@ +/** + * The native folder picker (src-tauri/src/main.rs pick_folder): checked from the sources, so it runs + * where cargo does not. The hub page gets two app commands, never a dialog:* or fs:* permission. + * + * bun test packages/desktop/test + */ +import { expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; + +const read = (p) => readFileSync(new URL(`../src-tauri/${p}`, import.meta.url), 'utf8'); +const main = read('src/main.rs'); +const grant = main.slice(main.indexOf('fn grant_hub_ipc'), main.indexOf('fn hub_page(')); + +test('the hub page may call native_folder_device and pick_folder, and no dialog or fs permission', () => { + expect(grant).toContain('.permission("allow-native-folder-device")'); + expect(grant).toContain('.permission("allow-pick-folder")'); + for (const text of [grant, read('capabilities/default.json')]) { + expect(text).not.toMatch(/"(dialog|fs):/); + } + const build = read('build.rs'); + expect(build).toContain('"native_folder_device"'); + expect(build).toContain('"pick_folder"'); + expect(main).toMatch(/generate_handler!\[[\s\S]*native_folder_device,\s*pick_folder\s*\]/); +}); + +test('only the main or quick window on the current hub origin reaches the folder commands', () => { + const hubWindow = main.slice(main.indexOf('fn hub_window'), main.indexOf('/// The device id the hub page')); + expect(hubWindow).toContain('matches!(window.label(), MAIN | QUICK)'); + expect(hubWindow).toContain('on_current_hub(hub_base(window.app_handle()).as_ref(), &u)'); + expect(main).toContain('base.is_some_and(|b| b.origin() == page.origin())'); +}); + +test('native_folder_device answers only a current hub window, before and after the daemon check', () => { + const device = main.slice(main.indexOf('async fn native_folder_device'), main.indexOf('fn start_dir')); + expect(device).toMatch(/^async fn native_folder_device\(window: WebviewWindow\) -> Option/); + expect(device.split('hub_window(&window)').length - 1).toBe(2); +}); + +test('pick_folder checks hub window, focus and device, rechecks after the lookup and after the dialog', () => { + const pick = main.slice(main.indexOf('async fn pick_folder')); + expect(pick).toMatch(/^async fn pick_folder\(window: WebviewWindow, device: String, start: Option\) -> Result, String>/); + const deviceAt = pick.indexOf('proven.as_deref() != Some(device.as_str())'); + const dialogAt = pick.indexOf('.dialog()'); + expect(deviceAt).toBeGreaterThan(-1); + for (const check of ['hub_window(window)', 'is_focused()', 'ready(&window)?']) { + const i = pick.indexOf(check); + expect(i).toBeGreaterThan(-1); + expect(i).toBeLessThan(deviceAt); + } + expect(pick.slice(deviceAt, dialogAt)).toContain('ready(&window)?'); + const after = pick.slice(dialogAt); + expect(after.indexOf('hub_window(&window)')).toBeGreaterThan(-1); + expect(after.indexOf('hub_window(&window)')).toBeLessThan(after.indexOf('folder_text(picked)')); +}); + +test('Cargo.lock carries the dialog plugin for cargo --locked', () => { + const lock = read('Cargo.lock'); + const block = (name) => lock.split('\n\n').find((b) => b.includes(`\nname = "${name}"\n`)) ?? ''; + expect(block('tauri-plugin-dialog')).toContain('version = "2.8.4"'); + expect(block('tauri-plugin-dialog')).toContain('checksum = "ce0fb9c2b6d34a9720627ed930ebc8af26f61e648695aecaeb03d5c33c5896f5"'); + expect(block('tauri-plugin-fs')).toContain('version = "2.7.1"'); + expect(block('rfd')).toContain('version = "0.17.2"'); + expect(block('conclave-desktop')).toContain(' "tauri-plugin-dialog",\n'); + expect(read('Cargo.toml')).toContain('tauri-plugin-dialog = "2.8"'); + // packages sorted by name, as cargo writes them + const names = [...lock.matchAll(/^name = "([^"]+)"$/gm)].map((m) => m[1]); + expect(names).toEqual([...names].sort()); +}); diff --git a/packages/web/src/features/home/FolderPicker.tsx b/packages/web/src/features/home/FolderPicker.tsx index ba6115853..f362b99af 100644 --- a/packages/web/src/features/home/FolderPicker.tsx +++ b/packages/web/src/features/home/FolderPicker.tsx @@ -4,7 +4,9 @@ * bottom: Search folders…, No folder, Recent (the project's or folder's name * over its muted path), Open folder…, then "On " to switch the * device. A typed path lists matching folders on the device and is checked - * as before (folderCheck.tsx). Open folder… opens FolderBrowser over + * as before (folderCheck.tsx). On this desktop's proven paired device, + * Open folder… first asks the OS, then confirms the folder in FolderBrowser. + * Else it opens FolderBrowser over * GET /api/devices/:device/files: breadcrumbs, Up, folders only, Show hidden, * Home, Desktop and Documents, New folder (POST /api/devices/:device/folder) * and Select this folder. A folder that is no project yet can be added as @@ -26,6 +28,7 @@ import { FolderCheckNote, useFolderCheck, useMissingFolders } from '@/features/c import { tildePath } from '@/features/chat/FolderChooser'; import { placeName } from './start'; import { computerList } from './Where'; +import { desktop } from '@/overlay/desktop'; const trim = (p: string) => (p.length > 1 ? p.replace(/[\\/]+$/, '') : p); const base = (p: string) => trim(p).split(/[\\/]/).pop() || p; @@ -334,7 +337,7 @@ const joinPath = (dir: string, name: string) => `${trim(dir)}${dir.endsWith('/') * The folder browser. Desktop: a dialog; phones: a tall sheet. Typing a path * in the bar and Go still works, checked as before. */ -export function FolderBrowser({ open, device, start, onSelect, onClose }: { open: boolean; device: string; start?: string; onSelect: (path: string) => void; onClose: () => void }) { +export function FolderBrowser({ open, device, start, notice, onSelect, onClose }: { open: boolean; device: string; start?: string; notice?: string; onSelect: (path: string) => void; onClose: () => void }) { const d = useHub((s) => s.devices[device]); const home = d?.info?.home; const startAt = expandHome(start && start !== '~' ? start : (home ?? '/'), home); @@ -441,6 +444,7 @@ export function FolderBrowser({ open, device, start, onSelect, onClose }: { open } > + {notice &&

{notice}

}
{ @@ -525,21 +529,54 @@ export function FolderBrowser({ open, device, start, onSelect, onClose }: { open ); } -/** The menu's way to the browser: state for the browser, and the browser to render beside the menu. */ +/** Native selection still goes through the browser's device checks and optional Add as project. */ export function useOpenFolder(device: string, cwd: string | undefined, onSelect: (path: string) => void): { open: () => void; browser: ReactNode } { - const [open, setOpen] = useState(false); - const started = useRef(cwd); - if (!open) started.current = cwd; + const [browse, setBrowse] = useState<{ device: string; start?: string; notice?: string }>(); + const current = useRef(device); + current.current = device; + useEffect(() => setBrowse(undefined), [device]); + const pending = useRef(false); + const live = useRef(true); + useEffect(() => { + live.current = true; + return () => { live.current = false; }; + }, []); + const open = async () => { + if (pending.current) return; + pending.current = true; + let start = cwd; + let notice: string | undefined; + try { + const app = desktop(); + // 'local' always means the hub, not the desktop, including a member's stale selection. + if (app && device !== 'local') { + const here = await app.invoke('native_folder_device'); + if (here === device) { + const home = useHub.getState().devices[device]?.info?.home; + const picked = await app.invoke('pick_folder', { device, start: cwd ? expandHome(cwd, home) : null }); + if (picked === null) return; + start = picked; + } + } + } catch { + notice = 'The native folder picker could not open. Use the folder browser below.'; + } finally { + pending.current = false; + } + // A device change or unmount while the OS dialog was open must not apply its path elsewhere. + if (live.current && current.current === device) setBrowse({ device, start, notice }); + }; return { - open: () => setOpen(true), - browser: ( + open: () => { void open(); }, + browser: browse?.device === device && ( setOpen(false)} + start={browse.start} + notice={browse.notice} + onClose={() => setBrowse(undefined)} onSelect={(p) => { - setOpen(false); + setBrowse(undefined); onSelect(p); }} /> diff --git a/packages/web/src/features/home/Where.tsx b/packages/web/src/features/home/Where.tsx index 973813688..1713192b5 100644 --- a/packages/web/src/features/home/Where.tsx +++ b/packages/web/src/features/home/Where.tsx @@ -40,7 +40,7 @@ export function FolderChip({ device, cwd, onCwd, onDevice, open: openProp, onOpe onCwd?.(p.trim() || '~'); setOpen(false); }; - // Open folder…: the in-app browser everywhere (the desktop app has no native folder dialog: no tauri-plugin-dialog or rfd) + // Open folder…: native on this desktop's paired device, then the shared validation and project browser. const browse = useOpenFolder(device, cwd, (p) => onCwd?.(p)); if (!onCwd && !devices) return null; const shown = cwd && cwd !== '~' ? shortPath(cwd, 2) : undefined; diff --git a/packages/web/test/folder-check.test.tsx b/packages/web/test/folder-check.test.tsx index 22807c03c..43684a0e5 100644 --- a/packages/web/test/folder-check.test.tsx +++ b/packages/web/test/folder-check.test.tsx @@ -9,14 +9,15 @@ * * cd packages/web && bun test test/folder-check.test.tsx */ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test'; import { createRequire } from 'node:module'; import { join } from 'node:path'; import type { ProjectDto } from '@conclave/core/client'; import type { Session } from '@conclave/core/types'; import { api, connectClient } from '../src/lib/api'; import { useHub } from '../src/store/store'; -import { crumbs, filterFolders, folderNameOk, looksLikePath, parentPath, recentFolders } from '../src/features/home/FolderPicker'; +import { crumbs, filterFolders, folderNameOk, looksLikePath, parentPath, recentFolders, useOpenFolder } from '../src/features/home/FolderPicker'; +import { setDesktop } from '../src/overlay/desktop'; const saved: Record = {}; const GLOBALS = ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'Event', 'KeyboardEvent', 'matchMedia', 'IS_REACT_ACT_ENVIRONMENT', 'localStorage', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'MutationObserver', 'ResizeObserver', 'IntersectionObserver']; @@ -261,6 +262,158 @@ describe('the folder menu', () => { }); }); +describe('native folder routing', () => { + afterEach(() => { + setDesktop(undefined); + useHub.setState({ me: undefined, projects: {} } as never); + }); + + function native(result: string | null | Error, here: string | null = 'pc') { + const calls: Array<[string, Record | undefined]> = []; + setDesktop({ + listen: async () => () => {}, + invoke: async (cmd: string, args?: Record): Promise => { + calls.push([cmd, args]); + if (cmd === 'native_folder_device') return here as T; + if (result instanceof Error) throw result; + return result as T; + }, + }); + useHub.setState((s) => ({ devices: { ...s.devices, pc: { id: 'pc', name: 'arch-desktop', online: true, info: { home: '/home/kai' } } } }) as never); + return calls; + } + + test('same device: native success keeps server validation and Add as project before selection', async () => { + const calls = native('/home/kai/code/conclave'); + const v = await chip('pc', '~/code'); + await v.act(async () => v.button('Open folder…')!.click()); + await v.act(async () => Bun.sleep(320)); + expect(calls).toEqual([ + ['native_folder_device', undefined], + ['pick_folder', { device: 'pc', start: '/home/kai/code' }], + ]); + expect(document.querySelector('input[aria-label="Folder path"]')?.value).toBe('~/code/conclave'); + expect(v.picked).toEqual([]); + const added: unknown[] = []; + const old = api().addProject; + api().addProject = async (...args) => { + added.push(args); + return { id: 'native-project', name: 'conclave', locations: [{ device: 'pc', path: '/home/kai/code/conclave' }] } as ProjectDto; + }; + try { + await v.act(async () => v.button('Add as project')!.click()); + await v.act(async () => v.button('Add and select')!.click()); + expect(added).toEqual([['pc', '/home/kai/code/conclave', 'conclave']]); + expect(v.picked).toEqual(['~/code/conclave']); + } finally { + api().addProject = old; + await v.unmount(); + } + }); + + test('cancel preserves selection and opens neither fallback nor error', async () => { + const calls = native(null); + const v = await chip('pc', '~/code'); + await v.act(async () => v.button('Open folder…')!.click()); + expect(calls.map(([c]) => c)).toEqual(['native_folder_device', 'pick_folder']); + expect(v.picked).toEqual([]); + expect(document.querySelector('input[aria-label="Folder path"]')).toBeNull(); + expect(document.querySelector('[role=alert]')).toBeNull(); + await v.unmount(); + }); + + test('native failure explains fallback, using the unchanged current folder', async () => { + native(new Error('dialog unavailable')); + const v = await chip('pc', '~/code'); + await v.act(async () => v.button('Open folder…')!.click()); + await v.act(async () => Bun.sleep(320)); + expect(document.querySelector('[role=alert]')?.textContent).toContain('native folder picker could not open'); + expect(document.querySelector('input[aria-label="Folder path"]')?.value).toBe('~/code'); + expect(v.picked).toEqual([]); + await v.act(async () => v.button('Select this folder')!.click()); + expect(v.picked).toEqual(['~/code']); + await v.unmount(); + }); + + test('remote device with identical name and unproven device keep the browser', async () => { + for (const here of ['different-id', null]) { + const calls = native('/wrong/folder', here); + const v = await chip('pc', '~/code'); + await v.act(async () => v.button('Open folder…')!.click()); + expect(calls.map(([c]) => c)).toEqual(['native_folder_device']); + expect(document.querySelector('input[aria-label="Folder path"]')?.value).toBe('~/code'); + expect(document.querySelector('[role=alert]')).toBeNull(); + await v.unmount(); + } + }); + + test('hub local is never this desktop, even for a member or a misleading native ID', async () => { + const calls = native('/wrong/folder', 'local'); + useHub.setState({ me: { role: 'member' } } as never); + const v = await chip('local', '~/code'); + await v.act(async () => v.button('Open folder…')!.click()); + expect(calls).toEqual([]); + expect(document.querySelector('input[aria-label="Folder path"]')).not.toBeNull(); + expect(v.picked).toEqual([]); + await v.unmount(); + }); + + test('member paired device uses native ID, not the hub alias', async () => { + const calls = native('/home/kai/code'); + useHub.setState({ me: { role: 'member' } } as never); + const v = await chip('pc'); + await v.act(async () => v.button('Open folder…')!.click()); + await v.act(async () => Bun.sleep(320)); + expect(calls[1]).toEqual(['pick_folder', { device: 'pc', start: null }]); + await v.act(async () => v.button('Select this folder')!.click()); + expect(v.picked).toEqual(['~/code']); + await v.unmount(); + }); + + test('browser and phone without desktop IPC keep the existing folder browser', async () => { + const v = await chip('local', '~/code'); + await v.act(async () => v.button('Open folder…')!.click()); + expect(document.querySelector('input[aria-label="Folder path"]')?.value).toBe('~/code'); + expect(v.picked).toEqual([]); + await v.unmount(); + }); + + test('native result missing on server cannot be selected', async () => { + native('/home/kai/missing-native'); + const v = await chip('pc'); + await v.act(async () => v.button('Open folder…')!.click()); + await v.act(async () => Bun.sleep(320)); + expect(v.note()?.textContent).toContain('No folder at /home/kai/missing-native'); + expect(v.button('Select this folder')?.getAttribute('aria-disabled')).toBe('true'); + await v.act(async () => v.button('Select this folder')!.click()); + expect(v.picked).toEqual([]); + await v.unmount(); + }); + + test('device changes while native selection waits discard the old device path', async () => { + let finish!: (path: string | null) => void; + setDesktop({ listen: async () => () => {}, invoke: async (cmd: string) => (cmd === 'native_folder_device' ? 'pc' : await new Promise((resolve) => { finish = resolve; })) as T }); + const { act } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const host = document.createElement('div'); + document.body.appendChild(host); + const root = createRoot(host); + const picked: string[] = []; + function Fixture({ device }: { device: string }) { + const browse = useOpenFolder(device, '~/code', (p) => picked.push(p)); + return <>{browse.browser}; + } + await act(async () => root.render()); + await act(async () => host.querySelector('button')!.click()); + await act(async () => root.render()); + await act(async () => finish('/old-device/path')); + expect(document.querySelector('input[aria-label="Folder path"]')).toBeNull(); + expect(picked).toEqual([]); + await act(async () => root.unmount()); + host.remove(); + }); +}); + describe('the folder browser', () => { test('folders only, Show hidden, into a folder, breadcrumbs, Up, Select', async () => { const { act } = await import('react');