From 9b278099cf92609fec24e070427fbd044fafa4a7 Mon Sep 17 00:00:00 2001 From: danny Date: Sun, 18 Oct 2026 00:23:09 +0200 Subject: [PATCH] M3.7: lutra CLI and single instance - crates/control: rendezvous file (/instance.json, port + random token, atomic write, 0600 on Unix, stale detection), token-protected listener (start_with_token, app.auth first, constant-time compare, 10 s auth timeout), app.focus, and a blocking client (connect_live, request/execute/subscribe/next_event, open_folder/open_file/reveal) - lutra-desktop: a normal start forwards its path to a running instance and exits, otherwise claims the rendezvous; --control instances skip it unless LUTRA_RENDEZVOUS_DIR is set; non-Unicode args are usage errors - lutra-cli (binary lutra, now L6): path[:line[:column]] targets, folder -> project.open, file -> file.open (parent opened without a project, outside the project refused), editor.reveal, starts the desktop if needed, --wait until bufferClosed, --version/--help, exit codes 0/1/2 - tests: proptest target parsing, rendezvous read/write/stale, token check over TCP, forwarding against a test backend, --wait end to end - docs: architecture, G7, ROADMAP (agent automation 18% est.), roadmap, README Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 10 + README.md | 2 + ROADMAP.md | 8 +- apps/lutra-cli/Cargo.toml | 14 +- apps/lutra-cli/src/args.rs | 261 +++++++++++++++ apps/lutra-cli/src/launch.rs | 105 ++++++ apps/lutra-cli/src/main.rs | 50 ++- apps/lutra-cli/src/open.rs | 244 ++++++++++++++ apps/lutra-cli/tests/cli.rs | 156 +++++++++ apps/lutra-desktop/Cargo.toml | 3 + apps/lutra-desktop/src/args.rs | 22 ++ apps/lutra-desktop/src/host.rs | 15 +- apps/lutra-desktop/src/instance.rs | 139 ++++++++ apps/lutra-desktop/src/main.rs | 45 ++- crates/control/Cargo.toml | 1 + crates/control/src/backend.rs | 9 + crates/control/src/client.rs | 425 ++++++++++++++++++++++++ crates/control/src/lib.rs | 9 +- crates/control/src/methods.rs | 14 + crates/control/src/protocol.rs | 28 +- crates/control/src/rendezvous.rs | 288 ++++++++++++++++ crates/control/src/server.rs | 108 +++++- crates/control/tests/single_instance.rs | 212 ++++++++++++ docs/architecture.md | 23 +- docs/gaps.md | 5 +- docs/roadmap.md | 3 +- 26 files changed, 2162 insertions(+), 37 deletions(-) create mode 100644 apps/lutra-cli/src/args.rs create mode 100644 apps/lutra-cli/src/launch.rs create mode 100644 apps/lutra-cli/src/open.rs create mode 100644 apps/lutra-cli/tests/cli.rs create mode 100644 apps/lutra-desktop/src/instance.rs create mode 100644 crates/control/src/client.rs create mode 100644 crates/control/src/rendezvous.rs create mode 100644 crates/control/tests/single_instance.rs diff --git a/Cargo.lock b/Cargo.lock index fda53f2..57f13c0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2551,11 +2551,20 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "lutra-cli" version = "0.0.0" +dependencies = [ + "lutra-control", + "lutra-engine", + "lutra-testkit", + "proptest", + "serde_json", + "tempfile", +] [[package]] name = "lutra-control" version = "0.0.0" dependencies = [ + "getrandom 0.3.4", "lutra-engine", "lutra-testkit", "proptest", @@ -2575,6 +2584,7 @@ dependencies = [ "tauri", "tauri-build", "tauri-plugin-dialog", + "tempfile", "xcap", ] diff --git a/README.md b/README.md index d55b04f..8fec867 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ cargo xtask ci # fmt, clippy, tests, layers, a ### The `lutra` command +Works today (M3.7): opening folders and files (at a line) in the running Lutra or starting it, and `--wait`. The rest arrives with M3 and later. + ```sh lutra . # open the current folder as a project lutra src/Kernel.php:42 # open a file at a line diff --git a/ROADMAP.md b/ROADMAP.md index e286fe8..53569b7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: pre-alpha (M2 done)** · next: M3 language server, terminal, CLI and MCP (the MVP); alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate)) -> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-17 · **Change:** minor (M2.6: go-to popup) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only +> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-17 · **Change:** minor (M3.7: `lutra` CLI and single instance) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md). @@ -33,9 +33,9 @@ Dimension hours overlap: language, framework and tooling hours are part of the f | Localization (en, de) | 5% | ~38 | [localization-parity.md](docs/localization-parity.md) | | Performance | 0% | ~100 | [gaps.md › G12](docs/gaps.md) | | Stability | 8% | ~95 | [gaps.md › G11](docs/gaps.md) | -| Agent automation | 10% | ~60 | AGENTS.md | +| Agent automation | 18% (est.) | ~52 | AGENTS.md | -Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a crash-recovery journal for unsaved buffers (property-tested: random edits, crash, restore) exist; the journal is not yet checked in the running app. Agent automation 10%: the control channel (ping, execute, listCommands, screenshot) works, and since M1.8 it also reaches the frontend's UI commands (opening the palette, toggling the project tree) through the `uiCommand` event; MCP and the CLI do not exist yet. Both are estimated. Localization 5% (estimated): every UI string comes from an English catalog enforced by lint; engine messages, the language switch and German are missing. UI/UX fidelity 1% (estimated): light and dark themes switch live and pass a WCAG AA contrast test; the rest of the ui-parity checklist is open. +Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a crash-recovery journal for unsaved buffers (property-tested: random edits, crash, restore) exist; the journal is not yet checked in the running app. Agent automation 10%: the control channel (ping, execute, listCommands, screenshot) works, and since M1.8 it also reaches the frontend's UI commands (opening the palette, toggling the project tree) through the `uiCommand` event; since M3.7 the `lutra` CLI opens folders and files at a line in the running instance (or starts it), `--wait` blocks until the tabs close (usable as `core.editor`), and a token-protected rendezvous file lets local tools find the instance; MCP does not exist yet. Both are estimated. Localization 5% (estimated): every UI string comes from an English catalog enforced by lint; engine messages, the language switch and German are missing. UI/UX fidelity 1% (estimated): light and dark themes switch live and pass a WCAG AA contrast test; the rest of the ui-parity checklist is open. ## Features @@ -75,6 +75,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a | Date | What landed | |---|---| +| 2026-10-17 | M3.7: the `lutra` command: `lutra src/Kernel.php:42` opens the file at line 42 in the running Lutra or starts it, `lutra .` opens a folder, `lutra --wait FILE` returns when the tab is closed (for `git commit`). Starting Lutra a second time hands the path to the first window. Only your user account can talk to the running instance. | | 2026-10-17 | M2.6: go to any file, class or symbol by name: `Mod+P`, `Mod+Alt+C` and `Mod+T` open one popup with Files, Classes and Symbols tabs (Tab switches); results update as you type with the matched letters marked, library code is labelled, a hint shows while the index is still building, and Enter jumps there. Agents can open it with a query. | | 2026-10-17 | M2.7: a Structure tool window next to Project (new left stripe, `Mod+2`) shows the classes, functions, methods, properties and constants of the active PHP file as a tree that follows tabs and edits; click or Enter jumps to the declaration. The file is reparsed in the background, so big files never stall typing. | | 2026-10-17 | M2.4: Find in files has a window: `Mod+Alt+F` opens a bottom panel with the selection or the word at the cursor as the query; results stream in grouped by file with the hit highlighted, with match case, whole words, regex and file globs; Enter or a click jumps to the match; a new search cancels the old one. | @@ -94,6 +95,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | M3.7: `lutra` CLI and single instance; agent automation 10% → 18% (est.) | | 2026-10-17 | minor | Cycle C3 review: M2 done (~6.1 h measured), factor 0.14, MVP ~12 h left | | 2026-10-17 | minor | M2.6: Navigation 4% → 10%, feature depth ~3.2% | | 2026-10-17 | minor | M2.7: Navigation 4%, feature depth ~2.6% | diff --git a/apps/lutra-cli/Cargo.toml b/apps/lutra-cli/Cargo.toml index 74a1ce3..e09308e 100644 --- a/apps/lutra-cli/Cargo.toml +++ b/apps/lutra-cli/Cargo.toml @@ -9,9 +9,21 @@ authors.workspace = true publish.workspace = true [package.metadata.lutra] -layer = 5 +layer = 6 + +[[bin]] +name = "lutra" +path = "src/main.rs" [dependencies] +lutra-control.workspace = true +serde_json = "1.0.154" + +[dev-dependencies] +lutra-engine.workspace = true +lutra-testkit.workspace = true +proptest.workspace = true +tempfile.workspace = true [lints] workspace = true diff --git a/apps/lutra-cli/src/args.rs b/apps/lutra-cli/src/args.rs new file mode 100644 index 0000000..037d88d --- /dev/null +++ b/apps/lutra-cli/src/args.rs @@ -0,0 +1,261 @@ +//! Command-line arguments of `lutra`, and `path[:line[:column]]` targets. +//! +//! Arguments are untrusted: parsing never panics, and every problem is a +//! usage error (exit code 2). + +use std::ffi::OsString; + +/// Usage text for `--help`. +pub const USAGE: &str = "usage: lutra [--wait] [PATH[:LINE[:COLUMN]]]... + +Opens folders and files in the running Lutra, or starts it. + + PATH a folder becomes the project; a file opens in a tab + :LINE[:COLUMN] moves the cursor there (1-based) + --wait returns only after the opened files' tabs are closed + --version prints the version + --help prints this help + -- treats every later argument as a path + +A file outside the open project is refused; without an open project, the +file's folder is opened as the project. Lutra is started from +LUTRA_DESKTOP, else lutra-desktop next to lutra, else lutra-desktop on PATH. + +Exit codes: 0 ok, 1 error, 2 bad usage."; + +/// One `path[:line[:column]]` argument. Line and column are 1-based as +/// typed; [`Target::raw`] keeps the whole argument for paths that contain +/// `:digits` themselves. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Target { + /// The argument as given. + pub raw: String, + /// The path part. + pub path: String, + /// The line, from 1. + pub line: Option, + /// The column, from 1; only with a line. + pub column: Option, +} + +/// Parsed arguments. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Args { + /// `--wait` was given. + pub wait: bool, + /// `--help` was given. + pub help: bool, + /// `--version` was given. + pub version: bool, + /// The targets, in order. + pub targets: Vec, +} + +/// Most targets accepted in one call. +pub const MAX_TARGETS: usize = 256; + +/// Parses the raw arguments after the program name. +/// +/// # Errors +/// A message for an argument that is not valid Unicode, an unknown option, +/// a bad line or column, or too many targets. +pub fn parse(args: impl IntoIterator) -> Result { + let mut parsed = Args::default(); + let mut options = true; + for arg in args { + let arg = arg + .into_string() + .map_err(|arg| format!("argument {arg:?} is not valid Unicode"))?; + if options { + match arg.as_str() { + "--" => { + options = false; + continue; + } + "--wait" | "-w" => { + parsed.wait = true; + continue; + } + "--help" | "-h" => { + parsed.help = true; + continue; + } + "--version" | "-V" => { + parsed.version = true; + continue; + } + flag if flag.starts_with('-') && flag.len() > 1 => { + return Err(format!("unknown option {flag}")); + } + _ => {} + } + } + if parsed.targets.len() >= MAX_TARGETS { + return Err(format!("at most {MAX_TARGETS} paths can be given")); + } + parsed.targets.push(parse_target(&arg)?); + } + Ok(parsed) +} + +/// Splits `path[:line[:column]]`. A trailing `:N` counts as a position only +/// if `N` is all ASCII digits and something is left before it; on Windows a +/// lone drive letter (`C:5`) is not split off. +/// +/// # Errors +/// A message for an empty argument, a line or column of 0, or a number +/// that does not fit in 32 bits. +pub fn parse_target(raw: &str) -> Result { + if raw.is_empty() { + return Err("an empty path was given".into()); + } + let mut path = raw; + let mut numbers: Vec<&str> = Vec::new(); + while numbers.len() < 2 { + let Some((head, tail)) = path.rsplit_once(':') else { + break; + }; + let digits = !tail.is_empty() && tail.bytes().all(|b| b.is_ascii_digit()); + if !digits || head.is_empty() || is_drive(head) { + break; + } + numbers.push(tail); + path = head; + } + let number = |text: &str| -> Result { + match text.parse::() { + Ok(0) => Err(format!("{raw}: lines and columns start at 1")), + Ok(n) => Ok(n), + Err(_) => Err(format!("{raw}: {text} is not a valid line or column")), + } + }; + let (line, column) = match numbers.as_slice() { + [] => (None, None), + [line] => (Some(number(line)?), None), + [column, line, ..] => (Some(number(line)?), Some(number(column)?)), + }; + Ok(Target { + raw: raw.to_string(), + path: path.to_string(), + line, + column, + }) +} + +/// Whether `head` is a bare drive letter, which on Windows makes `C:5` a +/// path rather than file `C` at line 5. +fn is_drive(head: &str) -> bool { + cfg!(windows) && head.len() == 1 && head.bytes().all(|b| b.is_ascii_alphabetic()) +} + +#[cfg(test)] +mod tests { + use proptest::prelude::*; + + use super::*; + + fn p(args: &[&str]) -> Result { + parse(args.iter().map(OsString::from)) + } + + fn t(raw: &str) -> (String, Option, Option) { + let t = parse_target(raw).unwrap(); + (t.path, t.line, t.column) + } + + #[test] + fn parses_flags_and_targets() { + let a = p(&["--wait", "a.php:3", "src"]).unwrap(); + assert!(a.wait); + assert_eq!(a.targets.len(), 2); + assert_eq!(a.targets[0].line, Some(3)); + assert!(p(&["--help"]).unwrap().help); + assert!(p(&["-V"]).unwrap().version); + assert_eq!(p(&[]).unwrap(), Args::default()); + let a = p(&["--", "--wait", "-"]).unwrap(); + assert!(!a.wait); + assert_eq!(a.targets[0].path, "--wait"); + assert_eq!(a.targets[1].path, "-"); + } + + #[test] + fn rejects_bad_usage() { + assert!(p(&["--frobnicate"]).is_err()); + assert!(p(&[""]).is_err()); + assert!(p(&["a.php:0"]).is_err()); + assert!(p(&["a.php:1:0"]).is_err()); + assert!(p(&["a.php:99999999999"]).is_err()); + let many: Vec = (0..=MAX_TARGETS).map(|i| format!("f{i}")).collect(); + let many: Vec<&str> = many.iter().map(String::as_str).collect(); + assert!(p(&many).is_err()); + } + + #[test] + fn splits_positions() { + assert_eq!(t("a.php"), ("a.php".into(), None, None)); + assert_eq!(t("a.php:10"), ("a.php".into(), Some(10), None)); + assert_eq!(t("a.php:10:5"), ("a.php".into(), Some(10), Some(5))); + assert_eq!(t("a:b:1:2:3"), ("a:b:1".into(), Some(2), Some(3))); + assert_eq!(t("a.php:"), ("a.php:".into(), None, None)); + assert_eq!(t("a.php:x"), ("a.php:x".into(), None, None)); + assert_eq!(t(":5"), (":5".into(), None, None)); + assert_eq!(t("a.php:+5"), ("a.php:+5".into(), None, None)); + assert_eq!( + t(r"C:\src\a.php:7:2"), + (r"C:\src\a.php".into(), Some(7), Some(2)) + ); + } + + #[cfg(windows)] + #[test] + fn keeps_drive_letters() { + assert_eq!(t("C:5"), ("C:5".into(), None, None)); + assert_eq!(t("C:5:6"), ("C:5".into(), Some(6), None)); + } + + #[test] + fn rejects_non_unicode() { + #[cfg(unix)] + { + use std::os::unix::ffi::OsStringExt; + assert!(parse([OsString::from_vec(vec![0xff, b'a'])]).is_err()); + } + #[cfg(windows)] + { + use std::os::windows::ffi::OsStringExt; + assert!(parse([OsString::from_wide(&[0xd800, 0x61])]).is_err()); + } + } + + proptest! { + #[test] + fn round_trips_path_line_column( + path in "[a-zA-Z0-9_./\\\\-]{2,40}", + line in 1u32.., + column in proptest::option::of(1u32..), + ) { + let raw = match column { + Some(c) => format!("{path}:{line}:{c}"), + None => format!("{path}:{line}"), + }; + let target = parse_target(&raw).unwrap(); + prop_assert_eq!(target.path, path); + prop_assert_eq!(target.line, Some(line)); + prop_assert_eq!(target.column, column); + prop_assert_eq!(target.raw, raw); + } + + #[test] + fn never_panics(raw in ".{0,80}") { + if let Ok(target) = parse_target(&raw) { + prop_assert!(raw.starts_with(&target.path)); + prop_assert!(target.column.is_none() || target.line.is_some()); + } + } + + #[test] + fn any_arguments_parse_or_fail(args in proptest::collection::vec(".{0,20}", 0..8)) { + let _ = parse(args.into_iter().map(OsString::from)); + } + } +} diff --git a/apps/lutra-cli/src/launch.rs b/apps/lutra-cli/src/launch.rs new file mode 100644 index 0000000..36ed239 --- /dev/null +++ b/apps/lutra-cli/src/launch.rs @@ -0,0 +1,105 @@ +//! Finding and starting the desktop app when no Lutra is running. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::thread; +use std::time::{Duration, Instant}; + +use lutra_control::client::{self, Client}; + +/// Environment variable with the path of the desktop binary to start. +pub const DESKTOP_ENV: &str = "LUTRA_DESKTOP"; + +/// File name of the desktop binary. +const DESKTOP_NAME: &str = if cfg!(windows) { + "lutra-desktop.exe" +} else { + "lutra-desktop" +}; + +/// How long to wait for a started app to write its rendezvous file and +/// answer. +pub const START_TIMEOUT: Duration = Duration::from_secs(60); + +/// Time between two looks at the rendezvous file while the app starts. +const POLL: Duration = Duration::from_millis(150); + +/// Time to wait for one connection attempt while the app starts. +const PROBE: Duration = Duration::from_secs(2); + +/// The desktop binary: `LUTRA_DESKTOP` if set, else `lutra-desktop` next to +/// this executable, else the first `lutra-desktop` on `PATH`. +/// +/// # Errors +/// A message naming the places that were tried. +pub fn find_desktop() -> Result { + if let Some(path) = std::env::var_os(DESKTOP_ENV).filter(|v| !v.is_empty()) { + return Ok(PathBuf::from(path)); + } + let sibling = std::env::current_exe() + .ok() + .and_then(|exe| Some(exe.parent()?.join(DESKTOP_NAME))) + .filter(|path| path.is_file()); + if let Some(path) = sibling { + return Ok(path); + } + std::env::var_os("PATH") + .and_then(|paths| { + std::env::split_paths(&paths) + .map(|dir| dir.join(DESKTOP_NAME)) + .find(|path| path.is_file()) + }) + .ok_or_else(|| { + format!( + "cannot find {DESKTOP_NAME}: set {DESKTOP_ENV}, or put it next to lutra or on PATH" + ) + }) +} + +/// Starts `desktop` detached from this terminal and waits until it answers +/// on the rendezvous file in `dir`. A desktop that exits successfully may +/// have forwarded to an instance that started at the same time, so only a +/// failed exit ends the wait early. +/// +/// # Errors +/// A message if it cannot be started, exits early, or does not answer +/// within [`START_TIMEOUT`]. +pub fn start(desktop: &Path, dir: &Path) -> Result { + let mut command = Command::new(desktop); + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const DETACHED_PROCESS: u32 = 0x0000_0008; + const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; + command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP); + } + let mut child = command + .spawn() + .map_err(|e| format!("cannot start {}: {e}", desktop.display()))?; + let deadline = Instant::now() + START_TIMEOUT; + loop { + if let Ok((_, client)) = client::connect_live(dir, PROBE) { + return Ok(client); + } + if let Ok(Some(status)) = child.try_wait() + && !status.success() + { + return Err(format!( + "{} exited before it was ready ({status})", + desktop.display() + )); + } + if Instant::now() >= deadline { + return Err(format!( + "{} did not answer within {} s", + desktop.display(), + START_TIMEOUT.as_secs() + )); + } + thread::sleep(POLL); + } +} diff --git a/apps/lutra-cli/src/main.rs b/apps/lutra-cli/src/main.rs index 8c4aa12..7f0ba28 100644 --- a/apps/lutra-cli/src/main.rs +++ b/apps/lutra-cli/src/main.rs @@ -1,10 +1,46 @@ -//! The `lutra` command-line tool (layer L5). +//! The `lutra` command-line tool (layer L6, on top of the control channel). //! -//! Will open projects and files in a running Lutra, wait for tabs to close, -//! open the diff viewer and serve MCP. Until milestone M3 it only reports its -//! version. +//! `lutra [--wait] [PATH[:LINE[:COLUMN]]]...` opens folders and files in +//! the running Lutra, or starts it, through the single-instance rendezvous +//! file (see `lutra_control::rendezvous`). Later milestones add the diff +//! viewer, `lutra mcp`, `lutra perf` and `lutra bench`. +//! +//! Exit codes: 0 ok, 1 error, 2 bad usage. -/// Prints the version and exits. -fn main() { - println!("lutra {}", env!("CARGO_PKG_VERSION")); +mod args; +mod launch; +mod open; + +use std::process::ExitCode; + +use crate::open::Failure; + +/// Parses the arguments and runs the command. +fn main() -> ExitCode { + let args = match args::parse(std::env::args_os().skip(1)) { + Ok(args) => args, + Err(message) => return usage_error(&message), + }; + if args.help { + println!("{}", args::USAGE); + return ExitCode::SUCCESS; + } + if args.version { + println!("lutra {}", env!("CARGO_PKG_VERSION")); + return ExitCode::SUCCESS; + } + match open::run(&args) { + Ok(()) => ExitCode::SUCCESS, + Err(Failure::Usage(message)) => usage_error(&message), + Err(Failure::Error(message)) => { + eprintln!("lutra: {message}"); + ExitCode::FAILURE + } + } +} + +/// Prints a usage error and returns exit code 2. +fn usage_error(message: &str) -> ExitCode { + eprintln!("lutra: {message}\n\n{}", args::USAGE); + ExitCode::from(2) } diff --git a/apps/lutra-cli/src/open.rs b/apps/lutra-cli/src/open.rs new file mode 100644 index 0000000..066ae49 --- /dev/null +++ b/apps/lutra-cli/src/open.rs @@ -0,0 +1,244 @@ +//! `lutra [--wait] [PATH[:LINE[:COLUMN]]]...`: resolve the targets, reach +//! or start Lutra, open them, and optionally wait for their tabs to close. + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use lutra_control::client::{self, Client, ClientError}; +use lutra_control::rendezvous; +use serde_json::{Value, json}; + +use crate::args::{Args, Target}; +use crate::launch; + +/// How long `editor.reveal` is retried while the window is still loading. +const REVEAL_WAIT: Duration = Duration::from_secs(20); + +/// Why `lutra` failed, which decides the exit code. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Failure { + /// Bad usage: exit code 2. + Usage(String), + /// Anything else: exit code 1. + Error(String), +} + +/// A target checked against the file system. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Resolved { + /// A folder to open as the project. + Folder(PathBuf), + /// A file to open, with an optional 1-based position. + File { + /// Absolute path. + path: PathBuf, + /// Line from 1. + line: Option, + /// Column from 1. + column: Option, + }, +} + +/// Checks every target: the path part must exist (if it does not but the +/// whole argument does, the argument is a path containing `:digits`), a +/// folder has no position, and at most one folder is given. The folder +/// comes first, files keep their order. +/// +/// # Errors +/// [`Failure::Usage`] for a positioned folder or two folders, +/// [`Failure::Error`] for a path that does not exist. +pub fn resolve(targets: &[Target]) -> Result, Failure> { + let mut folder = None; + let mut files = Vec::new(); + for target in targets { + let (path, line, column) = if Path::new(&target.path).exists() { + (target.path.as_str(), target.line, target.column) + } else if Path::new(&target.raw).exists() { + (target.raw.as_str(), None, None) + } else { + return Err(Failure::Error(format!("{} does not exist", target.path))); + }; + let path = std::path::absolute(path).map_err(|e| Failure::Error(format!("{path}: {e}")))?; + if path.is_dir() { + if line.is_some() { + return Err(Failure::Usage(format!( + "{} is a folder and has no lines", + target.raw + ))); + } + if folder.is_some() { + return Err(Failure::Usage("only one folder can be opened".into())); + } + folder = Some(Resolved::Folder(path)); + } else { + files.push(Resolved::File { path, line, column }); + } + } + Ok(folder.into_iter().chain(files).collect()) +} + +/// Runs `lutra` with parsed arguments. +/// +/// # Errors +/// The [`Failure`] to report. +pub fn run(args: &Args) -> Result<(), Failure> { + let targets = resolve(&args.targets)?; + let dir = rendezvous::dir() + .ok_or_else(|| Failure::Error("cannot find the Lutra data directory".into()))?; + let mut client = match client::connect_live(&dir, client::DEFAULT_TIMEOUT) { + Ok((_, client)) => client, + Err(_) => { + let desktop = launch::find_desktop().map_err(Failure::Error)?; + launch::start(&desktop, &dir).map_err(Failure::Error)? + } + }; + if args.wait { + client.subscribe().map_err(failed)?; + } + let opened = open_all(&mut client, &targets, REVEAL_WAIT)?; + let _ = client.focus(); + if args.wait { + wait_closed(client, &dir, opened.into_iter().collect())?; + } + Ok(()) +} + +/// Opens the targets in order and moves to their positions. +/// +/// # Returns +/// The buffer ids of the opened files. +/// +/// # Errors +/// [`Failure::Error`] naming the first target that could not be opened. +pub fn open_all( + client: &mut Client, + targets: &[Resolved], + reveal_wait: Duration, +) -> Result, Failure> { + let mut ids = Vec::new(); + for target in targets { + match target { + Resolved::Folder(path) => { + client + .open_folder(path) + .map_err(|e| cannot_open(path, &e))?; + } + Resolved::File { path, line, column } => { + let file = client.open_file(path).map_err(|e| cannot_open(path, &e))?; + if let Some(line) = line { + let column = column.unwrap_or(1); + client + .reveal( + &file.path, + line.saturating_sub(1), + column.saturating_sub(1), + reveal_wait, + ) + .map_err(|e| cannot_open(path, &e))?; + } + ids.push(file.id); + } + } + } + Ok(ids) +} + +/// Blocks until every buffer in `ids` is closed: by `bufferClosed`, by +/// `projectClosed`, or because Lutra exited (its tabs are gone too). A lost +/// subscription is renewed through the rendezvous file in `dir`, and +/// buffers that closed meanwhile are found with `buffer.get`. +/// +/// # Errors +/// [`Failure::Error`] for a malformed line or a subscription that cannot +/// be renewed. +pub fn wait_closed(mut client: Client, dir: &Path, mut ids: BTreeSet) -> Result<(), Failure> { + while !ids.is_empty() { + let event = match client.next_event(None) { + Ok(Some(event)) => event, + Ok(None) => continue, + Err(ClientError::Io(_)) => return Ok(()), + Err(e) => return Err(failed(e)), + }; + match event.get("kind").and_then(Value::as_str) { + Some("bufferClosed") => { + if let Some(id) = event.get("id").and_then(Value::as_u64) { + ids.remove(&id); + } + } + Some("projectClosed") => ids.clear(), + Some("subscriptionLost") => { + client = match client::connect_live(dir, client::DEFAULT_TIMEOUT) { + Ok((_, client)) => client, + Err(_) => return Ok(()), + }; + client.subscribe().map_err(failed)?; + ids.retain(|id| client.execute("buffer.get", json!({ "id": id })).is_ok()); + } + _ => {} + } + } + Ok(()) +} + +/// A failure to open `path`. +fn cannot_open(path: &Path, error: &ClientError) -> Failure { + Failure::Error(format!("cannot open {}: {error}", path.display())) +} + +/// A failure talking to Lutra. +fn failed(error: ClientError) -> Failure { + Failure::Error(error.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::args::parse_target; + + #[test] + fn resolves_targets() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("a.php"); + std::fs::write(&file, " Arc { + use lutra_control::Backend; + let backend = Arc::new(EngineBackend::new()); + backend + .execute( + "ui.registerCommands", + json!({"commands": [{"id": "editor.reveal", "labelKey": "command.editor.reveal"}]}), + ) + .unwrap(); + let token = rendezvous::new_token().unwrap(); + let server = lutra_control::start_with_token(0, backend.clone(), &token).unwrap(); + rendezvous::write( + dir, + &Instance { + port: server.local_addr().port(), + token, + pid: std::process::id(), + version: "test".into(), + }, + ) + .unwrap(); + backend +} + +fn lutra(dir: &Path, args: &[&str]) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_lutra")); + command + .args(args) + .env(rendezvous::DIR_ENV, dir) + .env("LUTRA_DESKTOP", dir.join("no-such-desktop")) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + command +} + +fn run(dir: &Path, args: &[&str]) -> Output { + lutra(dir, args).output().unwrap() +} + +fn buffer_ids(backend: &EngineBackend) -> Vec { + backend.engine.lock().unwrap().state().buffers.ids() +} + +#[test] +fn version_help_and_usage_errors() { + let dir = tempfile::tempdir().unwrap(); + let out = run(dir.path(), &["--version"]); + assert_eq!(out.status.code(), Some(0)); + assert!(String::from_utf8_lossy(&out.stdout).starts_with("lutra ")); + let out = run(dir.path(), &["--help"]); + assert_eq!(out.status.code(), Some(0)); + assert!(String::from_utf8_lossy(&out.stdout).contains("--wait")); + assert_eq!(run(dir.path(), &["--bogus"]).status.code(), Some(2)); + assert_eq!(run(dir.path(), &["a.php:0"]).status.code(), Some(2)); + assert_eq!(run(dir.path(), &[""]).status.code(), Some(2)); +} + +#[test] +fn errors_exit_with_one() { + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("missing.php"); + let out = run(dir.path(), &[missing.to_str().unwrap()]); + assert_eq!(out.status.code(), Some(1)); + let out = run(dir.path(), &[]); + assert_eq!( + out.status.code(), + Some(1), + "no instance and no desktop to start" + ); + assert!(String::from_utf8_lossy(&out.stderr).contains("no-such-desktop")); +} + +#[test] +fn opens_a_file_at_a_line_in_the_running_instance() { + let rv = tempfile::tempdir().unwrap(); + let project = tempfile::tempdir().unwrap(); + let file = project.path().join("a.php"); + std::fs::write(&file, ") -> Result { + let args = args + .into_iter() + .map(|arg| { + arg.into_string() + .map_err(|arg| format!("argument {arg:?} is not valid Unicode")) + }) + .collect::, _>>()?; + parse(args) +} + /// Parses the arguments after the program name. /// /// # Errors @@ -90,4 +106,10 @@ mod tests { assert!(p(&["--frobnicate"]).is_err()); assert!(p(&["a", "b"]).is_err()); } + + #[test] + fn reads_raw_arguments() { + let a = parse_os([OsString::from("--control"), OsString::from("7937")]).unwrap(); + assert_eq!(a.control, Some(7937)); + } } diff --git a/apps/lutra-desktop/src/host.rs b/apps/lutra-desktop/src/host.rs index 965bc1b..2e101b9 100644 --- a/apps/lutra-desktop/src/host.rs +++ b/apps/lutra-desktop/src/host.rs @@ -22,7 +22,7 @@ use std::time::Duration; use lutra_control::{Backend, EventSink, Subscribers}; use lutra_engine::{CommandInfo, Effect, Engine, EngineError, Event, NotificationLevel}; use serde_json::{Map, Value, json}; -use tauri::{AppHandle, Emitter}; +use tauri::{AppHandle, Emitter, Manager}; use tauri_plugin_dialog::DialogExt; use crate::screenshot; @@ -386,6 +386,19 @@ impl Backend for Host { fn subscribe(&self, sink: EventSink) { self.subscribers.add(sink); } + + /// Restores, shows and focuses the main window. Failures to restore or + /// show are ignored because focusing still works on a visible window; + /// the focus error is returned. + fn focus(&self) -> Result<(), String> { + let app = self.app.get().ok_or("the window is not open yet")?; + let window = app + .get_webview_window(MAIN_WINDOW) + .ok_or("the window is not open yet")?; + let _ = window.unminimize(); + let _ = window.show(); + window.set_focus().map_err(|e| e.to_string()) + } } #[cfg(test)] diff --git a/apps/lutra-desktop/src/instance.rs b/apps/lutra-desktop/src/instance.rs new file mode 100644 index 0000000..ee51ef7 --- /dev/null +++ b/apps/lutra-desktop/src/instance.rs @@ -0,0 +1,139 @@ +//! Single instance: forwarding a second start to the running app, and +//! claiming the rendezvous file for this one. +//! +//! A normal start (no `--control`) looks for a running Lutra through the +//! rendezvous file in the app data directory. If one answers and accepts +//! its token, the start forwards its path (a folder becomes the project, a +//! file opens in a tab), brings that window to the front and exits. +//! Otherwise it starts, serves a token-protected listener on a free port +//! of `127.0.0.1` and writes the rendezvous file, replacing a stale one. +//! +//! A start with `--control PORT` is a development or automation instance: +//! it skips all of this, so several of them can run side by side, unless +//! `LUTRA_RENDEZVOUS_DIR` names a rendezvous directory for it. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use lutra_control::client::{self, Unavailable}; +use lutra_control::rendezvous::{self, Instance}; + +use crate::args::Args; +use crate::host::Host; + +/// How long a second start waits for the running instance to answer. +const PROBE_TIMEOUT: Duration = Duration::from_secs(5); + +/// The rendezvous directory this start uses, `None` if it does not take +/// part in the single instance (see the module docs). +pub fn rendezvous_dir(args: &Args) -> Option { + let explicit = std::env::var_os(rendezvous::DIR_ENV).is_some_and(|v| !v.is_empty()); + if args.control.is_some() && !explicit { + return None; + } + rendezvous::dir() +} + +/// Forwards `path` to a running instance found through `dir`. +/// +/// # Returns +/// `Ok(true)` if an instance took the request (this process should exit), +/// `Ok(false)` if none is running or its file is stale. +/// +/// # Errors +/// A message if a running instance refused to open the path. +pub fn forward(dir: &Path, path: Option<&Path>) -> Result { + let mut client = match client::connect_live(dir, PROBE_TIMEOUT) { + Ok((_, client)) => client, + Err(Unavailable::Missing | Unavailable::Stale(_)) => return Ok(false), + }; + if let Some(path) = path { + let path = std::path::absolute(path).map_err(|e| e.to_string())?; + let opened = if path.is_dir() { + client.open_folder(&path).map(|_| ()) + } else { + client.open_file(&path).map(|_| ()) + }; + opened.map_err(|e| format!("the running Lutra cannot open {}: {e}", path.display()))?; + } + let _ = client.focus(); + Ok(true) +} + +/// This process's claim on the rendezvous directory. +#[derive(Debug)] +pub struct Claim { + /// The directory. + dir: PathBuf, + /// The token written there. + token: String, +} + +impl Claim { + /// Serves the token-protected listener for `host` and writes the + /// rendezvous file in `dir`, replacing any file there. + /// + /// # Errors + /// A message if no token can be made, the port cannot be bound or the + /// file cannot be written. + pub fn take(dir: &Path, host: &Arc) -> Result { + let token = rendezvous::new_token().map_err(|e| format!("cannot create a token: {e}"))?; + let server = lutra_control::start_with_token(0, host.clone(), &token) + .map_err(|e| format!("cannot serve the single-instance listener: {e}"))?; + let instance = Instance { + port: server.local_addr().port(), + token: token.clone(), + pid: std::process::id(), + version: env!("CARGO_PKG_VERSION").to_string(), + }; + rendezvous::write(dir, &instance) + .map_err(|e| format!("cannot write {}: {e}", rendezvous::path(dir).display()))?; + Ok(Self { + dir: dir.to_path_buf(), + token, + }) + } + + /// Removes the rendezvous file if it is still this process's. Called + /// when the app exits; a failure only leaves a stale file, which the + /// next start replaces, so it is ignored. + pub fn release(&self) { + let _ = rendezvous::remove_if_ours(&self.dir, &self.token); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn control_instances_skip_the_single_instance_by_default() { + if std::env::var_os(rendezvous::DIR_ENV).is_some() { + return; + } + let dev = Args { + control: Some(7937), + ..Args::default() + }; + assert_eq!(rendezvous_dir(&dev), None); + assert_eq!(rendezvous_dir(&Args::default()), rendezvous::dir()); + } + + #[test] + fn nothing_to_forward_to_without_a_file() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(forward(dir.path(), None), Ok(false)); + rendezvous::write( + dir.path(), + &Instance { + port: 1, + token: "t".into(), + pid: 1, + version: "0".into(), + }, + ) + .unwrap(); + assert_eq!(forward(dir.path(), None), Ok(false), "stale file"); + } +} diff --git a/apps/lutra-desktop/src/main.rs b/apps/lutra-desktop/src/main.rs index cd97e90..8cb2e77 100644 --- a/apps/lutra-desktop/src/main.rs +++ b/apps/lutra-desktop/src/main.rs @@ -4,12 +4,15 @@ //! first paint, //! bridges frontend IPC to engine commands and engine events to the window //! (see [`host`]), opens the project given on the command line, and -//! optionally serves the JSON control channel (`--control PORT`). +//! optionally serves the JSON control channel (`--control PORT`). A normal +//! start is a single instance (see [`instance`]): a second start forwards +//! its path to the running app and exits. #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] mod args; mod host; +mod instance; mod screenshot; use std::process::ExitCode; @@ -25,7 +28,7 @@ use crate::host::{Host, MAIN_WINDOW, WINDOW_TITLE}; /// Parses the arguments, starts the control channel if asked, and runs the /// app until it quits. fn main() -> ExitCode { - let args = match args::parse(std::env::args().skip(1)) { + let args = match args::parse_os(std::env::args_os().skip(1)) { Ok(args) => args, Err(message) => { eprintln!("lutra: {message}\n\n{}", args::USAGE); @@ -49,15 +52,24 @@ fn main() -> ExitCode { } } -/// Builds the Tauri app, starts the engine with the app's config and data -/// directories, the host, the control channel, and runs the event loop. -/// The window is created in the setup hook, which runs once the event loop -/// has started. +/// Forwards to a running instance if there is one; otherwise builds the +/// Tauri app, starts the engine with the app's config and data directories, +/// the host, the control channel and the single-instance listener, and runs +/// the event loop. The window is created in the setup hook, which runs once +/// the event loop has started. A single-instance listener or rendezvous +/// file that cannot be set up is reported and the app runs without it. /// /// # Errors -/// A message if Tauri cannot build the app or resolve its directories, the -/// engine cannot start, or the control port cannot be bound. +/// A message if a running instance refused the forwarded path, Tauri cannot +/// build the app or resolve its directories, the engine cannot start, or +/// the control port cannot be bound. fn run(args: &args::Args) -> Result<(), String> { + let instance_dir = instance::rendezvous_dir(args); + if let Some(dir) = &instance_dir + && instance::forward(dir, args.path.as_deref())? + { + return Ok(()); + } let slot: Arc>> = Arc::new(OnceLock::new()); let setup_slot = slot.clone(); let initial_path = args.path.clone(); @@ -106,9 +118,24 @@ fn run(args: &args::Args) -> Result<(), String> { .map_err(|e| format!("cannot serve the control channel on port {port}: {e}"))?; eprintln!("lutra: control channel on {}", server.local_addr()); } + let claim = instance_dir + .as_deref() + .and_then(|dir| match instance::Claim::take(dir, &host) { + Ok(claim) => Some(claim), + Err(message) => { + eprintln!("lutra: running without single instance: {message}"); + None + } + }); host.start_pump() .map_err(|e| format!("cannot start watching for changes: {e}"))?; - app.run(|_, _| {}); + app.run(move |_, event| { + if let tauri::RunEvent::Exit = event + && let Some(claim) = &claim + { + claim.release(); + } + }); Ok(()) } diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 67497fa..19a3308 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -12,6 +12,7 @@ publish.workspace = true layer = 5 [dependencies] +getrandom = "0.3.4" lutra-engine.workspace = true serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" diff --git a/crates/control/src/backend.rs b/crates/control/src/backend.rs index 5df70ba..05b2c2c 100644 --- a/crates/control/src/backend.rs +++ b/crates/control/src/backend.rs @@ -39,6 +39,15 @@ pub trait Backend: Send + Sync + 'static { /// Adds a subscriber that receives every engine event from now on. fn subscribe(&self, sink: EventSink); + + /// Brings the main window to the front, for the CLI and a second app + /// start. The default has no window and fails. + /// + /// # Errors + /// A message if there is no window or it cannot be focused. + fn focus(&self) -> Result<(), String> { + Err("there is no window".into()) + } } /// The event subscribers of a host. diff --git a/crates/control/src/client.rs b/crates/control/src/client.rs new file mode 100644 index 0000000..a0a1f7d --- /dev/null +++ b/crates/control/src/client.rs @@ -0,0 +1,425 @@ +//! A blocking client for the control channel, and the open logic the +//! `lutra` CLI and a second app start share. +//! +//! [`connect_live`] reads the rendezvous file, connects to the listener it +//! names and authenticates; [`Client::request`] sends one request and reads +//! lines until its response arrives, keeping event lines that arrive in +//! between for [`Client::next_event`]. Every line read is untrusted: lines +//! are capped at [`MAX_RESPONSE_BYTES`] and malformed lines are errors, +//! never panics. +//! +//! [`Client::open_folder`] and [`Client::open_file`] implement `lutra PATH`: +//! a folder becomes the project; a file is opened with `file.open`, and if +//! no project is open its parent folder is opened first. A file outside an +//! open project is refused instead of replacing the project. + +use std::collections::VecDeque; +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::net::{Ipv4Addr, SocketAddr, TcpStream}; +use std::path::Path; +use std::thread; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use crate::methods::{APP_AUTH, APP_FOCUS, APP_PING, ENGINE_EXECUTE, EVENTS_SUBSCRIBE}; +use crate::rendezvous::{self, Instance, ReadError}; + +/// Largest line the client reads, newline excluded. Responses carry whole +/// buffer texts (`file.open`), so this is larger than the request cap. +pub const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024; + +/// Default time to connect and to wait for one response. +pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); + +/// Most event lines kept while waiting for a response; older ones are +/// dropped. +const MAX_QUEUED_EVENTS: usize = 4096; + +/// Engine error code of a command the engine does not know, which is what +/// a UI command answers before the window has registered it. +const UNKNOWN_COMMAND: &str = "unknown_command"; + +/// Engine error code of a command that needs a project. +const DISABLED: &str = "disabled"; + +/// What went wrong talking to Lutra. +#[derive(Debug)] +pub enum ClientError { + /// Connecting, reading or writing failed, or the peer closed the + /// connection. + Io(io::Error), + /// The peer answered with an error. + Remote { + /// The stable error code, e.g. `unauthorized` or `disabled`. + code: String, + /// The message. + message: String, + }, + /// The peer sent something that is not a protocol line. + Protocol(String), +} + +impl ClientError { + /// The remote error code, if this is a remote error. + pub fn code(&self) -> Option<&str> { + match self { + Self::Remote { code, .. } => Some(code), + _ => None, + } + } +} + +impl std::fmt::Display for ClientError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Io(e) => write!(f, "{e}"), + Self::Remote { code, message } => write!(f, "{message} ({code})"), + Self::Protocol(why) => write!(f, "unexpected answer from Lutra: {why}"), + } + } +} + +impl std::error::Error for ClientError {} + +impl From for ClientError { + fn from(e: io::Error) -> Self { + Self::Io(e) + } +} + +/// Why no running instance could be reached through the rendezvous file. +#[derive(Debug)] +pub enum Unavailable { + /// There is no rendezvous file. + Missing, + /// The file is unreadable or invalid, or its listener does not answer + /// or does not accept its token: the instance is gone. + Stale(String), +} + +impl std::fmt::Display for Unavailable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Missing => write!(f, "Lutra is not running"), + Self::Stale(why) => write!(f, "stale rendezvous file: {why}"), + } + } +} + +/// Connects to the instance named by the rendezvous file in `dir`, +/// authenticates and pings it. +/// +/// # Errors +/// [`Unavailable::Missing`] without a file, [`Unavailable::Stale`] if the +/// file is invalid or nobody answers it properly within `timeout`. +pub fn connect_live(dir: &Path, timeout: Duration) -> Result<(Instance, Client), Unavailable> { + let instance = match rendezvous::read(dir) { + Ok(instance) => instance, + Err(ReadError::Missing) => return Err(Unavailable::Missing), + Err(e) => return Err(Unavailable::Stale(e.to_string())), + }; + match Client::connect_instance(&instance, timeout) { + Ok(client) => Ok((instance, client)), + Err(e) => Err(Unavailable::Stale(e.to_string())), + } +} + +/// A file opened in Lutra. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OpenedFile { + /// The buffer id, for `bufferClosed`. + pub id: u64, + /// The project-relative path the engine reported. + pub path: String, +} + +/// A connection to the control channel. +#[derive(Debug)] +pub struct Client { + /// Read side. + reader: BufReader, + /// Write side. + writer: TcpStream, + /// Bytes of a line whose end has not arrived yet (after a timeout). + partial: Vec, + /// Event lines read while waiting for a response. + events: VecDeque, + /// The id of the next request. + next_id: u64, + /// How long one response may take. + timeout: Duration, +} + +impl Client { + /// Connects to `127.0.0.1:port` without authenticating, for the + /// `--control` channel. + /// + /// # Errors + /// The connect error. + pub fn connect(port: u16, timeout: Duration) -> Result { + let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); + let stream = TcpStream::connect_timeout(&addr, timeout)?; + stream.set_nodelay(true)?; + Ok(Self { + writer: stream.try_clone()?, + reader: BufReader::new(stream), + partial: Vec::new(), + events: VecDeque::new(), + next_id: 1, + timeout, + }) + } + + /// Connects to `instance`, authenticates with its token and pings it. + /// + /// # Errors + /// The connect error, `unauthorized`, or a ping failure. + pub fn connect_instance(instance: &Instance, timeout: Duration) -> Result { + let mut client = Self::connect(instance.port, timeout)?; + client.request(APP_AUTH, json!({ "token": instance.token }))?; + client.request(APP_PING, Value::Null)?; + Ok(client) + } + + /// Sends one request and waits for its response; event lines read + /// meanwhile are kept for [`Client::next_event`]. + /// + /// # Errors + /// I/O errors and timeouts, the remote error, or a malformed line. + pub fn request(&mut self, method: &str, params: Value) -> Result { + let id = self.next_id; + self.next_id = self.next_id.saturating_add(1); + let line = json!({ "id": id, "method": method, "params": params }).to_string(); + let mut bytes = line.into_bytes(); + bytes.push(b'\n'); + self.writer.write_all(&bytes)?; + self.writer.flush()?; + let deadline = Instant::now() + self.timeout; + loop { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(ClientError::Io(io::Error::new( + io::ErrorKind::TimedOut, + format!("no answer to {method} within {:?}", self.timeout), + ))); + } + let Some(value) = self.read_value(Some(left))? else { + continue; + }; + if let Some(event) = value.get("event") { + if self.events.len() >= MAX_QUEUED_EVENTS { + self.events.pop_front(); + } + self.events.push_back(event.clone()); + continue; + } + if value.get("id").and_then(Value::as_u64) != Some(id) { + continue; + } + if let Some(error) = value.get("error") { + let text = |key: &str| { + error + .get(key) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }; + return Err(ClientError::Remote { + code: text("code"), + message: text("message"), + }); + } + return Ok(value.get("result").cloned().unwrap_or(Value::Null)); + } + } + + /// Runs an engine command (`engine.execute`). + /// + /// # Errors + /// As [`Client::request`]. + pub fn execute(&mut self, command: &str, params: Value) -> Result { + self.request( + ENGINE_EXECUTE, + json!({ "command": command, "params": params }), + ) + } + + /// Subscribes this connection to engine events. + /// + /// # Errors + /// As [`Client::request`]. + pub fn subscribe(&mut self) -> Result<(), ClientError> { + self.request(EVENTS_SUBSCRIBE, Value::Null).map(|_| ()) + } + + /// The next event (the object inside `{"event": ...}`), waiting at most + /// `timeout` (`None`: as long as it takes). + /// + /// # Returns + /// `Ok(None)` on timeout. + /// + /// # Errors + /// [`ClientError::Io`] with `UnexpectedEof` when the connection closed, + /// other I/O errors, or a malformed line. + pub fn next_event(&mut self, timeout: Option) -> Result, ClientError> { + let deadline = timeout.map(|t| Instant::now() + t); + loop { + if let Some(event) = self.events.pop_front() { + return Ok(Some(event)); + } + let left = match deadline { + Some(deadline) => { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Ok(None); + } + Some(left) + } + None => None, + }; + if let Some(value) = self.read_value(left)? + && let Some(event) = value.get("event") + { + return Ok(Some(event.clone())); + } + } + } + + /// Reads one line as JSON, waiting at most `timeout`. + /// + /// # Returns + /// `Ok(None)` if the time ran out before a whole line arrived; the part + /// read so far is kept for the next call. + /// + /// # Errors + /// End of stream, other I/O errors, an oversized or malformed line. + fn read_value(&mut self, timeout: Option) -> Result, ClientError> { + self.reader.get_ref().set_read_timeout(timeout)?; + let room = MAX_RESPONSE_BYTES.saturating_sub(self.partial.len()); + let limit = u64::try_from(room).unwrap_or(u64::MAX).saturating_add(1); + let read = (&mut self.reader) + .take(limit) + .read_until(b'\n', &mut self.partial); + match read { + Ok(0) if self.partial.is_empty() => { + return Err(ClientError::Io(io::Error::new( + io::ErrorKind::UnexpectedEof, + "Lutra closed the connection", + ))); + } + Ok(_) => {} + Err(e) + if matches!( + e.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut + ) => + { + return Ok(None); + } + Err(e) if e.kind() == io::ErrorKind::Interrupted => return Ok(None), + Err(e) => return Err(ClientError::Io(e)), + } + if self.partial.last() != Some(&b'\n') { + if self.partial.len() > MAX_RESPONSE_BYTES { + return Err(ClientError::Protocol(format!( + "a line is longer than {MAX_RESPONSE_BYTES} bytes" + ))); + } + return Err(ClientError::Io(io::Error::new( + io::ErrorKind::UnexpectedEof, + "Lutra closed the connection in the middle of a line", + ))); + } + let line = std::mem::take(&mut self.partial); + serde_json::from_slice(&line) + .map(Some) + .map_err(|e| ClientError::Protocol(e.to_string())) + } + + /// Brings the window to the front. Failures are ignored by callers that + /// only want to be helpful (there may be no window yet). + /// + /// # Errors + /// As [`Client::request`]. + pub fn focus(&mut self) -> Result<(), ClientError> { + self.request(APP_FOCUS, Value::Null).map(|_| ()) + } + + /// Opens `folder` as the project (`project.open`). + /// + /// # Errors + /// The engine's error, e.g. `unsaved_changes` when the open project has + /// dirty buffers. + pub fn open_folder(&mut self, folder: &Path) -> Result { + self.execute("project.open", json!({ "path": path_text(folder)? })) + } + + /// Opens `file` in a tab. If no project is open, the file's parent + /// folder is opened as the project first. A file outside the open + /// project fails with the engine's error; the project is never replaced + /// behind the user's back. + /// + /// # Errors + /// The engine's error, or [`ClientError::Protocol`] for a result + /// without a buffer id. + pub fn open_file(&mut self, file: &Path) -> Result { + let text = path_text(file)?; + let result = match self.execute("file.open", json!({ "path": text })) { + Err(e) if e.code() == Some(DISABLED) => { + let parent = file.parent().ok_or_else(|| { + ClientError::Protocol(format!("{} has no parent folder", file.display())) + })?; + self.open_folder(parent)?; + self.execute("file.open", json!({ "path": text }))? + } + other => other?, + }; + let id = result + .get("id") + .and_then(Value::as_u64) + .ok_or_else(|| ClientError::Protocol("file.open returned no buffer id".into()))?; + let path = result + .get("path") + .and_then(Value::as_str) + .map_or_else(|| text.clone(), str::to_string); + Ok(OpenedFile { id, path }) + } + + /// Moves the cursor of the open tab `path` to 0-based `line` and + /// UTF-16 `column` with the UI command `editor.reveal`. Until the + /// window has registered its UI commands (it is still starting) the + /// engine answers `unknown_command`; the call is retried until `wait` + /// has passed. + /// + /// # Errors + /// The last error once `wait` has passed, or any other error at once. + pub fn reveal( + &mut self, + path: &str, + line: u32, + column: u32, + wait: Duration, + ) -> Result<(), ClientError> { + let deadline = Instant::now() + wait; + let params = json!({ "path": path, "line": line, "column": column }); + loop { + match self.execute("editor.reveal", params.clone()) { + Err(e) if e.code() == Some(UNKNOWN_COMMAND) && Instant::now() < deadline => { + thread::sleep(Duration::from_millis(200)); + } + other => return other.map(|_| ()), + } + } + } +} + +/// The path as UTF-8 text for a JSON param. +/// +/// # Errors +/// [`ClientError::Protocol`] if the path is not valid Unicode. +fn path_text(path: &Path) -> Result { + path.to_str() + .map(str::to_string) + .ok_or_else(|| ClientError::Protocol(format!("{} is not valid Unicode", path.display()))) +} diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index aab30e3..1162aa0 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -6,11 +6,18 @@ //! single lines, [`server`] owns the sockets, [`methods`] lists the //! methods. Hosts plug in through [`Backend`] and publish engine events to //! subscribed connections through [`Subscribers`]. +//! +//! The single instance (M3.7) adds [`rendezvous`], the per-user file that +//! names the token-protected listener of the running app, and [`client`], +//! the client that the `lutra` CLI, a second app start and `lutra mcp` use +//! to reach it. mod backend; +pub mod client; pub mod methods; pub mod protocol; +pub mod rendezvous; pub mod server; pub use backend::{Backend, EVENT_QUEUE, EventSink, Subscribers}; -pub use server::{ServerHandle, start}; +pub use server::{ServerHandle, start, start_with_token}; diff --git a/crates/control/src/methods.rs b/crates/control/src/methods.rs index 1405799..fe7ac3b 100644 --- a/crates/control/src/methods.rs +++ b/crates/control/src/methods.rs @@ -15,6 +15,10 @@ pub const ENGINE_LIST_COMMANDS: &str = "engine.listCommands"; pub const UI_SCREENSHOT: &str = "ui.screenshot"; /// `events.subscribe`: streams engine events on this connection. pub const EVENTS_SUBSCRIBE: &str = "events.subscribe"; +/// `app.auth`: authenticates a connection to the rendezvous listener. +pub const APP_AUTH: &str = "app.auth"; +/// `app.focus`: brings the main window to the front. +pub const APP_FOCUS: &str = "app.focus"; /// Documentation of one method. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -29,6 +33,16 @@ pub struct MethodDoc { /// Every method, for help output and agents. pub const METHODS: &[MethodDoc] = &[ + MethodDoc { + name: APP_AUTH, + params: "{ token: string }", + result: "{ authenticated: true }. On the rendezvous listener it must be the first request; any other first request or a wrong token gets error unauthorized and the connection is closed. On the --control listener it always succeeds", + }, + MethodDoc { + name: APP_FOCUS, + params: "none", + result: "{ focused: true }; error focus_failed if there is no window", + }, MethodDoc { name: APP_PING, params: "none", diff --git a/crates/control/src/protocol.rs b/crates/control/src/protocol.rs index 9b35151..4216837 100644 --- a/crates/control/src/protocol.rs +++ b/crates/control/src/protocol.rs @@ -14,7 +14,8 @@ use serde_json::{Value, json}; use crate::Backend; use crate::methods::{ - APP_PING, ENGINE_EXECUTE, ENGINE_LIST_COMMANDS, EVENTS_SUBSCRIBE, UI_SCREENSHOT, + APP_AUTH, APP_FOCUS, APP_PING, ENGINE_EXECUTE, ENGINE_LIST_COMMANDS, EVENTS_SUBSCRIBE, + UI_SCREENSHOT, }; /// Largest accepted request line in bytes, newline excluded. @@ -35,6 +36,10 @@ pub mod codes { pub const LINE_TOO_LONG: &str = "line_too_long"; /// The screenshot could not be taken. pub const SCREENSHOT_FAILED: &str = "screenshot_failed"; + /// The connection has not authenticated with the right token. + pub const UNAUTHORIZED: &str = "unauthorized"; + /// The window could not be brought to the front. + pub const FOCUS_FAILED: &str = "focus_failed"; } /// A parsed request. @@ -143,6 +148,14 @@ pub fn parse_request(line: &str) -> Result { .map_err(|e| Response::err(echo, codes::INVALID_REQUEST, e.to_string())) } +/// Params of `app.auth`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuthParams { + /// The token from the rendezvous file. + pub token: String, +} + /// Answers one request line. Never panics: a panic in the backend becomes an /// `internal` error response. pub fn handle_line(line: &str, backend: &dyn Backend) -> Response { @@ -183,6 +196,11 @@ fn dispatch(request: Request, backend: &dyn Backend) -> Response { }, Err(e) => Response::err(id, codes::INVALID_PARAMS, e.to_string()), }, + APP_AUTH => Response::ok(id, json!({ "authenticated": true })), + APP_FOCUS => match backend.focus() { + Ok(()) => Response::ok(id, json!({ "focused": true })), + Err(message) => Response::err(id, codes::FOCUS_FAILED, message), + }, EVENTS_SUBSCRIBE => Response::err( id, codes::INVALID_REQUEST, @@ -256,6 +274,14 @@ mod tests { assert_eq!(r.error.unwrap().code, "invalid_request"); } + #[test] + fn auth_and_focus_on_an_open_channel() { + let r = call(r#"{"id":1,"method":"app.auth","params":{"token":"x"}}"#); + assert_eq!(r.result.unwrap()["authenticated"], true); + let r = call(r#"{"id":2,"method":"app.focus"}"#); + assert_eq!(r.error.unwrap().code, "focus_failed"); + } + #[test] fn ping() { let r = call(r#"{"id":1,"method":"app.ping"}"#); diff --git a/crates/control/src/rendezvous.rs b/crates/control/src/rendezvous.rs new file mode 100644 index 0000000..9a1337d --- /dev/null +++ b/crates/control/src/rendezvous.rs @@ -0,0 +1,288 @@ +//! The single-instance rendezvous file. +//! +//! A desktop app that owns the single instance writes `instance.json` into +//! its data directory: the port of a token-protected control listener on +//! `127.0.0.1`, a random token, its process id and its version. The `lutra` +//! CLI, a second app start and (from M3.8) `lutra mcp` read the file, +//! connect to the port and authenticate with `app.auth {token}` before any +//! other request (see [`crate::client::Client::connect_instance`]). +//! +//! The file is the only place the token is stored, so it must be readable +//! by the user only. On Unix it is created with mode `0600`. On Windows it +//! lives in the user's roaming application data folder, whose ACL grants +//! access to the user, `SYSTEM` and administrators only; the file inherits +//! that ACL. A file whose listener does not answer, or answers without +//! accepting the token, is stale: the next app start replaces it. +//! +//! The directory is [`dir`]: `LUTRA_RENDEZVOUS_DIR` if set, otherwise +//! [`default_data_dir`], which matches Tauri's `app_data_dir()` for the +//! identifier [`APP_IDENTIFIER`]. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +/// Name of the rendezvous file inside its directory. +pub const FILE_NAME: &str = "instance.json"; + +/// Environment variable that overrides the rendezvous directory. Tests and +/// isolated live checks set it; a desktop started with `--control PORT` +/// takes part in the single instance only when it is set. +pub const DIR_ENV: &str = "LUTRA_RENDEZVOUS_DIR"; + +/// The Tauri app identifier, the last part of the data directory. +pub const APP_IDENTIFIER: &str = "dev.lutra.desktop"; + +/// Random bytes in a token; the token is their lowercase hex form. +pub const TOKEN_BYTES: usize = 32; + +/// Largest rendezvous file that is read; anything bigger is invalid. +pub const MAX_FILE_BYTES: u64 = 4096; + +/// The contents of the rendezvous file. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Instance { + /// Port of the token-protected control listener on `127.0.0.1`. + pub port: u16, + /// Token for `app.auth`, [`TOKEN_BYTES`] random bytes as hex. + pub token: String, + /// Process id of the instance, for diagnostics only. + pub pid: u32, + /// Version of the instance. + pub version: String, +} + +/// Why the rendezvous file could not be read. +#[derive(Debug)] +pub enum ReadError { + /// There is no file: no instance has claimed the directory. + Missing, + /// The file exists but is too big, not JSON or not an [`Instance`]. + Invalid(String), + /// The file could not be read. + Io(io::Error), +} + +impl std::fmt::Display for ReadError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Missing => write!(f, "no rendezvous file"), + Self::Invalid(why) => write!(f, "invalid rendezvous file: {why}"), + Self::Io(e) => write!(f, "cannot read the rendezvous file: {e}"), + } + } +} + +impl std::error::Error for ReadError {} + +/// The rendezvous directory: `LUTRA_RENDEZVOUS_DIR` if set and not empty, +/// otherwise [`default_data_dir`]. +pub fn dir() -> Option { + match std::env::var_os(DIR_ENV) { + Some(value) if !value.is_empty() => Some(PathBuf::from(value)), + _ => default_data_dir(), + } +} + +/// The app data directory as Tauri computes it for [`APP_IDENTIFIER`]: +/// `%APPDATA%\` on Windows, `~/Library/Application Support/` on +/// macOS, `$XDG_DATA_HOME/` or `~/.local/share/` elsewhere. `None` +/// if the needed environment variables are missing or relative. +pub fn default_data_dir() -> Option { + let absolute = |name: &str| { + std::env::var_os(name) + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + }; + let base = if cfg!(windows) { + absolute("APPDATA")? + } else if cfg!(target_os = "macos") { + absolute("HOME")? + .join("Library") + .join("Application Support") + } else { + absolute("XDG_DATA_HOME") + .or_else(|| Some(absolute("HOME")?.join(".local").join("share")))? + }; + Some(base.join(APP_IDENTIFIER)) +} + +/// The path of the rendezvous file in `dir`. +pub fn path(dir: &Path) -> PathBuf { + dir.join(FILE_NAME) +} + +/// A new random token from the operating system's generator. +/// +/// # Errors +/// If the generator fails. +pub fn new_token() -> io::Result { + let mut bytes = [0u8; TOKEN_BYTES]; + getrandom::fill(&mut bytes).map_err(|e| io::Error::other(e.to_string()))?; + Ok(bytes.iter().map(|b| format!("{b:02x}")).collect()) +} + +/// Compares two tokens in time that depends only on their lengths, so a +/// client cannot find the token byte by byte by timing rejections. +pub fn tokens_match(given: &str, expected: &str) -> bool { + let (a, b) = (given.as_bytes(), expected.as_bytes()); + if a.len() != b.len() { + return false; + } + a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +/// Reads the rendezvous file in `dir`. +/// +/// # Errors +/// [`ReadError::Missing`] without a file, [`ReadError::Invalid`] for a file +/// over [`MAX_FILE_BYTES`] or with the wrong shape, [`ReadError::Io`] for +/// other read failures. +pub fn read(dir: &Path) -> Result { + let file = match File::open(path(dir)) { + Ok(file) => file, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Err(ReadError::Missing), + Err(e) => return Err(ReadError::Io(e)), + }; + let mut bytes = Vec::new(); + file.take(MAX_FILE_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(ReadError::Io)?; + if bytes.len() as u64 > MAX_FILE_BYTES { + return Err(ReadError::Invalid(format!( + "larger than {MAX_FILE_BYTES} bytes" + ))); + } + serde_json::from_slice(&bytes).map_err(|e| ReadError::Invalid(e.to_string())) +} + +/// Writes `instance` as the rendezvous file in `dir`, replacing any file +/// there. The directory is created if needed. The text goes to a temporary +/// file in the same directory first (mode `0600` on Unix) and is renamed +/// over the old file, so readers never see half a file. +/// +/// # Errors +/// If the directory, the temporary file or the rename fails. +pub fn write(dir: &Path, instance: &Instance) -> io::Result<()> { + fs::create_dir_all(dir)?; + let text = serde_json::to_vec(instance).map_err(io::Error::other)?; + let tmp = dir.join(format!("{FILE_NAME}.{}.tmp", std::process::id())); + let result = write_private(&tmp, &text).and_then(|()| fs::rename(&tmp, path(dir))); + if result.is_err() { + let _ = fs::remove_file(&tmp); + } + result +} + +/// Creates `path` readable and writable by the owner only and writes +/// `bytes` to it. +/// +/// # Errors +/// If the file cannot be created or written. +fn write_private(path: &Path, bytes: &[u8]) -> io::Result<()> { + let mut options = OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(path)?; + file.write_all(bytes)?; + file.sync_all() +} + +/// Removes the rendezvous file in `dir` if it still holds `token`, so an +/// instance that exits never deletes the file of a newer one. +/// +/// # Errors +/// If the file holds `token` but cannot be removed. +pub fn remove_if_ours(dir: &Path, token: &str) -> io::Result<()> { + match read(dir) { + Ok(instance) if tokens_match(&instance.token, token) => fs::remove_file(path(dir)), + _ => Ok(()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn instance(token: &str) -> Instance { + Instance { + port: 4242, + token: token.into(), + pid: 7, + version: "0.0.0".into(), + } + } + + #[test] + fn tokens_are_random_hex() { + let a = new_token().unwrap(); + let b = new_token().unwrap(); + assert_eq!(a.len(), TOKEN_BYTES * 2); + assert!(a.chars().all(|c| c.is_ascii_hexdigit())); + assert_ne!(a, b); + } + + #[test] + fn compares_tokens() { + assert!(tokens_match("abc", "abc")); + assert!(!tokens_match("abd", "abc")); + assert!(!tokens_match("ab", "abc")); + assert!(!tokens_match("", "abc")); + } + + #[test] + fn writes_reads_and_replaces() { + let dir = tempfile::tempdir().unwrap(); + let nested = dir.path().join("a").join("b"); + assert!(matches!(read(&nested), Err(ReadError::Missing))); + write(&nested, &instance("one")).unwrap(); + assert_eq!(read(&nested).unwrap(), instance("one")); + write(&nested, &instance("two")).unwrap(); + assert_eq!(read(&nested).unwrap().token, "two"); + let leftovers: Vec<_> = fs::read_dir(&nested).unwrap().collect(); + assert_eq!(leftovers.len(), 1, "no temporary file is left behind"); + } + + #[test] + fn rejects_broken_files() { + let dir = tempfile::tempdir().unwrap(); + fs::write(path(dir.path()), b"{not json").unwrap(); + assert!(matches!(read(dir.path()), Err(ReadError::Invalid(_)))); + fs::write( + path(dir.path()), + br#"{"port":70000,"token":"x","pid":1,"version":"v"}"#, + ) + .unwrap(); + assert!(matches!(read(dir.path()), Err(ReadError::Invalid(_)))); + fs::write(path(dir.path()), vec![b' '; 5000]).unwrap(); + assert!(matches!(read(dir.path()), Err(ReadError::Invalid(_)))); + } + + #[test] + fn removes_only_its_own_file() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), &instance("newer")).unwrap(); + remove_if_ours(dir.path(), "older").unwrap(); + assert!(path(dir.path()).exists()); + remove_if_ours(dir.path(), "newer").unwrap(); + assert!(!path(dir.path()).exists()); + remove_if_ours(dir.path(), "newer").unwrap(); + } + + #[cfg(unix)] + #[test] + fn file_is_private_on_unix() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), &instance("t")).unwrap(); + let mode = fs::metadata(path(dir.path())).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + } +} diff --git a/crates/control/src/server.rs b/crates/control/src/server.rs index 1640ce3..c60ec7b 100644 --- a/crates/control/src/server.rs +++ b/crates/control/src/server.rs @@ -1,6 +1,12 @@ //! The TCP side: a listener on the loopback interface, one thread per //! connection, JSON lines in and out. //! +//! [`start`] serves the open `--control PORT` channel. [`start_with_token`] +//! serves the rendezvous listener of the single instance: there the first +//! request must be `app.auth {token}` with the token of the rendezvous +//! file, sent within [`AUTH_TIMEOUT`]; anything else gets `unauthorized` +//! and the connection is closed. +//! //! A connection that sent `events.subscribe` also gets a forwarder thread //! that writes event lines. Responses and events share one writer behind a //! lock and each line is written whole, so lines never interleave. The @@ -20,12 +26,28 @@ use serde_json::{Value, json}; use crate::Backend; use crate::backend::EVENT_QUEUE; -use crate::methods::EVENTS_SUBSCRIBE; -use crate::protocol::{MAX_LINE_BYTES, Response, codes, handle_line, parse_request}; +use crate::methods::{APP_AUTH, EVENTS_SUBSCRIBE}; +use crate::protocol::{ + AuthParams, MAX_LINE_BYTES, Request, Response, codes, handle_line, parse_request, +}; +use crate::rendezvous::tokens_match; /// How often an idle forwarder checks whether its connection closed. const FORWARDER_TICK: Duration = Duration::from_millis(250); +/// How long a connection to the rendezvous listener may take to +/// authenticate before it is closed. +pub const AUTH_TIMEOUT: Duration = Duration::from_secs(10); + +/// Who may use a listener's connections. +#[derive(Debug, Clone)] +enum Access { + /// Everyone who can reach `127.0.0.1` (the `--control` channel). + Open, + /// Connections that authenticated with this token first. + Token(Arc), +} + /// A running control server. #[derive(Debug)] pub struct ServerHandle { @@ -46,24 +68,47 @@ impl ServerHandle { /// # Errors /// The bind error, e.g. when the port is taken. pub fn start(port: u16, backend: Arc) -> io::Result { + serve(port, backend, Access::Open) +} + +/// Binds `127.0.0.1:port` (0 for any free port) and serves requests from +/// connections that authenticate with `token` first, for the rest of the +/// process's life. +/// +/// # Errors +/// The bind error. +pub fn start_with_token( + port: u16, + backend: Arc, + token: &str, +) -> io::Result { + serve(port, backend, Access::Token(Arc::from(token))) +} + +/// Binds the listener and starts the accept thread. +/// +/// # Errors +/// The bind error. +fn serve(port: u16, backend: Arc, access: Access) -> io::Result { let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port))?; let addr = listener.local_addr()?; thread::Builder::new() .name("lutra-control".into()) - .spawn(move || accept_loop(&listener, &backend))?; + .spawn(move || accept_loop(&listener, &backend, &access))?; Ok(ServerHandle { addr }) } /// Accepts connections until the listener fails. Failed accepts and threads /// that cannot be spawned drop that one connection and keep serving. -fn accept_loop(listener: &TcpListener, backend: &Arc) { +fn accept_loop(listener: &TcpListener, backend: &Arc, access: &Access) { for stream in listener.incoming() { let Ok(stream) = stream else { continue }; let backend = Arc::clone(backend); + let access = access.clone(); let spawned = thread::Builder::new() .name("lutra-control-conn".into()) .spawn(move || { - let _ = serve_connection(stream, backend.as_ref()); + let _ = serve_connection(stream, backend.as_ref(), &access); }); drop(spawned); } @@ -91,24 +136,31 @@ fn write_line(writer: &SharedWriter, line: &str) -> io::Result<()> { /// /// # Errors /// The first read or write error. -fn serve_connection(stream: TcpStream, backend: &dyn Backend) -> io::Result<()> { +fn serve_connection(stream: TcpStream, backend: &dyn Backend, access: &Access) -> io::Result<()> { let writer: SharedWriter = Arc::new(Mutex::new(stream.try_clone()?)); let closed = Arc::new(AtomicBool::new(false)); - let result = read_loop(stream, backend, &writer, &closed); + let result = read_loop(stream, backend, access, &writer, &closed); closed.store(true, Ordering::Relaxed); result } -/// Reads and answers request lines. +/// Reads and answers request lines. On a token listener the first request +/// must authenticate (see [`authenticate`]); until then reads time out after +/// [`AUTH_TIMEOUT`]. /// /// # Errors /// The first read or write error. fn read_loop( stream: TcpStream, backend: &dyn Backend, + access: &Access, writer: &SharedWriter, closed: &Arc, ) -> io::Result<()> { + let mut authenticated = matches!(access, Access::Open); + if !authenticated { + stream.set_read_timeout(Some(AUTH_TIMEOUT))?; + } let mut reader = BufReader::new(stream); let mut buf = Vec::new(); let mut subscribed = false; @@ -137,6 +189,20 @@ fn read_loop( if buf.iter().all(u8::is_ascii_whitespace) { continue; } + if !authenticated { + let Access::Token(token) = access else { + return Ok(()); + }; + let response = authenticate(&buf, token); + let accepted = response.error.is_none(); + write_line(writer, &response.to_line())?; + if !accepted { + return Ok(()); + } + authenticated = true; + reader.get_ref().set_read_timeout(None)?; + continue; + } let response = match std::str::from_utf8(&buf) { Ok(line) => match parse_request(line) { Ok(request) if request.method == EVENTS_SUBSCRIBE => { @@ -154,6 +220,32 @@ fn read_loop( } } +/// Answers the first request of a token connection: `app.auth` with the +/// right token succeeds, everything else is `unauthorized`. The message +/// does not say whether the token or the method was wrong. +fn authenticate(line: &[u8], token: &str) -> Response { + let request = std::str::from_utf8(line) + .ok() + .and_then(|line| parse_request(line).ok()); + let id = request.as_ref().map_or(Value::Null, |r| r.id.clone()); + let accepted = match request { + Some(Request { method, params, .. }) if method == APP_AUTH => { + serde_json::from_value::(params) + .is_ok_and(|p| tokens_match(&p.token, token)) + } + _ => false, + }; + if accepted { + Response::ok(id, json!({ "authenticated": true })) + } else { + Response::err( + id, + codes::UNAUTHORIZED, + "authenticate with app.auth and the rendezvous token first", + ) + } +} + /// Registers a subscription with the backend and starts its forwarder. /// /// # Errors diff --git a/crates/control/tests/single_instance.rs b/crates/control/tests/single_instance.rs new file mode 100644 index 0000000..e53a3a4 --- /dev/null +++ b/crates/control/tests/single_instance.rs @@ -0,0 +1,212 @@ +//! The single instance over real sockets: the token check of the +//! rendezvous listener, stale rendezvous files, and forwarding a second +//! start's path to the running instance. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)] + +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpStream; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +use lutra_control::client::{self, Client, Unavailable}; +use lutra_control::rendezvous::{self, Instance}; +use lutra_testkit::EngineBackend; +use serde_json::{Value, json}; + +const TIMEOUT: Duration = Duration::from_secs(10); + +/// Starts a token listener for `backend` and writes its rendezvous file in +/// `dir`, as the desktop's claim does. +fn claim(dir: &Path, backend: Arc) -> Instance { + let token = rendezvous::new_token().unwrap(); + let server = lutra_control::start_with_token(0, backend, &token).unwrap(); + let instance = Instance { + port: server.local_addr().port(), + token, + pid: std::process::id(), + version: "test".into(), + }; + rendezvous::write(dir, &instance).unwrap(); + instance +} + +/// Sends raw lines and reads one response line, or `None` at end of stream. +fn exchange(port: u16, lines: &[Value]) -> Vec> { + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + stream.set_read_timeout(Some(TIMEOUT)).unwrap(); + let mut writer = stream.try_clone().unwrap(); + let mut reader = BufReader::new(stream); + lines + .iter() + .map(|line| { + if writer.write_all(format!("{line}\n").as_bytes()).is_err() { + return None; + } + let mut text = String::new(); + match reader.read_line(&mut text) { + Ok(0) | Err(_) => None, + Ok(_) => Some(serde_json::from_str(&text).unwrap()), + } + }) + .collect() +} + +#[test] +fn the_rendezvous_listener_needs_the_token_first() { + let dir = tempfile::tempdir().unwrap(); + let instance = claim(dir.path(), Arc::new(EngineBackend::new())); + let ping = json!({"id": 2, "method": "app.ping"}); + + let r = exchange(instance.port, &[ping.clone(), ping.clone()]); + assert_eq!(r[0].as_ref().unwrap()["error"]["code"], "unauthorized"); + assert!(r[1].is_none(), "the connection is closed"); + + let wrong = json!({"id": 1, "method": "app.auth", "params": {"token": "0".repeat(64)}}); + let r = exchange(instance.port, &[wrong, ping.clone()]); + assert_eq!(r[0].as_ref().unwrap()["error"]["code"], "unauthorized"); + assert!(r[1].is_none()); + + let r = exchange(instance.port, &[json!("garbage"), ping.clone()]); + assert_eq!(r[0].as_ref().unwrap()["error"]["code"], "unauthorized"); + + let right = json!({"id": 1, "method": "app.auth", "params": {"token": instance.token}}); + let r = exchange(instance.port, &[right, ping]); + assert_eq!(r[0].as_ref().unwrap()["result"]["authenticated"], true); + assert_eq!(r[1].as_ref().unwrap()["result"]["pong"], true); +} + +#[test] +fn the_open_control_channel_still_needs_no_token() { + let server = lutra_control::start(0, Arc::new(EngineBackend::new())).unwrap(); + let mut client = Client::connect(server.local_addr().port(), TIMEOUT).unwrap(); + assert_eq!( + client.request("app.ping", Value::Null).unwrap()["pong"], + true + ); +} + +#[test] +fn stale_files_are_detected() { + let dir = tempfile::tempdir().unwrap(); + assert!(matches!( + client::connect_live(dir.path(), TIMEOUT), + Err(Unavailable::Missing) + )); + + std::fs::write(rendezvous::path(dir.path()), "{").unwrap(); + assert!(matches!( + client::connect_live(dir.path(), TIMEOUT), + Err(Unavailable::Stale(_)) + )); + + let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = closed.local_addr().unwrap().port(); + drop(closed); + let dead = Instance { + port, + token: "t".into(), + pid: 1, + version: "old".into(), + }; + rendezvous::write(dir.path(), &dead).unwrap(); + assert!(matches!( + client::connect_live(dir.path(), TIMEOUT), + Err(Unavailable::Stale(_)) + )); + + let live = claim(dir.path(), Arc::new(EngineBackend::new())); + let reused = Instance { + token: "f".repeat(64), + ..live.clone() + }; + rendezvous::write(dir.path(), &reused).unwrap(); + assert!( + matches!( + client::connect_live(dir.path(), TIMEOUT), + Err(Unavailable::Stale(_)) + ), + "a listener that refuses the token is not ours" + ); + + rendezvous::write(dir.path(), &live).unwrap(); + let (found, _) = client::connect_live(dir.path(), TIMEOUT).unwrap(); + assert_eq!(found, live, "the stale file was replaced"); +} + +#[test] +fn a_second_start_forwards_folders_and_files() { + let rv = tempfile::tempdir().unwrap(); + let project = tempfile::tempdir().unwrap(); + let other = tempfile::tempdir().unwrap(); + let file = project.path().join("a.php"); + std::fs::write(&file, " **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup · **Last updated:** 2026-10-17 +> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance · **Last updated:** 2026-10-17 ## Overview ``` apps/lutra-desktop (L6) Tauri 2 shell: windows, menus, IPC bridge to the engine ui/ (L6) Vue 3 + TypeScript + Vite frontend, Pinia, CodeMirror 6 -apps/lutra-cli (L5) the `lutra` command: open, diff, --wait, mcp, perf, bench +apps/lutra-cli (L6) the `lutra` command: open, --wait; later diff, mcp, perf, bench crates/control (L5) JSON-lines control channel (--control PORT) crates/mcp (L5) MCP server over stdio crates/engine (L4) command registry, workspace state, guard, recovery journal, theme tokens @@ -59,11 +59,27 @@ As built in M0: - Transport: one JSON object per line, UTF-8, at most 16 MiB per line; longer lines get an error response and the connection is closed. - Request: `{"id": , "method": "", "params": {...}}`. Response: `{"id": ..., "result": ...}` or `{"id": ..., "error": {"code": "...", "message": "..."}}`. A line that is not valid JSON gets an error response with `"id": null`. -- Methods: `app.ping`, `engine.execute {command, params}`, `engine.listCommands`, `ui.screenshot {path}`, `events.subscribe`. Names and docs live in `crates/control/src/methods.rs`. +- Methods: `app.ping`, `app.auth {token}`, `app.focus`, `engine.execute {command, params}`, `engine.listCommands`, `ui.screenshot {path}`, `events.subscribe`. Names and docs live in `crates/control/src/methods.rs`. - `events.subscribe` answers `{subscribed: true}` and from then on writes `{"event": {...}}` lines for every engine event on that connection, between responses; a shared writer writes each line whole. Subscribing twice is a no-op. Each subscriber has a queue of 4096 events (`lutra_control::EVENT_QUEUE`); a subscriber that falls behind or disconnects is dropped by `Subscribers::publish`, and the connection gets a final `{"event": {"kind": "subscriptionLost"}}` line if it is still open. - `lutra_control` defines a `Backend` trait; the desktop app implements it (engine access, effects, screenshots, event subscribers), tests implement it with a bare engine (`lutra_testkit::EngineBackend`). Hosts publish each outcome's events through `lutra_control::Subscribers`. One thread accepts connections and each connection gets its own thread; no async runtime is needed in the crate. - Screenshots: `xcap` does not enumerate windows of its own process (querying their titles can deadlock), so the desktop focuses its main window, reads the client area's physical position and size from Tauri and captures that region of the monitor with `xcap::Monitor::capture_region`. Windows covering Lutra at that moment appear in the image. A webview-native capture (WebView2 `CapturePreview`, WKWebView snapshots) can replace it later. +### CLI and single instance (M3.7) + +- **Rendezvous file:** a desktop that owns the single instance serves a second, token-protected control listener on a free port of `127.0.0.1` (`lutra_control::start_with_token`) and writes `/instance.json` = `{port, token, pid, version}` (`lutra_control::rendezvous`). The token is 32 bytes from the OS generator (`getrandom`), hex. The file is written to a temporary file and renamed, so readers never see half a file; on exit the app removes it if it still holds its own token. +- **Directory:** `LUTRA_RENDEZVOUS_DIR` if set, else `rendezvous::default_data_dir()`, which computes Tauri's `app_data_dir()` for the identifier `dev.lutra.desktop` without Tauri (`%APPDATA%\dev.lutra.desktop` on Windows, `~/Library/Application Support/dev.lutra.desktop` on macOS, `$XDG_DATA_HOME` or `~/.local/share` + the identifier elsewhere), so the CLI and the desktop agree without sharing a runtime. +- **Security:** only the user may read the token. Unix: the file is created with mode `0600`. Windows: it lives in the user's roaming AppData folder, whose inherited ACL grants the user, `SYSTEM` and Administrators only (checked with `icacls` in the M3.7 live check); Lutra sets no ACL of its own. Both listeners bind `127.0.0.1` only. On the token listener the first request must be `app.auth {token}` within 10 s (`AUTH_TIMEOUT`); a wrong token, another method or garbage gets `unauthorized` and the connection is closed. Tokens are compared in constant time. The `--control PORT` listener stays open (no token) for development and agents; it is opt-in and documented as such. +- **Second start:** `lutra-desktop [PATH]` without `--control` reads the rendezvous file first. If the listener answers, accepts the token and pings, the start forwards `PATH` (folder → `project.open`, file → `file.open`), calls `app.focus` and exits 0. If the file is missing, unreadable, invalid, or its port refuses or rejects the token, it is stale: this start becomes the instance and replaces the file. Two starts in the same instant can both become instances; the later file wins (accepted, rare). +- **Development instances:** a start with `--control PORT` skips the single instance (no forwarding, no rendezvous file) so parallel agents' instances never forward to each other, unless `LUTRA_RENDEZVOUS_DIR` is set, which opts it into the single instance in that directory (used for isolated live checks). +- **New methods:** `app.auth {token}` (always succeeds on the open listener) and `app.focus` (restore, show and focus the main window; `focus_failed` without a window; `Backend::focus` has a default that fails, so test backends need no change). +- **`lutra` CLI** (`apps/lutra-cli`, binary `lutra`, now L6 so it can use `lutra-control`): `lutra [--wait] [PATH[:LINE[:COLUMN]]]...`. + - **Targets:** up to two trailing `:N` groups are a 1-based line and column (`N` all digits, something before it; on Windows a lone drive letter is never split). If the path part does not exist but the whole argument does, the argument is the path. Paths are made absolute against the current directory without resolving symlinks. + - **Opening:** a folder (at most one, no position) → `project.open`. A file → `file.open`; with no project open its parent folder is opened first. **A file outside the open project is refused** (exit 1, the engine's `… is outside the project`), because Lutra has one window and replacing the project behind the user's back could lose their context; out-of-project buffers are a gap (G7). A line → `editor.reveal {path, line-1, column-1}`, retried for up to 20 s while the window has not registered its UI commands yet (`unknown_command`). + - **Starting Lutra:** if no instance answers, the CLI starts the desktop detached (`LUTRA_DESKTOP`, else `lutra-desktop` next to `lutra`, else on `PATH`) and polls the rendezvous file for up to 60 s. + - **`--wait`:** subscribes before opening, then blocks until every opened file's `bufferClosed` arrived (or `projectClosed`, or the connection ends because Lutra quit). A `subscriptionLost` renews the subscription and checks the remaining ids with `buffer.get`. Folders are not waited for. + - **Exit codes:** 0 ok, 1 error (cannot start, open failed, missing path), 2 bad usage (unknown option, line or column 0 or too big, two folders, a positioned folder, non-Unicode argument). Arguments are untrusted; parsing is property-tested. +- **Rendezvous API for M3.8 (`lutra mcp`):** `lutra_control::client::connect_live(&rendezvous::dir()?, timeout)` returns the `Instance` and an authenticated `Client`; `Client::request(method, params)`, `execute(command, params)`, `subscribe()`, `next_event(timeout)` (events read while waiting for a response are queued, at most 4096), `open_folder`, `open_file`, `reveal`, `focus`. To start Lutra when none runs, reuse the CLI's `launch` logic (move it into the client if MCP needs it outside the CLI binary). Response lines are capped at 64 MiB. + ## Frontend ↔ engine The frontend calls `run(id, params)` over Tauri IPC (`engine_execute`, `engine_list_commands`) and subscribes to state events. Buffer contents live in the engine; CodeMirror sends edits as transactions and receives authoritative changes back. @@ -290,6 +306,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | M3.7: `lutra` CLI, single instance, rendezvous file and token listener, `app.auth`/`app.focus`, CLI to L6 | | 2026-10-17 | minor | M2.6: go-to popup (store, debounce and stale drop, modes, `editor.reveal`), `library` on `goto.file` items | | 2026-10-17 | minor | M2.7: per-buffer syntax tree off the engine lock, `syntax.outline`, `outlineChanged`, left stripe, Structure tool window | | 2026-10-17 | minor | M2.5: symbol index (`crates/index`: parallel build, updater, fuzzy queries), `index.status`, `goto.file`/`goto.class`/`goto.symbol`, `indexProgress`/`indexReady` via the pump, timing | diff --git a/docs/gaps.md b/docs/gaps.md index 10fc3c6..cfba1d5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal); G3 M1 part done (project tree, palette, settings dialog, themes); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G14 English UI catalog in place · **Last updated:** 2026-10-17 +> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal); G3 M1 part done (project tree, palette, settings dialog, themes); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G7 under way (`lutra` CLI and single instance); G14 English UI catalog in place · **Last updated:** 2026-10-17 Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated. @@ -12,7 +12,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t | G4 | Syntax and structure: tree-sitter PHP, ~~Lezer highlighting~~ (M2.2: PHP with embedded HTML plus HTML, CSS, JS/TS, JSON, YAML, Markdown; `--lt-syntax-*` tokens; `editor.reveal`), ~~file structure~~ (M2.7: Structure tool window, `syntax.outline`), semantic highlighting, folding in the editor | M2 | ~8 h | | G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h | | G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor | M3 | ~45 h | -| G7 | Terminal, `lutra` CLI and MCP server | M3 | ~35 h | +| G7 | Terminal, ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), MCP server, files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~30 h | | G8 | Git integration | M4 | ~150 h | | G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h | | G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h | @@ -43,6 +43,7 @@ Known smaller items from M0: | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | G7: `lutra` CLI and single instance (M3.7); out-of-project files and `lutra diff` listed | | 2026-10-17 | minor | G5: go-to popup (M2.6) | | 2026-10-17 | minor | G4: Structure tool window (M2.7); G12: raw-JSON command results | | 2026-10-17 | minor | G5: symbol index and go-to commands (M2.5) | diff --git a/docs/roadmap.md b/docs/roadmap.md index deed6c1..15047f9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -9,7 +9,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t | M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) | | M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~5.6 (measured: C1 2.5, C2 3.1) | | M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | done 2026-10-17 (C3: M2.1 tree-sitter syntax, M2.2 highlighting + `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index + go-to commands, M2.6 go-to popup, M2.7 Structure tool window) | ~6.1 (measured) | -| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | not started | ~12 | +| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | in progress (M3.7 CLI and single instance done) | ~12 | | M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 | | M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 | | M6 | Own indexer and inspections; Symfony, Laravel, Shopware, WordPress support | not started | ~1,100 | @@ -31,6 +31,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | M3.7 CLI and single instance | | 2026-10-17 | minor | M2 done (C3 review), M3 ~12 h at ×0.15 | | 2026-10-17 | minor | M2.6 go-to popup | | 2026-10-17 | minor | M2.7 Structure tool window |