diff --git a/CHANGELOG.md b/CHANGELOG.md index 548ee926..fee8c00b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,16 @@ and listed with their assets on the ### Added +- **Open a stack's folder from the dashboard** + ([ADR-0046](docs/adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md)): + the path in the stack header is a menu. It copies the path, or opens the + shown tree (the main working tree or a lane's worktree) in Explorer or the + file manager, Windows Terminal, PowerShell or a terminal, VS Code, Cursor, + Windsurf, Zed, Claude Desktop, Claude Code or Orca: whichever of them the + hub finds on this machine (an editor or agent by the URL scheme it + registered). The hub opens only a registered stack's own trees, with a + program from that list (`GET /hub/openers`, `POST /hub/open`). A lane + shared with you offers the copy only. - **winget**: `winget install nuetzliches.devstack` (once winget's catalogue has the release). Each release submits its manifests (`packaging/winget/`) to `microsoft/winget-pkgs`; the release workflow diff --git a/Cargo.toml b/Cargo.toml index f22ea149..8c3b6723 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,11 +66,13 @@ windows-sys = { version = "0.61", features = [ "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", + "Win32_System_Com", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", ] } diff --git a/crates/devstack-daemon/src/lanes.rs b/crates/devstack-daemon/src/lanes.rs index 303bda83..afce80c1 100644 --- a/crates/devstack-daemon/src/lanes.rs +++ b/crates/devstack-daemon/src/lanes.rs @@ -557,6 +557,20 @@ fn worktrees(repo: &Path) -> Option<(Vec, Vec)> { Some((here, missing.into_iter().map(|w| w.path).collect())) } +/// The worktree of `repo` (the main working tree included) that `path` +/// names, as git lists it; `repo` itself also without git. `None` when +/// `path` is none of them. What the hub opens (ADR-0046) is checked against +/// it. +pub fn worktree_of(repo: &Path, path: &Path) -> Option { + if same_tree(repo, path) { + return Some(repo.to_path_buf()); + } + let (here, _) = worktrees(repo)?; + here.into_iter() + .map(|w| w.path) + .find(|w| same_tree(w, path)) +} + /// What changes in `/worktrees` when a worktree is added or /// removed or checks out another branch: its entries and their `HEAD`s. fn fingerprint(dir: &Path) -> Vec<(std::ffi::OsString, Option)> { @@ -2408,6 +2422,32 @@ impl Lanes { mod tests { use super::*; + #[test] + fn only_the_repository_and_its_worktrees_are_its_trees() { + let d = tempfile::tempdir().unwrap(); + let repo = d.path().join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + let g = |args: &[&str]| git(&repo, args).unwrap(); + g(&["init", "-q"]); + g(&[ + "-c", + "user.name=t", + "-c", + "user.email=t@t", + "commit", + "-q", + "--allow-empty", + "-m", + "x", + ]); + let wt = d.path().join("wt"); + g(&["worktree", "add", "-q", &wt.to_string_lossy()]); + assert!(worktree_of(&repo, &repo).is_some()); + assert!(worktree_of(&repo, &wt).is_some_and(|p| same_tree(&p, &wt))); + assert!(worktree_of(&repo, &repo.join(".git")).is_none()); + assert!(worktree_of(&repo, d.path()).is_none()); + } + #[test] fn the_state_of_a_forgotten_lane_is_swept() { let d = tempfile::tempdir().unwrap(); diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index bc652e2f..90632337 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -36,6 +36,7 @@ static UI: Dir<'_> = include_dir!("$OUT_DIR/ui"); mod dialog; mod guests; mod notify; +mod open; mod pool; pub mod release; mod share; @@ -452,6 +453,8 @@ fn router(state: AppState) -> axum::Router { .route("/hub/notify/test", post(notify::test)) .route("/hub/inspect", get(inspect)) .route("/hub/pick-folder", post(pick_folder)) + .route("/hub/openers", get(openers)) + .route("/hub/open", post(open_tree)) .route("/hub/stacks/add", post(stack_add)) .route("/hub/stacks/init", post(stack_init)) .route("/hub/stacks/scan", post(stack_scan)) @@ -1455,6 +1458,71 @@ async fn pick_folder() -> Response { } } +/// `GET /hub/openers`: what this machine can open a stack's tree with +/// (ADR-0046), `[{id, label, kind}]`; empty without a desktop. +async fn openers() -> Response { + match tokio::task::spawn_blocking(open::found).await { + Ok(found) => Json(found.into_iter().map(|f| f.opener).collect::>()).into_response(), + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + +#[derive(Deserialize)] +struct OpenQuery { + stack: String, + path: String, + with: String, +} + +/// `POST /hub/open {stack, path, with}`: open one of the stack's trees (its +/// repository or a worktree of it) with a program `GET /hub/openers` lists. +/// Anything else is refused: the page names a tree and a program, never a +/// command (ADR-0046). +async fn open_tree(State(s): State, Json(q): Json) -> Response { + let Some(e) = entry(&s, &q.stack) else { + return err(StatusCode::NOT_FOUND, "no such stack"); + }; + let opened = tokio::task::spawn_blocking(move || { + let raw = PathBuf::from(&q.path); + if !raw.is_absolute() || !local_path(&q.path, &raw) { + return Err(( + StatusCode::BAD_REQUEST, + "a folder on this machine".to_string(), + )); + } + let Some(tree) = devstack_daemon::lanes::worktree_of(&e.repo, &raw) else { + return Err(( + StatusCode::BAD_REQUEST, + "not a worktree of this stack".to_string(), + )); + }; + let file = e + .file + .strip_prefix(&e.repo) + .map(|rel| tree.join(rel)) + .unwrap_or_else(|_| e.file.clone()); + open::open(&q.with, &tree, &e.repo, &file).map_err(|e| match e { + open::OpenError::Unknown => ( + StatusCode::BAD_REQUEST, + format!( + "{} is not a program this machine opens folders with", + q.with + ), + ), + open::OpenError::Failed(why) => (StatusCode::BAD_GATEWAY, why), + }) + }) + .await; + match opened { + Ok(Ok(())) => StatusCode::NO_CONTENT.into_response(), + Ok(Err((status, msg))) => { + diag::warn("open_failed", serde_json::json!({ "error": msg })); + err(status, msg) + } + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + /// `GET /hub/inspect?path=`: is it a folder, does it have a stack file, is /// it registered already. async fn inspect(Query(q): Query) -> Response { diff --git a/crates/devstack-hub/src/open.rs b/crates/devstack-hub/src/open.rs new file mode 100644 index 00000000..f47abe3f --- /dev/null +++ b/crates/devstack-hub/src/open.rs @@ -0,0 +1,568 @@ +//! Opening a stack's tree in the user's own programs (ADR-0046): +//! `GET /hub/openers`, `POST /hub/open`. +//! +//! A fixed list. Each program is found the way it makes itself known: an +//! editor or agent by the URL scheme it registered (`vscode`, `claude`, ...), +//! started by a link of that scheme, as the shell opens it; a terminal and +//! Orca by their program on `PATH`. The page never names a program or a +//! command line, only one of the ids found here. + +use serde::Serialize; +use std::path::{Path, PathBuf}; + +/// What a program is for, to group the menu. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + Files, + Terminal, + Editor, + Agent, +} + +/// One entry of `GET /hub/openers`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Opener { + pub id: &'static str, + pub label: &'static str, + pub kind: Kind, +} + +/// A program found, and how it is started. +#[derive(Debug, Clone)] +pub struct Found { + pub opener: Opener, + how: How, +} + +#[derive(Debug, Clone)] +enum How { + /// The folder, opened by the shell (Explorer, the file manager). + Folder, + /// A link of the program's scheme (`LINKS`). + Link(&'static str), + /// Windows Terminal: `wt -d `. + #[cfg_attr(not(windows), allow(dead_code))] + Wt(PathBuf), + /// A shell in a console of its own, in the folder (PowerShell). + #[cfg_attr(not(windows), allow(dead_code))] + Console(PathBuf), + /// A terminal emulator in the folder (Linux). + #[cfg_attr(windows, allow(dead_code))] + Terminal(PathBuf), + /// Orca's CLI. + Orca(PathBuf), +} + +/// The programs found by their registered scheme, in menu order. +const LINKS: &[(&str, &str, Kind)] = &[ + ("vscode", "VS Code", Kind::Editor), + ("vscode-insiders", "VS Code Insiders", Kind::Editor), + ("cursor", "Cursor", Kind::Editor), + ("windsurf", "Windsurf", Kind::Editor), + ("zed", "Zed", Kind::Editor), + ("claude", "Claude Desktop", Kind::Agent), + ("claude-cli", "Claude Code", Kind::Agent), +]; + +/// What this machine can open a folder with, in menu order: files, +/// terminals, editors, agents. Nothing without a desktop. +pub fn found() -> Vec { + let mut out = imp::files_and_terminals(); + if out.is_empty() { + return out; + } + for &(scheme, label, kind) in LINKS { + if imp::registered(scheme) { + out.push(Found { + opener: Opener { + id: scheme, + label, + kind, + }, + how: How::Link(scheme), + }); + } + } + if let Some(orca) = imp::orca() { + out.push(Found { + opener: Opener { + id: "orca", + label: "Orca", + kind: Kind::Agent, + }, + how: How::Orca(orca), + }); + } + out +} + +/// Why opening failed: the program is not (or no longer) here, or it +/// refused. +#[derive(Debug)] +pub enum OpenError { + Unknown, + Failed(String), +} + +/// Open `tree` (a worktree of a stack, checked by the caller) with the +/// program `id`; `stack_file` is the stack file's path inside `tree` (Orca +/// shows it). +pub fn open(id: &str, tree: &Path, repo: &Path, stack_file: &Path) -> Result<(), OpenError> { + let f = found() + .into_iter() + .find(|f| f.opener.id == id) + .ok_or(OpenError::Unknown)?; + let path = display(tree); + match &f.how { + How::Folder => imp::shell_open(&path), + How::Link(scheme) => imp::shell_open(&link(scheme, &path)), + How::Wt(exe) => imp::wt(exe, &path), + How::Console(exe) => imp::console(exe, tree), + How::Terminal(exe) => imp::terminal(exe, tree), + How::Orca(exe) => orca(exe, &path, &display(repo), stack_file), + } + .map_err(OpenError::Failed) +} + +/// A path as the programs take it: the platform's separators, without the +/// `\\?\` prefix. +fn display(p: &Path) -> String { + let s = p.to_string_lossy(); + let s = s.strip_prefix(r"\\?\").unwrap_or(&s); + if cfg!(windows) { + s.replace('/', "\\") + } else { + s.to_string() + } +} + +/// The link that opens `path` in the program of `scheme`. +fn link(scheme: &str, path: &str) -> String { + match scheme { + "claude" => format!("claude://code/new?folder={}", encode(path, b"")), + "claude-cli" => format!("claude-cli://open?cwd={}", encode(path, b"")), + // The editors' `file` links (VS Code and its forks, Zed): + // `vscode://file/C:/src/app`, `vscode://file/home/me/app`. + _ => { + let p = path.replace('\\', "/"); + let p = p.trim_start_matches('/'); + format!("{scheme}://file/{}", encode(p, b"/:")) + } + } +} + +/// Percent-encode all but the unreserved characters and `keep`. +fn encode(s: &str, keep: &[u8]) -> String { + s.bytes() + .map(|b| { + if b.is_ascii_alphanumeric() || b"-._~".contains(&b) || keep.contains(&b) { + (b as char).to_string() + } else { + format!("%{b:02X}") + } + }) + .collect() +} + +/// Orca: start it if it does not run, bring its window to the tree with the +/// stack file open; a repository Orca does not know yet is added first. +fn orca(exe: &Path, path: &str, repo: &str, stack_file: &Path) -> Result<(), String> { + // Err: Orca's error code (`selector_not_found`) and what to say. + let run = |args: &[&str]| -> Result<(), (String, String)> { + let mut cmd = std::process::Command::new(exe); + cmd.args(args) + .arg("--json") + .stdin(std::process::Stdio::null()); + crate::no_window(&mut cmd); + let out = cmd + .output() + .map_err(|e| (String::new(), format!("run orca: {e}")))?; + if out.status.success() { + return Ok(()); + } + let answer = serde_json::from_slice::(&out.stdout).ok(); + let at = |p: &str| { + answer + .as_ref() + .and_then(|v| v.pointer(p)) + .and_then(|m| m.as_str()) + .map(String::from) + }; + let code = at("/error/code").unwrap_or_default(); + let why = at("/error/data/nextSteps/0") + .or_else(|| at("/error/message")) + .unwrap_or_else(|| String::from_utf8_lossy(&out.stderr).trim().to_string()); + Err((code, format!("orca {}: {why}", args[0]))) + }; + run(&["open"]).map_err(|e| e.1)?; + let tree = format!("path:{path}"); + let file = stack_file.to_string_lossy(); + let show = || { + if stack_file.is_file() { + run(&["file", "open", &file, "--worktree", &tree, "--focus"]) + } else { + run(&["terminal", "create", "--worktree", &tree, "--focus"]) + } + }; + match show() { + Err((code, _)) if code == "selector_not_found" => { + run(&["repo", "add", "--path", repo]).map_err(|e| e.1)?; + show().map_err(|e| e.1) + } + r => r.map_err(|e| e.1), + } +} + +/// Where `name` is on `PATH`, as a program (`.exe` added on Windows). +fn on_path(name: &str) -> Option { + let file = if cfg!(windows) && !name.ends_with(".exe") { + format!("{name}.exe") + } else { + name.to_string() + }; + std::env::split_paths(&std::env::var_os("PATH")?) + .map(|d| d.join(&file)) + // An app execution alias (`wt.exe`) is a reparse point that + // `metadata` cannot follow; it is there all the same. + .find(|p| std::fs::symlink_metadata(p).is_ok_and(|m| !m.is_dir())) +} + +#[cfg(windows)] +mod imp { + use super::{Found, How, Kind, Opener, on_path}; + use std::path::{Path, PathBuf}; + + fn wide(s: &str) -> Vec { + s.encode_utf16().chain(std::iter::once(0)).collect() + } + + pub fn files_and_terminals() -> Vec { + let mut out = vec![Found { + opener: Opener { + id: "files", + label: "Explorer", + kind: Kind::Files, + }, + how: How::Folder, + }]; + if let Some(wt) = on_path("wt") { + out.push(Found { + opener: Opener { + id: "wt", + label: "Windows Terminal", + kind: Kind::Terminal, + }, + how: How::Wt(wt), + }); + } + let ps = on_path("pwsh") + .or_else(|| on_path("powershell")) + .or_else(|| { + let root = std::env::var_os("SystemRoot")?; + let p = PathBuf::from(root).join(r"System32\WindowsPowerShell\v1.0\powershell.exe"); + p.is_file().then_some(p) + }); + if let Some(ps) = ps { + out.push(Found { + opener: Opener { + id: "powershell", + label: "PowerShell", + kind: Kind::Terminal, + }, + how: How::Console(ps), + }); + } + out + } + + /// `HKCR\` with a `URL Protocol` value: what the shell opens + /// a link of that scheme with, packaged apps included. + pub fn registered(scheme: &str) -> bool { + use windows_sys::Win32::Foundation::ERROR_SUCCESS; + use windows_sys::Win32::System::Registry::{ + HKEY, HKEY_CLASSES_ROOT, KEY_READ, RegCloseKey, RegOpenKeyExW, RegQueryValueExW, + }; + let key_name = wide(scheme); + let value = wide("URL Protocol"); + let mut key: HKEY = std::ptr::null_mut(); + // SAFETY: plain registry calls on our own buffers; the key is closed. + unsafe { + if RegOpenKeyExW(HKEY_CLASSES_ROOT, key_name.as_ptr(), 0, KEY_READ, &mut key) + != ERROR_SUCCESS + { + return false; + } + let found = RegQueryValueExW( + key, + value.as_ptr(), + std::ptr::null(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) == ERROR_SUCCESS; + RegCloseKey(key); + found + } + } + + pub fn orca() -> Option { + on_path("orca").or_else(|| { + let p = PathBuf::from(std::env::var_os("LOCALAPPDATA")?) + .join(r"Programs\orca\resources\bin\orca.exe"); + p.is_file().then_some(p) + }) + } + + /// What double-clicking `target` does: a folder opens in Explorer, a + /// link in the program its scheme names. + pub fn shell_open(target: &str) -> Result<(), String> { + use windows_sys::Win32::System::Com::{ + COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE, CoInitializeEx, CoUninitialize, + }; + use windows_sys::Win32::UI::Shell::ShellExecuteW; + use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; + let verb = wide("open"); + let file = wide(target); + // SAFETY: COM for this thread (the shell's handlers may need it), + // released again; ShellExecuteW on our own buffers. + let code = unsafe { + let com = CoInitializeEx( + std::ptr::null(), + (COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) as u32, + ); + let h = ShellExecuteW( + std::ptr::null_mut(), + verb.as_ptr(), + file.as_ptr(), + std::ptr::null(), + std::ptr::null(), + SW_SHOWNORMAL, + ); + if com >= 0 { + CoUninitialize(); + } + h as isize + }; + // Above 32 is success; below, one of the shell's error codes. + if code > 32 { + Ok(()) + } else { + Err(format!("the shell could not open it (error {code})")) + } + } + + pub fn wt(exe: &Path, path: &str) -> Result<(), String> { + // `;` separates Windows Terminal's commands, also inside a path. + std::process::Command::new(exe) + .arg("-d") + .arg(path.replace(';', r"\;")) + .spawn() + .map(drop) + .map_err(|e| format!("start Windows Terminal: {e}")) + } + + pub fn console(exe: &Path, dir: &Path) -> Result<(), String> { + use std::os::windows::process::CommandExt; + const CREATE_NEW_CONSOLE: u32 = 0x0000_0010; + std::process::Command::new(exe) + .arg("-NoExit") + .current_dir(dir) + .creation_flags(CREATE_NEW_CONSOLE) + .spawn() + .map(drop) + .map_err(|e| format!("start {}: {e}", exe.display())) + } + + pub fn terminal(_exe: &Path, _dir: &Path) -> Result<(), String> { + Err("no terminal emulator on Windows".into()) + } +} + +#[cfg(target_os = "linux")] +mod imp { + use super::{Found, How, Kind, Opener, on_path}; + use std::path::{Path, PathBuf}; + + /// The terminals tried after `$TERMINAL`, in order. + const TERMINALS: &[&str] = &[ + "x-terminal-emulator", + "gnome-terminal", + "konsole", + "xfce4-terminal", + "kitty", + "alacritty", + "wezterm", + "foot", + "xterm", + ]; + + fn desktop() -> bool { + std::env::var_os("DISPLAY").is_some() || std::env::var_os("WAYLAND_DISPLAY").is_some() + } + + pub fn files_and_terminals() -> Vec { + if !desktop() { + return Vec::new(); + } + let mut out = Vec::new(); + if on_path("xdg-open").is_some() { + out.push(Found { + opener: Opener { + id: "files", + label: "Files", + kind: Kind::Files, + }, + how: How::Folder, + }); + } + let term = std::env::var("TERMINAL") + .ok() + .and_then(|t| on_path(&t)) + .or_else(|| TERMINALS.iter().find_map(|t| on_path(t))); + if let Some(t) = term { + out.push(Found { + opener: Opener { + id: "terminal", + label: "Terminal", + kind: Kind::Terminal, + }, + how: How::Terminal(t), + }); + } + out + } + + /// `xdg-mime` names a handler for `x-scheme-handler/`. + pub fn registered(scheme: &str) -> bool { + std::process::Command::new("xdg-mime") + .args(["query", "default", &format!("x-scheme-handler/{scheme}")]) + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .output() + .is_ok_and(|o| o.status.success() && !o.stdout.trim_ascii().is_empty()) + } + + pub fn orca() -> Option { + on_path("orca") + } + + /// Start `cmd` and let it go; a thread waits for it, so it leaves no + /// zombie behind. + fn detach(mut cmd: std::process::Command, what: &str) -> Result<(), String> { + let mut child = cmd + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .map_err(|e| format!("start {what}: {e}"))?; + std::thread::spawn(move || child.wait()); + Ok(()) + } + + pub fn shell_open(target: &str) -> Result<(), String> { + let mut cmd = std::process::Command::new("xdg-open"); + cmd.arg(target); + detach(cmd, "xdg-open") + } + + pub fn wt(_exe: &Path, _path: &str) -> Result<(), String> { + Err("no Windows Terminal on Linux".into()) + } + + pub fn console(_exe: &Path, _dir: &Path) -> Result<(), String> { + Err("no console on Linux".into()) + } + + /// The terminal in `dir`: most take the working directory they are + /// started in; those that hand the window to a server need it said. + pub fn terminal(exe: &Path, dir: &Path) -> Result<(), String> { + let name = exe.file_name().and_then(|n| n.to_str()).unwrap_or(""); + let mut cmd = std::process::Command::new(exe); + match name { + "gnome-terminal" | "xfce4-terminal" => { + cmd.arg(format!("--working-directory={}", dir.display())); + } + "konsole" => { + cmd.arg("--workdir").arg(dir); + } + "wezterm" => { + cmd.args(["start", "--cwd"]).arg(dir); + } + _ => {} + } + cmd.current_dir(dir); + detach(cmd, name) + } +} + +/// Nothing to open with until #66 (macOS). +#[cfg(not(any(windows, target_os = "linux")))] +mod imp { + use super::Found; + use std::path::{Path, PathBuf}; + + pub fn files_and_terminals() -> Vec { + Vec::new() + } + pub fn registered(_scheme: &str) -> bool { + false + } + pub fn orca() -> Option { + None + } + pub fn shell_open(_target: &str) -> Result<(), String> { + Err("not supported on this platform".into()) + } + pub fn wt(_exe: &Path, _path: &str) -> Result<(), String> { + Err("not supported on this platform".into()) + } + pub fn console(_exe: &Path, _dir: &Path) -> Result<(), String> { + Err("not supported on this platform".into()) + } + pub fn terminal(_exe: &Path, _dir: &Path) -> Result<(), String> { + Err("not supported on this platform".into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn editor_links_carry_the_path_with_forward_slashes() { + assert_eq!( + link("vscode", r"D:\Sources\my app"), + "vscode://file/D:/Sources/my%20app" + ); + assert_eq!(link("cursor", "/home/me/app"), "cursor://file/home/me/app"); + } + + #[test] + fn agent_links_carry_the_path_as_a_query_value() { + assert_eq!( + link("claude", r"D:\src\app"), + "claude://code/new?folder=D%3A%5Csrc%5Capp" + ); + assert_eq!( + link("claude-cli", "/home/me/a&b"), + "claude-cli://open?cwd=%2Fhome%2Fme%2Fa%26b" + ); + } + + #[test] + fn a_link_cannot_be_given_more_parameters_by_a_path() { + let l = link("vscode", "/x?windowId=_blank#y"); + assert_eq!(l, "vscode://file/x%3FwindowId%3D_blank%23y"); + } + + #[test] + fn display_drops_the_verbatim_prefix() { + if cfg!(windows) { + assert_eq!(display(Path::new(r"\\?\D:\src\app")), r"D:\src\app"); + assert_eq!(display(Path::new("D:/src/app")), r"D:\src\app"); + } else { + assert_eq!(display(Path::new("/home/me/app")), "/home/me/app"); + } + } +} diff --git a/docs/adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md b/docs/adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md new file mode 100644 index 00000000..0cd2755d --- /dev/null +++ b/docs/adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md @@ -0,0 +1,106 @@ +# ADR-0046: The hub opens a stack's worktree in the user's own programs, from a fixed list + +- **Status:** Accepted (2026-10-21) +- **Date:** 2026-10-21 +- **Deciders:** project owner +- **Related:** [ADR-0011](0011-platform-windows-native-first.md), [ADR-0019](0019-control-api-security.md), [ADR-0021](0021-a-hub-serves-the-dashboard.md), [ADR-0024](0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md), [ADR-0040](0040-a-shared-lane-can-be-watched-like-ones-own.md) + +## Context + +The stack header shows where the shown tree lives (`D:\src\app`, or a lane's +worktree). The next step from there is nearly always another program: the +folder in the file manager, a terminal in it, an editor, an agent. A web +page can do none of that: it can copy the path, and it can open a link +whose scheme a program registered (`vscode://file/…`), but it cannot tell +whether that program is there. A link nobody handles does nothing, and the +browser asks before every external scheme until told not to. + +The hub is a local program of the user (ADR-0021) and already does for the +page what the page cannot: the folder dialog (`POST /hub/pick-folder`). + +Looked at on Windows 11 (2026-10-21): the editors and agents register their +scheme under `HKCR\` with a `URL Protocol` value, packaged ones too +(Claude Desktop: `claude`); VS Code `vscode`, the Claude Code CLI +`claude-cli` (`HKCU`, written at its first prompt). Orca registers no scheme; +its CLI (`orca`) brings its window to a worktree (`orca file open … --focus`). +Windows Terminal is the `wt.exe` app alias on `PATH`. + +## Decision + +1. **The hub opens, the page asks.** `GET /hub/openers` lists what this + machine can open a folder with; `POST /hub/open {stack, path, with}` + opens it. Copying the path stays in the page. +2. **A fixed list, found, not configured.** The hub knows each program and + how to start it; it lists the ones it finds: + + | id | Program | Found by | Started as | + |---|---|---|---| + | `files` | Explorer / the file manager | always (Windows); `xdg-open` on `PATH` (Linux) | the folder, opened by the shell / `xdg-open` | + | `wt` | Windows Terminal | `wt.exe` on `PATH` | `wt -d ` | + | `powershell` | PowerShell | always (Windows); `pwsh` before `powershell` | a new console in the folder | + | `terminal` | Terminal (Linux) | `$TERMINAL`, `x-terminal-emulator`, then common ones | the terminal in the folder | + | `vscode`, `vscode-insiders`, `cursor`, `windsurf`, `zed` | the editor | its scheme is registered | `://file/` | + | `claude` | Claude (desktop, Code) | `claude` is registered | `claude://code/new?folder=` | + | `claude-cli` | Claude Code (terminal) | `claude-cli` is registered | `claude-cli://open?cwd=` | + | `orca` | Orca | `orca` on `PATH` or in its install folder | `orca file open --worktree path: --focus` (the repository added to Orca first, if Orca does not know it) | + + A scheme is "registered" when Windows has `HKCR\` with `URL + Protocol`, or when `xdg-mime` names a handler for + `x-scheme-handler/` (Linux). A link is opened the way the shell + opens it (`ShellExecuteW`, `xdg-open`), so the program's own handler + decides how it opens. +3. **Only a stack's own trees.** `path` must be the stack's repository or + one of its worktrees (`git worktree list`), and `with` must be in the + list just found. A path the page invents, a program it names or a + command line it writes are refused (`400`). Like every mutation, the + request needs the cookie and the hub's own Origin (ADR-0019). +4. **Where it makes no sense, nothing is offered.** A hub without a desktop + (Linux without `DISPLAY`/`WAYLAND_DISPLAY`) lists nothing; a lane shared + with the user (ADR-0040) lives on someone else's machine: the page only + offers to copy its path. A lane that runs on a node has its worktree here + (ADR-0025) and is opened like any other. + +## Alternatives considered + +- **Scheme links from the page only.** No hub code, but the page cannot + know which programs exist, so it offers all of them; a click on one that + is not installed does nothing, and the browser asks before each. +- **A program the user configures** (a command line in the hub's settings). + The hub would start whatever a setting says, a setting the page writes: + one XSS away from running anything. A fixed list cannot be talked into + more. It may come later for one "own editor" entry, set from the CLI. +- **`$EDITOR`/`$VISUAL`.** Mostly terminal editors, started without a + terminal. +- **Each program's CLI** (`code`, `cursor`) instead of its scheme. On + Windows those are `.cmd` files (a console window, and `cmd.exe` parsing + the path); the scheme handler is the program's own, and the same on every + platform. Orca has no scheme, so it is the one exception. +- **The file manager by `explorer.exe `.** It exits with 1 when it + worked; the shell's `open` verb says what happened. + +## Consequences + +- The hub starts programs on request of the page. Narrowed by point 3: a + known program, on a known tree of a registered stack. +- `windows-sys` needs `Win32_UI_Shell` (`ShellExecuteW`) and + `Win32_System_Com`. +- A program the list does not know (JetBrains IDEs, Visual Studio, Sublime) + is not offered; adding one is a code change. JetBrains' scheme + (`jetbrains://`) needs Toolbox and a project name, not a path. +- The hub runs in the background: a window it starts may open behind the + browser where Windows does not let it take the foreground. +- macOS lists nothing until #66. + +## Enforced by + +- `crates/devstack-hub/src/open.rs` (the list, finding, starting), routes + `/hub/openers` and `/hub/open` in `crates/devstack-hub/src/lib.rs`. +- `crates/devstack-daemon/src/lanes.rs` (`worktree_of`). +- `ui/src/components/StackHeader.vue` (the path's menu). +- `docs/dashboard-api.md` (`/hub/openers`, `/hub/open`). + +## What this ADR does not say + +- That the hub opens files or lines (a failed build's error in the editor). + It opens trees; a file could follow with the same list. +- That the CLI gets a `devstack open`: the terminal is already in the tree. diff --git a/docs/adr/README.md b/docs/adr/README.md index b3ed525e..5120e52c 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -94,3 +94,4 @@ stay. | [0043](0043-a-dev-servers-fixed-port-is-devstacks.md) | A dev server's fixed port is devstack's, forwarded to its instance | Accepted | | [0044](0044-a-lanes-prepared-directories-can-be-linked-into-its-worktree.md) | A lane's prepared directories can be linked into its worktree | Accepted | | [0045](0045-the-hub-notifies-the-desktop.md) | The hub notifies the desktop of what needs attention, without a tray | Accepted, amended 2026-10-21 (`guest_lane`) | +| [0046](0046-the-hub-opens-a-worktree-in-the-users-programs.md) | The hub opens a stack's worktree in the user's own programs, from a fixed list | Accepted | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index ccbd9d42..819e516c 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -54,6 +54,8 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `POST /hub/update/check` | cookie + Origin | look for a newer release now: `{"current", "newer": string\|null}`, the same as the next `release` event; asked again within 30 s, the last answer (GitHub allows 60 unauthenticated requests an hour). `409` with `DEVSTACK_NO_UPDATE_CHECK`, `502` when GitHub cannot be asked, `504` after 30 s | | `POST /hub/stacks/scan` | cookie + Origin | `{"path", "add"?, "depth"?}`: every repository with a `devstack.toml` below a folder (default three levels, `depth` is clamped to 1 to 6; a repository only at its root, linked worktrees skipped), `[{repo, id, name, error, registered, added}]`; with `add` the valid new ones are registered | | `POST /hub/pick-folder` | cookie + Origin | the operating system's folder dialog, shown by the hub (Windows: Explorer picker, Linux: XDG portal): `{"path": "..."}`, `{"path": null}` when cancelled, `501` without a desktop, `409` while one is open | +| `GET /hub/openers` | cookie | what this machine opens a stack's folder with ([ADR-0046](adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md)), in menu order: `[{id, label, kind}]`, `kind` one of `files`, `terminal`, `editor`, `agent`. Ids: `files`, `wt`, `powershell` (Windows), `terminal` (Linux), `vscode`, `vscode-insiders`, `cursor`, `windsurf`, `zed`, `claude`, `claude-cli`, `orca`; only those found (a scheme registered, a program on `PATH`). Empty without a desktop | +| `POST /hub/open {"stack", "path", "with"}` | cookie + Origin | open `path` with the program `with`: `204`. `path` must be the stack's repository or one of its worktrees (`git worktree list`), `with` an id `GET /hub/openers` lists now; `400` otherwise, `404` for an unknown stack, `502 {"error"}` when the program could not be started | | `GET /hub/inspect?path=` | cookie | `{repo, is_dir, has_stack_file, valid, registered, id}` for an absolute folder path (the "Add a stack" dialog). `valid` is `null` without a stack file, `{"Ok":null}` when it loads, `{"Err":""}` when not; `registered` is the id or `null`. Every route that takes a `path` takes a local one only: `400` for a network path (`\\host\share`, `//host/share`; on Windows anything but a drive, `C:\` or `\\?\C:\`) | | `POST /hub/stacks/add {"path"}` | cookie + Origin | registers a folder that has a `devstack.toml`; `{id, name}` | | `POST /hub/stacks/init {"path"}` | cookie + Origin | writes a first draft (`devstack init`, never over an existing file) and registers it when it loads; `{file, services, compose_files, todos, id}` | diff --git a/ui/src/api/mock/index.ts b/ui/src/api/mock/index.ts index e18a1639..e27e2789 100644 --- a/ui/src/api/mock/index.ts +++ b/ui/src/api/mock/index.ts @@ -433,6 +433,17 @@ export class MockTransport implements Transport { return empty(202); } if (p === '/hub/pick-folder' && method === 'POST') return json(200, { path: 'C:\\src\\new-shop' }); + if (p === '/hub/openers' && method === 'GET') + return json(200, [ + { id: 'files', label: 'Explorer', kind: 'files' }, + { id: 'wt', label: 'Windows Terminal', kind: 'terminal' }, + { id: 'powershell', label: 'PowerShell', kind: 'terminal' }, + { id: 'vscode', label: 'VS Code', kind: 'editor' }, + { id: 'claude', label: 'Claude Desktop', kind: 'agent' }, + { id: 'claude-cli', label: 'Claude Code', kind: 'agent' }, + { id: 'orca', label: 'Orca', kind: 'agent' }, + ]); + if (p === '/hub/open' && method === 'POST') return empty(204); if (p === '/hub/stacks/add' && method === 'POST') return json(200, { id: hub.stacks[0].entry.id, name: hub.stacks[0].entry.name }); if (p === '/hub/stacks/init' && method === 'POST') return json(200, { file: `${String(body?.path)}\\devstack.toml`, services: ['api', 'web'], compose_files: ['deploy/compose.yml'], todos: 9, id: null }); diff --git a/ui/src/api/transport.ts b/ui/src/api/transport.ts index bae63c42..58bc86a0 100644 --- a/ui/src/api/transport.ts +++ b/ui/src/api/transport.ts @@ -56,6 +56,8 @@ export const paths = { inspect: (path: string) => `/hub/inspect?path=${encodeURIComponent(path)}`, stackAdd: '/hub/stacks/add', pickFolder: '/hub/pick-folder', + openers: '/hub/openers', + open: '/hub/open', scanStacks: '/hub/stacks/scan', stackInit: '/hub/stacks/init', up: (stack: string) => `/hub/stacks/${enc(stack)}/up`, diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index c9353aa4..07caa670 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -448,6 +448,9 @@ export type CapacityPoint = { gpu_memory_used: number; }; +/** A program this machine can open a stack's folder with (`GET /hub/openers`, ADR-0046). */ +export type Opener = { id: string; label: string; kind: 'files' | 'terminal' | 'editor' | 'agent' }; + /** A kind of desktop notification and whether it is on (ADR-0045). */ export type NotifyKind = { kind: string; label: string; on: boolean; default: boolean }; diff --git a/ui/src/components/StackHeader.vue b/ui/src/components/StackHeader.vue index 8bcb3dbf..dc5c83f9 100644 --- a/ui/src/components/StackHeader.vue +++ b/ui/src/components/StackHeader.vue @@ -6,10 +6,11 @@ import { computed, onBeforeUnmount, ref } from 'vue'; import { duration, ago, useNow } from '@/lib/format'; import { laneLabel, orderLanes, nodeLabel } from '@/lib/lanes'; import { usePopover } from '@/lib/popover'; -import type { LaneView } from '@/api/types'; +import type { LaneView, Opener } from '@/api/types'; import { useHub } from '@/stores/hub'; import { useStack } from '@/stores/stack'; import { usePool } from '@/stores/pool'; +import { useUi } from '@/stores/ui'; import Icon from './icons/Icon.vue'; const hub = useHub(); @@ -94,6 +95,33 @@ function moveTo(to: string) { if (current.value) void stack.moveLane(current.value.name, to); } +// The path's menu (ADR-0046): copy it, or open the tree with a program the +// hub found. A lane shared with us lives on another machine: copy only. +const ui = useUi(); +const pathRoot = ref(null); +const pathTrigger = ref(null); +const { open: pathOpen, close: pathClose } = usePopover(pathRoot, pathTrigger); +const canOpen = computed(() => !hubAway.value && !stack.sharedLane && !!stack.id); +const openers = computed(() => (canOpen.value ? (hub.openers ?? []) : [])); +const openerIcon = { files: 'folder', terminal: 'terminal', editor: 'file', agent: 'zap' } as const; +function togglePath() { + pathOpen.value = !pathOpen.value; + if (pathOpen.value && canOpen.value) void hub.loadOpeners(); +} +async function copyPath() { + pathClose(); + try { + await navigator.clipboard.writeText(path.value); + ui.toast('info', 'Copied', path.value); + } catch { + ui.toast('info', path.value, 'Copying is not allowed here.'); + } +} +function openWith(o: Opener) { + pathClose(); + if (stack.id) void hub.openWith(stack.id, path.value, o); +} + const root = ref(null); const trigger = ref(null); const { open, close } = usePopover(root, trigger); @@ -214,7 +242,42 @@ function pick(l: LaneView | null) {
- {{ path }} +
+ + +