M3.7: lutra CLI and single instance

- crates/control: rendezvous file (<data_dir>/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 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-18 00:23:09 +02:00
parent 9ccfc1bf6a
commit 9b278099cf
26 changed files with 2162 additions and 37 deletions

View file

@ -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

261
apps/lutra-cli/src/args.rs Normal file
View file

@ -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<u32>,
/// The column, from 1; only with a line.
pub column: Option<u32>,
}
/// 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<Target>,
}
/// 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<Item = OsString>) -> Result<Args, String> {
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<Target, String> {
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<u32, String> {
match text.parse::<u32>() {
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<Args, String> {
parse(args.iter().map(OsString::from))
}
fn t(raw: &str) -> (String, Option<u32>, Option<u32>) {
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<String> = (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));
}
}
}

View file

@ -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<PathBuf, String> {
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<Client, String> {
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);
}
}

View file

@ -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)
}

244
apps/lutra-cli/src/open.rs Normal file
View file

@ -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<u32>,
/// Column from 1.
column: Option<u32>,
},
}
/// 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<Vec<Resolved>, 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<Vec<u64>, 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<u64>) -> 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, "<?php\n").unwrap();
let odd = dir.path().join("b:3");
if std::fs::write(&odd, "x").is_err() {
return;
}
let t = |raw: &Path| parse_target(raw.to_str().unwrap()).unwrap();
let positioned = parse_target(&format!("{}:4:2", file.display())).unwrap();
let resolved = resolve(&[positioned, t(dir.path()), t(&odd)]).unwrap();
assert_eq!(resolved[0], Resolved::Folder(dir.path().to_path_buf()));
assert_eq!(
resolved[1],
Resolved::File {
path: file.clone(),
line: Some(4),
column: Some(2)
}
);
assert_eq!(
resolved[2],
Resolved::File {
path: odd,
line: None,
column: None
}
);
}
#[test]
fn rejects_bad_targets() {
let dir = tempfile::tempdir().unwrap();
let t = |raw: String| parse_target(&raw).unwrap();
let missing = t(dir.path().join("nope.php").display().to_string());
assert!(matches!(resolve(&[missing]), Err(Failure::Error(_))));
let folder_line = t(format!("{}:3", dir.path().display()));
assert!(matches!(resolve(&[folder_line]), Err(Failure::Usage(_))));
let folder = t(dir.path().display().to_string());
assert!(matches!(
resolve(&[folder.clone(), folder]),
Err(Failure::Usage(_))
));
}
}

156
apps/lutra-cli/tests/cli.rs Normal file
View file

@ -0,0 +1,156 @@
//! The `lutra` binary end to end against a test backend that claims a
//! temporary rendezvous directory (`LUTRA_RENDEZVOUS_DIR`).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
use std::path::Path;
use std::process::{Command, Output, Stdio};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
use lutra_control::rendezvous::{self, Instance};
use lutra_engine::Event;
use lutra_testkit::EngineBackend;
use serde_json::json;
/// A backend with a token listener and the UI command `editor.reveal`
/// registered, as a loaded window would have it.
fn instance(dir: &Path) -> Arc<EngineBackend> {
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<u64> {
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, "<?php\n".repeat(20)).unwrap();
let backend = instance(rv.path());
let (sink, events) = std::sync::mpsc::sync_channel(64);
lutra_control::Backend::subscribe(backend.as_ref(), sink);
let arg = format!("{}:10:3", file.display());
let out = run(rv.path(), &[&arg]);
assert_eq!(
out.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert_eq!(buffer_ids(&backend).len(), 1);
let reveal = events
.try_iter()
.find(|e| matches!(e, Event::UiCommand { .. }))
.unwrap();
assert_eq!(
reveal,
Event::UiCommand {
id: "editor.reveal".into(),
params: json!({"path": "a.php", "line": 9, "column": 2}),
}
);
}
#[test]
fn wait_returns_after_the_tab_is_closed() {
use lutra_control::Backend;
let rv = tempfile::tempdir().unwrap();
let project = tempfile::tempdir().unwrap();
let file = project.path().join("COMMIT_EDITMSG");
std::fs::write(&file, "msg\n").unwrap();
let backend = instance(rv.path());
let mut child = lutra(rv.path(), &["--wait", file.to_str().unwrap()])
.spawn()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(20);
let id = loop {
if let Some(id) = buffer_ids(&backend).first() {
break *id;
}
assert!(Instant::now() < deadline, "the file was never opened");
thread::sleep(Duration::from_millis(50));
};
thread::sleep(Duration::from_millis(300));
assert!(child.try_wait().unwrap().is_none(), "--wait returned early");
backend.execute("buffer.close", json!({"id": id})).unwrap();
let deadline = Instant::now() + Duration::from_secs(20);
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
break status;
}
assert!(Instant::now() < deadline, "--wait did not return");
thread::sleep(Duration::from_millis(50));
};
assert_eq!(status.code(), Some(0));
}

View file

@ -22,6 +22,9 @@ tauri = { version = "2.11.6", features = [] }
tauri-plugin-dialog = "2.7.3"
xcap = "0.9.8"
[dev-dependencies]
tempfile.workspace = true
[build-dependencies]
png = "0.18.1"
tauri-build = { version = "2.6.3", features = [] }

View file

@ -1,5 +1,6 @@
//! Command-line arguments of the desktop app.
use std::ffi::OsString;
use std::path::PathBuf;
/// Parsed arguments.
@ -22,6 +23,21 @@ pub const USAGE: &str = "usage: lutra-desktop [--control PORT] [PATH]
--version print the version
--help print this help";
/// Parses the raw arguments after the program name.
///
/// # Errors
/// A message for an argument that is not valid Unicode, or as [`parse`].
pub fn parse_os(args: impl IntoIterator<Item = OsString>) -> Result<Args, String> {
let args = args
.into_iter()
.map(|arg| {
arg.into_string()
.map_err(|arg| format!("argument {arg:?} is not valid Unicode"))
})
.collect::<Result<Vec<_>, _>>()?;
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));
}
}

View file

@ -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)]

View file

@ -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<PathBuf> {
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<bool, String> {
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<Host>) -> Result<Self, String> {
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");
}
}

View file

@ -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<OnceLock<Arc<Host>>> = 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(())
}