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:
parent
9ccfc1bf6a
commit
9b278099cf
26 changed files with 2162 additions and 37 deletions
|
|
@ -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 = [] }
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)]
|
||||
|
|
|
|||
139
apps/lutra-desktop/src/instance.rs
Normal file
139
apps/lutra-desktop/src/instance.rs
Normal 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");
|
||||
}
|
||||
}
|
||||
|
|
@ -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(())
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue