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

@ -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<PathBuf> {
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%\<id>` on Windows, `~/Library/Application Support/<id>` on
/// macOS, `$XDG_DATA_HOME/<id>` or `~/.local/share/<id>` elsewhere. `None`
/// if the needed environment variables are missing or relative.
pub fn default_data_dir() -> Option<PathBuf> {
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<String> {
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<Instance, ReadError> {
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);
}
}