diff --git a/README.md b/README.md index a47b1e6..5e224ab 100644 --- a/README.md +++ b/README.md @@ -14,4 +14,4 @@ Claudiu never calls the Anthropic API or deletes a transcript, and it changes Cl ## Development -You need stable Rust, plus Visual Studio Build Tools on Windows or the headers Rune builds against on Linux, and [just](https://just.systems): `just run`, `just test`, `just ci`. `src/` is the app, `mod/` is the Claude Code plugin each session loads, and `web/` is the site. `CLAUDE.md` has the conventions. To release, bump `version` in `Cargo.toml` and push a `vX.Y.Z` tag. +You need stable Rust, plus Visual Studio Build Tools on Windows or the headers Rune builds against on Linux, and [just](https://just.systems): `just run`, `just test`, `just ci`. `src/` is the app, `mod/` is the Claude Code plugin each session loads, and `web/` is the site. `CLAUDE.md` has the conventions. A debug build keeps its data in its own folder, so it runs beside the installed app; a second app on the same folder says Claudiu is already running and quits. To release, bump `version` in `Cargo.toml` and push a `vX.Y.Z` tag. diff --git a/src/app/already_running.rs b/src/app/already_running.rs new file mode 100644 index 0000000..519def2 --- /dev/null +++ b/src/app/already_running.rs @@ -0,0 +1,35 @@ +//! The window a second Claudiu shows when another one already uses its data folder, before it quits. + +use rune::{Cx, El, col, row}; + +use crate::panels::theme; +use crate::panels::widgets::{button, label}; +use crate::platform; + +const SIZE: (f32, f32) = (420.0, 170.0); + +pub struct AlreadyRunning; + +fn render(_: &AlreadyRunning, _cx: &mut Cx) -> El { + col() + .w_full() + .h_full() + .fill(theme::rgb(theme::APP_BG)) + .padding(24.0) + .gap(10.0) + .child(label("Claudiu is already running", 15.0, theme::TEXT)) + .child(label("Another Claudiu window uses the same data folder. Switch to it instead.", 13.0, theme::TEXT_DIM).wrap()) + .child(rune::el().grow(1.0)) + .child(row().w_full().child(rune::el().grow(1.0)).child(button("OK", true).key("already-running-ok").on_press_tx(|_: &mut AlreadyRunning, tx: &mut rune::Tx| tx.quit()))) +} + +/// Shows the notice until it is closed, then returns. +pub fn show() { + let spec = rune::AppSpec { + min_size: Some(SIZE), + families: (platform::ui_font(), platform::monospace_font()), + ..rune::AppSpec::new("Claudiu", SIZE, || AlreadyRunning, render) + }; + let app = rune::App::new(spec).on_close(|_: &mut AlreadyRunning, tx: &mut rune::Tx| tx.quit()); + rune::run_windows(move |_| vec![rune::WindowSpec::from_app("already-running", app).options(rune::WindowOptions { resizable: false, min_size: Some(SIZE), ..Default::default() })]); +} diff --git a/src/app/mod.rs b/src/app/mod.rs index 734d2d7..d8f7b0f 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -29,6 +29,7 @@ use crate::updater::UpdateState; pub use rt::{HasRt, Rt}; +pub mod already_running; mod alt_accounts; mod ask_claude; mod attached_sync; diff --git a/src/datadir.rs b/src/datadir.rs index 16efe82..4b7af96 100644 --- a/src/datadir.rs +++ b/src/datadir.rs @@ -36,6 +36,23 @@ pub fn write_atomic(path: &Path, text: &str) -> std::io::Result<()> { std::fs::rename(&tmp, path) } +/// Takes the data folder for this process: the lock lasts as long as the returned file is open. `Ok(None)` when another +/// Claudiu holds it, so two apps never race on `state.json` and the request files. It waits up to `patience` first, +/// because an update or restart starts the new app while the old one is still closing. +pub fn lock(dir: &Path, patience: std::time::Duration) -> std::io::Result> { + std::fs::create_dir_all(dir)?; + let file = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(dir.join("claudiu.lock"))?; + let start = std::time::Instant::now(); + loop { + match file.try_lock() { + Ok(()) => return Ok(Some(file)), + Err(std::fs::TryLockError::WouldBlock) if start.elapsed() < patience => std::thread::sleep(std::time::Duration::from_millis(100)), + Err(std::fs::TryLockError::WouldBlock) => return Ok(None), + Err(std::fs::TryLockError::Error(e)) => return Err(e), + } + } +} + /// Remove the files in `dir` that have not been modified for `max_age_secs`. The caller decides the age. pub fn prune(dir: PathBuf, max_age_secs: u64) { let Ok(entries) = std::fs::read_dir(dir) else { return }; @@ -56,6 +73,18 @@ pub fn prune(dir: PathBuf, max_age_secs: u64) { mod tests { use super::*; + #[test] + fn a_second_app_cannot_take_a_data_folder_until_the_first_lets_go() { + let dir = tempfile::tempdir().unwrap(); + let none = std::time::Duration::ZERO; + let first = lock(dir.path(), none).unwrap().expect("the first app takes the folder"); + assert!(lock(dir.path(), none).unwrap().is_none(), "a second app finds it taken"); + let other = tempfile::tempdir().unwrap(); + assert!(lock(other.path(), none).unwrap().is_some(), "another data folder is free"); + drop(first); + assert!(lock(dir.path(), none).unwrap().is_some(), "free again once the first app is gone"); + } + #[test] fn session_ids_cannot_escape_the_directory() { assert_eq!(safe_file_stem("../../evil"), "______evil"); diff --git a/src/main.rs b/src/main.rs index ccd15c1..5341cdc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -81,6 +81,18 @@ fn main() { // Velopack install/update hooks must run before anything else. A no-op for dev builds. velopack::VelopackApp::build().run(); + // One app per data folder: a second one would race the first on state.json and the request files (#84). Debug + // builds have their own folder, so a dev build still runs beside the installed app. + let _data_folder = match datadir::lock(&datadir::data_dir(), std::time::Duration::from_secs(5)) { + Ok(Some(lock)) => Some(lock), + Ok(None) => { + app::already_running::show(); + return; + } + // A folder that can't be locked (a read-only disk, say) is reported where it is first written, not here. + Err(_) => None, + }; + // TERM=xterm-256color / COLORTERM=truecolor for child processes. alacritty_terminal::tty::setup_env(); terminal::prepare_child_env();