From 5f1c9a42af71e676ab2fac3c4069078f092cd898 Mon Sep 17 00:00:00 2001 From: 7schmiede Date: Fri, 23 Oct 2026 23:18:16 +0200 Subject: [PATCH] feat(desktop): the dashboard opens in its installed app (ADR-0061) A Chromium-family browser does not capture links into an installed web app on Linux, so the tray's Open Dashboard, `devstack ui` and a click on a notification opened a browser tab beside the installed dashboard app. devstack now computes the app id Chromium gives the hub's dashboard (the double SHA-256 of its manifest id `http://127.0.0.1:/`), finds the app (Linux: the launcher's `.desktop` file in the applications and the desktop folder; Windows: the browser profile that has it; not on macOS yet) and starts the browser with `--app-id` and the pairing link. The manifest names its `id` and asks for the open window to be reused (`launch_handler: navigate-existing`). `--browser`, `DEVSTACK_BROWSER` and `BROWSER` still win; a failed launch falls back to the browser. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 + Cargo.lock | 1 + README.md | 6 +- crates/devstack-desktop/Cargo.toml | 1 + crates/devstack-desktop/src/lib.rs | 20 + crates/devstack-desktop/src/linux.rs | 46 +++ crates/devstack-desktop/src/macos.rs | 6 + crates/devstack-desktop/src/webapp.rs | 360 ++++++++++++++++++ crates/devstack-desktop/src/windows.rs | 26 ++ crates/devstack-hub/src/lib.rs | 10 +- crates/devstack/src/hubcmd.rs | 27 +- ...he-dashboard-opens-in-its-installed-app.md | 127 ++++++ docs/adr/README.md | 1 + ui/vite.config.ts | 6 + 14 files changed, 632 insertions(+), 17 deletions(-) create mode 100644 crates/devstack-desktop/src/webapp.rs create mode 100644 docs/adr/0061-the-dashboard-opens-in-its-installed-app.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d2d25d8..50696038 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,18 @@ and listed with their assets on the ## [Unreleased] +### Added + +- **The dashboard opens in its installed app** (ADR-0061, Proposed). With + the dashboard installed as an app in Chrome, Edge, Brave or Chromium, the + tray's *Open Dashboard*, `devstack ui` and a click on a notification open + it there instead of in a browser tab: on Linux found by its launcher (the + applications folder and the desktop folder), on Windows by the browser + profile it is installed in; not on macOS yet. The app is recognised by + the id Chromium derives from the hub's origin. The manifest asks for the + open window to be reused (`launch_handler`), and names its `id`. + `--browser`, `DEVSTACK_BROWSER` and `BROWSER` still win. + ## [0.21.0] - 2026-10-23 A tray icon on Windows, Linux and macOS, a client of the hub (ADR-0060). A diff --git a/Cargo.lock b/Cargo.lock index 5ebb7466..3c1c026a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -657,6 +657,7 @@ dependencies = [ "raw-window-handle", "rfd", "serde", + "sha2", "tempfile", "tokio", "tokio-stream", diff --git a/README.md b/README.md index 9d6bb6d0..5486ca03 100644 --- a/README.md +++ b/README.md @@ -216,9 +216,9 @@ Every command and flag: `devstack --help`, `devstack --help`. | `devstack builds `, `logs`, `top`, `env [--export dotenv]` | what ran, what it printed, what it uses, what it gets | | `devstack run ` | a command of the stack file | | `devstack lane list\|start\|stop\|reset\|prune\|move\|share` | the lanes (worktrees), see above; `reset` throws a stopped lane's data away, `prune` removes what gone lanes left behind | -| `devstack ui [--lane ] [--browser ] [--link\|--print]` | open and pair the dashboard, on this stack (in a worktree on its lane, or on `--lane`); the browser is `--browser`, else `DEVSTACK_BROWSER`, else `BROWSER`, else the system's default. `--link` prints the lasting links to the stack or lane instead (the page, and the `devstack://open` link that pairs first); `--print` the one-time pairing link. `status`, `up` and `lane start` end with the page as `dashboard: ` | +| `devstack ui [--lane ] [--browser ] [--link\|--print]` | open and pair the dashboard, on this stack (in a worktree on its lane, or on `--lane`); the browser is `--browser`, else `DEVSTACK_BROWSER`, else `BROWSER`, else the dashboard's installed app when a Chromium-family browser has it (Linux, Windows; [ADR-0061](docs/adr/0061-the-dashboard-opens-in-its-installed-app.md)), else the system's default. `--link` prints the lasting links to the stack or lane instead (the page, and the `devstack://open` link that pairs first); `--print` the one-time pairing link. `status`, `up` and `lane start` end with the page as `dashboard: ` | | `devstack hub [status\|stop\|start\|install\|uninstall]` | the hub that serves the dashboard: without an action in the foreground; `stop` leaves the stacks running; `install` registers it at logon and the `devstack://` link (`--no-autostart`: the link only), `uninstall` removes both, and `devstack up` then leaves them alone | -| `devstack hub tray [on\|off]` | the tray icon ([ADR-0060](docs/adr/0060-the-tray-is-a-client-of-the-hub.md)): the state of every stack in the icon's colour, a menu to open the dashboard, start or stop a stack and open its folder. The hub starts it (`devstack tray`); `off` ends it and keeps it off, `on` brings it back. Windows, Linux (a StatusNotifierItem: KDE, Xfce, GNOME with the AppIndicator extension) and macOS | +| `devstack hub tray [on\|off]` | the tray icon ([ADR-0060](docs/adr/0060-the-tray-is-a-client-of-the-hub.md)): the state of every stack in the icon's colour, a menu to open the dashboard (in its installed app when there is one, as `devstack ui`), start or stop a stack and open its folder. The hub starts it (`devstack tray`); `off` ends it and keeps it off, `on` brings it back. Windows, Linux (a StatusNotifierItem: KDE, Xfce, GNOME with the AppIndicator extension) and macOS | | `devstack skills install [--dir] [--force]`, `skills check` | write the agent skills; check that they match this devstack and stack file (exits 1 when not) | | `devstack mcp` | the MCP server (above) | | `devstack join --fingerprint [--name] [--pool] [--telemetry] [--no-wait]` | ask a pool to admit this machine ([pool.md](docs/pool.md#join-a-pool)) | @@ -251,7 +251,7 @@ dashboard ─────┘ one per repo, └── services: main slot (f | Variable | Effect | |---|---| -| `DEVSTACK_BROWSER` | the browser `devstack ui` pairs (`chrome`, `edge`, `firefox`, `brave`, a path), and that a click on a notification opens | +| `DEVSTACK_BROWSER` | the browser `devstack ui` pairs (`chrome`, `edge`, `firefox`, `brave`, a path), and that a click on a notification or the tray opens; set, it wins over the dashboard's installed app | | `DEVSTACK_HUB_PORT` | the hub's port (default 4250) | | `DEVSTACK_NO_HUB` | `devstack up` does not start the dashboard hub | | `DEVSTACK_NO_HUB_INTEGRATION` | the installer registers no hub at logon and no `devstack://` link (and records that); `devstack up` registers neither while it is set | diff --git a/crates/devstack-desktop/Cargo.toml b/crates/devstack-desktop/Cargo.toml index 132f48a5..3dc805d3 100644 --- a/crates/devstack-desktop/Cargo.toml +++ b/crates/devstack-desktop/Cargo.toml @@ -8,6 +8,7 @@ rust-version.workspace = true publish.workspace = true [dependencies] +sha2.workspace = true tokio.workspace = true [target.'cfg(windows)'.dependencies] diff --git a/crates/devstack-desktop/src/lib.rs b/crates/devstack-desktop/src/lib.rs index 81eb0fc3..977604f9 100644 --- a/crates/devstack-desktop/src/lib.rs +++ b/crates/devstack-desktop/src/lib.rs @@ -20,6 +20,7 @@ pub mod channel; mod mac; pub mod notify; pub mod tray; +pub mod webapp; #[cfg(target_os = "linux")] mod linux; @@ -107,6 +108,25 @@ pub fn open_browser(url: &str) -> std::io::Result<()> { os::open_browser(url) } +/// The dashboard's web app, installed from the hub on `origin` +/// (`http://127.0.0.1:4250`) in a Chromium-family browser, if this +/// platform's module finds one (ADR-0061). +pub fn dashboard_app(origin: &str) -> Option { + os::dashboard_app(&webapp::app_id(&webapp::manifest_id(origin))) +} + +/// Open `url` (a page of the hub on its origin) in the dashboard's installed +/// app when there is one, else in the default browser. `Ok(true)`: in the +/// app. +pub fn open_dashboard_page(url: &str) -> std::io::Result { + if let Some(app) = webapp::origin_of(url).and_then(dashboard_app) + && app.open(url).is_ok() + { + return Ok(true); + } + os::open_browser(url).map(|()| false) +} + /// Browsers known by name: the names one may give, and the program (Windows, /// Linux) or application (macOS, `open -a`) each is on the platform. const BROWSERS: &[(&[&str], [&str; 3])] = &[ diff --git a/crates/devstack-desktop/src/linux.rs b/crates/devstack-desktop/src/linux.rs index c5fed940..ef05eb92 100644 --- a/crates/devstack-desktop/src/linux.rs +++ b/crates/devstack-desktop/src/linux.rs @@ -183,6 +183,52 @@ pub fn start_browser(program: &str, url: &str) -> std::io::Result { Command::new(program).arg(url).status().map(|_| true) } +/// The launcher of the installed web app `id` (ADR-0061): a `.desktop` file +/// in the applications folder, then the desktop folder, whose `Exec` has +/// `--app-id=`. +pub fn dashboard_app(id: &str) -> Option { + use crate::webapp; + let home = home(); + let desktop = std::fs::read_to_string(config_dir().join("user-dirs.dirs")) + .ok() + .and_then(|t| webapp::desktop_dir(&t, &home)) + .unwrap_or_else(|| home.join("Desktop")); + for dir in [data_dir().join("applications"), desktop] { + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + let mut files: Vec = entries + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "desktop")) + .collect(); + files.sort(); + for file in files { + let Some(mut app) = std::fs::read_to_string(&file) + .ok() + .and_then(|t| webapp::desktop_entry_app(&t)) + .filter(|a| a.id == id) + else { + continue; + }; + let name = file.file_name().and_then(|n| n.to_str()).unwrap_or(""); + let program = webapp::snap_command(&app.program) + .filter(|p| p.exists()) + .or_else(|| app.program.exists().then(|| app.program.clone())) + .or_else(|| { + webapp::programs_for_launcher(name) + .iter() + .find_map(|p| on_path(p)) + }); + if let Some(program) = program { + app.program = program; + return Some(app); + } + } + } + None +} + // -------------------------------------------- the user's programs (ADR-0046) /// The terminals tried after `$TERMINAL`, in order. diff --git a/crates/devstack-desktop/src/macos.rs b/crates/devstack-desktop/src/macos.rs index aefad39e..94c12682 100644 --- a/crates/devstack-desktop/src/macos.rs +++ b/crates/devstack-desktop/src/macos.rs @@ -200,6 +200,12 @@ pub fn pick_folder() -> Result, String> { pub const URL_OPENER: &str = "open"; +/// The installed web app (ADR-0061): not on macOS yet, the dashboard opens +/// in the browser. +pub fn dashboard_app(_id: &str) -> Option { + None +} + pub fn open_browser(url: &str) -> std::io::Result<()> { let mut child = Command::new("open").arg(url).stdin(Stdio::null()).spawn()?; std::thread::spawn(move || child.wait()); diff --git a/crates/devstack-desktop/src/webapp.rs b/crates/devstack-desktop/src/webapp.rs new file mode 100644 index 00000000..637e2684 --- /dev/null +++ b/crates/devstack-desktop/src/webapp.rs @@ -0,0 +1,360 @@ +//! The dashboard's installed web app (ADR-0061): its id, and what each +//! platform's module needs to find and start it. Built and tested on every +//! platform; `linux.rs` and `windows.rs` use their parts. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use sha2::{Digest, Sha256}; + +/// An installed web app of a Chromium-family browser, and how to start it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WebApp { + /// The browser's program. + pub program: PathBuf, + /// The browser profile it is installed in (`Default`, `Profile 1`). + pub profile: String, + /// The app's id (32 letters `a`–`p`). + pub id: String, +} + +impl WebApp { + /// The browser's arguments that open the app on `url` (in its scope). + pub fn args(&self, url: &str) -> Vec { + vec![ + format!("--profile-directory={}", self.profile), + format!("--app-id={}", self.id), + format!("--app-launch-url-for-shortcuts-menu-item={url}"), + ] + } + + /// Start the app on `url`, in the background. A browser already running + /// takes the command line over and the started process ends. + pub fn open(&self, url: &str) -> std::io::Result<()> { + let mut cmd = Command::new(&self.program); + cmd.args(self.args(url)); + let mut child = cmd.spawn()?; + // Reaped, so a long-lived caller (the tray) keeps no zombie. + std::thread::spawn(move || child.wait()); + Ok(()) + } +} + +/// The manifest id of the dashboard the hub serves on `origin` +/// (`http://127.0.0.1:4250`): the manifest's `id`, `/`, resolved. +pub fn manifest_id(origin: &str) -> String { + format!("{}/", origin.trim_end_matches('/')) +} + +/// The origin of a page's `url` (`http://127.0.0.1:4250/auth?…` → +/// `http://127.0.0.1:4250`). +pub fn origin_of(url: &str) -> Option<&str> { + let rest = url.find("://")? + 3; + let end = url[rest..] + .find(['/', '?', '#']) + .map_or(url.len(), |i| rest + i); + (end > rest).then(|| &url[..end]) +} + +/// The id Chromium gives the web app of `manifest_id`: SHA-256 of the +/// SHA-256 of it, the first 16 bytes as hex digits written `a`–`p`. +pub fn app_id(manifest_id: &str) -> String { + let inner = Sha256::digest(manifest_id.as_bytes()); + let outer = Sha256::digest(inner); + outer[..16] + .iter() + .flat_map(|b| [b >> 4, b & 0xf]) + .map(|n| char::from(b'a' + n)) + .collect() +} + +// --------------------------------------------------- Linux: .desktop files + +/// A launcher's `Exec` line in words, as the Desktop Entry spec quotes them: +/// double quotes group, a backslash in them escapes the next character. +/// Field codes (`%U`) are dropped. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) fn exec_words(exec: &str) -> Vec { + let mut out = Vec::new(); + let mut word = String::new(); + let mut in_word = false; + let mut quoted = false; + let mut chars = exec.chars(); + while let Some(c) = chars.next() { + match c { + '"' => { + quoted = !quoted; + in_word = true; + } + '\\' if quoted => { + if let Some(n) = chars.next() { + word.push(n); + } + } + c if c.is_whitespace() && !quoted => { + if in_word { + out.push(std::mem::take(&mut word)); + in_word = false; + } + } + c => { + word.push(c); + in_word = true; + } + } + } + if in_word { + out.push(word); + } + out.retain(|w| !(w.len() == 2 && w.starts_with('%'))); + out +} + +/// The program, profile and app id of a launcher's `[Desktop Entry]`, if +/// its `Exec` starts a web app (`--app-id=`). +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) fn desktop_entry_app(text: &str) -> Option { + let mut in_entry = false; + let mut exec = None; + for line in text.lines() { + let line = line.trim(); + if line.starts_with('[') { + in_entry = line == "[Desktop Entry]"; + } else if in_entry && let Some(v) = line.strip_prefix("Exec=") { + exec = Some(v); + } + } + let words = exec_words(exec?); + let (program, args) = words.split_first()?; + let flag = |name: &str| { + args.iter() + .find_map(|a| a.strip_prefix(name)) + .map(str::to_string) + }; + Some(WebApp { + program: PathBuf::from(program), + id: flag("--app-id=")?, + profile: flag("--profile-directory=").unwrap_or_else(|| "Default".into()), + }) +} + +/// The desktop folder from `user-dirs.dirs` (`XDG_DESKTOP_DIR="$HOME/…"`). +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) fn desktop_dir(user_dirs: &str, home: &Path) -> Option { + let v = user_dirs + .lines() + .find_map(|l| l.trim().strip_prefix("XDG_DESKTOP_DIR="))? + .trim() + .trim_matches('"'); + if let Some(rest) = v.strip_prefix("$HOME") { + Some(home.join(rest.trim_start_matches('/'))) + } else { + v.starts_with('/').then(|| PathBuf::from(v)) + } +} + +/// The browser programs a launcher's file name (`brave--Default.desktop`) +/// stands for, to look up on `PATH` when its program is gone. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) fn programs_for_launcher(file_name: &str) -> &'static [&'static str] { + const FAMILIES: &[(&str, &[&str])] = &[ + ("brave-", &["brave-browser", "brave"]), + ("chrome-", &["google-chrome", "google-chrome-stable"]), + ("chromium-", &["chromium", "chromium-browser"]), + ("msedge-", &["microsoft-edge", "microsoft-edge-stable"]), + ]; + FAMILIES + .iter() + .find(|(p, _)| file_name.starts_with(p)) + .map_or(&[], |(_, names)| names) +} + +/// `/snap///…` → `/snap/bin/`: a launcher names the +/// snap's revision at install, which its updates remove. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) fn snap_command(program: &Path) -> Option { + let rest = program.to_str()?.strip_prefix("/snap/")?; + let name = rest.split('/').next()?; + (!name.is_empty() && name != "bin").then(|| PathBuf::from(format!("/snap/bin/{name}"))) +} + +// ------------------------------------------- Windows: the profile folders + +/// The Chromium-family browsers on Windows, in the order they are tried: +/// the `User Data` folder under `%LOCALAPPDATA%`, and the program under +/// `%ProgramFiles%`, `%ProgramFiles(x86)%` or `%LOCALAPPDATA%`. +#[cfg_attr(not(windows), allow(dead_code))] +pub(crate) const WINDOWS_BROWSERS: &[(&str, &str)] = &[ + (r"Google\Chrome", "chrome.exe"), + (r"Microsoft\Edge", "msedge.exe"), + (r"BraveSoftware\Brave-Browser", "brave.exe"), + ("Chromium", "chrome.exe"), +]; + +/// The profiles in a `User Data` folder that have the app `id` installed, +/// `Default` first: `\Web Applications\Manifest Resources\`. +#[cfg_attr(not(windows), allow(dead_code))] +pub(crate) fn profiles_with_app(user_data: &Path, id: &str) -> Vec { + let Ok(dir) = std::fs::read_dir(user_data) else { + return Vec::new(); + }; + let mut found: Vec = dir + .flatten() + .filter(|e| { + e.path() + .join("Web Applications") + .join("Manifest Resources") + .join(id) + .is_dir() + }) + .filter_map(|e| e.file_name().to_str().map(str::to_string)) + .collect(); + found.sort_by_key(|p| (p != "Default", p.clone())); + found +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_app_id_is_the_one_chromium_gives_the_hubs_dashboard() { + // Read from a Brave that installed the dashboard from the hub. + assert_eq!( + app_id(&manifest_id("http://127.0.0.1:4250")), + "imbjdaboabifmbceekoampobpbpodgfh" + ); + assert_ne!( + app_id(&manifest_id("http://localhost:4250")), + app_id(&manifest_id("http://127.0.0.1:4250")) + ); + assert_eq!( + manifest_id("http://127.0.0.1:4250/"), + "http://127.0.0.1:4250/" + ); + } + + #[test] + fn the_origin_is_read_from_the_pairing_link() { + assert_eq!( + origin_of("http://127.0.0.1:4250/auth?code=x&next=%2F%23%2F"), + Some("http://127.0.0.1:4250") + ); + assert_eq!( + origin_of("http://127.0.0.1:4251"), + Some("http://127.0.0.1:4251") + ); + assert_eq!( + origin_of("http://127.0.0.1:4250?x"), + Some("http://127.0.0.1:4250") + ); + assert_eq!(origin_of("no-scheme"), None); + assert_eq!(origin_of("http:///x"), None); + } + + #[test] + fn a_launcher_brave_wrote_is_read() { + let text = "#!/usr/bin/env xdg-open\n[Desktop Entry]\nVersion=1.0\nTerminal=false\n\ + Type=Application\nName=devstack\n\ + Exec=/snap/brave/698/opt/brave.com/brave/brave-browser --profile-directory=Default --app-id=imbjdaboabifmbceekoampobpbpodgfh\n\ + Icon=brave-imbjdaboabifmbceekoampobpbpodgfh-Default\n\ + StartupWMClass=crx_imbjdaboabifmbceekoampobpbpodgfh\n"; + let app = desktop_entry_app(text).unwrap(); + assert_eq!( + app.program, + PathBuf::from("/snap/brave/698/opt/brave.com/brave/brave-browser") + ); + assert_eq!(app.profile, "Default"); + assert_eq!(app.id, "imbjdaboabifmbceekoampobpbpodgfh"); + assert_eq!( + app.args("http://127.0.0.1:4250/auth?code=c"), + [ + "--profile-directory=Default", + "--app-id=imbjdaboabifmbceekoampobpbpodgfh", + "--app-launch-url-for-shortcuts-menu-item=http://127.0.0.1:4250/auth?code=c", + ] + ); + } + + #[test] + fn a_launcher_with_quotes_field_codes_and_other_sections() { + let text = "[Desktop Entry]\n\ + Exec=\"/opt/google/chrome/google-chrome\" \"--profile-directory=Profile 2\" --app-id=abc %U\n\ + [Desktop Action new]\nExec=/usr/bin/other --app-id=zzz\n"; + let app = desktop_entry_app(text).unwrap(); + assert_eq!( + app.program, + PathBuf::from("/opt/google/chrome/google-chrome") + ); + assert_eq!(app.profile, "Profile 2"); + assert_eq!(app.id, "abc"); + assert_eq!(exec_words(r#"a "b \"c\" d" e"#), ["a", r#"b "c" d"#, "e"]); + // Not a web app: a browser's own launcher. + assert_eq!( + desktop_entry_app("[Desktop Entry]\nExec=/usr/bin/brave-browser %U\n"), + None + ); + assert_eq!(desktop_entry_app("[Desktop Entry]\nName=x\n"), None); + } + + #[test] + fn the_desktop_folder_comes_from_user_dirs() { + let home = Path::new("/home/u"); + let dirs = "# written by xdg-user-dirs-update\nXDG_DESKTOP_DIR=\"$HOME/Schreibtisch\"\n\ + XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"\n"; + assert_eq!( + desktop_dir(dirs, home), + Some(PathBuf::from("/home/u/Schreibtisch")) + ); + assert_eq!( + desktop_dir("XDG_DESKTOP_DIR=\"/data/desk\"", home), + Some(PathBuf::from("/data/desk")) + ); + assert_eq!(desktop_dir("XDG_MUSIC_DIR=\"$HOME/M\"", home), None); + } + + #[test] + fn a_stale_program_has_a_stand_in() { + assert_eq!( + snap_command(Path::new( + "/snap/brave/603/opt/brave.com/brave/brave-browser" + )), + Some(PathBuf::from("/snap/bin/brave")) + ); + assert_eq!(snap_command(Path::new("/snap/bin/brave")), None); + assert_eq!(snap_command(Path::new("/opt/google/chrome/chrome")), None); + assert_eq!( + programs_for_launcher("brave-imbj-Default.desktop"), + ["brave-browser", "brave"] + ); + assert_eq!( + programs_for_launcher("chrome-imbj-Profile_1.desktop")[0], + "google-chrome" + ); + assert!(programs_for_launcher("org.gnome.Nautilus.desktop").is_empty()); + } + + #[test] + fn the_profiles_with_the_app_are_found_default_first() { + let dir = tempfile::tempdir().unwrap(); + let app = |profile: &str, id: &str| { + std::fs::create_dir_all( + dir.path() + .join(profile) + .join("Web Applications") + .join("Manifest Resources") + .join(id), + ) + .unwrap(); + }; + app("Profile 1", "abc"); + app("Default", "abc"); + app("Profile 2", "other"); + assert_eq!( + profiles_with_app(dir.path(), "abc"), + ["Default", "Profile 1"] + ); + assert!(profiles_with_app(dir.path(), "none").is_empty()); + assert!(profiles_with_app(&dir.path().join("missing"), "abc").is_empty()); + } +} diff --git a/crates/devstack-desktop/src/windows.rs b/crates/devstack-desktop/src/windows.rs index 0d11cf29..0257043a 100644 --- a/crates/devstack-desktop/src/windows.rs +++ b/crates/devstack-desktop/src/windows.rs @@ -170,6 +170,32 @@ pub fn start_browser(program: &str, url: &str) -> std::io::Result { Ok(c.status()?.success()) } +/// The installed web app `id` (ADR-0061): the first Chromium-family +/// browser with a profile that has it, and that browser's program. +pub fn dashboard_app(id: &str) -> Option { + let local = PathBuf::from(std::env::var_os("LOCALAPPDATA")?); + let program_dirs: Vec = ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] + .iter() + .filter_map(|v| std::env::var_os(v).map(PathBuf::from)) + .collect(); + crate::webapp::WINDOWS_BROWSERS + .iter() + .find_map(|(dir, exe)| { + let profile = crate::webapp::profiles_with_app(&local.join(dir).join("User Data"), id) + .into_iter() + .next()?; + let program = program_dirs + .iter() + .map(|p| p.join(dir).join("Application").join(exe)) + .find(|p| p.is_file())?; + Some(crate::webapp::WebApp { + program, + profile, + id: id.to_string(), + }) + }) +} + // -------------------------------------------- the user's programs (ADR-0046) #[derive(Debug, Clone)] diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index 35d1a7de..007a2a56 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -832,17 +832,17 @@ async fn pair(State(s): State) -> Response { Json(serde_json::json!({ "code": code, "url": url })).into_response() } -/// Open the dashboard at `route` in the default browser, paired: what a -/// click on a notification the hub hears itself does (Linux, ADR-0045; a -/// Windows toast opens a link). `Err` with why it could not, for the -/// notifications' `trouble`. +/// Open the dashboard at `route`, paired, in its installed app or else the +/// default browser (ADR-0061): what a click on a notification the hub hears +/// itself does (Linux, ADR-0045; a Windows toast opens a link). `Err` with +/// why it could not, for the notifications' `trouble`. fn open_dashboard(port: u16, codes: &Codes, route: &str) -> Result<(), String> { let code = new_code(codes); let url = format!( "http://127.0.0.1:{port}/auth?code={code}&next={}", next_param(route) ); - if let Err(e) = devstack_desktop::open_browser(&url) { + if let Err(e) = devstack_desktop::open_dashboard_page(&url) { diag::warn( "open_dashboard_failed", serde_json::json!({ "error": e.to_string() }), diff --git a/crates/devstack/src/hubcmd.rs b/crates/devstack/src/hubcmd.rs index 4c3587c0..4615fb2d 100644 --- a/crates/devstack/src/hubcmd.rs +++ b/crates/devstack/src/hubcmd.rs @@ -368,7 +368,7 @@ pub fn open_dashboard(route: &str) -> Result<()> { ); match chosen_browser(None) { Some(b) => open_in(&b, &url), - None => open_browser(&url), + None => open_dashboard_page(&url).map(drop), } } @@ -421,14 +421,15 @@ pub fn ui( // The pairing belongs to the browser that opens the link, so it must be // the one you develop in, not just the system default (#9). let chosen = chosen_browser(browser); - match &chosen { - Some(b) => open_in(b, &url)?, - None => open_browser(&url)?, - } - println!( - "dashboard opened{} (the link works once, for 60 s): {url}", - chosen.map(|b| format!(" in {b}")).unwrap_or_default() - ); + let place = match &chosen { + Some(b) => { + open_in(b, &url)?; + format!(" in {b}") + } + None if open_dashboard_page(&url)? => " in its installed app".into(), + None => String::new(), + }; + println!("dashboard opened{place} (the link works once, for 60 s): {url}"); Ok(()) } @@ -461,6 +462,14 @@ fn web_url(url: &str) -> Result<()> { } } +/// The dashboard's page `url`: in its installed app, when there is one +/// (ADR-0061), else in the default browser. `true`: in the app. +fn open_dashboard_page(url: &str) -> Result { + web_url(url)?; + devstack_desktop::open_dashboard_page(url) + .map_err(|e| anyhow!("cannot open a browser ({e}); open {url} yourself")) +} + fn open_browser(url: &str) -> Result<()> { web_url(url)?; devstack_desktop::open_browser(url) diff --git a/docs/adr/0061-the-dashboard-opens-in-its-installed-app.md b/docs/adr/0061-the-dashboard-opens-in-its-installed-app.md new file mode 100644 index 00000000..682198ba --- /dev/null +++ b/docs/adr/0061-the-dashboard-opens-in-its-installed-app.md @@ -0,0 +1,127 @@ +# ADR-0061: The dashboard opens in its installed app, when there is one + +- **Status:** Proposed +- **Date:** 2026-10-23 +- **Deciders:** project owner +- **Related:** [ADR-0018](0018-dashboard-is-a-browser-page.md), [ADR-0021](0021-a-hub-serves-the-dashboard.md) (the hub's origin, the PWA, pairing), [ADR-0045](0045-the-hub-notifies-the-desktop.md) (a click on a notification), [ADR-0060](0060-the-tray-is-a-client-of-the-hub.md) (the tray's *Open Dashboard*), [ADR-0011](0011-platform-windows-native-first.md), [ADR-0054](0054-macos-is-a-developer-platform-in-preview.md) + +## Context + +The hub serves the dashboard as a progressive web app on a fixed origin, +`http://127.0.0.1:4250` (ADR-0021), and a Chromium-family browser (Chrome, +Edge, Brave, Chromium) installs it as an app with a window of its own. Every +way devstack opens the dashboard, `devstack ui`, the tray's *Open Dashboard* +and its per-stack entries, a click on a notification and a +`devstack://open` link, hands the pairing link to the default browser +(`xdg-open`, the shell on Windows, `open` on macOS), or to `--browser`, +`DEVSTACK_BROWSER` or `BROWSER`. + +The browser opens that link in a tab. Chromium captures links into an +installed app only on some platforms and only behind a setting; on Linux it +does not at all. So a user who installed the dashboard as an app, to have it +beside their editor as a window of its own, gets a second copy in a tab each +time they click the tray icon. + +Two facts make a precise answer cheap: + +- **An installed web app's id follows from its manifest id.** Chromium names + an app by the hash of its manifest id (the manifest's `id`, or its + `start_url`, resolved against the origin): the SHA-256 of the SHA-256 of the + URL, its first 16 bytes written with the letters `a` to `p`. The + dashboard's manifest id is `http://127.0.0.1:/`, so the app id is + known without reading the browser's data, and it is the same in every + Chromium browser and profile. Checked: an app installed by Brave from the + hub has the id this computes. +- **Every Chromium-family browser starts an installed app by that id:** + `--profile-directory= --app-id=`, and + `--app-launch-url-for-shortcuts-menu-item=` opens it on a URL in the + app's scope, as a shortcut of the app's jump list does. A browser already + running hands the command line to its running instance. + +## Decision + +1. **devstack opens the dashboard in its installed app when it finds one, + else in the browser as before.** This holds for every way it opens the + dashboard: `devstack ui`, the tray, a click on a notification (the hub's + own on Linux, a `devstack://open` link elsewhere). `--browser`, + `DEVSTACK_BROWSER` and `BROWSER` still win: naming a browser means that + browser, in a tab. +2. **What counts as the dashboard's app is decided by its id**, computed from + the manifest id `http://127.0.0.1:/`. An app installed from + `localhost` has another id and origin, and another cookie, and is not + taken. The manifest names its `id` (`/`), so a later change of + `start_url` does not change the app's id. +3. **Where devstack looks, per platform:** + - **Linux:** the launchers Chromium writes on install, the `.desktop` + files in `$XDG_DATA_HOME/applications` (`~/.local/share/applications`) + and in the desktop folder (`XDG_DESKTOP_DIR` from `user-dirs.dirs`, + else `~/Desktop`). A launcher is the app's when its `Exec` line has + `--app-id=`; it gives the browser's program and the profile + (`--profile-directory`). A program under `/snap///` is + started as `/snap/bin/`, since the revision in the launcher goes + stale with the snap's updates; a program that no longer exists is + looked up on `PATH` by the browser the launcher's file name names + (`brave-…`, `chrome-…`, `chromium-…`, `msedge-…`). + - **Windows:** the browsers' profile folders under `%LOCALAPPDATA%` + (Chrome, Edge, Brave, Chromium, `User Data\`): the app is + installed in a profile that has `Web Applications\Manifest + Resources\`. The browser is its `…\Application\.exe` under + `%ProgramFiles%`, `%ProgramFiles(x86)%` or `%LOCALAPPDATA%`. The Start + menu shortcut is not read: it is a `.lnk`, and the profile folder says + the same. + - **macOS: not yet.** No maintainer has a Mac to check Chromium's app + shims (`~/Applications/ Apps.localized/`) against; the + dashboard opens in the browser as before. + When several launchers or profiles have the app, the first found is + taken (Linux: the applications folder before the desktop folder; + Windows: Chrome, Edge, Brave, Chromium, and `Default` before the other + profiles). +4. **The app is started on the pairing link:** + ` --profile-directory= --app-id= + --app-launch-url-for-shortcuts-menu-item=`. The link is in + the app's scope; the app shares the profile's cookies, so pairing it + pairs that profile, as before. The program is started directly, with no + shell in between. +5. **The open window is reused:** the manifest says + `launch_handler: { client_mode: "navigate-existing" }`, so a launch + navigates the app's open window to the link instead of opening a second + one. A browser that does not know `launch_handler` opens a window. +6. **A launch that fails falls back to the browser**, as if no app were + installed; nothing waits for the app's window. + +## Alternatives considered + +- **Leave it to the browser's link capturing.** Not on Linux, and elsewhere + behind a per-app setting the user has to find. +- **Read the browser's web app database** (`Web Applications`, a LevelDB of + protocol buffers) to match the app by its start URL. A second format to + parse per browser for an answer the id already gives. +- **Match the launcher by its name (`Name=devstack`).** The user can rename + an app, and another app may be called the same. +- **A setting naming the app's command** (`DEVSTACK_APP`). Possible later + for a browser this does not find; the user would have to find the app id + first. +- **Open the app without the pairing link** (`--app-id` alone, the start + URL). The app is usually paired already, but a stack's route + (`/#/s/?lane=`) would be lost, and an unpaired profile would land on + the pairing notice. + +## Consequences + +- A user with the dashboard installed as an app gets the app from the tray, + from `devstack ui` and from a notification, and one window of it. +- Firefox has no installable web apps; nothing changes for it. +- Chromium's flags and folders are not a published interface. If a browser + changes them, devstack falls back to the browser tab, which is today's + behaviour. +- On Windows the reused window is a Chromium decision (`launch_handler`) + devstack cannot test in CI. + +## Enforced by + +- `crates/devstack-desktop/src/webapp.rs`: the app id, the launcher's + parsing and matching (with tests); `linux.rs`, `windows.rs`, `macos.rs`: + `dashboard_app`. +- `crates/devstack/src/hubcmd.rs`: `open_dashboard` and `devstack ui`; + `crates/devstack-hub/src/lib.rs`: a notification's click. +- `ui/vite.config.ts`: the manifest's `id` and `launch_handler`. diff --git a/docs/adr/README.md b/docs/adr/README.md index 7d11cb6f..ff50c206 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -109,3 +109,4 @@ stay. | [0058](0058-a-profile-can-leave-out-containers-and-services.md) | A profile can leave out containers, whole Compose groups and services | Accepted | | [0059](0059-a-services-stop-command-ends-what-its-run-started.md) | A service's `stop` command ends what its `run` started outside its process tree | Accepted | | [0060](0060-the-tray-is-a-client-of-the-hub.md) | The tray is a client of the hub, a process of its own, on every desktop | Accepted | +| [0061](0061-the-dashboard-opens-in-its-installed-app.md) | The dashboard opens in its installed app, when there is one | Proposed | diff --git a/ui/vite.config.ts b/ui/vite.config.ts index 6297fe7a..f3c0184c 100644 --- a/ui/vite.config.ts +++ b/ui/vite.config.ts @@ -40,9 +40,15 @@ export default defineConfig(({ mode }) => { name: 'devstack', short_name: 'devstack', description: 'Dashboard for devstack: services, candidates, logs and resources of your local stacks.', + // The app's id: Chromium names the installed app by its hash, and + // devstack finds the app by it (ADR-0061). + id: '/', start_url: '/', scope: '/', display: 'standalone', + // A launch (the tray, `devstack ui`) navigates the open window + // instead of opening a second one (ADR-0061). + launch_handler: { client_mode: 'navigate-existing' }, background_color: '#0f1115', theme_color: '#0f1115', icons: [