Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
35 changes: 35 additions & 0 deletions src/app/already_running.rs
Original file line number Diff line number Diff line change
@@ -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<AlreadyRunning>) -> 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() })]);
}
1 change: 1 addition & 0 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
29 changes: 29 additions & 0 deletions src/datadir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<std::fs::File>> {
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 };
Expand All @@ -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");
Expand Down
12 changes: 12 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading