diff --git a/README.md b/README.md index f386dbe..7c1bbcf 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,13 @@ Claudiu is a native desktop app, written in Rust with [GPUI](https://gpui.rs), t Each session is your own `claude` process in a real pseudo-terminal, so Claude Code's keys, mouse and paste work unchanged. Claudiu has no API keys and never calls the Anthropic API. Sign-in stays with Claude Code. The first launch opens a setup window that checks for `claude` (required) and `gh` (optional), links to their install pages and installs nothing. Settings has a Check setup button to open it again. A sidebar lists your projects and sessions. Ended sessions resume through `claude --resume`, and sessions that were running come back at the next start. -Around the terminal, Claudiu adds an editor mode (Ctrl+Shift+E) with files, tabs, search, Git change marks and language-server diagnostics, definitions and completion. It also adds usage and context meters, a GitHub pane for issues and pull requests through your `gh` login, defaults for the model, effort and permission mode of new sessions, and extra Claude accounts that share one configuration. Settings lists the rest. +Around the terminal, Claudiu adds an editor mode (Ctrl+Shift+E) with files, tabs, search, Git change marks and language-server diagnostics, definitions and completion. It also adds usage and context meters, a GitHub pane for issues and pull requests through your `gh` login, defaults for the model, effort and permission mode of new sessions, and extra Claude accounts that share one configuration. A session can move between git worktrees the way it switches branches, so several agents work on separate branches at once: the worktree button in the top bar switches the shown session into another worktree, or into a new one that Claudiu makes on a branch you name, and its conversation continues there. Its hover x removes a worktree, the branch button's x deletes a local branch after telling you which commits would be lost, and ending the last session in a worktree offers to remove it. Claudiu keeps the worktrees it makes in its own data folder, outside your repositories, so they never show up in `git status`; Settings has a Worktrees page that lists them to show in the file manager or remove. Settings lists the rest. Ctrl+Shift (Cmd+Shift on macOS) plus a letter drives the app. Everything else reaches Claude Code. Editor mode finds `rust-analyzer`, `tsc --lsp` and `gleam` on your PATH and installs nothing. ## What it touches -Claudiu never deletes a transcript. It writes to Claude Code's own data only to change the settings you switch in Claudiu, as `/config` does, and to sync shared files between accounts. Nothing is uploaded and terminal contents are never logged. The only network use is GitHub: the update check (off with `"settings": { "update_url": "" }` in `state.json`) and the GitHub pane. State lives in `%LOCALAPPDATA%\m4rocks\Claudiu\data` on Windows, `~/Library/Application Support/Claudiu` on macOS and `~/.local/share/claudiu` on Linux, and crashes go to `crash.log` there. +Claudiu never deletes a transcript. It writes to Claude Code's own data only to change the settings you switch in Claudiu, as `/config` does, to sync shared files between accounts, and to append one line to a transcript when a session that `claude --worktree` put in a worktree moves to another folder, so Claude Code knows it has left that worktree. Nothing is uploaded and terminal contents are never logged. The only network use is GitHub: the update check (off with `"settings": { "update_url": "" }` in `state.json`) and the GitHub pane. State lives in `%LOCALAPPDATA%\m4rocks\Claudiu\data` on Windows, `~/Library/Application Support/Claudiu` on macOS and `~/.local/share/claudiu` on Linux, and crashes go to `crash.log` there. ## Known gaps diff --git a/src/app/background.rs b/src/app/background.rs index 7bcc650..c7df825 100644 --- a/src/app/background.rs +++ b/src/app/background.rs @@ -2,6 +2,18 @@ use super::*; +/// What a Claude session's row shows, given what Claude Code says it is doing, what the row showed before, and +/// whether the user is looking at it. A question is shown even to someone looking at it, since only they can answer; +/// a finished turn is shown only to someone who was elsewhere and clears once they look. +fn next_activity(working: bool, waiting: bool, before: Option, viewing: bool) -> Option { + match (working, waiting, before) { + (true, _, _) => Some(Activity::Working), + (false, true, _) => Some(Activity::Waiting), + (false, false, Some(Activity::Working | Activity::Attention)) if !viewing => Some(Activity::Attention), + _ => None, + } +} + impl Workspace { /// Startup reconciliation: scan Claude Code's records off the UI thread, then merge. pub fn start_scan(&mut self, cx: &mut Context) { @@ -46,21 +58,21 @@ impl Workspace { .detach(); } - /// While a session works, its sidebar dot pulses: the session list is redrawn a few times a second (with the + /// While a session works, its sidebar icon spins: the session list is redrawn many times a second (with the /// window's top level, which reuses the other cached parts). It stops once nothing works. - fn start_pulse(&mut self, cx: &mut Context) { - if self.pulsing { + fn start_spin(&mut self, cx: &mut Context) { + if self.spinning { return; } - self.pulsing = true; + self.spinning = true; cx.spawn(async move |this, cx| { loop { - cx.background_executor().timer(crate::panels::sidebar::PULSE_STEP).await; + cx.background_executor().timer(crate::panels::status_icon::SPIN_STEP).await; let working = this.update(cx, |ws, cx| { let working = ws.activity.values().any(|a| *a == Activity::Working); match &ws.session_list { Some(list) if working => list.update(cx, |_, cx| cx.notify()), - _ => ws.pulsing = working, + _ => ws.spinning = working, } working }); @@ -118,18 +130,12 @@ impl Workspace { let viewing = window_active && shown.as_deref() == Some(l.id.as_str()); let status = self.store.session(&l.id).and_then(|r| statuses.get(r.claude_id()?)); let working = status.map_or_else(|| view.is_working(), |s| s == "busy"); - match (working, self.activity.get(&l.id)) { - (true, _) => { - next.insert(l.id.clone(), Activity::Working); - } - (false, Some(Activity::Working)) if !viewing => { - flash |= !window_active; - next.insert(l.id.clone(), Activity::Attention); - } - (false, Some(Activity::Attention)) if !viewing => { - next.insert(l.id.clone(), Activity::Attention); - } - _ => {} + let waiting = status.is_some_and(|s| s == "waiting"); + let before = self.activity.get(&l.id).copied(); + let now = next_activity(working, waiting, before, viewing); + flash |= !window_active && before == Some(Activity::Working) && matches!(now, Some(Activity::Attention | Activity::Waiting)); + if let Some(now) = now { + next.insert(l.id.clone(), now); } } if next != self.activity { @@ -137,7 +143,7 @@ impl Workspace { cx.notify(); } if self.activity.values().any(|a| *a == Activity::Working) { - self.start_pulse(cx); + self.start_spin(cx); } if flash { platform::request_attention(window); @@ -287,3 +293,36 @@ impl Workspace { crate::updater::check(self, cx); } } + +#[cfg(test)] +mod tests { + use super::{Activity, next_activity}; + + #[test] + fn busy_is_working_whatever_came_before() { + for before in [None, Some(Activity::Working), Some(Activity::Waiting), Some(Activity::Attention)] { + assert_eq!(next_activity(true, false, before, true), Some(Activity::Working)); + assert_eq!(next_activity(true, false, before, false), Some(Activity::Working)); + } + } + + #[test] + fn a_question_shows_even_to_someone_looking_at_the_session() { + assert_eq!(next_activity(false, true, Some(Activity::Working), true), Some(Activity::Waiting)); + assert_eq!(next_activity(false, true, None, false), Some(Activity::Waiting)); + } + + #[test] + fn a_finished_turn_waits_to_be_seen_and_clears_once_looked_at() { + assert_eq!(next_activity(false, false, Some(Activity::Working), false), Some(Activity::Attention)); + assert_eq!(next_activity(false, false, Some(Activity::Attention), false), Some(Activity::Attention)); + assert_eq!(next_activity(false, false, Some(Activity::Working), true), None); + assert_eq!(next_activity(false, false, Some(Activity::Attention), true), None); + } + + #[test] + fn an_idle_session_nobody_is_owed_news_from_shows_nothing() { + assert_eq!(next_activity(false, false, None, false), None); + assert_eq!(next_activity(false, false, Some(Activity::Waiting), false), None); + } +} diff --git a/src/app/editor_mode.rs b/src/app/editor_mode.rs index b7908c1..0784954 100644 --- a/src/app/editor_mode.rs +++ b/src/app/editor_mode.rs @@ -241,7 +241,8 @@ impl Workspace { /// List the shown session's folder again (files Claude added, changed marks), off the UI thread. pub(super) fn refresh_files(&mut self, cx: &mut Context) { let Some(id) = self.active_id().filter(|_| self.editor_mode).cloned() else { return }; - let Some(root) = self.store.session(&id).map(|s| s.cwd.clone()) else { return }; + // A worktree that Claude Code is still making has no folder to list yet. + let Some(root) = self.store.session(&id).map(|s| s.cwd.clone()).filter(|root| root.is_dir()) else { return }; let Some(pane) = self.panes.get_mut(&id) else { return }; if pane.listing { pane.relist = true; @@ -257,6 +258,7 @@ impl Workspace { let relist = std::mem::take(&mut pane.relist); pane.changed = std::sync::Arc::new(listing.changed); pane.truncated = listing.truncated; + let moved = !pane.root.as_os_str().is_empty() && pane.root != listing.root; pane.root = listing.root; if pane.nodes != listing.nodes { let items = tree_items(&listing.nodes, &pane.expanded); @@ -273,6 +275,13 @@ impl Workspace { pane.files = std::sync::Arc::new(all); pane.nodes = listing.nodes; } + if moved { + // The session went to another folder: the old watcher watches the wrong one. + if let Some(pane) = ws.panes.get_mut(&id) { + pane.watcher = None; + } + ws.watch_folder(&id, cx); + } if relist { ws.refresh_files(cx); } diff --git a/src/app/handoff.rs b/src/app/handoff.rs index 1dbb78d..894ff9d 100644 --- a/src/app/handoff.rs +++ b/src/app/handoff.rs @@ -60,7 +60,7 @@ impl Workspace { let to_name = self.store.active_account().map_or_else(|| "the active account".into(), |a| a.name()); let since = Instant::now(); self.handoffs.insert(id.into(), Handoff { asked: crate::store::now(), compacted: false, since }); - self.set_handover(id, Some(Handover { to: to_name, since }), cx); + self.set_handover(id, Some(Handover { message: format!("Handing over to {to_name}…"), since }), cx); usage::send_ctl(&usage::ctl_file(id), "compact", serde_json::json!(true)); } @@ -106,11 +106,11 @@ impl Workspace { } self.restart_session(id, window, cx); let to_name = self.store.active_account().map_or_else(|| "the active account".into(), |a| a.name()); - self.set_handover(id, Some(Handover { to: to_name, since }), cx); + self.set_handover(id, Some(Handover { message: format!("Handing over to {to_name}…"), since }), cx); } /// The skeleton says "Handing over to …" while this is set; the new process clears it once its prompt is ready. - fn set_handover(&self, id: &str, handover: Option, cx: &mut App) { + pub(super) fn set_handover(&self, id: &str, handover: Option, cx: &mut App) { if let Some(view) = self.live_view(id) { view.update(cx, |v, cx| { v.handover = handover; diff --git a/src/app/headless.rs b/src/app/headless.rs index 6150b5b..1eaa57b 100644 --- a/src/app/headless.rs +++ b/src/app/headless.rs @@ -88,6 +88,8 @@ fn run() { serve(&mut cx, take()); assert!(h.join().unwrap().unwrap().contains("latest terminal output")); step(&mut cx, &|ws, w, cx| ws.close_live(&id, w, cx)); + // Closing goes to the home screen; the ended session is picked from the sidebar. + step(&mut cx, &|ws, w, cx| ws.act(Act::Select(id.clone()), w, cx)); } /// Sessions, the shell panel and the GitHub view, with the real `claude` and shell but no model calls. @@ -1221,6 +1223,363 @@ fn the_session_list_draws_rows_where_scrolling_brings_them() { assert!(after > before + 20, "row {before} before scrolling, {after} after"); } +/// The worktree dialog and the switch of a session between worktrees, with a stand-in for `claude`, so what Claude Code +/// does in the new folder is not checked. +fn switching_between_worktrees_in_the_workspace() { + let data = tempfile::tempdir().unwrap(); + // SAFETY: set before any other thread reads the environment; this test owns the process. + unsafe { std::env::set_var("CLAUDIU_DATA_DIR", data.path()) }; + // Claude Code's data directory, where the conversation of a session is looked for. + let home = tempfile::tempdir().unwrap(); + // SAFETY: as above. + unsafe { std::env::set_var("CLAUDE_CONFIG_DIR", home.path()) }; + let work = tempfile::tempdir().unwrap(); + let repo_dir = dunce::canonicalize(work.path()).unwrap().join("proj"); + let repo = git2::Repository::init(&repo_dir).unwrap(); + { + let sig = git2::Signature::now("t", "t@t").unwrap(); + let tree = repo.find_tree(repo.index().unwrap().write_tree().unwrap()).unwrap(); + repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[]).unwrap(); + } + let mut cx = TestAppContext::single(); + cx.update(|app| { + gpui_kit::init(app); + gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, app); + }); + let initial = vec![repo_dir.clone()]; + let (window, ws) = cx + .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| Workspace::new(window, initial, cx)))) + .unwrap(); + let step = |cx: &mut TestAppContext, f: &dyn Fn(&mut Workspace, &mut Window, &mut Context)| { + let t = std::time::Instant::now(); + cx.update_window(window, |_, window, app| ws.update(app, |ws, cx| f(ws, window, cx))).unwrap(); + let acted = t.elapsed(); + for _ in 0..2 { + cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); + cx.run_until_parked(); + } + assert!(acted < Duration::from_millis(400), "the window was blocked for {acted:?}"); + }; + + let wait = |cx: &mut TestAppContext, what: &str, done: &dyn Fn(&Workspace, &App) -> bool| { + let t = std::time::Instant::now(); + let mut said = None; + while !ws.read_with(cx, |ws, app| done(ws, app)) { + said = ws.read_with(cx, |ws, _| ws.toast.as_ref().map(|t| t.text.clone())).or(said); + assert!(t.elapsed() < Duration::from_secs(30), "{what} never happened; the last toast said {said:?}"); + std::thread::sleep(Duration::from_millis(100)); + cx.executor().advance_clock(Duration::from_millis(100)); + cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); + cx.run_until_parked(); + } + }; + let active = |ws: &Workspace| ws.store.session(ws.active.as_ref().unwrap()).unwrap().clone(); + // A stand-in for `claude` that shows a line and stays up whatever it is asked, since a real one would end at once on + // a conversation that is not its own. + let fake = work.path().join(if cfg!(windows) { "claude.cmd" } else { "claude" }); + std::fs::write(&fake, if cfg!(windows) { "@echo off\r\necho ready\r\nping -n 120 127.0.0.1 >nul\r\n" } else { "#!/bin/sh\necho ready\nsleep 120\n" }).unwrap(); + #[cfg(unix)] + std::fs::set_permissions(&fake, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap(); + ws.update(&mut cx, |ws, _| ws.claude_exe = Some(fake.clone())); + + // A new session starts in the main checkout. The menu is there but cannot switch until a session runs. + step(&mut cx, &|ws, w, cx| ws.act(Act::NewClaude { cwd: repo_dir.clone() }, w, cx)); + assert!(ws.read_with(&cx, |ws, _| ws.modal.is_none() && ws.live.len() == 1)); + let session = ws.read_with(&cx, |ws, _| active(ws)); + assert_eq!(session.cwd, repo_dir); + // The conversation exists once Claude Code has had a prompt; the test stands one in, in Claude Code's own place. + let claude_id = session.claude_id().unwrap().to_string(); + let transcript = home.path().join("projects/p").join(format!("{claude_id}.jsonl")); + std::fs::create_dir_all(transcript.parent().unwrap()).unwrap(); + std::fs::write(&transcript, "{\"type\":\"user\"} +").unwrap(); + wait(&mut cx, "the first screen", &|ws, app| ws.live.iter().all(|l| !l.view.read(app).is_loading() && !l.view.read(app).is_working())); + + // Files open in the editor when the session moves: two are committed, so the new worktree has them, and one is + // ignored, so it only exists in the main checkout. + let cli = |args: &[&str]| assert!(std::process::Command::new("git").args(["-c", "user.name=t", "-c", "user.email=t@t"]).args(args).current_dir(&repo_dir).status().unwrap().success()); + std::fs::write(repo_dir.join(".gitignore"), "only_main.txt\n").unwrap(); + std::fs::write(repo_dir.join("same.txt"), "committed\n").unwrap(); + std::fs::write(repo_dir.join("dirty.txt"), "committed\n").unwrap(); + std::fs::write(repo_dir.join("only_main.txt"), "ignored\n").unwrap(); + cli(&["add", "."]); + cli(&["commit", "-q", "-m", "files"]); + let id = session.id.clone(); + step(&mut cx, &|ws, w, cx| ws.toggle_editor(w, cx)); + wait(&mut cx, "listing the folder", &|ws, _| ws.panes.get(&id).is_some_and(|p| p.nodes.iter().any(|n| n.name == "same.txt"))); + for name in ["same.txt", "dirty.txt", "only_main.txt"] { + step(&mut cx, &|ws, w, cx| ws.open_file(&id, repo_dir.join(name), None, w, cx)); + } + wait(&mut cx, "the three tabs", &|ws, _| ws.panes[&id].tabs.len() == 3); + step(&mut cx, &|ws, w, cx| { + let tab = ws.panes[&id].tabs.iter().find(|t| t.path.ends_with("dirty.txt")).unwrap(); + tab.buffer.clone().update(cx, |b, cx| b.replace_all("edited\n", w, cx)); + }); + assert!(ws.read_with(&cx, |ws, _| ws.panes[&id].tabs.iter().any(|t| t.path.ends_with("dirty.txt") && t.dirty)), "the edit marks the tab"); + let tab_paths = |ws: &Workspace| ws.panes[&id].tabs.iter().map(|t| t.path.clone()).collect::>(); + let canonical = |p: &std::path::Path| dunce::canonicalize(p).unwrap(); + assert_eq!(ws.read_with(&cx, |ws, _| ws.panes[&id].root.clone()), canonical(&repo_dir), "the file tree starts at the main checkout"); + + // A shell is open under the session at a height of the user's choosing. + step(&mut cx, &|ws, w, cx| { + ws.toggle_shell(&id, w, cx); + ws.shells.get_mut(&id).unwrap().height = 333.0; + }); + let shell = |ws: &Workspace| ws.shells.get(&id).map(|p| (p.view.entity_id(), p.open, p.height)); + let (shell_before, ..) = ws.read_with(&cx, |ws, _| shell(ws)).unwrap(); + + // A bad name keeps the dialog open; a typed one moves the session into the worktree Claude Code will make. + step(&mut cx, &|ws, w, cx| ws.act(Act::NewWorktree(repo_dir.clone()), w, cx)); + step(&mut cx, &|ws, w, cx| { + let Some(Modal::NewWorktree { input, .. }) = &ws.modal else { panic!("no dialog") }; + input.clone().update(cx, |i, cx| i.set_value("bad name", w, cx)); + ws.submit_modal(w, cx); + }); + assert!(ws.read_with(&cx, |ws, _| matches!(ws.modal, Some(Modal::NewWorktree { .. }))), "a bad name is refused"); + step(&mut cx, &|ws, w, cx| { + let Some(Modal::NewWorktree { input, .. }) = &ws.modal else { panic!("no dialog") }; + input.clone().update(cx, |i, cx| i.set_value("fix-login", w, cx)); + ws.act(Act::PickBase(crate::git::worktree::Base::Current), w, cx); + ws.submit_modal(w, cx); + }); + let worktree = crate::git::worktree::folder(&repo_dir, "fix-login"); + let skeleton = |ws: &Workspace, app: &App| ws.live_view(&session.id).and_then(|v| v.read(app).handover.as_ref().map(|h| h.message.clone())); + assert_eq!(ws.read_with(&cx, |ws, app| skeleton(ws, app)).as_deref(), Some("Switching to fix-login…"), "the skeleton names the worktree"); + // The grid the pane draws terminals on. A new terminal starts at a default size until it is first laid out. + let grid = ws.read_with(&cx, |ws, app| ws.live_view(&session.id).unwrap().read(app).terminal.size()); + assert_ne!(grid, (120, 32), "the window must not happen to match the default size"); + // Until the new process is up, the session stays shown and running behind its skeleton, never an empty pane, and + // the skeleton sits on the pane's grid from the first frame on. + let moved_to = |folder: &std::path::Path, ws: &Workspace, app: &App| { + let loading = ws.live_view(&session.id).is_some_and(|v| v.read(app).is_loading()); + assert_eq!(ws.live_view(&session.id).map(|v| v.read(app).terminal.size()), Some(grid), "mid-switch the skeleton is on another grid"); + assert!(ws.active.as_ref() == Some(&session.id) && ws.is_running(&session.id, app), "mid-switch the session is not shown running"); + let moved = ws.store.session(&session.id).is_some_and(|r| r.cwd == folder); + assert!(loading || moved, "mid-switch the pane has no skeleton"); + moved && !loading + }; + wait(&mut cx, "the switch", &|ws, app| moved_to(&worktree, ws, app)); + let branch = std::process::Command::new("git").args(["branch", "--show-current"]).current_dir(&worktree).output().unwrap(); + assert_eq!(String::from_utf8_lossy(&branch.stdout).trim(), "fix-login", "the branch is named as typed"); + assert_eq!(ws.read_with(&cx, |ws, _| ws.live.len()), 1, "the same session, not a new one"); + assert_eq!(ws.read_with(&cx, |ws, _| active(ws).id), session.id); + assert_eq!(ws.read_with(&cx, |ws, _| active(ws).claude_id().map(str::to_string)), Some(claude_id.clone()), "the same conversation"); + assert_eq!(std::fs::read_to_string(&transcript).unwrap().lines().count(), 1, "making a worktree writes nothing to the conversation"); + + // The shell is a new one, open and as tall as before. + let (shell_now, open, height) = ws.read_with(&cx, |ws, _| shell(ws)).expect("the session still has a shell"); + assert!(shell_now != shell_before && open && height == 333.0, "a fresh shell, open at {height}"); + + // The editor follows the session: a clean tab whose file the worktree has moves with it, one with unsaved edits or + // whose file the worktree lacks stays where it was and the user is told, and the file tree shows the worktree. + let (in_worktree, in_main) = (canonical(&worktree), canonical(&repo_dir)); + assert_eq!(ws.read_with(&cx, |ws, _| tab_paths(ws)), [in_worktree.join("same.txt"), in_main.join("dirty.txt"), in_main.join("only_main.txt")], "tabs after the switch"); + assert!(ws.read_with(&cx, |ws, _| ws.toast.as_ref().is_some_and(|t| t.text.contains("2 open files stay"))), "the toast counts the tabs that stayed"); + wait(&mut cx, "the file tree at the worktree", &|ws, _| ws.panes[&id].root == in_worktree && ws.panes[&id].nodes.iter().any(|n| n.name == "same.txt")); + assert_eq!(ws.read_with(&cx, |ws, _| ws.panes[&id].tabs.iter().find(|t| t.path.ends_with("dirty.txt")).map(|t| t.dirty)), Some(true), "the unsaved edit is kept"); + + // The worktree is outside the repository, so git has nothing to list there and no .gitignore line is offered. + let status = std::process::Command::new("git").args(["status", "--porcelain"]).current_dir(&repo_dir).output().unwrap(); + assert!(status.stdout.is_empty(), "the main checkout is unchanged: {}", String::from_utf8_lossy(&status.stdout)); + assert!(ws.read_with(&cx, |ws, _| ws.toast.as_ref().is_none_or(|t| t.action.is_none())), "no toast offers anything"); + + // Back to the main checkout, as a session that `claude --worktree` put in the worktree: Claude Code's record of the + // worktree would win over the folder, so one line is appended. + std::fs::write(worktree.join("wip.txt"), "x").unwrap(); + std::fs::write(&transcript, "{\"type\":\"user\"} +{\"type\":\"worktree-state\",\"worktreeSession\":{\"worktreeName\":\"fix-login\"},\"sessionId\":\"x\"} +").unwrap(); + wait(&mut cx, "the first screen again", &|ws, app| ws.live.iter().all(|l| !l.view.read(app).is_loading() && !l.view.read(app).is_working())); + step(&mut cx, &|ws, w, cx| ws.act(Act::SwitchWorktree { folder: repo_dir.clone(), base: Default::default() }, w, cx)); + // The work file stays in the worktree the session leaves, so it asks first. + wait(&mut cx, "the question", &|ws, _| matches!(&ws.modal, Some(Modal::Confirm { body, .. }) if body.contains("1 uncommitted file stays"))); + step(&mut cx, &|ws, w, cx| ws.act(Act::Dismiss, w, cx)); + assert!(ws.read_with(&cx, |ws, app| ws.modal.is_none() && skeleton(ws, app).is_none() && active(ws).cwd == worktree), "cancelling leaves the session where it was, with no skeleton"); + step(&mut cx, &|ws, w, cx| ws.act(Act::SwitchWorktree { folder: repo_dir.clone(), base: Default::default() }, w, cx)); + wait(&mut cx, "the question again", &|ws, _| matches!(&ws.modal, Some(Modal::Confirm { .. }))); + step(&mut cx, &|ws, w, cx| ws.submit_modal(w, cx)); + assert_eq!(ws.read_with(&cx, |ws, app| skeleton(ws, app)).as_deref(), Some("Switching to the main checkout…")); + wait(&mut cx, "the switch back", &|ws, app| moved_to(&repo_dir, ws, app)); + // The tab that moved into the worktree moves back; the ones that stayed in the main checkout are not under the + // tree's root any more, so they stay. + assert_eq!(ws.read_with(&cx, |ws, _| tab_paths(ws)), [in_main.join("same.txt"), in_main.join("dirty.txt"), in_main.join("only_main.txt")], "tabs after the switch back"); + wait(&mut cx, "the file tree at the main checkout", &|ws, _| ws.panes[&id].root == in_main); + assert!(!crate::claude::worktree_recorded(&transcript).unwrap(), "the transcript no longer names the worktree"); + assert!(std::fs::read_to_string(&transcript).unwrap().lines().count() == 3); + + // A restart (a switch, a hand-off) puts the new terminal on the pane's grid before its first frame, which is drawn + // before the terminal is laid out: on a default grid the skeleton's prompt would jump to the middle for a frame. + step(&mut cx, &|ws, w, cx| { + ws.restart_session(&session.id, w, cx); + assert_eq!(ws.live_view(&session.id).map(|v| v.read(cx).terminal.size()), Some(grid), "the new terminal starts on another grid"); + }); + wait(&mut cx, "the restart", &|ws, app| ws.live_view(&session.id).is_some_and(|v| !v.read(app).is_loading())); + + // Mid-turn nothing changes: a session that has not shown its first screen is not idle. + step(&mut cx, &|ws, w, cx| ws.act(Act::SwitchWorktree { folder: worktree.clone(), base: Default::default() }, w, cx)); + // Either the check ran before the screen was ready (told to wait) or after (switched); it never half-switches. + wait(&mut cx, "a settled state", &|ws, app| ws.is_running(&session.id, app) && ws.live_view(&session.id).is_some_and(|v| !v.read(app).is_loading())); + + // A project without commits has a disabled "New worktree…". + let bare = dunce::canonicalize(work.path()).unwrap().join("bare"); + git2::Repository::init(&bare).unwrap(); + let bare_project = ws.update(&mut cx, |ws, _| ws.store.add_project(&bare)); + let bare_cwd = bare.clone(); + let at = crate::panels::widgets::Dropdown { pos: gpui::point(gpui::px(100.0), gpui::px(30.0)), min_w: gpui::px(0.0) }; + step(&mut cx, &|ws, _w, cx| ws.open_worktree_menu(bare_project.clone(), bare_cwd.clone(), crate::panels::widgets::Dropdown { pos: at.pos, min_w: at.min_w }, cx)); + let last = ws.read_with(&cx, |ws, _| ws.menu.as_ref().and_then(|m| m.items.last().map(|i| (i.label.clone(), i.disabled, i.hint.clone())))); + assert!(matches!(&last, Some((label, true, Some(hint))) if label == "New worktree…" && hint.contains("no commits")), "{last:?}"); +} + +#[test] +#[ignore] +fn switching_between_worktrees() { + let t = std::thread::spawn(switching_between_worktrees_in_the_workspace); + let start = std::time::Instant::now(); + while !t.is_finished() { + assert!(start.elapsed() < Duration::from_secs(120), "the workspace froze"); + std::thread::sleep(Duration::from_millis(100)); + } + t.join().unwrap(); +} + +/// A running session refuses the removal of its worktree. Ending it offers the removal, and confirming removes the folder +/// (with a real `claude` running in it until the session ends, which on Windows holds the folder until the process is gone). +fn removing_a_worktree_when_its_session_ends() { + let data = tempfile::tempdir().unwrap(); + // SAFETY: set before any other thread reads the environment; this test owns the process. + unsafe { std::env::set_var("CLAUDIU_DATA_DIR", data.path()) }; + let work = tempfile::tempdir().unwrap(); + let repo_dir = dunce::canonicalize(work.path()).unwrap().join("proj"); + let git = |args: &[&str]| std::process::Command::new("git").args(args).current_dir(&repo_dir).output().unwrap(); + std::fs::create_dir_all(&repo_dir).unwrap(); + for args in [&["init", "-q", "-b", "main"][..], &["config", "user.email", "t@t"], &["config", "user.name", "t"], &["commit", "-q", "--allow-empty", "-m", "one"]] { + git(args); + } + let folder = crate::git::worktree::folder(&repo_dir, "fix"); + let added = git(&["worktree", "add", "-q", "-b", "worktree-fix", &folder.to_string_lossy()]); + assert!(added.status.success(), "{}", String::from_utf8_lossy(&added.stderr)); + + let mut cx = TestAppContext::single(); + cx.update(|app| { + gpui_kit::init(app); + gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, app); + }); + let initial = vec![repo_dir.clone()]; + let (window, ws) = cx + .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| Workspace::new(window, initial, cx)))) + .unwrap(); + let step = |cx: &mut TestAppContext, f: &dyn Fn(&mut Workspace, &mut Window, &mut Context)| { + cx.update_window(window, |_, window, app| ws.update(app, |ws, cx| f(ws, window, cx))).unwrap(); + for _ in 0..2 { + cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); + cx.run_until_parked(); + } + }; + let wait = |cx: &mut TestAppContext, what: &str, done: &dyn Fn(&Workspace) -> bool| { + let t = std::time::Instant::now(); + while !ws.read_with(cx, |ws, _| done(ws)) { + assert!(t.elapsed() < Duration::from_secs(30), "{what} never happened: {:?}", ws.read_with(cx, |ws, _| ws.toast.as_ref().map(|t| t.text.clone()))); + std::thread::sleep(Duration::from_millis(100)); + cx.executor().advance_clock(Duration::from_millis(100)); + cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); + cx.run_until_parked(); + } + }; + // The worktree is known to the project once git has been read again. + step(&mut cx, &|ws, _w, _cx| ws.store.refresh_git()); + // A new session never starts inside a worktree; Fix-with-Claude is the one starter that keeps the folder it is given. + step(&mut cx, &|ws, w, cx| ws.new_claude_with(folder.clone(), vec![], crate::claude::defaults::Starter::FixGit, w, cx)); + let id = ws.read_with(&cx, |ws, _| ws.active.clone().unwrap()); + + // Any other way of starting a session, asked to start inside the worktree, starts in the main checkout. + step(&mut cx, &|ws, w, cx| ws.new_claude(folder.clone(), w, cx)); + let (other, started_in) = ws.read_with(&cx, |ws, _| (ws.active.clone().unwrap(), ws.store.session(ws.active.as_ref().unwrap()).unwrap().cwd.clone())); + assert_eq!(started_in, repo_dir); + step(&mut cx, &|ws, w, cx| ws.close_live(&other, w, cx)); + step(&mut cx, &|ws, w, cx| ws.act(Act::Select(id.clone()), w, cx)); + + // The top-bar menu offers the removal for the session's own worktree, and not in the main checkout. + let project = ws.read_with(&cx, |ws, _| ws.store.data.projects[0].id.clone()); + let menu_of = |cx: &mut TestAppContext, cwd: PathBuf| { + let at = crate::panels::widgets::Dropdown { pos: gpui::point(gpui::px(100.0), gpui::px(30.0)), min_w: gpui::px(0.0) }; + step(cx, &|ws, _w, cx| ws.open_worktree_menu(project.clone(), cwd.clone(), crate::panels::widgets::Dropdown { pos: at.pos, min_w: at.min_w }, cx)); + // Each row's label and whether it has an x. + ws.read_with(cx, |ws, _| ws.menu.as_ref().map(|m| m.items.iter().map(|i| (i.label.trim().to_string(), i.remove.is_some())).collect::>()).unwrap_or_default()) + }; + for cwd in [folder.clone(), repo_dir.clone()] { + let rows = menu_of(&mut cx, cwd); + assert_eq!(rows[0].0, "Worktrees"); + assert!(rows[1].0.contains("main checkout") && !rows[1].1, "the main checkout has no x: {rows:?}"); + assert!(rows[2].0.contains("fix") && rows[2].1, "the worktree has an x: {rows:?}"); + assert!(rows.last().is_some_and(|r| r.0 == "New worktree…" && !r.1), "{rows:?}"); + } + + // The x on the worktree a session is running in is refused, naming the session. + let own_x = ws.read_with(&cx, |ws, _| ws.menu.as_ref().and_then(|m| m.items[2].remove.clone())); + let Some(x) = own_x else { panic!("no x on the worktree's row") }; + step(&mut cx, &|ws, w, cx| ws.act(x.clone(), w, cx)); + let toast = ws.read_with(&cx, |ws, _| ws.toast.as_ref().map(|t| t.text.clone())); + assert!(toast.as_deref().is_some_and(|t| t.contains("is in fix. Switch it to main first.")), "{toast:?}"); + assert!(folder.exists() && ws.read_with(&cx, |ws, _| ws.modal.is_none() && ws.live.len() == 1), "nothing changes"); + + // Ending the session by itself offers the removal. + step(&mut cx, &|ws, w, cx| ws.close_live(&id, w, cx)); + wait(&mut cx, "the offer", &|ws| matches!(&ws.modal, Some(Modal::Confirm { act: Act::ConfirmRemoveWorktree { .. }, .. }))); + step(&mut cx, &|ws, w, cx| ws.submit_modal(w, cx)); + wait(&mut cx, "the folder to go", &|_| !folder.exists()); + let toast = ws.read_with(&cx, |ws, _| ws.toast.as_ref().map(|t| t.text.clone())); + assert!(toast.as_deref().is_some_and(|t| t.contains("Removed worktree fix")), "{toast:?}"); + assert!(!git(&["rev-parse", "--verify", "-q", "worktree-fix"]).status.success(), "the merged branch went with it"); + + // The branch menu has a title and an x on every local branch but the current one. + assert!(git(&["branch", "spare"]).status.success()); + let at = crate::panels::widgets::Dropdown { pos: gpui::point(gpui::px(100.0), gpui::px(30.0)), min_w: gpui::px(0.0) }; + step(&mut cx, &|ws, _w, cx| ws.open_branch_menu(repo_dir.clone(), crate::panels::widgets::Dropdown { pos: at.pos, min_w: at.min_w }, cx)); + wait(&mut cx, "the branch menu", &|ws| ws.menu.is_some()); + let rows = ws.read_with(&cx, |ws, _| ws.menu.as_ref().map(|m| m.items.iter().map(|i| (i.label.trim().to_string(), i.remove.clone())).collect::>()).unwrap_or_default()); + assert_eq!(rows[0].0, "Branches"); + let spare = rows.iter().find(|r| r.0 == "spare").and_then(|r| r.1.clone()); + assert!(spare.is_some(), "a local branch has an x: {rows:?}"); + assert!(rows.iter().find(|r| r.0.starts_with('✓')).is_some_and(|r| r.1.is_none()), "the current branch has none: {rows:?}"); + + let x = spare.unwrap(); + step(&mut cx, &|ws, w, cx| ws.act(x.clone(), w, cx)); + wait(&mut cx, "the question", &|ws| matches!(&ws.modal, Some(Modal::Confirm { confirm, .. }) if confirm == "Delete")); + step(&mut cx, &|ws, w, cx| ws.submit_modal(w, cx)); + wait(&mut cx, "the branch to go", &|_| !git(&["rev-parse", "--verify", "-q", "spare"]).status.success()); + + // Settings lists the worktrees in Claudiu's data folder. Removing one asks inside the page, so the dialog stays open. + let listed = crate::git::worktree::folder(&repo_dir, "listed"); + assert!(git(&["worktree", "add", "-q", "-b", "listed", &listed.to_string_lossy()]).status.success()); + step(&mut cx, &|ws, w, cx| { + ws.act(Act::OpenSettings, w, cx); + ws.set_settings_page(SettingsPage::Worktrees, cx); + }); + let shown = |ws: &Workspace| ws.worktrees_page.stored.as_ref().is_some_and(|s| s.iter().any(|w| w.folder == listed)); + wait(&mut cx, "the page to list it", &shown); + let main_checkout = repo_dir.clone(); + step(&mut cx, &|ws, w, cx| ws.act(Act::RemoveWorktree { main_checkout: main_checkout.clone(), folder: listed.clone() }, w, cx)); + wait(&mut cx, "the question in the page", &|ws| ws.worktrees_page.asking.as_ref().is_some_and(|a| a.folder == listed)); + assert!(ws.read_with(&cx, |ws, _| matches!(ws.modal, Some(Modal::Settings { .. }))), "the dialog stays open"); + let confirm = ws.read_with(&cx, |ws, _| ws.worktrees_page.asking.as_ref().unwrap().act.clone()); + step(&mut cx, &|ws, w, cx| ws.act(confirm.clone(), w, cx)); + wait(&mut cx, "the folder to go", &|_| !listed.exists()); + wait(&mut cx, "the page to drop it", &|ws| !shown(ws)); +} + +#[test] +#[ignore] +fn removing_a_worktree() { + let t = std::thread::spawn(removing_a_worktree_when_its_session_ends); + let start = std::time::Instant::now(); + while !t.is_finished() { + assert!(start.elapsed() < Duration::from_secs(120), "the workspace froze"); + std::thread::sleep(Duration::from_millis(100)); + } + t.join().unwrap(); +} + /// With no `claude` found, starting a session says so and offers the setup window; asking for it twice shows one. #[test] #[ignore] diff --git a/src/app/layout.rs b/src/app/layout.rs index d644c1c..148a125 100644 --- a/src/app/layout.rs +++ b/src/app/layout.rs @@ -24,29 +24,35 @@ impl Workspace { return; } } else { - let (program, args) = self.shell.clone(); // A session's folder may be gone (temp dirs, deleted worktrees); CreateProcess then fails with "filename syntax is incorrect". let cwd = if rec.cwd.is_dir() { rec.cwd.clone() } else { platform::home_dir().unwrap_or(rec.cwd.clone()) }; - let spec = SpawnSpec { program, args, cwd: Some(cwd), ..Default::default() }; - let (terminal, rx) = TerminalView::spawn(&spec); - let view = cx.new(|cx| TerminalView::new(terminal, rx, cx)); - let owner = id.to_string(); - let sub = cx.subscribe_in(&view, window, move |ws: &mut Workspace, view, ev: &TerminalEvent, window, cx| { - if matches!(ev, TerminalEvent::Exited(_)) { - if let Some(err) = view.read(cx).start_error() { - ws.toast(format!("Could not start the shell: {err}"), true, cx); - } - ws.shells.remove(&owner); - ws.focus_active(window, cx); - cx.notify(); - } - }); - self.shells.insert(id.to_string(), ShellPanel { view, _sub: sub, open: true, height: SHELL_HEIGHT }); + let panel = self.new_shell_panel(id, cwd, window, cx); + self.shells.insert(id.to_string(), panel); } self.focus_shell(window, cx); cx.notify(); } + /// A shell for the session, started in `cwd`. When the shell ends, its panel goes away, with a toast if it never started. + pub(super) fn new_shell_panel(&mut self, id: &str, cwd: PathBuf, window: &mut Window, cx: &mut Context) -> ShellPanel { + let (program, args) = self.shell.clone(); + let spec = SpawnSpec { program, args, cwd: Some(cwd), ..Default::default() }; + let (terminal, rx) = TerminalView::spawn(&spec); + let view = cx.new(|cx| TerminalView::new(terminal, rx, cx)); + let owner = id.to_string(); + let sub = cx.subscribe_in(&view, window, move |ws: &mut Workspace, view, ev: &TerminalEvent, window, cx| { + if matches!(ev, TerminalEvent::Exited(_)) { + if let Some(err) = view.read(cx).start_error() { + ws.toast(format!("Could not start the shell: {err}"), true, cx); + } + ws.shells.remove(&owner); + ws.focus_active(window, cx); + cx.notify(); + } + }); + ShellPanel { view, _sub: sub, open: true, height: SHELL_HEIGHT } + } + fn focus_shell(&self, window: &mut Window, cx: &mut Context) { if let Some(p) = self.active_id().and_then(|id| self.shells.get(id)).filter(|p| p.open) { window.focus(&p.view.read(cx).focus_handle(cx), cx); diff --git a/src/app/mod.rs b/src/app/mod.rs index 971fcc1..7180127 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -19,6 +19,7 @@ use crate::panels::sidebar::{SIDEBAR_MAX, SIDEBAR_MIN, SIDEBAR_W}; use crate::github::view::{GhEvent, GithubView}; use crate::claude::defaults::{Effort, PermissionMode, Starter}; use crate::claude::mcp; +use crate::git::worktree::Base; use crate::platform::{self, Editor}; use crate::{claude::usage, datadir}; use crate::store::{ @@ -58,6 +59,8 @@ mod settings; mod setup; mod titles; mod visuals; +mod switch; +mod worktrees; pub use editor_mode::{EditorPane, Tab, register_languages}; pub use ask_claude::Ask; @@ -65,6 +68,7 @@ pub use lifecycle::saved_window_bounds; pub use editor_mode::EditorCommand; pub use file_ops::NameFor; pub use settings::SettingsPage; +pub use worktrees::WorktreesPage; pub use setup::{Mode as SetupMode, SetupEvent, SetupView, window_options as setup_window_options}; actions!( @@ -111,6 +115,32 @@ pub enum Act { NewClaude { cwd: PathBuf, }, + /// The worktree dialog for a repository's main checkout (see `worktrees.rs`). + NewWorktree(PathBuf), + PickBase(Base), + /// Move the shown session into this working tree of its project (`base` is for a worktree that does not exist yet). + SwitchWorktree { + folder: PathBuf, + base: Base, + }, + /// `SwitchWorktree`, after the user agreed to leave uncommitted files behind. + ConfirmSwitch { + folder: PathBuf, + base: Base, + }, + /// Ask before removing a worktree. A running session in it refuses. + RemoveWorktree { + main_checkout: PathBuf, + folder: PathBuf, + }, + ConfirmRemoveWorktree { + main_checkout: PathBuf, + folder: PathBuf, + discard: bool, + }, + /// Ask before deleting a folder in Claudiu's worktrees folder that git no longer lists. + AskDeleteUnlisted(PathBuf), + ConfirmDeleteUnlisted(PathBuf), /// Show or hide the shell under a Claude session's terminal (started on first use, in the session's folder). ToggleShell(Id), /// Turn editor mode on or off for the shown session (see `editor_mode.rs`). @@ -157,6 +187,9 @@ pub enum Act { CommitPush(Id, PathBuf), Pull(PathBuf), SwitchBranch(PathBuf, String), + /// Read what deleting the local branch would lose, then ask. + DeleteBranch(PathBuf, String), + ConfirmDeleteBranch(PathBuf, String), /// Ask for a name, then `CreateBranch`. NewBranch(PathBuf), CreateBranch(PathBuf, String), @@ -194,7 +227,7 @@ pub enum Act { impl MenuItem { /// A plain entry: not dangerous, enabled, no hint, no separator above. pub fn new(label: impl Into, act: Act) -> Self { - Self { label: label.into(), hint: None, act, danger: false, disabled: false, separator_before: false } + Self { label: label.into(), hint: None, detail: None, act, danger: false, disabled: false, separator_before: false, remove: None, icon: None } } } @@ -202,11 +235,17 @@ pub struct MenuItem { pub label: String, /// Faint text on the right that is never cut, so a long `label` is shortened with "…" instead. pub hint: Option, + /// Faint second line under the label, for text too long to sit beside it (a project path). + pub detail: Option, pub act: Act, pub danger: bool, /// Shown greyed out and does nothing when clicked. pub disabled: bool, pub separator_before: bool, + /// Shows an x on the row while the pointer is over it; clicking it runs this instead of `act`. + pub remove: Option, + /// Drawn before the hint. + pub icon: Option, } pub struct Menu { @@ -240,6 +279,12 @@ pub enum Modal { cwd: PathBuf, input: Entity, }, + /// Empty name = a generated one. + NewWorktree { + main_checkout: PathBuf, + input: Entity, + base: Base, + }, Advisor { id: Id, input: Entity, @@ -273,9 +318,11 @@ pub enum Main { /// What a running Claude session is doing, as shown by its sidebar dot. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Activity { - /// Output is streaming (pulsing dot). + /// Output is streaming (spinning icon). Working, - /// Finished working while the user was looking elsewhere (orange dot). + /// Claude Code stopped to wait for the user, a question or a permission (question mark). + Waiting, + /// Finished working while the user was looking elsewhere (check mark). Attention, } @@ -285,6 +332,7 @@ pub enum GitOp { CommitPush, Pull, Branch, + Worktree, } pub struct Live { @@ -403,6 +451,8 @@ pub struct Workspace { pub modal_focus: FocusHandle, /// The Settings category last shown. Kept here because opening Settings builds the modal anew; not saved to disk. pub settings_page: SettingsPage, + /// What the Worktrees page of Settings shows. Not saved to disk. + pub worktrees_page: worktrees::WorktreesPage, /// Smooth wheel scrolling of the settings page. pub settings_scroll: crate::panels::glide::Smooth, /// Whether this run already said it couldn't write a session's tool settings file (said at most once). @@ -436,10 +486,12 @@ pub struct Workspace { pub list_model: crate::panels::sidebar::ListModel, /// The sidebar row under the pointer, the only one built with its × or archive button. pub hovered_row: Option, + /// Running rows the pointer just left, whose × slot is still shrinking away (see `shrink_close_slot`). + pub unhovered_rows: std::collections::HashSet, /// The minute (Unix time / 60) of the last tick's redraw, see `tick`. pub tick_minute: i64, - /// The working dot's pulse is running, see `start_pulse`. - pub pulsing: bool, + /// The working icon's spin is running, see `start_spin`. + pub spinning: bool, /// When a drag last reordered the sidebar, see `pointer_moved`. pub last_swap: std::time::Instant, /// Attached issues and pull requests are asked about on GitHub from time to time, see `attached_sync.rs`. @@ -521,6 +573,7 @@ impl Workspace { modal: None, modal_focus: cx.focus_handle(), settings_page: SettingsPage::default(), + worktrees_page: Default::default(), settings_scroll: Default::default(), menu: None, toast: None, @@ -544,8 +597,9 @@ impl Workspace { session_list: None, list_model: Default::default(), hovered_row: None, + unhovered_rows: Default::default(), tick_minute: 0, - pulsing: false, + spinning: false, last_swap: std::time::Instant::now(), attached_sync: Default::default(), config_sync: Default::default(), @@ -605,6 +659,31 @@ impl Workspace { self.menu = None; match act { Act::NewClaude { cwd } => self.new_claude(cwd, window, cx), + Act::NewWorktree(main_checkout) => self.ask_worktree(main_checkout, window, cx), + Act::PickBase(choice) => { + if let Some(Modal::NewWorktree { base, .. }) = self.modal.as_mut() { + *base = choice; + } + } + Act::SwitchWorktree { folder, base } => self.switch_shown(folder, base, false, window, cx), + Act::ConfirmSwitch { folder, base } => { + self.modal = None; + self.switch_shown(folder, base, true, window, cx) + } + Act::RemoveWorktree { main_checkout, folder } => self.ask_remove_worktree(main_checkout, folder, cx), + Act::AskDeleteUnlisted(folder) => self.ask_delete_unlisted(folder, cx), + Act::ConfirmDeleteUnlisted(folder) => { + self.worktrees_page.asking = None; + self.run_git(GitOp::Worktree, move || Ok(crate::git::worktree::delete_unlisted(&folder)?), cx); + } + Act::ConfirmRemoveWorktree { main_checkout, folder, discard } => { + self.worktrees_page.asking = None; + self.run_git( + GitOp::Worktree, + move || Ok(crate::git::worktree::remove(&main_checkout, &folder, discard, Duration::from_secs(10))?), + cx, + ); + } Act::ToggleShell(id) => self.toggle_shell(&id, window, cx), Act::ToggleEditor => self.toggle_editor(window, cx), Act::Editor(command) => self.run_editor_command(command, window, cx), @@ -682,6 +761,10 @@ impl Workspace { Act::SwitchBranch(cwd, name) => { self.run_git(GitOp::Branch, move || Ok(crate::git::commit::switch_branch(&cwd, &name)?), cx) } + Act::DeleteBranch(cwd, name) => self.ask_delete_branch(cwd, name, cx), + Act::ConfirmDeleteBranch(cwd, name) => { + self.run_git(GitOp::Branch, move || Ok(crate::git::commit::delete_branch(&cwd, &name)?), cx) + } Act::FixGitWithClaude(cwd) => { let prompt = "Claudiu's Pull or Commit & Push just failed in this repository because of a merge conflict, a diverged branch or a rejected push. Run git status, fix it (resolve conflicts keeping the intent of both sides, finish the merge or rebase, then push if the push was rejected). Ask me whenever a conflict is ambiguous or you are unsure which side to keep."; match self.running_claude_in(&cwd, cx) { @@ -715,6 +798,7 @@ impl Workspace { let shell = self.modal_input(&shell_t, &platform::default_shell(None).0, window, cx); let list_focus = cx.focus_handle(); window.focus(&list_focus, cx); + self.set_settings_page(self.settings_page, cx); self.modal = Some(Modal::Settings { shell, claude, model, effort: defaults.effort, permission: defaults.permission_mode, updates, chrome, scale: crate::panels::scale::percent(), trimmed: self.store.data.settings.trimmed_tools.clone(), claudiu_off: self.store.data.settings.claudiu_tools_off.clone(), list_focus }); } Act::PickEffort(choice) => { diff --git a/src/app/modal.rs b/src/app/modal.rs index 21db4d1..e801849 100644 --- a/src/app/modal.rs +++ b/src/app/modal.rs @@ -1,6 +1,7 @@ //! Overlays: toasts, the context menu, input modals, the editor choice and the project import. use super::*; +use crate::git::worktree; use crate::panels::widgets::Dropdown; impl Workspace { @@ -91,6 +92,22 @@ impl Workspace { let name = input.read(cx).value().split_whitespace().collect::>().join("-"); if name.is_empty() { Act::Dismiss } else { Act::CreateBranch(cwd, name) } } + Some(Modal::NewWorktree { main_checkout, input, base }) => { + let typed = input.read(cx).value().trim().to_string(); + let name = if typed.is_empty() { + Ok(worktree::generate_name(uuid::Uuid::new_v4().as_u128(), worktree::name_taken(&main_checkout))) + } else { + worktree::check_name(&typed).and_then(|()| worktree::check_unused(&main_checkout, &typed)).map(|()| typed) + }; + match name { + Ok(name) => Act::SwitchWorktree { folder: worktree::folder(&main_checkout, &name), base }, + Err(why) => { + self.modal = Some(Modal::NewWorktree { main_checkout, input, base }); + self.toast(why, true, cx); + return; + } + } + } Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, list_focus }) => { let clean = |s: &str| s.trim().trim_matches('"').to_string(); let (shell_t, claude_t) = (clean(shell.read(cx).value().as_ref()), clean(claude.read(cx).value().as_ref())); diff --git a/src/app/repo.rs b/src/app/repo.rs index cdbdf6c..ef863f5 100644 --- a/src/app/repo.rs +++ b/src/app/repo.rs @@ -23,6 +23,10 @@ impl Workspace { ws.store.refresh_git(); ws.store.save_if_dirty(); ws.refresh_pending(cx); + // The Worktrees page of Settings lists what a removal just deleted. + if op == GitOp::Worktree && ws.settings_page == SettingsPage::Worktrees { + ws.load_stored_worktrees(cx); + } match result { Ok(summary) => ws.toast(summary, false, cx), Err(fail) => match fail.conflict_in { @@ -117,20 +121,36 @@ impl Workspace { cx.notify(); cx.spawn(async move |this, cx| { let dir = cwd.clone(); - let result = cx.background_executor().spawn(async move { crate::git::commit::branches(&dir) }).await; + let result = cx + .background_executor() + .spawn(async move { + let list = crate::git::commit::branches(&dir)?; + let deletable = crate::git::commit::deletable_branches(&dir, list.current.as_deref()); + Ok::<_, String>((list, deletable)) + }) + .await; let _ = this.update(cx, |ws, cx| { ws.git_busy = None; match result { - Ok((names, current)) => { + Ok((list, deletable)) => { + let mut items = vec![MenuItem::new("Branches", Act::Dismiss)]; + items[0].disabled = true; // ponytail: the menu doesn't scroll, so only the most recently used branches are listed. - let mut items: Vec = names - .into_iter() - .take(15) - .map(|name| MenuItem::new(format!("{}{name}", crate::panels::widgets::tick(current.as_deref() == Some(name.as_str()))), Act::SwitchBranch(cwd.clone(), name))) - .collect(); - let first = items.is_empty(); - items.push(MenuItem { label: "New branch…".into(), hint: None, act: Act::NewBranch(cwd), danger: false, disabled: false, separator_before: !first }); - ws.open_dropdown(at, items, cx); + items.extend(list.names.into_iter().take(15).map(|name| { + let label = format!("{}{name}", crate::panels::widgets::tick(list.current.as_deref() == Some(name.as_str()))); + let held = list.elsewhere.iter().find(|h| h.branch == name); + let hint = held.map(|h| format!("opens {}", h.tree)); + // Git won't check a branch out twice, so the row moves the session into the working tree that has it. + let act = match held { + Some(h) => Act::SwitchWorktree { folder: h.folder.clone(), base: Default::default() }, + None => Act::SwitchBranch(cwd.clone(), name.clone()), + }; + // Remote-only branches have nothing local to delete. + let remove = (held.is_none() && deletable.contains(&name)).then(|| Act::DeleteBranch(cwd.clone(), name.clone())); + MenuItem { remove, hint, icon: held.map(|_| gpui_kit::assets::IconName::FolderGit2), ..MenuItem::new(label, act) } + })); + items.push(MenuItem { separator_before: true, ..MenuItem::new("New branch…", Act::NewBranch(cwd)) }); + ws.open_dropdown(crate::panels::widgets::Dropdown { min_w: at.min_w.max(gpui::px(300.0)), ..at }, items, cx); } Err(e) => ws.toast(e, true, cx), } @@ -139,4 +159,47 @@ impl Workspace { }) .detach(); } + + /// Ask before deleting a local branch, after counting the commits only it has. + pub(super) fn ask_delete_branch(&mut self, cwd: PathBuf, name: String, cx: &mut Context) { + cx.spawn(async move |this, cx| { + let (dir, branch) = (cwd.clone(), name.clone()); + let lost = cx.background_executor().spawn(async move { crate::git::commit::commits_only_on(&dir, &branch) }).await; + let _ = this.update(cx, |ws, cx| match lost { + Ok(lost) => { + let (title, body, confirm, danger) = delete_branch_question(&name, lost); + ws.modal = Some(Modal::Confirm { title, body, confirm, danger, act: Act::ConfirmDeleteBranch(cwd, name) }); + cx.notify(); + } + Err(e) => ws.toast(e, true, cx), + }); + }) + .detach(); + } +} + +/// The dialog's title, text, button and whether the button is red. Only the local branch goes; origin's copy stays. +fn delete_branch_question(name: &str, lost: usize) -> (String, String, String, bool) { + let title = format!("Delete branch {name}?"); + if lost == 0 { + return (title, "Every commit on it is also on another branch, so nothing is lost. A copy on origin is not deleted.".into(), "Delete".into(), false); + } + let commits = if lost == 1 { "1 commit is".to_string() } else { format!("{lost} commits are") }; + (title, format!("{commits} on no other branch and will be lost."), "Delete anyway".into(), true) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn deleting_a_branch_is_plain_until_commits_would_be_lost() { + let (title, body, button, red) = delete_branch_question("fix", 0); + assert_eq!((title.as_str(), button.as_str(), red), ("Delete branch fix?", "Delete", false)); + assert!(body.contains("nothing is lost"), "{body}"); + + let (_, body, button, red) = delete_branch_question("fix", 1); + assert_eq!((body.as_str(), button.as_str(), red), ("1 commit is on no other branch and will be lost.", "Delete anyway", true)); + assert_eq!(delete_branch_question("fix", 3).1, "3 commits are on no other branch and will be lost."); + } } diff --git a/src/app/sessions.rs b/src/app/sessions.rs index 1292d59..561c290 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -107,6 +107,8 @@ impl Workspace { /// `leading` goes before every other argument: the initial prompt must come ahead of the variadic /// `--allowedTools` / `--mcp-config` flags, or they would swallow it. pub(super) fn new_claude_with(&mut self, cwd: PathBuf, mut leading: Vec, by: Starter, window: &mut Window, cx: &mut Context) { + // A new session starts in the main checkout, not in a linked worktree. Fix-with-Claude works where the failure was. + let cwd = if by == Starter::FixGit { cwd } else { self.outside_linked_worktree(cwd) }; let Some(exe) = self.claude_exe.clone() else { self.show_toast("Could not find the `claude` CLI. Install Claude Code, or set its path in Settings.".into(), true, Some(("Check setup".into(), Act::OpenSetup)), cx); return; @@ -141,12 +143,26 @@ impl Workspace { self.start(record, spec, true, window, cx); } + /// `cwd`, or the project's main checkout when `cwd` is inside one of its linked worktrees. + fn outside_linked_worktree(&self, cwd: PathBuf) -> PathBuf { + let git = self.store.project_for_cwd(&cwd).and_then(|id| self.store.project(&id)).and_then(|p| p.git.as_ref()); + match git.and_then(|g| g.folder_of(&cwd).filter(|f| !g.is_main(f)).map(|_| g.main_checkout())) { + Some(main) if main.is_dir() => main.to_path_buf(), + _ => cwd, + } + } + /// Resume a Claude session through `claude --resume`. Reuses the history record. pub fn resume(&mut self, id: &str, window: &mut Window, cx: &mut Context) { if self.is_running(id, cx) { self.show_session(id, window, cx); return; } + self.relaunch(id, window, cx); + } + + /// `claude --resume` in the record's folder. A running view of the session is replaced, which ends its process. + pub(super) fn relaunch(&mut self, id: &str, window: &mut Window, cx: &mut Context) { let Some(rec) = self.store.session(id).cloned() else { return; }; @@ -157,7 +173,8 @@ impl Workspace { self.toast("Could not find the `claude` CLI.", true, cx); return; }; - let mut spec = claude::resume_spec(&exe, &rec.cwd, &meta.session_id); + let cwd = self.resume_cwd(&rec, cx); + let mut spec = claude::resume_spec(&exe, &cwd, &meta.session_id); // Hand Claudiu's tab title to Claude Code so its own name (prompt box, /resume, Remote Control) matches. if let Some(name) = rec.chosen_title() { spec.args.extend(["--name".into(), name.into()]); @@ -166,12 +183,33 @@ impl Workspace { self.start(rec, spec, false, window, cx); } + /// Where a resumed session starts: its folder, or its project's main checkout when the folder is gone (Claude Code's + /// exit prompt removes a worktree). Claude Code then tells the user in the session that the worktree is gone. + fn resume_cwd(&mut self, rec: &SessionRecord, cx: &mut Context) -> PathBuf { + if rec.cwd.is_dir() { + return rec.cwd.clone(); + } + let project = rec.project_id.as_ref().and_then(|id| self.store.project(id)); + let fallback = project.map(|p| p.git.as_ref().map_or(p.path.as_path(), |g| g.main_checkout()).to_path_buf()).filter(|p| p.is_dir()); + match fallback { + Some(main) => { + let short = crate::panels::widgets::short_path; + self.toast(format!("{} is gone, so the session starts in {}.", short(&rec.cwd), short(&main)), false, cx); + // The record follows, so the shell, the files and the next resume start there too. + if let Some(r) = self.store.session_mut(&rec.id) { + r.cwd = main.clone(); + } + main + } + None => rec.cwd.clone(), + } + } + /// End the session's process and resume the same conversation. The shell and cards belong to the session, so they stay. pub(super) fn restart_session(&mut self, id: &str, window: &mut Window, cx: &mut Context) { let was_shown = self.active_id().is_some_and(|a| a == id); let shell = self.shells.remove(id); - self.live.retain(|l| l.id != id); // dropping the view closes the old process - self.resume(id, window, cx); + self.relaunch(id, window, cx); if let Some(shell) = shell { self.shells.insert(id.into(), shell); } @@ -193,7 +231,9 @@ impl Workspace { let loading = record.kind == SessionKind::Claude; record.exit_code = None; record.last_active = now(); - // Re-resuming: drop the previous (exited) terminal view for this record. + // The pane's grid: from the view this one replaces, or the one shown there now. + let layout = self.live_view(&id).or_else(|| self.active.as_ref().and_then(|a| self.live_view(a))).and_then(|v| v.read(cx).layout()); + // Drop the previous terminal view for this record: an exited one, or a running one whose process this ends. self.live.retain(|l| l.id != id); self.purge_dead_shells(); self.transcript_mtimes.remove(&id); @@ -206,6 +246,9 @@ impl Workspace { let view = cx.new(|cx| { let mut v = TerminalView::new(terminal, rx, cx); v.loading = loading; + if let Some(layout) = layout { + v.take_layout(layout); + } v }); let sub_id = id.clone(); @@ -343,7 +386,17 @@ impl Workspace { window.focus(&self.root_focus, cx); } + /// End a session. One that ran in a Claude Code worktree no other session uses then gets the offer to remove it, + /// since Claude Code's own prompt only appears when a session exits with `/exit`. pub(super) fn close_live(&mut self, id: &str, window: &mut Window, cx: &mut Context) { + let was_in = self.store.session(id).map(|s| (s.cwd.clone(), s.project_id.clone())); + self.end_live(id, window, cx); + if let Some((cwd, project)) = was_in { + self.offer_worktree_removal(&cwd, project.as_deref(), cx); + } + } + + pub(super) fn end_live(&mut self, id: &str, window: &mut Window, cx: &mut Context) { if self.logins.remove(id) { self.refresh_accounts(cx); } diff --git a/src/app/settings.rs b/src/app/settings.rs index aa8d9b5..3fad218 100644 --- a/src/app/settings.rs +++ b/src/app/settings.rs @@ -11,11 +11,12 @@ pub enum SettingsPage { Sessions, ClaudeTools, ClaudiuTools, + Worktrees, About, } impl SettingsPage { - pub const ALL: [SettingsPage; 5] = [Self::General, Self::Sessions, Self::ClaudeTools, Self::ClaudiuTools, Self::About]; + pub const ALL: [SettingsPage; 6] = [Self::General, Self::Sessions, Self::ClaudeTools, Self::ClaudiuTools, Self::Worktrees, Self::About]; pub fn label(self) -> &'static str { match self { @@ -23,6 +24,7 @@ impl SettingsPage { Self::Sessions => "Sessions", Self::ClaudeTools => "Claude Code tools", Self::ClaudiuTools => "Claudiu tools", + Self::Worktrees => "Worktrees", Self::About => "About", } } @@ -53,8 +55,8 @@ impl Workspace { }; let on_list = list_focus.is_focused(window); match ev.keystroke.key.as_str() { - "up" if on_list => self.settings_page = self.settings_page.prev(), - "down" if on_list => self.settings_page = self.settings_page.next(), + "up" if on_list => self.set_settings_page(self.settings_page.prev(), cx), + "down" if on_list => self.set_settings_page(self.settings_page.next(), cx), "enter" if on_list => self.submit_modal(window, cx), "tab" => { let here = if on_list { @@ -84,9 +86,10 @@ mod tests { #[test] fn next_and_prev_walk_the_list_and_stop_at_the_ends() { assert_eq!(General.next(), Sessions); - assert_eq!(ClaudiuTools.next(), About); + assert_eq!(ClaudiuTools.next(), Worktrees); + assert_eq!(Worktrees.next(), About); assert_eq!(About.next(), About); - assert_eq!(About.prev(), ClaudiuTools); + assert_eq!(About.prev(), Worktrees); assert_eq!(Sessions.prev(), General); assert_eq!(General.prev(), General); } diff --git a/src/app/switch.rs b/src/app/switch.rs new file mode 100644 index 0000000..30c3233 --- /dev/null +++ b/src/app/switch.rs @@ -0,0 +1,218 @@ +//! Switching a running session into another working tree of its repository, the way a session switches branches. +//! The process ends and `claude --resume` continues the same conversation in the target folder; the Claudiu session +//! (its title, cards, place in the sidebar) is the same record, whose folder is now the target's. A new worktree is +//! made with git first (`worktree::add`). +//! +//! A session that Claude Code itself put in a worktree (`claude --worktree`) has that worktree recorded in its +//! transcript, and Claude Code restores it on every resume, which wins over the folder `claude` is started in. So +//! before such a session moves, Claudiu appends the line that Claude Code's own ExitWorktree writes (see +//! `claude::clear_recorded_worktree`). + +use std::path::Path; +use std::time::Instant; + +use super::*; +use crate::git::GitInfo; +use crate::git::worktree::{self, Base}; +use crate::terminal::view::Handover; + +const BUSY: &str = "Wait until Claude finishes, then switch."; + +/// What the skeleton says while the session moves to `folder`. +fn switching_message(git: &GitInfo, folder: &Path) -> String { + match folder.file_name() { + Some(name) if !git.is_main(folder) => format!("Switching to {}…", name.to_string_lossy()), + _ => "Switching to the main checkout…".into(), + } +} + +/// What the background look at a session found before it may be switched. +struct Checked { + idle: bool, + uncommitted: usize, + transcript: Option, +} + +/// Claude Code's registry says whether the session is busy, idle or waiting; without an entry (older versions) the +/// terminal's own activity decides. +fn inspect(claude_id: &str, folder: &Path, quiet: bool) -> Checked { + let home = claude::claude_home(); + let statuses = home.as_deref().map(|h| claude::session_statuses(h, &mut Default::default())).unwrap_or_default(); + Checked { + idle: statuses.get(claude_id).map_or(quiet, |s| s == "idle"), + uncommitted: worktree::uncommitted(folder).unwrap_or(0), + transcript: home.and_then(|h| claude::find_transcript(&h, claude_id)), + } +} + +/// Ready the target before the session moves: make the worktree when it is new, and clear a worktree Claude Code +/// recorded, so the resume starts in the folder `claude` is launched in. Blocking. +fn prepare(main_checkout: &Path, folder: &Path, base: Base, transcript: &Path, claude_id: &str) -> Result<(), String> { + if !folder.exists() { + worktree::add(main_checkout, folder, base).map_err(|e| format!("could not make the worktree: {}", e.trim()))?; + } + clear_worktree_record(transcript, claude_id) +} + +fn clear_worktree_record(transcript: &Path, claude_id: &str) -> Result<(), String> { + if claude::worktree_recorded(transcript).map_err(|e| format!("could not read the conversation: {e}"))? { + claude::clear_recorded_worktree(transcript, claude_id).map_err(|e| format!("could not update the conversation: {e}"))?; + } + Ok(()) +} + +impl Workspace { + /// Switch the shown session into `folder`, a working tree of its project. `asked` is set once the user has + /// confirmed leaving uncommitted files behind. + pub(super) fn switch_shown(&mut self, folder: PathBuf, base: Base, asked: bool, window: &mut Window, cx: &mut Context) { + let Some(id) = self.active_id().cloned() else { return }; + let Some(rec) = self.store.session(&id).cloned() else { return }; + let Some(claude_id) = rec.claude_id().map(str::to_string) else { return }; + let Some(git) = rec.project_id.as_ref().and_then(|p| self.store.project(p)).and_then(|p| p.git.clone()) else { return }; + let Some(view) = self.live_view(&id).filter(|v| v.read(cx).is_running()).cloned() else { + self.toast("Resume the session to switch.", false, cx); + return; + }; + // The skeleton is up while a switch readies its target, so this also refuses a second switch. + let loading = view.read(cx).is_loading(); + if loading || self.handoffs.contains_key(&id) { + self.toast(BUSY, false, cx); + return; + } + let quiet = !view.read(cx).is_working(); + let from = git.folder_of(&rec.cwd).unwrap_or(&rec.cwd).to_path_buf(); + // Looking at the session takes a moment (git, the registry, the transcript): the skeleton answers the click at once. + self.set_handover(&id, Some(Handover { message: switching_message(&git, &folder), since: Instant::now() }), cx); + cx.spawn_in(window, async move |this, cx| { + let looked = from.clone(); + let checked = cx.background_executor().spawn(async move { inspect(&claude_id, &looked, quiet) }).await; + let _ = this.update_in(cx, |ws, window, cx| ws.after_inspection(id, folder, base, from, asked, checked, window, cx)); + }) + .detach(); + } + + #[allow(clippy::too_many_arguments)] + fn after_inspection(&mut self, id: Id, folder: PathBuf, base: Base, from: PathBuf, asked: bool, checked: Checked, window: &mut Window, cx: &mut Context) { + if !checked.idle { + self.set_handover(&id, None, cx); + self.toast(BUSY, false, cx); + return; + } + let Some(transcript) = checked.transcript else { + self.set_handover(&id, None, cx); + self.toast("Couldn't switch: this session has no conversation to resume yet.", true, cx); + return; + }; + if checked.uncommitted > 0 && !asked { + self.set_handover(&id, None, cx); + let files = if checked.uncommitted == 1 { "1 uncommitted file stays".to_string() } else { format!("{} uncommitted files stay", checked.uncommitted) }; + let name = from.file_name().map_or_else(|| from.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()); + self.modal = Some(Modal::Confirm { + title: "Switch worktree?".into(), + body: format!("{files} in {name}. Your shell restarts."), + confirm: "Switch".into(), + danger: false, + act: Act::ConfirmSwitch { folder, base }, + }); + return; + } + self.perform_switch(id, folder, base, transcript, window, cx); + } + + fn perform_switch(&mut self, id: Id, folder: PathBuf, base: Base, transcript: PathBuf, window: &mut Window, cx: &mut Context) { + let Some(rec) = self.store.session(&id) else { return }; + let Some(claude_id) = rec.claude_id().map(str::to_string) else { return }; + let Some(git) = rec.project_id.as_ref().and_then(|p| self.store.project(p)).and_then(|p| p.git.clone()) else { return }; + let main = git.main_checkout().to_path_buf(); + let message = switching_message(&git, &folder); + cx.spawn_in(window, async move |this, cx| { + let (target, main_checkout) = (folder.clone(), main.clone()); + let ready = cx.background_executor().spawn(async move { prepare(&main_checkout, &target, base, &transcript, &claude_id) }).await; + let _ = this.update_in(cx, |ws, window, cx| match ready { + Ok(()) => ws.move_into(&id, folder, message, window, cx), + Err(why) => { + ws.set_handover(&id, None, cx); + ws.toast(format!("Couldn't switch: {why}."), true, cx); + } + }); + }) + .detach(); + } + + /// The old process ends and a new one resumes the conversation in `folder`, as a restart does. + fn move_into(&mut self, id: &str, folder: PathBuf, message: String, window: &mut Window, cx: &mut Context) { + // Closed while the target was readied. + if !self.is_running(id, cx) { + return; + } + let was_shown = self.active_id().is_some_and(|a| a == id); + let shell = self.shells.remove(id).map(|p| (p.open, p.height)); + self.repoint_tabs(id, &folder, window, cx); + if let Some(r) = self.store.session_mut(id) { + r.cwd = folder; + } + self.relaunch(id, window, cx); // replacing the view ends the old process + self.set_handover(id, Some(Handover { message, since: Instant::now() }), cx); + self.restore_shell(id, shell, window, cx); + if was_shown { + self.show_session(id, window, cx); + } + self.store.refresh_git(); + } + + /// A shell in the session's folder where there was one, open and as tall as before. + fn restore_shell(&mut self, id: &str, shell: Option<(bool, f32)>, window: &mut Window, cx: &mut Context) { + let Some((open, height)) = shell else { return }; + let Some(rec) = self.store.session(id) else { return }; + let cwd = if rec.cwd.is_dir() { rec.cwd.clone() } else { platform::home_dir().unwrap_or(rec.cwd.clone()) }; + let mut panel = self.new_shell_panel(id, cwd, window, cx); + (panel.open, panel.height) = (open, height); + self.shells.insert(id.to_string(), panel); + } + + /// Open files move to the same path in `folder` when it has the file; a file with unsaved edits, or one the folder + /// lacks, stays on its old path and a toast says how many. + fn repoint_tabs(&mut self, id: &str, folder: &Path, window: &mut Window, cx: &mut Context) { + let Some(pane) = self.panes.get_mut(id).filter(|p| folder.is_dir() && !p.root.as_os_str().is_empty()) else { return }; + let folder = dunce::canonicalize(folder).unwrap_or_else(|_| folder.to_path_buf()); + let (mut moved, mut stayed) = (vec![], 0); + for tab in &mut pane.tabs { + let there = tab.path.strip_prefix(&pane.root).ok().map(|rel| folder.join(rel)).filter(|p| p.is_file()); + match there { + Some(path) if !tab.dirty => { + let old = std::mem::replace(&mut tab.path, path.clone()); + moved.push((old, path)); + } + _ => stayed += 1, + } + } + for (_, path) in moved { + self.reload_tab(&id.to_string(), path, window, cx); + } + if stayed > 0 { + let files = if stayed == 1 { "1 open file stays".to_string() } else { format!("{stayed} open files stay") }; + self.toast(format!("{files} on its old path: it has unsaved edits, or the new folder lacks it."), false, cx); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clearing_appends_one_line_only_while_a_worktree_is_recorded() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("s.jsonl"); + std::fs::write(&path, r#"{"type":"worktree-state","worktreeSession":{"worktreeName":"t"},"sessionId":"s"}"#.to_string() + "\n").unwrap(); + // A worktree Claude Code recorded: the line is appended. + clear_worktree_record(&path, "s").unwrap(); + assert!(!claude::worktree_recorded(&path).unwrap()); + // Nothing recorded, nothing appended. + let before = std::fs::read_to_string(&path).unwrap(); + clear_worktree_record(&path, "s").unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), before); + // A missing transcript is an error the user is told about. + assert!(clear_worktree_record(&dir.path().join("gone.jsonl"), "s").is_err()); + } +} diff --git a/src/app/worktrees.rs b/src/app/worktrees.rs new file mode 100644 index 0000000..3766f1b --- /dev/null +++ b/src/app/worktrees.rs @@ -0,0 +1,201 @@ +//! Git worktrees in the app: the dialog for a new one, the top-bar menu that switches the shown session between them +//! (see `switch.rs`), and removing them. Claudiu makes the worktrees with git (see `git/worktree.rs`). + +use std::path::Path; + +use super::*; +use crate::git::GitInfo; +use crate::git::worktree; +use crate::panels::widgets::tick; +use crate::platform::path_key; + +/// What the Worktrees page of Settings shows. +#[derive(Default)] +pub struct WorktreesPage { + /// The worktree folders in Claudiu's data folder; none until the first look at the disk ends. + pub stored: Option>, + /// The removal the page is asking the user to confirm. + pub asking: Option, +} + +/// A removal question shown inside a row of the Worktrees page, so the dialog's unsaved fields stay where they are. +pub struct Asked { + pub folder: PathBuf, + pub body: String, + pub confirm: String, + pub danger: bool, + pub act: Act, +} + +impl Workspace { + /// Show a page of the Settings dialog. The Worktrees page looks at the disk every time it opens. + pub(crate) fn set_settings_page(&mut self, page: SettingsPage, cx: &mut Context) { + self.settings_page = page; + self.worktrees_page.asking = None; + if page == SettingsPage::Worktrees { + self.load_stored_worktrees(cx); + } + cx.notify(); + } + + pub(super) fn load_stored_worktrees(&mut self, cx: &mut Context) { + cx.spawn(async move |this, cx| { + let found = cx.background_executor().spawn(async move { worktree::stored() }).await; + let _ = this.update(cx, |ws, cx| { + ws.worktrees_page.stored = Some(found); + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn ask_worktree(&mut self, main_checkout: PathBuf, window: &mut Window, cx: &mut Context) { + let input = self.modal_input("", "Name, or leave blank for a random one", window, cx); + self.modal = Some(Modal::NewWorktree { main_checkout, input, base: Base::default() }); + } + + /// The top-bar menu: the repository's working trees, each switching the shown session into it, and a new worktree. + pub fn open_worktree_menu(&mut self, project: Id, cwd: PathBuf, at: crate::panels::widgets::Dropdown, cx: &mut Context) { + let Some(git) = self.store.project(&project).and_then(|p| p.git.clone()) else { return }; + let here = git.folder_of(&cwd).map(path_key); + // A switch restarts the process, so it needs one that is running. + let can_switch = self.active_id().is_some_and(|id| self.is_running(id, cx)); + let mut title = MenuItem::new("Worktrees", Act::Dismiss); + title.disabled = true; + title.hint = (!can_switch).then(|| "Resume the session to switch".to_string()); + let mut items = vec![title]; + items.extend(worktree::folders(&git).into_iter().map(|folder| { + let name = worktree::label(&git, folder).unwrap_or_default(); + let running = self.live.iter().any(|l| self.store.session(&l.id).is_some_and(|s| same_folder(&git, &s.cwd, folder))); + let own = here.as_deref() == Some(path_key(folder).as_str()); + let remove = worktree::removable(git.main_checkout(), folder).then(|| Act::RemoveWorktree { main_checkout: git.main_checkout().to_path_buf(), folder: folder.to_path_buf() }); + MenuItem { + label: format!("{}{name}{}", tick(own), if running { " ●" } else { "" }), + hint: git.branch_in(folder).map(str::to_string), + act: if own { Act::Dismiss } else { Act::SwitchWorktree { folder: folder.to_path_buf(), base: Base::default() } }, + disabled: !can_switch, + remove, + ..MenuItem::new("", Act::Dismiss) + } + })); + let source = worktree::source(Some(&git)); + items.push(MenuItem { + hint: source.err().map(str::to_string), + disabled: source.is_err() || !can_switch, + separator_before: true, + ..MenuItem::new("New worktree…", Act::NewWorktree(git.main_checkout().to_path_buf())) + }); + // Each row holds a name, its branch and a hover button; the default 232 px leaves the name no room. + self.open_dropdown(crate::panels::widgets::Dropdown { min_w: at.min_w.max(gpui::px(340.0)), ..at }, items, cx); + } + + /// The most recently active Claudiu session that runs in `folder`. + fn running_in(&self, folder: &Path) -> Option<&SessionRecord> { + self.live.iter().filter_map(|l| self.store.session(&l.id)).filter(|s| crate::platform::is_same_or_under(&s.cwd, folder)).max_by_key(|s| s.last_active) + } + + /// Whether a running session is in `folder`, which refuses removing it with a toast. + fn refuse_while_running(&mut self, folder: &Path, cx: &mut Context) -> bool { + let name = folder.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let Some(inside) = self.running_in(folder) else { return false }; + let title = inside.display_title().to_string(); + self.toast(format!("“{title}” is in {name}. Switch it to main first."), true, cx); + true + } + + /// Ask whether to remove `folder`, after reading what it holds. A running session in it refuses: it has to leave first. + /// The question appears in the Worktrees page while Settings is open, and in a dialog otherwise. + pub(super) fn ask_remove_worktree(&mut self, main_checkout: PathBuf, folder: PathBuf, cx: &mut Context) { + if self.refuse_while_running(&folder, cx) { + return; + } + let name = folder.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + cx.spawn(async move |this, cx| { + let dir = folder.clone(); + let found = cx.background_executor().spawn(async move { worktree::leftovers(&dir) }).await; + let _ = this.update(cx, |ws, cx| match found { + Ok(left) => { + let (title, body, confirm, danger) = removal_question(&name, left); + let act = Act::ConfirmRemoveWorktree { main_checkout, folder: folder.clone(), discard: left.files > 0 }; + ws.show_removal_question(folder, title, body, confirm, danger, act); + cx.notify(); + } + Err(e) => ws.toast(e, true, cx), + }); + }) + .detach(); + } + + /// Ask whether to delete a folder of Claudiu's that git no longer lists, so only the folder can go. + pub(super) fn ask_delete_unlisted(&mut self, folder: PathBuf, cx: &mut Context) { + if self.refuse_while_running(&folder, cx) { + return; + } + let name = folder.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let body = "Git no longer lists this worktree, so Claudiu cannot say what is in it. The folder and everything in it will be deleted.".to_string(); + self.show_removal_question(folder.clone(), format!("Delete the folder {name}?"), body, "Delete".into(), true, Act::ConfirmDeleteUnlisted(folder)); + cx.notify(); + } + + fn show_removal_question(&mut self, folder: PathBuf, title: String, body: String, confirm: String, danger: bool, act: Act) { + if matches!(self.modal, Some(Modal::Settings { .. })) { + self.worktrees_page.asking = Some(Asked { folder, body, confirm, danger, act }); + } else { + self.modal = Some(Modal::Confirm { title, body, confirm, danger, act }); + } + } + + /// A session that ran in `cwd` has ended: offer to remove its worktree when Claudiu made it and no + /// other session is still in it. + pub(super) fn offer_worktree_removal(&mut self, cwd: &Path, project: Option<&str>, cx: &mut Context) { + let Some(git) = project.and_then(|id| self.store.project(id)).and_then(|p| p.git.clone()) else { return }; + let Some(folder) = git.folder_of(cwd).filter(|f| worktree::removable(git.main_checkout(), f) && f.is_dir()) else { return }; + if self.running_in(folder).is_none() { + self.ask_remove_worktree(git.main_checkout().to_path_buf(), folder.to_path_buf(), cx); + } + } +} + +/// The dialog's title, text, button and whether the button is red. Only changed and new files are thrown away: commits no +/// remote has stay on the branch, which is kept when it is not merged. +fn removal_question(name: &str, left: worktree::Leftovers) -> (String, String, String, bool) { + let plural = |n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); + let mut lines = vec![]; + if left.files > 0 { + lines.push(format!("{} will be deleted.", plural(left.files, "uncommitted file", "uncommitted files"))); + } + if left.unpushed > 0 { + let (commits, verb) = if left.unpushed == 1 { ("1 commit".to_string(), "stays") } else { (format!("{} commits", left.unpushed), "stay") }; + lines.push(format!("{commits} that no remote branch has {verb} on the worktree's branch, which is kept.")); + } + if !left.any() { + lines.push("It has no uncommitted files, and every commit is on a remote branch.".into()); + } + let discard = left.files > 0; + (format!("Remove worktree {name}?"), lines.join(" "), if discard { "Remove and discard" } else { "Remove" }.into(), discard) +} + +/// Whether `cwd` is in the working tree `folder` of the repository, not in another one nested inside it. +fn same_folder(git: &GitInfo, cwd: &Path, folder: &Path) -> bool { + git.folder_of(cwd).is_some_and(|f| path_key(f) == path_key(folder)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_removal_dialog_says_what_is_deleted_and_only_turns_red_for_files() { + let ask = |files, unpushed| removal_question("fix", worktree::Leftovers { files, unpushed }); + let (title, body, button, red) = ask(0, 0); + assert_eq!((title.as_str(), button.as_str(), red), ("Remove worktree fix?", "Remove", false)); + assert!(body.contains("no uncommitted files"), "{body}"); + + let (_, body, button, red) = ask(2, 1); + assert!(body.contains("2 uncommitted files will be deleted") && body.contains("1 commit that no remote branch has stays")&& !body.contains("ends the session"), "{body}"); + assert_eq!((button.as_str(), red), ("Remove and discard", true)); + + let (_, body, _, red) = ask(0, 3); + assert!(body.contains("3 commits that no remote branch has stay") && !red, "{body}"); + } +} diff --git a/src/claude/mod.rs b/src/claude/mod.rs index 519e38d..bd0ed83 100644 --- a/src/claude/mod.rs +++ b/src/claude/mod.rs @@ -1,4 +1,6 @@ -//! Claude Code integration. Strictly read-only against Claude Code's data and never touches its config. +//! Claude Code integration. Read-only against Claude Code's data, with one exception: `clear_recorded_worktree` appends a +//! line to a transcript when a session that Claude Code put in a worktree moves to another folder. It never touches +//! Claude Code's config. //! Launching/resuming uses documented CLI flags (`--session-id`, `--resume`); the transcript scan is a //! best-effort, tolerant *import* aid: every field is optional and any unparseable line is skipped. //! @@ -160,6 +162,58 @@ pub fn find_transcript(home: &Path, session_id: &str) -> Option { fs::read_dir(home.join("projects")).ok()?.flatten().map(|d| d.path().join(&name)).find(|p| p.is_file()) } +/// Whether the transcript's last `worktree-state` line names a worktree. Claude Code writes the line whenever a session +/// enters or leaves one and restores it on every resume, which wins over the folder `claude` is started in. +pub fn worktree_recorded(transcript: &Path) -> std::io::Result { + const CHUNK: u64 = 1 << 20; + let mut file = File::open(transcript)?; + let mut start = file.metadata()?.len(); + let mut tail: Vec = vec![]; + // The line repeats every few lines of a transcript, so the last one is nearly always in the final chunk. + while start > 0 { + let from = start.saturating_sub(CHUNK); + file.seek(SeekFrom::Start(from))?; + let mut chunk = vec![0; (start - from) as usize]; + file.read_exact(&mut chunk)?; + chunk.extend(tail); + (tail, start) = (chunk, from); + let text = String::from_utf8_lossy(&tail); + // Unless the whole file is in view, the first line may be cut in half. + let whole = if start == 0 { &text[..] } else { text.split_once('\n').map_or("", |(_, rest)| rest) }; + if let Some(recorded) = whole.lines().rev().find_map(worktree_state) { + return Ok(recorded); + } + } + Ok(false) +} + +fn worktree_state(line: &str) -> Option { + if !line.contains("\"worktree-state\"") { + return None; + } + let v: Value = serde_json::from_str(line).ok()?; + (v["type"] == "worktree-state").then(|| !v["worktreeSession"].is_null()) +} + +/// Append the line Claude Code's own ExitWorktree writes, so that a resume starts in the folder `claude` is launched +/// from. Only appends, and only while no process of the session runs. Blocking. +pub fn clear_recorded_worktree(transcript: &Path, session_id: &str) -> std::io::Result<()> { + use std::io::Write; + let mut file = fs::OpenOptions::new().read(true).append(true).open(transcript)?; + let mut line = String::new(); + if file.metadata()?.len() > 0 { + file.seek(SeekFrom::End(-1))?; + let mut last = [0u8]; + file.read_exact(&mut last)?; + if last[0] != b'\n' { + line.push('\n'); + } + } + line.push_str(&serde_json::json!({"type": "worktree-state", "worktreeSession": null, "sessionId": session_id}).to_string()); + line.push('\n'); + file.write_all(line.as_bytes()) +} + pub struct SessionScan { pub session: ExternalSession, } @@ -484,6 +538,47 @@ Claude: Found it. assert!(find_transcript(tmp.path(), "nope").is_none()); } + #[test] + fn the_last_worktree_state_line_decides_and_clearing_appends_one() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("s.jsonl"); + let entered = r#"{"type":"worktree-state","worktreeSession":{"worktreeName":"t1"},"sessionId":"s"}"#; + fs::write(&path, format!("{{\"type\":\"user\"}} +{entered} +{{\"type\":\"assistant\"}}")).unwrap(); + assert!(worktree_recorded(&path).unwrap()); + + clear_recorded_worktree(&path, "s").unwrap(); + assert!(!worktree_recorded(&path).unwrap(), "the appended null line is the last one"); + let text = fs::read_to_string(&path).unwrap(); + assert!(text.starts_with(&format!("{{\"type\":\"user\"}} +{entered} +{{\"type\":\"assistant\"}} +")), "a missing final newline is added and nothing else changes"); + assert!(text.lines().last().unwrap().contains("\"worktreeSession\":null")); + + fs::write(&path, format!("{entered} +{{\"type\":\"user\"}} +")).unwrap(); + assert!(worktree_recorded(&path).unwrap()); + fs::write(&path, "{\"type\":\"user\"} +").unwrap(); + assert!(!worktree_recorded(&path).unwrap(), "no line at all means no worktree"); + } + + #[test] + fn a_worktree_state_line_far_from_the_end_is_found() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("s.jsonl"); + let filler = format!("{{\"type\":\"user\",\"text\":\"{}\"}} +", "x".repeat(1000)); + let state = r#"{"type":"worktree-state","worktreeSession":{"worktreeName":"t1"},"sessionId":"s"}"#; + fs::write(&path, format!("{state} +{}", filler.repeat(3000))).unwrap(); + assert!(fs::metadata(&path).unwrap().len() > 2 << 20); + assert!(worktree_recorded(&path).unwrap()); + } + #[test] fn the_bar_is_full_at_the_threshold_while_auto_compact_is_on() { assert_eq!(context_limit(Some(1_000_000), Some(167_000), Some(true)), Some(167_000)); diff --git a/src/git/commit.rs b/src/git/commit.rs index eb7d03b..de9757b 100644 --- a/src/git/commit.rs +++ b/src/git/commit.rs @@ -112,18 +112,39 @@ pub fn background_fetch(cwd: &Path) { } } -fn has_origin(cwd: &Path) -> bool { +pub(super) fn has_origin(cwd: &Path) -> bool { git(cwd, &["remote", "get-url", "origin"], None).is_ok() } -/// Branches for the branch menu, most recently committed first: origin's (as of the last background fetch) -/// plus local ones. Returns `(branches, current)`. Blocking. -pub fn branches(cwd: &Path) -> Result<(Vec, Option), String> { +/// A branch that a working tree has checked out. +#[derive(Debug, PartialEq)] +pub struct Held { + pub branch: String, + /// "main checkout" for the first working tree git lists, else the folder's name. + pub tree: String, + pub folder: PathBuf, +} + +/// What the branch menu shows. +#[derive(Debug, Default)] +pub struct BranchList { + /// Origin's branches (as of the last background fetch) plus local ones, most recently committed first. + pub names: Vec, + pub current: Option, + /// Branches another working tree has checked out, with that tree's name. Git refuses to switch to these. + pub elsewhere: Vec, +} + +/// Branches for the branch menu. Blocking. +pub fn branches(cwd: &Path) -> Result { let refs = git( cwd, &["for-each-ref", "--sort=-committerdate", "--format=%(refname)", "refs/heads", "refs/remotes/origin"], None, )?; + let current = git(cwd, &["branch", "--show-current"], None).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); + let worktrees = git(cwd, &["worktree", "list", "--porcelain"], None).unwrap_or_default(); + let elsewhere = checked_out(&worktrees).into_iter().filter(|h| current.as_ref() != Some(&h.branch)).collect(); let mut seen = std::collections::HashSet::new(); let names = refs .lines() @@ -131,8 +152,44 @@ pub fn branches(cwd: &Path) -> Result<(Vec, Option), String> { .filter(|n| *n != "HEAD" && seen.insert(n.to_string())) .map(str::to_string) .collect(); - let current = git(cwd, &["branch", "--show-current"], None).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); - Ok((names, current)) + Ok(BranchList { names, current, elsewhere }) +} + +/// The local branches the branch menu may delete: not the current one, and not origin's default branch. +pub fn deletable_branches(cwd: &Path, current: Option<&str>) -> Vec { + let default = git(cwd, &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], None).ok().map(|s| s.trim().trim_start_matches("origin/").to_string()); + let local = git(cwd, &["for-each-ref", "--format=%(refname:short)", "refs/heads"], None).unwrap_or_default(); + local.lines().filter(|b| Some(*b) != current && Some(*b) != default.as_deref()).map(str::to_string).collect() +} + +/// How many commits are on this branch and on no other local branch and no remote branch. Blocking. +pub fn commits_only_on(cwd: &Path, branch: &str) -> Result { + // The glob after --exclude is relative to refs/heads, so origin/ still counts as another place for the commits. + let count = git(cwd, &["rev-list", "--count", branch, "--not", &format!("--exclude={branch}"), "--branches", "--remotes"], None)?; + count.trim().parse().map_err(|_| format!("Could not count the commits on {branch}")) +} + +/// Delete a local branch, whatever it holds. The caller has shown what would be lost. Blocking. +pub fn delete_branch(cwd: &Path, branch: &str) -> Result { + git(cwd, &["branch", "-D", "--", branch], None)?; + Ok(format!("Deleted branch {branch}")) +} + +/// The branches that `git worktree list --porcelain` shows as checked out, each with the name of its working tree: +/// "main checkout" for the first one listed, else the folder's name. +fn checked_out(porcelain: &str) -> Vec { + let mut found = vec![]; + for (i, block) in porcelain.split(" + +").enumerate() { + let path = block.lines().find_map(|l| l.strip_prefix("worktree ")); + let branch = block.lines().find_map(|l| l.strip_prefix("branch refs/heads/")); + if let (Some(path), Some(branch)) = (path, branch) { + let name = if i == 0 { "main checkout".to_string() } else { path.rsplit(['/', '\\']).next().unwrap_or(path).to_string() }; + found.push(Held { branch: branch.to_string(), tree: name, folder: PathBuf::from(path) }); + } + } + found } /// Switch branch; a branch that only exists on origin gets a local tracking branch. Blocking. @@ -155,7 +212,7 @@ pub fn create_branch(cwd: &Path, name: &str) -> Result { } /// `origin/`: from the local `origin/HEAD` when set, else asked from the remote. -fn origin_default_branch(cwd: &Path) -> Result { +pub(super) fn origin_default_branch(cwd: &Path) -> Result { if let Ok(r) = git(cwd, &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], None) { return Ok(r.trim().to_string()); } @@ -188,7 +245,7 @@ fn clean_message(raw: &str) -> Option { (!t.is_empty()).then(|| t.to_string()) } -fn git(cwd: &Path, args: &[&str], stdin: Option<&str>) -> Result { +pub(super) fn git(cwd: &Path, args: &[&str], stdin: Option<&str>) -> Result { let mut cmd = Command::new("git"); cmd.args(args).current_dir(cwd).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); // No terminal can answer a credential prompt: fail instead of hanging (GUI credential helpers still work). @@ -213,6 +270,49 @@ fn git(cwd: &Path, args: &[&str], stdin: Option<&str>) -> Result mod tests { use super::*; + #[test] + fn branches_checked_out_in_worktrees_are_found() { + let porcelain = "worktree /p +HEAD aaa +branch refs/heads/main + +worktree /p/.claude/worktrees/x +HEAD bbb +branch refs/heads/feature/login +locked claude session x (pid 1) + +worktree /p/.claude/worktrees/d +HEAD ccc +detached +"; + let held = |b: &str, w: &str, f: &str| Held { branch: b.into(), tree: w.into(), folder: f.into() }; + assert_eq!(checked_out(porcelain), [held("main", "main checkout", "/p"), held("feature/login", "x", "/p/.claude/worktrees/x")]); + assert!(checked_out("").is_empty()); + } + + #[test] + fn the_branch_menu_names_the_worktree_that_has_a_branch() { + let tmp = tempfile::tempdir().unwrap(); + let main = dunce::canonicalize(tmp.path()).unwrap().join("main"); + std::fs::create_dir_all(&main).unwrap(); + for args in [&["init", "-q", "-b", "main"][..], &["config", "user.email", "t@t"], &["config", "user.name", "t"], &["commit", "-q", "--allow-empty", "-m", "one"], &["branch", "spare"]] { + git(&main, args, None).unwrap(); + } + let wt = tmp.path().join("wt"); + git(&main, &["worktree", "add", "-q", "-b", "in-worktree", &wt.to_string_lossy()], None).unwrap(); + + let from_main = branches(&main).unwrap(); + assert_eq!(from_main.current.as_deref(), Some("main")); + assert!(["spare", "main", "in-worktree"].iter().all(|b| from_main.names.contains(&b.to_string())), "{from_main:?}"); + assert_eq!((from_main.elsewhere[0].branch.as_str(), from_main.elsewhere[0].tree.as_str()), ("in-worktree", "wt")); + assert_eq!(from_main.elsewhere.len(), 1); + + let from_wt = branches(&wt).unwrap(); + assert_eq!(from_wt.current.as_deref(), Some("in-worktree")); + assert!(from_wt.names.contains(&"main".to_string()), "{from_wt:?}"); + assert_eq!((from_wt.elsewhere[0].branch.as_str(), from_wt.elsewhere[0].tree.as_str()), ("main", "main checkout")); + } + #[test] fn fences_are_unwrapped() { assert_eq!(clean_message("```\nFix bug\n\nbody\n```\n").as_deref(), Some("Fix bug\n\nbody")); @@ -273,8 +373,7 @@ mod tests { git(root, &["clone", "-q", "remote.git", "b"], None).unwrap(); background_fetch(&b); - let (names, current) = branches(&b).unwrap(); - let default = current.unwrap(); + let (names, default) = { let l = branches(&b).unwrap(); (l.names, l.current.unwrap()) }; assert!(names.contains(&"feature".to_string()) && names.contains(&default), "{names:?}"); switch_branch(&b, "feature").unwrap(); assert!(b.join("two.txt").exists(), "origin-only branch is checked out"); @@ -286,7 +385,40 @@ mod tests { git(root, &["init", "-q", "c"], None).unwrap(); commit(&c, "c.txt"); create_branch(&c, "x").unwrap(); - assert_eq!(branches(&c).unwrap().1.as_deref(), Some("x")); + assert_eq!(branches(&c).unwrap().current.as_deref(), Some("x")); + } + + #[test] + fn a_branch_is_deletable_unless_current_or_default_and_reports_commits_nowhere_else() { + let tmp = tempfile::tempdir().unwrap(); + let (root, a) = (tmp.path(), tmp.path().join("a")); + git(root, &["init", "-q", "--bare", "remote.git"], None).unwrap(); + git(root, &["clone", "-q", "remote.git", "a"], None).unwrap(); + commit(&a, "one.txt"); + git(&a, &["push", "-q", "-u", "origin", "HEAD"], None).unwrap(); + git(&a, &["remote", "set-head", "origin", "-a"], None).unwrap(); + let default = git(&a, &["branch", "--show-current"], None).unwrap().trim().to_string(); + + git(&a, &["switch", "-q", "-c", "pushed"], None).unwrap(); + commit(&a, "two.txt"); + git(&a, &["push", "-q", "origin", "pushed"], None).unwrap(); + git(&a, &["switch", "-q", "-c", "local-only"], None).unwrap(); + commit(&a, "three.txt"); + commit(&a, "four.txt"); + git(&a, &["switch", "-q", &default], None).unwrap(); + git(&a, &["branch", "merged"], None).unwrap(); + + let mut names = deletable_branches(&a, Some(&default)); + names.sort(); + assert_eq!(names, ["local-only", "merged", "pushed"], "not the current or default branch"); + assert!(!deletable_branches(&a, Some("pushed")).contains(&default), "origin's default is never offered"); + + assert_eq!(commits_only_on(&a, "merged").unwrap(), 0, "the default branch has them"); + assert_eq!(commits_only_on(&a, "pushed").unwrap(), 0, "origin has them"); + assert_eq!(commits_only_on(&a, "local-only").unwrap(), 2); + + assert_eq!(delete_branch(&a, "local-only").unwrap(), "Deleted branch local-only"); + assert!(!deletable_branches(&a, Some(&default)).contains(&"local-only".to_string())); } #[test] diff --git a/src/git/mod.rs b/src/git/mod.rs index 1e9b672..bbdfff3 100644 --- a/src/git/mod.rs +++ b/src/git/mod.rs @@ -3,13 +3,14 @@ pub mod commit; pub mod lines; +pub mod worktree; use std::path::{Path, PathBuf}; use git2::Repository; use serde::{Deserialize, Serialize}; -use crate::platform::{normalize, path_key}; +use crate::platform::{is_same_or_under, normalize, path_key}; #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct GitInfo { @@ -20,15 +21,56 @@ pub struct GitInfo { pub worktrees: Vec, /// True when `root` is itself a linked worktree rather than the main checkout. pub is_worktree: bool, + /// The repository's main checkout; `root` unless that is a linked worktree. Empty in state saved before this + /// field existed, until the next refresh. + #[serde(default)] + pub main: PathBuf, + /// The branch checked out in each of `worktrees`. A worktree whose branch can't be read is left out. + #[serde(default)] + pub worktree_branches: Vec<(PathBuf, String)>, + /// The repository has no commit yet, so a worktree has nothing to start from. + #[serde(default)] + pub unborn: bool, } -/// Find the repository containing `path`, if any. -pub fn detect(path: &Path) -> Option { - let repo = Repository::discover(path).ok()?; - let root = normalize(repo.workdir()?); - let is_worktree = repo.is_worktree(); +impl GitInfo { + /// The main checkout, also for state saved before `main` existed. + pub fn main_checkout(&self) -> &Path { + if self.main.as_os_str().is_empty() { &self.root } else { &self.main } + } + + /// The working tree (`root` or one of `worktrees`) that holds `cwd`. A worktree inside the main checkout, such as + /// Claude Code's `.claude/worktrees/`, wins over the checkout around it. + pub fn folder_of(&self, cwd: &Path) -> Option<&Path> { + std::iter::once(&self.root) + .chain(&self.worktrees) + .filter(|folder| is_same_or_under(cwd, folder)) + .max_by_key(|folder| path_key(folder).len()) + .map(PathBuf::as_path) + } + + /// The branch checked out in a working tree from `folder_of`. + pub fn branch_in(&self, folder: &Path) -> Option<&str> { + if path_key(folder) == path_key(&self.root) { + return self.branch.as_deref(); + } + let (_, branch) = self.worktree_branches.iter().find(|(path, _)| path_key(path) == path_key(folder))?; + Some(branch) + } - let branch = match repo.head() { + /// The branch of the working tree that holds `cwd`. + pub fn branch_at(&self, cwd: &Path) -> Option<&str> { + self.folder_of(cwd).map_or(self.branch.as_deref(), |folder| self.branch_in(folder)) + } + + pub fn is_main(&self, folder: &Path) -> bool { + path_key(folder) == path_key(self.main_checkout()) + } +} + +/// What `HEAD` of a repository is called: the branch, or "detached ". +fn head_name(repo: &Repository) -> Option { + match repo.head() { Ok(head) if head.is_branch() => head.shorthand().ok().map(str::to_string), Ok(head) => head.target().map(|oid| format!("detached {}", &oid.to_string()[..7])), // Fresh repo without commits: HEAD is symbolic but unborn. @@ -36,16 +78,24 @@ pub fn detect(path: &Path) -> Option { .find_reference("HEAD") .ok() .and_then(|r| r.symbolic_target().ok().flatten().map(|t| t.trim_start_matches("refs/heads/").to_string())), - }; + } +} + +/// Find the repository containing `path`, if any. +pub fn detect(path: &Path) -> Option { + let repo = Repository::discover(path).ok()?; + let root = normalize(repo.workdir()?); + let is_worktree = repo.is_worktree(); + let branch = head_name(&repo); // Worktrees are enumerated from the main repository. let main = if is_worktree { Repository::open(repo.commondir()).ok() } else { None }; let main_repo = main.as_ref().unwrap_or(&repo); + let main_dir = main_repo.workdir().map_or_else(|| root.clone(), normalize); let mut worktrees: Vec = Vec::new(); - if is_worktree - && let Some(wd) = main_repo.workdir() { - worktrees.push(normalize(wd)); - } + if is_worktree { + worktrees.push(main_dir.clone()); + } if let Ok(names) = main_repo.worktrees() { for name in names.iter().flatten().flatten() { if let Ok(wt) = main_repo.find_worktree(name) { @@ -56,7 +106,12 @@ pub fn detect(path: &Path) -> Option { worktrees.retain(|p| path_key(p) != path_key(&root)); worktrees.sort(); worktrees.dedup(); - Some(GitInfo { root, branch, worktrees, is_worktree }) + let worktree_branches = worktrees + .iter() + .filter_map(|path| Some((path.clone(), head_name(&Repository::open(path).ok()?)?))) + .collect(); + let unborn = repo.is_empty().unwrap_or(false); + Some(GitInfo { root, branch, worktrees, is_worktree, main: main_dir, worktree_branches, unborn }) } #[cfg(test)] @@ -122,6 +177,49 @@ mod tests { assert_eq!(path_key(&from_wt.worktrees[0]), path_key(&main_dir)); } + #[test] + fn a_worktree_inside_the_main_checkout_is_told_apart_from_it() { + let tmp = tempfile::tempdir().unwrap(); + let main_dir = long_path(tmp.path()).join("main"); + let wt_dir = main_dir.join(".claude/worktrees/fix"); + fs::create_dir_all(wt_dir.parent().unwrap()).unwrap(); + let repo = init_with_commit(&main_dir); + repo.worktree("fix", &wt_dir, None).unwrap(); + fs::create_dir_all(wt_dir.join("src")).unwrap(); + + let info = detect(&main_dir).unwrap(); + assert_eq!(path_key(info.main_checkout()), path_key(&main_dir)); + let folder = info.folder_of(&wt_dir.join("src")).unwrap(); + assert_eq!(path_key(folder), path_key(&wt_dir), "the deepest working tree wins"); + assert!(!info.is_main(folder)); + assert_eq!(info.branch_at(&wt_dir.join("src")), Some("fix")); + assert_eq!(path_key(info.folder_of(&main_dir.join("src")).unwrap()), path_key(&main_dir)); + assert_eq!(info.branch_at(&main_dir), info.branch.as_deref()); + + let from_wt = detect(&wt_dir).unwrap(); + assert_eq!(path_key(from_wt.main_checkout()), path_key(&main_dir)); + assert!(!from_wt.is_main(&from_wt.root)); + } + + #[test] + fn a_repository_without_commits_is_unborn() { + let tmp = tempfile::tempdir().unwrap(); + Repository::init(tmp.path()).unwrap(); + assert!(detect(tmp.path()).unwrap().unborn); + + let with_commit = tempfile::tempdir().unwrap(); + init_with_commit(with_commit.path()); + assert!(!detect(with_commit.path()).unwrap().unborn); + } + + #[test] + fn state_saved_before_worktree_sessions_still_loads() { + let old = r#"{"root":"/p","branch":"main","worktrees":["/p-wt"],"is_worktree":false}"#; + let info: GitInfo = serde_json::from_str(old).unwrap(); + assert_eq!(info.main_checkout(), Path::new("/p")); + assert!(!info.unborn && info.worktree_branches.is_empty()); + } + #[test] fn not_a_repo() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/git/worktree.rs b/src/git/worktree.rs new file mode 100644 index 0000000..a8981bd --- /dev/null +++ b/src/git/worktree.rs @@ -0,0 +1,614 @@ +//! Sessions in git worktrees. Claudiu makes a worktree with `git worktree add` in its own data folder, outside the +//! repository, so `git status` never lists it; a session moves into one by resuming there (see `app/switch.rs`). This +//! file holds the names, the folders, and making, finding and removing worktrees. + +use std::path::{Path, PathBuf}; + +use git2::Repository; + +use super::GitInfo; +use super::commit::{git, has_origin, origin_default_branch}; +use crate::platform::path_key; + +/// The folder in Claudiu's data folder that holds one folder of worktrees per repository. +const STORE: &str = "worktrees"; + +/// What a new worktree's branch starts from. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Base { + /// Origin's default branch, fetched first; the current commit when there is no origin. + #[default] + Main, + /// The commit the main checkout is on now. + Current, +} + +fn store() -> PathBuf { + let data = crate::datadir::data_dir(); + // Git lists a worktree under its real path, and `block_of` matches folders by path. A data folder reached through a + // link (macOS temp folders, a moved home) must be spelled the way git spells it. + dunce::canonicalize(&data).unwrap_or(data).join(STORE) +} + +/// Where the worktrees of one repository go: its name, so a person can tell the folders apart, and a hash of its path, +/// so two repositories with the same name don't share a folder. +fn repo_folder(main_checkout: &Path) -> PathBuf { + let name = main_checkout.file_name().map_or_else(|| "repo".into(), |n| crate::datadir::safe_file_stem(&n.to_string_lossy())); + // FNV-1a is fixed by definition, so a repository keeps its folder across Claudiu versions. + let hash = path_key(main_checkout).bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)); + store().join(format!("{name}-{:08x}", hash as u32)) +} + +pub fn folder(main_checkout: &Path, name: &str) -> PathBuf { + repo_folder(main_checkout).join(name) +} + +/// The name becomes a folder and a branch, so it is refused rather than rewritten when it holds anything else. +pub fn check_name(name: &str) -> Result<(), String> { + if name.is_empty() { + return Err("Give the worktree a name.".into()); + } + // A leading dash would be read as an option, and git refuses it in a branch name too. + if name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') && !name.starts_with('-') { + Ok(()) + } else { + Err("Use letters, digits, - and _ in a worktree name, and don't start with -.".into()) + } +} + +const ADJECTIVES: [&str; 16] = [ + "bright", "calm", "eager", "gentle", "happy", "keen", "lively", "mellow", "nimble", "proud", "quick", "quiet", "steady", "swift", "tidy", "warm", +]; +const ANIMALS: [&str; 16] = [ + "badger", "crane", "falcon", "fox", "heron", "lynx", "marten", "otter", "owl", "panda", "robin", "seal", "stoat", "swan", "wolf", "wren", +]; + +/// A two-word name such as `bright-fox`, picked by `seed` and moved on until `taken` is false. +pub fn generate_name(seed: u128, taken: impl Fn(&str) -> bool) -> String { + let combinations = (ADJECTIVES.len() * ANIMALS.len()) as u128; + let start = seed % combinations; + (0..combinations) + .map(|step| { + let pick = ((start + step) % combinations) as usize; + format!("{}-{}", ADJECTIVES[pick / ANIMALS.len()], ANIMALS[pick % ANIMALS.len()]) + }) + .find(|name| !taken(name)) + // Every one of the 256 names is in use: a numbered one is not among them. + .unwrap_or_else(|| format!("worktree-{start}")) +} + +/// The main checkout a new worktree would branch from, or why there is none. +pub fn source(git: Option<&GitInfo>) -> Result<&Path, &'static str> { + let git = git.ok_or("is not a git repository")?; + if git.unborn { + return Err("has no commits yet"); + } + Ok(git.main_checkout()) +} + +/// What the top-bar pill calls the working tree that holds `cwd`: its folder name, or "main checkout". +pub fn label(git: &GitInfo, cwd: &Path) -> Option { + let folder = git.folder_of(cwd)?; + if git.is_main(folder) { + return Some("main checkout".into()); + } + folder.file_name().map(|name| name.to_string_lossy().into_owned()) +} + +/// The repository's working trees as the top-bar menu lists them: the main checkout first, then the others by name. +pub fn folders(git: &GitInfo) -> Vec<&Path> { + let main = git.main_checkout(); + let mut others: Vec<&Path> = std::iter::once(&git.root).chain(&git.worktrees).map(PathBuf::as_path).filter(|p| path_key(p) != path_key(main)).collect(); + others.sort_by_key(|p| path_key(p)); + std::iter::once(main).chain(others).collect() +} + +/// Only the folders Claudiu made are removed from Claudiu: a worktree made anywhere else, `claude --worktree`'s in +/// `.claude/worktrees` included, is the user's own. +pub fn removable(main_checkout: &Path, folder: &Path) -> bool { + folder.parent().is_some_and(|parent| path_key(parent) == path_key(&repo_folder(main_checkout))) +} + +/// A worktree folder in Claudiu's data folder, found by looking at the disk. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Stored { + pub folder: PathBuf, + /// The repository's main checkout; none when it is gone, was moved, or git no longer lists this folder. + pub main_checkout: Option, +} + +/// Every worktree folder in Claudiu's data folder, by path. Blocking. +pub fn stored() -> Vec { + let subfolders = |parent: &Path| -> Vec { + std::fs::read_dir(parent).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect() + }; + let mut found: Vec = subfolders(&store()) + .iter() + .flat_map(|repo| subfolders(repo)) + .map(|folder| Stored { main_checkout: main_checkout_of(&folder).filter(|main| removable(main, &folder)), folder }) + .collect(); + found.sort_by_key(|s| path_key(&s.folder)); + found +} + +/// The main checkout of the repository a worktree folder belongs to, while both still exist. +fn main_checkout_of(folder: &Path) -> Option { + let common = Repository::open(folder).ok()?.commondir().parent()?.to_path_buf(); + common.is_dir().then_some(common) +} + +/// Delete a folder from Claudiu's data folder that git no longer lists, which `remove` cannot handle. Blocking. +pub fn delete_unlisted(folder: &Path) -> Result { + let in_store = folder.parent().and_then(Path::parent).is_some_and(|p| path_key(p) == path_key(&store())); + if !in_store { + return Err(format!("{} is not in Claudiu's worktrees folder, so Claudiu leaves it alone.", folder.display())); + } + let name = folder.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + std::fs::remove_dir_all(folder).map_err(|e| format!("Could not delete {name}: {e}"))?; + Ok(format!("Deleted the folder {name}.")) +} + +/// What removing a worktree throws away. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Leftovers { + /// Changed or new files, which git refuses to delete without `--force`. + pub files: usize, + /// Commits that no remote branch has. + pub unpushed: usize, +} + +impl Leftovers { + pub fn any(self) -> bool { + self.files > 0 || self.unpushed > 0 + } +} + +/// A typed name that names an existing worktree folder switches into it; one that only an existing branch has is +/// refused, so every branch in Claudiu's worktrees folder is one Claudiu made and removal may delete it once merged. +pub fn check_unused(main_checkout: &Path, name: &str) -> Result<(), String> { + if folder(main_checkout, name).exists() || !branch_exists(main_checkout, name) { + Ok(()) + } else { + Err(format!("A branch called {name} already exists. Pick another name.")) + } +} + +/// For `generate_name`: the folder or a local branch of that name exists. +pub fn name_taken(main_checkout: &Path) -> impl Fn(&str) -> bool + '_ { + let repo = Repository::open(main_checkout).ok(); + move |name| folder(main_checkout, name).exists() || repo.as_ref().is_some_and(|r| r.find_branch(name, git2::BranchType::Local).is_ok()) +} + +fn branch_exists(main_checkout: &Path, name: &str) -> bool { + Repository::open(main_checkout).is_ok_and(|r| r.find_branch(name, git2::BranchType::Local).is_ok()) +} + +/// Make the worktree `folder` on a new branch named like the folder, started from `base`. Blocking, and fetches from +/// origin for `Base::Main`. +pub fn add(main_checkout: &Path, folder: &Path, base: Base) -> Result<(), String> { + let name = folder.file_name().map(|n| n.to_string_lossy().into_owned()).ok_or("the worktree has no name")?; + let path = folder.to_string_lossy(); + let start = match base { + Base::Main if has_origin(main_checkout) => { + git(main_checkout, &["fetch", "origin"], None)?; + origin_default_branch(main_checkout)? + } + _ => "HEAD".into(), + }; + git(main_checkout, &["worktree", "add", "--no-track", "-b", &name, "--", &path, &start], None)?; + Ok(()) +} + +/// Changed and new files in a working tree, not counting anything under `.claude/`, which Claude Code keeps its own +/// files in. Blocking, and takes no `index.lock`. +pub fn uncommitted(folder: &Path) -> Result { + let status = git(folder, &["--no-optional-locks", "status", "--porcelain"], None)?; + Ok(status.lines().filter(|l| l.len() > 3 && !l[3..].trim_start_matches('"').starts_with(".claude/")).count()) +} + +/// Blocking. Does not take `index.lock`, since Claude may be running git in the same folder. +pub fn leftovers(folder: &Path) -> Result { + let files = git(folder, &["--no-optional-locks", "status", "--porcelain"], None)?.lines().filter(|l| !l.trim().is_empty()).count(); + let unpushed = git(folder, &["rev-list", "--count", "HEAD", "--not", "--remotes"], None)?.trim().parse().unwrap_or(0); + Ok(Leftovers { files, unpushed }) +} + +/// Remove the worktree, and its branch when that is fully merged. `discard` lets git delete changed and new files. +/// A Claude session that was just ended, and the programs it started, get `grace` to exit before they count as still +/// running. Returns a line for a toast. Blocking. +pub fn remove(main_checkout: &Path, folder: &Path, discard: bool, grace: std::time::Duration) -> Result { + if !removable(main_checkout, folder) { + return Err(format!("{} is not in Claudiu's worktrees folder, so Claudiu leaves it alone.", folder.display())); + } + let deadline = std::time::Instant::now() + grace; + let name = folder.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + let branch = git(folder, &["branch", "--show-current"], None).ok().map(|b| b.trim().to_string()).filter(|b| !b.is_empty()); + let listing = git(main_checkout, &["worktree", "list", "--porcelain"], None)?; + // A session that was ended leaves its lock behind. A lock set by anything else stays, and git then refuses. + if let Some(reason) = lock_reason(&listing, folder).filter(|r| r.starts_with("claude session")) { + if lock_pid(&reason).is_none_or(|pid| still_running(pid, grace)) { + return Err(format!("A Claude session is still running in {name} ({reason}).")); + } + git(main_checkout, &["worktree", "unlock", "--", &folder.to_string_lossy()], None)?; + } + let folder_in_use = delete_worktree(main_checkout, folder, discard, deadline)?; + let mut message = match branch { + None => format!("Removed worktree {name}."), + Some(branch) => match git(main_checkout, &["branch", "-d", "--", &branch], None) { + Ok(_) => format!("Removed worktree {name} and its merged branch {branch}."), + Err(_) => format!("Removed worktree {name}. The branch {branch} is kept: it has commits that are not merged."), + }, + }; + if folder_in_use { + message.push_str(" Its folder is still in use by a program, such as a terminal or a tool Claude started. Delete it once that ends."); + } + Ok(message) +} + +/// `git worktree remove`, tried again while programs that are shutting down still hold something in the folder. On +/// Windows git deletes the files and the registration first and the folder last, so a program running in the folder +/// makes it fail with "Permission denied" although the worktree is gone; then only the leftover folder is retried. +/// Returns whether that folder could not be deleted before the deadline. +fn delete_worktree(main_checkout: &Path, folder: &Path, discard: bool, deadline: std::time::Instant) -> Result { + let folder_arg = folder.to_string_lossy(); + let mut args = vec!["worktree", "remove"]; + if discard { + args.push("--force"); + } + args.extend(["--", &folder_arg]); + loop { + let Err(failure) = git(main_checkout, &args, None) else { return Ok(false) }; + let listing = git(main_checkout, &["worktree", "list", "--porcelain"], None).unwrap_or_default(); + if block_of(&listing, folder).is_none() { + return Ok(!delete_leftover(folder, deadline)); + } + if !is_busy(&failure) || std::time::Instant::now() >= deadline { + return Err(failure); + } + std::thread::sleep(std::time::Duration::from_millis(250)); + } +} + +/// Delete what git left of the folder; false when something still holds it at the deadline. +fn delete_leftover(folder: &Path, deadline: std::time::Instant) -> bool { + loop { + if !folder.exists() || std::fs::remove_dir_all(folder).is_ok() { + return true; + } + if std::time::Instant::now() >= deadline { + return false; + } + std::thread::sleep(std::time::Duration::from_millis(250)); + } +} + +/// The messages git and Windows give for a file or folder that a running program holds. +fn is_busy(failure: &str) -> bool { + ["Permission denied", "being used by another process", "busy"].iter().any(|m| failure.contains(m)) +} + +fn still_running(pid: u32, grace: std::time::Duration) -> bool { + let deadline = std::time::Instant::now() + grace; + while crate::platform::process_running(pid) { + if std::time::Instant::now() >= deadline { + return true; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + false +} + +/// The part of `git worktree list --porcelain` output that describes the worktree in `folder`, if git lists it. +fn block_of<'a>(porcelain: &'a str, folder: &Path) -> Option<&'a str> { + porcelain.split("\n\n").find(|block| { + block.lines().next().and_then(|line| line.strip_prefix("worktree ")).is_some_and(|path| path_key(Path::new(path)) == path_key(folder)) + }) +} + +/// The reason a worktree is locked (empty when none was given) in `git worktree list --porcelain` output. +fn lock_reason(porcelain: &str, folder: &Path) -> Option { + let line = block_of(porcelain, folder)?.lines().find(|l| *l == "locked" || l.starts_with("locked "))?; + Some(line.strip_prefix("locked").unwrap_or_default().trim().to_string()) +} + +/// The process id in Claude Code's lock reason, `claude session (pid )`. +fn lock_pid(reason: &str) -> Option { + reason.rsplit_once("(pid ")?.1.strip_suffix(')')?.parse().ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + const NO_WAIT: std::time::Duration = std::time::Duration::ZERO; + + #[test] + fn names_allow_letters_digits_dash_underscore() { + for ok in ["fix-login", "Fix_Login2", "a"] { + assert_eq!(check_name(ok), Ok(()), "{ok}"); + } + for bad in ["", "fix login", "feature/x", "v1.2", "naïve", "-x"] { + assert!(check_name(bad).is_err(), "{bad}"); + } + } + + #[test] + fn generated_names_are_two_words_and_skip_taken_ones() { + let first = generate_name(0, |_| false); + assert_eq!(first, "bright-badger"); + assert!(check_name(&first).is_ok()); + assert_eq!(generate_name(0, |n| n == "bright-badger"), "bright-crane"); + assert_eq!(generate_name(0, |_| true), "worktree-0"); + } + + /// Points Claudiu's data folder at a throwaway one for the rest of the test run. A repository's worktrees go in a + /// folder named after its path, so the tests do not meet each other there. + fn use_throwaway_data_folder() -> PathBuf { + static DATA: std::sync::OnceLock = std::sync::OnceLock::new(); + let data = DATA.get_or_init(|| { + let data = tempfile::tempdir().unwrap(); + // SAFETY: set once, before the tests that need it start threads of their own. + unsafe { std::env::set_var("CLAUDIU_DATA_DIR", data.path()) }; + data + }); + dunce::canonicalize(data.path()).unwrap().join(STORE) + } + + #[test] + fn folder_is_in_the_data_folder_under_a_name_that_tells_repositories_apart() { + let store = use_throwaway_data_folder(); + // The hash is part of the folder name on disk, so it must not change between versions. + assert_eq!(folder(Path::new("/p/app"), "fix"), store.join("app-2908e76a").join("fix")); + assert_ne!(folder(Path::new("/q/app"), "fix"), folder(Path::new("/p/app"), "fix"), "same name, other repository"); + } + + fn info(root: &str, main: &str, worktrees: &[&str], unborn: bool) -> GitInfo { + GitInfo { + root: root.into(), + main: main.into(), + worktrees: worktrees.iter().map(PathBuf::from).collect(), + is_worktree: root != main, + unborn, + ..Default::default() + } + } + + #[test] + fn a_worktree_needs_a_repository_with_a_commit() { + assert_eq!(source(None), Err("is not a git repository")); + assert_eq!(source(Some(&info("/p", "/p", &[], true))), Err("has no commits yet")); + assert_eq!(source(Some(&info("/p", "/p", &[], false))), Ok(Path::new("/p"))); + // A project added from inside a linked worktree still branches from the main checkout. + assert_eq!(source(Some(&info("/p/.claude/worktrees/a", "/p", &["/p"], false))), Ok(Path::new("/p"))); + } + + #[test] + fn the_pill_names_the_working_tree_a_session_is_in() { + let git = info("/p", "/p", &["/p/.claude/worktrees/fix"], false); + assert_eq!(label(&git, Path::new("/p/src")).as_deref(), Some("main checkout")); + assert_eq!(label(&git, Path::new("/p/.claude/worktrees/fix/src")).as_deref(), Some("fix")); + assert_eq!(label(&git, Path::new("/elsewhere")), None); + // A project added from inside a linked worktree: the checkout around it is still the main one. + let linked = info("/p/.claude/worktrees/fix", "/p", &["/p"], false); + assert_eq!(label(&linked, Path::new("/p/.claude/worktrees/fix")).as_deref(), Some("fix")); + assert_eq!(label(&linked, Path::new("/p")).as_deref(), Some("main checkout")); + } + + #[test] + fn folders_list_the_main_checkout_first_then_the_rest_by_name() { + let from_main = info("/p", "/p", &["/p/.claude/worktrees/zed", "/p/.claude/worktrees/ann"], false); + assert_eq!(folders(&from_main), ["/p", "/p/.claude/worktrees/ann", "/p/.claude/worktrees/zed"].map(Path::new)); + + let from_linked = info("/p/.claude/worktrees/ann", "/p", &["/p", "/p/.claude/worktrees/zed"], false); + assert_eq!(folders(&from_linked), ["/p", "/p/.claude/worktrees/ann", "/p/.claude/worktrees/zed"].map(Path::new)); + } + + #[test] + fn only_claudes_worktree_folders_are_removable() { + use_throwaway_data_folder(); + let main = Path::new("/p"); + let ours = folder(main, "fix"); + assert!(removable(main, &ours)); + assert!(!removable(main, Path::new("/p")), "the main checkout"); + assert!(!removable(main, Path::new("/p-feature")), "a worktree made elsewhere"); + assert!(!removable(main, Path::new("/p/.claude/worktrees/fix")), "one made by claude --worktree"); + assert!(!removable(main, &ours.join("src")), "a folder inside one"); + assert!(!removable(main, ours.parent().unwrap())); + assert!(!removable(Path::new("/q"), &ours), "another repository's"); + } + + #[test] + fn lock_reasons_are_read_from_the_listing() { + let listing = "worktree /p\nHEAD a\nbranch refs/heads/main\n\nworktree /p/.claude/worktrees/x\nHEAD b\nbranch refs/heads/x\nlocked claude session x (pid 4242)\n\nworktree /p/.claude/worktrees/y\nHEAD c\nbranch refs/heads/y\nlocked\n\nworktree /p/.claude/worktrees/z\nHEAD d\nbranch refs/heads/z\n"; + let reason = |folder: &str| lock_reason(listing, Path::new(folder)); + assert_eq!(reason("/p/.claude/worktrees/x").as_deref(), Some("claude session x (pid 4242)")); + assert_eq!(reason("/p/.claude/worktrees/y").as_deref(), Some("")); + assert_eq!(reason("/p/.claude/worktrees/z"), None); + assert_eq!(reason("/p/.claude/worktrees/none"), None); + assert_eq!(lock_pid("claude session x (pid 4242)"), Some(4242)); + assert_eq!(lock_pid("claude session x"), None); + } + + /// A repository with a commit and a worktree `fix` in Claude Code's folder, made with the real `git`. + fn repo_with_worktree(tmp: &Path) -> (PathBuf, PathBuf) { + let main = dunce::canonicalize(tmp).unwrap().join("main"); + std::fs::create_dir_all(&main).unwrap(); + for args in [&["init", "-q", "-b", "main"][..], &["config", "user.email", "t@t"], &["config", "user.name", "t"], &["commit", "-q", "--allow-empty", "-m", "one"]] { + git(&main, args, None).unwrap(); + } + use_throwaway_data_folder(); + let folder = folder(&main, "fix"); + git(&main, &["worktree", "add", "-q", "-b", "worktree-fix", &folder.to_string_lossy()], None).unwrap(); + (main, folder) + } + + #[test] + fn a_new_worktree_gets_a_new_branch_named_like_it() { + let tmp = tempfile::tempdir().unwrap(); + let (main, _) = repo_with_worktree(tmp.path()); + git(&main, &["commit", "-q", "--allow-empty", "-m", "two"], None).unwrap(); + // No origin: both bases start from the current commit. + let made = folder(&main, "fix-login"); + add(&main, &made, Base::Main).unwrap(); + assert_eq!(git(&made, &["branch", "--show-current"], None).unwrap().trim(), "fix-login"); + assert_eq!(git(&made, &["rev-parse", "HEAD"], None).unwrap(), git(&main, &["rev-parse", "HEAD"], None).unwrap()); + // A branch of that name already exists. + git(&main, &["branch", "kept"], None).unwrap(); + assert!(add(&main, &folder(&main, "kept"), Base::Current).is_err()); + } + + #[test] + fn a_name_only_an_existing_branch_has_is_refused() { + let tmp = tempfile::tempdir().unwrap(); + let (main, _) = repo_with_worktree(tmp.path()); + git(&main, &["branch", "kept"], None).unwrap(); + assert_eq!(check_unused(&main, "new-one"), Ok(())); + assert_eq!(check_unused(&main, "kept"), Err("A branch called kept already exists. Pick another name.".into())); + // The worktree `fix` exists, on its branch `worktree-fix`: typing its folder name switches into it. + assert_eq!(check_unused(&main, "fix"), Ok(())); + let taken = name_taken(&main); + assert!(taken("kept") && taken("fix") && taken("main") && !taken("new-one")); + } + + #[test] + fn leftovers_count_changed_files_and_commits_no_remote_has() { + let tmp = tempfile::tempdir().unwrap(); + let (_, folder) = repo_with_worktree(tmp.path()); + // The commit the branch started from is on no remote either, since this repository has none. + assert_eq!(leftovers(&folder).unwrap(), Leftovers { files: 0, unpushed: 1 }); + std::fs::write(folder.join("a.txt"), "a").unwrap(); + std::fs::write(folder.join("b.txt"), "b").unwrap(); + assert_eq!(leftovers(&folder).unwrap().files, 2); + } + + #[test] + fn the_uncommitted_count_leaves_out_claudes_own_folder() { + let tmp = tempfile::tempdir().unwrap(); + let (main, folder) = repo_with_worktree(tmp.path()); + assert_eq!(uncommitted(&main).unwrap(), 0); + // What Claude Code leaves in a checkout: its settings, and the worktrees `claude --worktree` makes. + std::fs::create_dir_all(main.join(".claude")).unwrap(); + std::fs::write(main.join(".claude/settings.local.json"), "{}").unwrap(); + assert_eq!(uncommitted(&main).unwrap(), 0, ".claude/ is not the user's work"); + std::fs::write(main.join("mine.txt"), "x").unwrap(); + assert_eq!(uncommitted(&main).unwrap(), 1); + std::fs::write(folder.join("a.txt"), "a").unwrap(); + assert_eq!(uncommitted(&folder).unwrap(), 1); + } + + #[test] + fn a_merged_worktree_goes_with_its_branch() { + let tmp = tempfile::tempdir().unwrap(); + let (main, folder) = repo_with_worktree(tmp.path()); + let message = remove(&main, &folder, false, NO_WAIT).unwrap(); + assert!(message.contains("merged branch worktree-fix"), "{message}"); + assert!(!folder.exists()); + assert!(git(&main, &["rev-parse", "--verify", "-q", "worktree-fix"], None).is_err(), "the branch is gone"); + } + + #[test] + fn unmerged_commits_keep_the_branch_and_changed_files_need_discard() { + let tmp = tempfile::tempdir().unwrap(); + let (main, folder) = repo_with_worktree(tmp.path()); + git(&folder, &["commit", "-q", "--allow-empty", "-m", "work"], None).unwrap(); + std::fs::write(folder.join("new.txt"), "x").unwrap(); + let refused = remove(&main, &folder, false, NO_WAIT).unwrap_err(); + assert!(refused.contains("untracked") || refused.contains("modified"), "{refused}"); + assert!(folder.exists()); + + let message = remove(&main, &folder, true, NO_WAIT).unwrap(); + assert!(message.contains("branch worktree-fix is kept"), "{message}"); + assert!(!folder.exists()); + assert!(git(&main, &["rev-parse", "--verify", "-q", "worktree-fix"], None).is_ok(), "the commits are still reachable"); + } + + #[test] + fn a_lock_left_by_an_ended_claude_session_is_released_but_a_live_one_is_not() { + let tmp = tempfile::tempdir().unwrap(); + let (main, folder) = repo_with_worktree(tmp.path()); + let lock = |pid: u32| git(&main, &["worktree", "lock", "--reason", &format!("claude session fix (pid {pid})"), &folder.to_string_lossy()], None).unwrap(); + + lock(std::process::id()); + let refused = remove(&main, &folder, false, NO_WAIT).unwrap_err(); + assert!(refused.contains("still running"), "{refused}"); + assert!(folder.exists()); + + git(&main, &["worktree", "unlock", &folder.to_string_lossy()], None).unwrap(); + lock(u32::MAX - 1); + remove(&main, &folder, false, NO_WAIT).unwrap(); + assert!(!folder.exists()); + } + + /// A program running in `folder`, which on Windows keeps the folder from being deleted. + #[cfg(windows)] + fn run_in(folder: &Path, seconds: u32) -> std::process::Child { + let mut cmd = std::process::Command::new("ping"); + cmd.args(["-n", &seconds.to_string(), "127.0.0.1"]).current_dir(folder).stdout(std::process::Stdio::null()); + crate::platform::no_window(&mut cmd); + cmd.spawn().unwrap() + } + + #[test] + #[cfg(windows)] + fn a_program_in_the_folder_leaves_the_folder_but_not_the_worktree_or_branch() { + let tmp = tempfile::tempdir().unwrap(); + let (main, folder) = repo_with_worktree(tmp.path()); + let mut holder = run_in(&folder, 60); + let message = remove(&main, &folder, false, std::time::Duration::from_millis(500)).unwrap(); + assert!(message.contains("merged branch worktree-fix") && message.contains("still in use"), "{message}"); + let listing = git(&main, &["worktree", "list", "--porcelain"], None).unwrap(); + assert!(block_of(&listing, &folder).is_none(), "git no longer lists it"); + holder.kill().unwrap(); + holder.wait().unwrap(); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + #[cfg(windows)] + fn a_program_that_exits_within_the_grace_does_not_leave_the_folder() { + let tmp = tempfile::tempdir().unwrap(); + let (main, folder) = repo_with_worktree(tmp.path()); + let mut holder = run_in(&folder, 3); + let message = remove(&main, &folder, false, std::time::Duration::from_secs(15)).unwrap(); + assert!(!message.contains("still in use") && !folder.exists(), "{message}"); + holder.wait().unwrap(); + } + + #[test] + fn only_claudes_folders_are_ever_removed() { + let tmp = tempfile::tempdir().unwrap(); + let (main, _) = repo_with_worktree(tmp.path()); + assert!(remove(&main, &main, true, NO_WAIT).unwrap_err().contains("not in Claudiu's worktrees folder")); + assert!(main.exists()); + } + + #[test] + fn stored_folders_know_their_repository_until_it_is_gone() { + let tmp = tempfile::tempdir().unwrap(); + let (main, folder) = repo_with_worktree(tmp.path()); + let ours = |found: Vec| found.into_iter().find(|s| s.folder == folder).expect("the worktree is listed"); + assert_eq!(ours(stored()).main_checkout, Some(main.clone())); + + std::fs::remove_dir_all(&main).unwrap(); + assert_eq!(ours(stored()).main_checkout, None, "a worktree whose repository was deleted"); + } + + #[test] + fn only_folders_in_the_data_folder_are_deleted_when_git_does_not_list_them() { + let tmp = tempfile::tempdir().unwrap(); + let (_, folder) = repo_with_worktree(tmp.path()); + let elsewhere = tmp.path().join("main"); + assert!(delete_unlisted(&elsewhere).unwrap_err().contains("not in Claudiu's worktrees folder")); + assert!(elsewhere.exists()); + assert!(delete_unlisted(&folder).is_ok() && !folder.exists()); + } + + #[test] + fn someone_elses_lock_stays_and_git_refuses() { + let tmp = tempfile::tempdir().unwrap(); + let (main, folder) = repo_with_worktree(tmp.path()); + git(&main, &["worktree", "lock", "--reason", "on a usb stick", &folder.to_string_lossy()], None).unwrap(); + assert!(remove(&main, &folder, true, NO_WAIT).unwrap_err().contains("locked")); + assert!(folder.exists()); + } +} diff --git a/src/main.rs b/src/main.rs index 3a779c3..c7eb116 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,7 +27,7 @@ gpui_kit::assets::icon_assets!( AppIcons, [ WindowMinimize, WindowMaximize, WindowRestore, WindowClose, Archive, ArchiveRestore, ArrowDownToLine, ArrowLeft, Brackets, Check, ChevronDown, ChevronRight, - CircleCheck, CircleDot, CircleSlash, CircleX, Clock, Ellipsis, Eye, ExternalLink, File, FileText, Folder, FolderOpen, GitBranch, GitCommitHorizontal, GitMerge, GitPullRequest, + CircleCheck, CircleDot, CircleDotDashed, CircleQuestionMark, CircleSlash, CircleSmall, CircleX, Clock, Ellipsis, Eye, ExternalLink, File, FileText, Folder, FolderGit2, FolderOpen, GitBranch, GitCommitHorizontal, GitMerge, GitPullRequest, GitPullRequestClosed, GitPullRequestDraft, HeartPlus, LoaderCircle, Lock, MessageSquare, FileCode, PanelBottom, PanelLeft, PanelRight, Pencil, RefreshCw, Search, Settings, Terminal, X ] diff --git a/src/panels/mod.rs b/src/panels/mod.rs index 590a8a0..418ae00 100644 --- a/src/panels/mod.rs +++ b/src/panels/mod.rs @@ -1,12 +1,13 @@ //! What Claudiu draws around the terminals. `workspace_view` is the root view (main area, overlays, toasts), `sidebar` //! and `inspector` are the two side panels, `editor_pane` is editor mode's files and editor, `widgets` holds the small -//! shared pieces. `theme` and `scale` set the look, and `glide` does the smooth scrolling. +//! shared pieces, `status_icon` the icon at the start of a session row. `theme` and `scale` set the look, and `glide` does the smooth scrolling. pub mod editor_pane; pub mod glide; pub mod inspector; pub mod scale; pub mod sidebar; +pub mod status_icon; pub mod theme; pub mod widgets; pub mod workspace_view; diff --git a/src/panels/sidebar.rs b/src/panels/sidebar.rs index 45ed1f7..7cc3d67 100644 --- a/src/panels/sidebar.rs +++ b/src/panels/sidebar.rs @@ -4,7 +4,7 @@ use std::time::{Duration, Instant}; use gpui::{ - Animation, AnimationExt, AnyElement, AppContext, DragMoveEvent, SharedString, WeakEntity, ease_out_quint, pulsating_between, ClickEvent, Context, Div, FontWeight, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, ParentElement, Pixels, Render, + Animation, AnimationExt, AnyElement, AppContext, DragMoveEvent, SharedString, WeakEntity, ease_out_quint, ClickEvent, Context, Div, FontWeight, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, ParentElement, Pixels, Render, Stateful, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px, }; @@ -13,6 +13,7 @@ use crate::app::{Act, Activity, MenuItem, SideDrag, Workspace}; use crate::store::{ExternalState, Id, Project, SessionKind, SessionRecord, now}; use crate::panels::theme::{self, hsla}; use gpui_kit::assets::IconName; +use crate::panels::status_icon::{SessionDot, StatusIcon}; use crate::panels::widgets::{Trigger, ago, avatar, button, clawd, countdown, icon, icon_button, key_hint, meter, section_label, shortcut, tick}; pub const SIDEBAR_W: f32 = 284.0; @@ -25,10 +26,14 @@ const RECENT_LIMIT: usize = 12; #[derive(Clone, PartialEq)] struct Row { id: Id, - /// What the leading status dot shows. + /// What the leading status icon shows. dot: SessionDot, title: String, right: String, + /// The project's name, on the first line of a running session's row. + project: String, + /// The branch checked out in the session's own working tree, on the last line of a running session's row. + branch: Option, active: bool, dim: bool, running: bool, @@ -39,19 +44,6 @@ struct Row { scope: &'static str, } -/// The four states a sidebar session dot can show. -#[derive(Clone, Copy, PartialEq, Eq)] -enum SessionDot { - /// Claude finished while the row was not being watched. - Attention, - /// The process is running and streaming output. - Working, - /// Running and idle, with the user up to date. - Active, - /// The session is not running. - Inactive, -} - /// Drag payload: a running session row, dropped onto another to reorder. struct DragSession(Id); @@ -81,17 +73,24 @@ fn lifted(el: T) -> T { el.bg(hsla(theme::ROW_ACTIVE)).border_1().border_color(hsla(theme::TEXT_FAINT)) } -/// Height of a session row plus the gap between rows. -const ROW_PITCH: f32 = ROW_H + LIST_GAP; +/// Height of a running session's row plus the gap between rows. +const ROW_PITCH: f32 = RUNNING_ROW_H + LIST_GAP; /// Heights of the list's parts, fixed so where each one sits is known before anything is drawn (see `visible_items`). const ROW_H: f32 = 25.0; +/// A running session's row has three lines: project, title and branch. +/// Its lines are 14 + 17 + 14 px with 2 px gaps (see `render_row`), which leaves 5.5 px above and below. +const RUNNING_ROW_H: f32 = 60.0; const HEADER_H: f32 = 20.0; const NOTE_H: f32 = 24.0; const SPACER_H: f32 = 10.0; const LIST_GAP: f32 = 2.0; /// Drawn beyond each edge of the view. The list is rebuilt for every frame its offset moves, so one row is enough. -const OVERSCAN: f32 = ROW_H + LIST_GAP; +const OVERSCAN: f32 = RUNNING_ROW_H + LIST_GAP; const SLIDE_MS: u64 = 160; +const CLOSE_SLIDE_MS: u64 = 140; +/// Width of a row's close button, and the gap between a row's parts. +const CLOSE_W: f32 = 22.0; +const ROW_GAP: f32 = 7.0; /// A row or project block that just changed places: it starts `from` px away from its new slot and slides in. /// `epoch` makes each reorder a fresh animation. @@ -120,30 +119,6 @@ fn slid(el: impl IntoElement + gpui::Styled + 'static, id: &Id, slide: Option f32 { - let t = (elapsed.as_millis() % PULSE.as_millis()) as f32 / PULSE.as_millis() as f32; - pulsating_between(0.35, 1.0)(t) -} - -/// The leading status dot: a small circle whose fill (and, when working, pulse) says what the session is doing. -fn session_dot(state: SessionDot) -> AnyElement { - static START: std::sync::OnceLock = std::sync::OnceLock::new(); - let dot = match state { - SessionDot::Attention => div().size(px(7.0)).rounded_full().bg(hsla(theme::ACCENT)), - SessionDot::Working => div().size(px(7.0)).rounded_full().bg(hsla(0xc8c8c8)).opacity(pulse_opacity(START.get_or_init(Instant::now).elapsed())), - SessionDot::Active => div().size(px(7.0)).rounded_full().bg(hsla(theme::TEXT_DIM)), - SessionDot::Inactive => div().size(px(7.0)).rounded_full().border_1().border_color(hsla(0x3d3d43)), - }; - div().w(px(14.0)).h(px(14.0)).flex_none().flex().items_center().justify_center().child(dot).into_any_element() -} - /// Moves `v[from]` into the slot of `v[to]`, shifting the items in between. fn move_to(v: &mut [T], from: usize, to: usize) { if from < to { @@ -184,6 +159,7 @@ impl Item { Item::Header(..) | Item::Older { .. } => HEADER_H, Item::Note(_) => NOTE_H, Item::Spacer => SPACER_H, + Item::Session { row, .. } if row.running => RUNNING_ROW_H, Item::Session { .. } => ROW_H, } } @@ -227,6 +203,21 @@ fn reveal_label() -> &'static str { } impl Workspace { + /// Keeps a running row's × slot drawn while it shrinks away after the pointer left, then redraws the list without it. + fn shrink_close_slot(&mut self, key: SharedString, cx: &mut Context) { + self.unhovered_rows.insert(key.clone()); + cx.spawn(async move |this, cx| { + cx.background_executor().timer(Duration::from_millis(CLOSE_SLIDE_MS)).await; + let _ = this.update(cx, |ws, cx| { + ws.unhovered_rows.remove(&key); + if let Some(list) = &ws.session_list { + list.update(cx, |_, cx| cx.notify()); + } + }); + }) + .detach(); + } + /// True when the pointer is somewhere new. A list shifting under a still pointer (a session ending, say) makes /// GPUI re-send a move at the same spot; that must not reorder anything. /// @@ -260,26 +251,27 @@ impl Workspace { SessionDot::Inactive } else { match activity { + Some(Activity::Waiting) => SessionDot::Waiting, Some(Activity::Attention) => SessionDot::Attention, Some(Activity::Working) => SessionDot::Working, None => SessionDot::Active, } }; let stale = rec.claude.as_ref().is_some_and(|c| c.external == ExternalState::Missing); + let project = { + let p = self.project_name(rec.project_id.as_ref()); + if p.is_empty() { rec.cwd.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default() } else { p } + }; + let branch = running + .then(|| rec.project_id.as_ref().and_then(|id| self.store.project(id)).and_then(|p| p.git.as_ref()).and_then(|g| g.branch_at(&rec.cwd)).map(str::to_string)) + .flatten(); Row { id: rec.id.clone(), dot, title: rec.display_title().to_string(), - right: if with_project { - let p = self.project_name(rec.project_id.as_ref()); - if p.is_empty() { - rec.cwd.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default() - } else { - p - } - } else { - ago(rec.last_active, now()) - }, + right: if with_project && !running { project.clone() } else { ago(rec.last_active, now()) }, + project, + branch, active: self.selected.as_deref() == Some(rec.id.as_str()), dim: !running, running, @@ -292,7 +284,7 @@ impl Workspace { fn session_menu(&self, rec: &SessionRecord, running: bool) -> Vec { let mut items = vec![]; - let item = |label: &str, act: Act, danger: bool, sep: bool| MenuItem { label: label.into(), hint: None, act, danger, disabled: false, separator_before: sep }; + let item = |label: &str, act: Act, danger: bool, sep: bool| MenuItem { label: label.into(), hint: None, detail: None, act, danger, disabled: false, separator_before: sep, remove: None, icon: None }; if running { items.push(item("Switch to session", Act::Select(rec.id.clone()), false, false)); } else if rec.kind == SessionKind::Claude { @@ -320,7 +312,7 @@ impl Workspace { } fn project_menu(&self, p: &Project) -> Vec { - let item = |label: String, act: Act, danger: bool, sep: bool| MenuItem { label, hint: None, act, danger, disabled: false, separator_before: sep }; + let item = |label: String, act: Act, danger: bool, sep: bool| MenuItem { label, hint: None, detail: None, act, danger, disabled: false, separator_before: sep, remove: None, icon: None }; let mut items = vec![item("New Claude session here".into(), Act::NewClaude { cwd: p.path.clone() }, false, false)]; if p.git.is_some() { items.push(item("GitHub issues & PRs".into(), Act::OpenGithub { cwd: p.path.clone() }, false, true)); @@ -371,21 +363,74 @@ impl Workspace { let close_id = id.clone(); let middle_id = id.clone(); let archive_id = id.clone(); - let dot = session_dot(row.dot); + let dot = StatusIcon::new(format!("dot-{}-{}", row.scope, id), row.dot); let key = gpui::SharedString::from(format!("row-{}-{}", row.scope, id)); // Only the row under the pointer gets its × or archive button; the others keep the space empty. Building a // hidden button on every row cost more than the rest of the row. let hovered = self.hovered_row.as_ref() == Some(&key); + let closing = !hovered && self.unhovered_rows.contains(&key); + let running = row.running; let ws = cx.entity().downgrade(); let hover_key = key.clone(); + let right_text = if row.archived { "archived".to_string() } else if row.stale { "stale".to_string() } else { row.right.clone() }; + let right_color = hsla(if row.stale { theme::WARN } else { theme::TEXT_FAINT }); + let title_color = hsla(if row.dim { theme::TEXT_DIM } else { theme::TEXT }); + let ellipsis = |el: Div| el.min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis(); + let content = if row.running { + // Project and age, then the title with the status icon, then the branch. + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.0)) + .child( + div() + .flex() + .gap(px(6.0)) + .text_size(crate::panels::scale::px(11.0)) + .line_height(crate::panels::scale::px(14.0)) + .text_color(hsla(theme::TEXT_FAINT)) + .child(ellipsis(div().flex_1()).child(row.project.clone())) + .child(div().flex_none().text_color(right_color).child(right_text)), + ) + .child( + div() + .flex() + .items_center() + .gap(px(7.0)) + .child(ellipsis(div().flex_1()).text_size(crate::panels::scale::px(13.0)).line_height(crate::panels::scale::px(17.0)).text_color(title_color).child(row.title.clone())) + .child(dot), + ) + .children(row.branch.clone().map(|b| ellipsis(div()).text_size(crate::panels::scale::px(11.0)).line_height(crate::panels::scale::px(14.0)).text_color(hsla(theme::TEXT_FAINT)).child(b))) + .into_any_element() + } else { + div() + .flex_1() + .min_w_0() + .flex() + .items_center() + .gap(px(7.0)) + .child(dot) + .child(ellipsis(div().flex_1()).text_size(crate::panels::scale::px(13.0)).text_color(title_color).child(row.title.clone())) + .child(div().flex_none().max_w(px(96.0)).overflow_hidden().whitespace_nowrap().text_ellipsis().text_size(crate::panels::scale::px(11.0)).text_color(right_color).child(right_text)) + .into_any_element() + }; div() .id(key) .group("row") .on_hover(move |inside, _window, cx| { let changed = ws - .update(cx, |ws, _| { + .update(cx, |ws, cx| { let now = if *inside { Some(hover_key.clone()) } else { ws.hovered_row.clone().filter(|k| *k != hover_key) }; - std::mem::replace(&mut ws.hovered_row, now.clone()) != now + let moved = std::mem::replace(&mut ws.hovered_row, now.clone()) != now; + if *inside { + return ws.unhovered_rows.remove(&hover_key) || moved; + } + if running { + ws.shrink_close_slot(hover_key.clone(), cx); + } + moved || running }) .unwrap_or(false); if changed { @@ -394,8 +439,8 @@ impl Workspace { }) .flex() .items_center() - .gap(px(7.0)) - .h(px(ROW_H)) + .gap(px(ROW_GAP)) + .h(px(if row.running { RUNNING_ROW_H } else { ROW_H })) .pl(px(if row.indent { 22.0 } else { 10.0 })) .pr(px(6.0)) .mx(px(5.0)) @@ -414,29 +459,7 @@ impl Workspace { } }), ) - .child(dot) - .child( - div() - .flex_1() - .min_w_0() - .overflow_hidden() - .whitespace_nowrap() - .text_ellipsis() - .text_size(crate::panels::scale::px(13.0)) - .text_color(hsla(if row.dim { theme::TEXT_DIM } else { theme::TEXT })) - .child(row.title), - ) - .child( - div() - .flex_none() - .max_w(px(96.0)) - .overflow_hidden() - .whitespace_nowrap() - .text_ellipsis() - .text_size(crate::panels::scale::px(11.0)) - .text_color(hsla(if row.stale { theme::WARN } else { theme::TEXT_FAINT })) - .child(if row.archived { "archived".to_string() } else if row.stale { "stale".to_string() } else { row.right }), - ) + .child(content) .when(row.running, |d| { // A middle click ends a running session, like its ×. d.on_mouse_up( @@ -444,17 +467,35 @@ impl Workspace { cx.listener(move |ws, _: &gpui::MouseUpEvent, window, cx| ws.act(Act::CloseLive(middle_id.clone()), window, cx)), ) }) - .when(!hovered, |d| d.child(div().flex_none().size(px(22.0)))) - .when(hovered && row.running, |d| { + .when(!hovered && !row.running, |d| d.child(div().flex_none().size(px(22.0)))) + .when((hovered || closing) && row.running, |d| { + // The slot grows from nothing to the button's width, pushing the age to the left, and shrinks back + // the same way once the pointer leaves. Its margin cancels the row's gap when the slot is empty, so + // nothing jumps. + let slide_key = SharedString::from(format!("close-{}-{}-{close_id}", if closing { "hide" } else { "show" }, row.scope)); + let button = icon_button(gpui::SharedString::from(format!("close-{}-{close_id}", row.scope)), IconName::X) + // Shown by hover style: a list that scrolled under a still pointer leaves the old row marked. + // While shrinking away the pointer is outside the row, so it is simply shown. + .when(!closing, |b| b.invisible().group_hover("row", |s| s.visible())) + .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| { + cx.stop_propagation(); + ws.act(Act::CloseLive(close_id.clone()), window, cx); + })); d.child( - // Still shown by hover style: a list that scrolled under a still pointer leaves the old row marked. - icon_button(gpui::SharedString::from(format!("close-{}-{close_id}", row.scope)), IconName::X) - .invisible() - .group_hover("row", |s| s.visible()) - .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| { - cx.stop_propagation(); - ws.act(Act::CloseLive(close_id.clone()), window, cx); - })), + div() + .flex() + .flex_none() + .justify_end() + .overflow_hidden() + .child(button) + .with_animation( + slide_key, + Animation::new(Duration::from_millis(CLOSE_SLIDE_MS)).with_easing(ease_out_quint()), + move |d, t| { + let open = if closing { 1.0 - t } else { t }; + d.w(px(CLOSE_W * open)).ml(px(-ROW_GAP * (1.0 - open))) + }, + ), ) }) .when(hovered && !row.running, |d| { @@ -631,7 +672,7 @@ impl Workspace { /// "+ Code session" with no project chosen: pick where it starts. fn new_session_menu(&self) -> Vec { - let item = |label: String, hint: Option, act: Act, disabled: bool, sep: bool| MenuItem { label, hint, act, danger: false, disabled, separator_before: sep }; + let item = |label: String, detail: Option, act: Act, disabled: bool, sep: bool| MenuItem { label, hint: None, detail, act, danger: false, disabled, separator_before: sep, remove: None, icon: None }; let mut items = vec![item("Start the session in…".into(), None, Act::Dismiss, true, false)]; items.extend(self.store.data.projects.iter().map(|p| item(p.name.clone(), Some(crate::panels::widgets::short_path(&p.path)), Act::NewClaude { cwd: p.path.clone() }, false, false))); items.push(item("Add project…".into(), None, Act::ImportProject, false, true)); @@ -664,7 +705,7 @@ impl Workspace { cx, move |ws, at, _w, cx| { let chosen = ws.project_filter().map(|p| p.id.clone()); - let item = |label: String, act: Act, sep: bool| MenuItem { label, hint: None, act, danger: false, disabled: false, separator_before: sep }; + let item = |label: String, act: Act, sep: bool| MenuItem { label, hint: None, detail: None, act, danger: false, disabled: false, separator_before: sep, remove: None, icon: None }; let mut items = vec![item(format!("{}All projects", tick(chosen.is_none())), Act::FilterProject(None), false)]; items.extend(ws.store.data.projects.iter().map(|p| item(format!("{}{}", tick(chosen.as_ref() == Some(&p.id)), p.name), Act::FilterProject(Some(p.id.clone())), false))); items.push(item("Add project…".into(), Act::ImportProject, true)); @@ -827,10 +868,13 @@ impl Workspace { let item = |label: String, hint: Option, act: Act, danger: bool, sep: bool| MenuItem { label, hint, + detail: None, act, danger, disabled: false, separator_before: sep, + remove: None, + icon: None, }; let accounts = &self.store.data.accounts; let mut items: Vec = accounts @@ -933,18 +977,30 @@ fn plan_label(plan: &str) -> String { #[cfg(test)] mod tests { - use super::{PULSE, is_reorder, move_to, pulse_opacity, visible_items}; - use std::time::Duration; + use super::{Item, ROW_H, RUNNING_ROW_H, Row, SessionDot, is_reorder, move_to, visible_items}; - #[test] - fn the_working_dot_fades_between_its_bounds_and_repeats_each_pulse() { - for ms in (0..2400).step_by(50) { - let o = pulse_opacity(Duration::from_millis(ms)); - assert!((0.35..=1.0).contains(&o), "{o} at {ms} ms"); - assert_eq!(o, pulse_opacity(Duration::from_millis(ms) + PULSE)); + fn row(running: bool) -> Row { + Row { + id: "s".into(), + dot: SessionDot::Active, + title: String::new(), + right: String::new(), + project: String::new(), + branch: None, + active: false, + dim: false, + running, + indent: false, + stale: false, + archived: false, + scope: "cur", } - // gpui's breathing curve: brightest a quarter of the way through, dimmest at three quarters. - assert!(pulse_opacity(PULSE / 4) > 0.99 && pulse_opacity(PULSE * 3 / 4) < 0.36); + } + + #[test] + fn a_running_session_gets_the_tall_row_and_a_recent_one_stays_short() { + assert_eq!(Item::Session { row: row(true), reorder: true }.height(), RUNNING_ROW_H); + assert_eq!(Item::Session { row: row(false), reorder: false }.height(), ROW_H); } #[test] diff --git a/src/panels/status_icon.rs b/src/panels/status_icon.rs new file mode 100644 index 0000000..febf79f --- /dev/null +++ b/src/panels/status_icon.rs @@ -0,0 +1,178 @@ +//! The status icon at the start of a session row: one Lucide circle per state, spinning while Claude works. When the +//! state changes, the old icon turns, shrinks and fades away while the new one does the same in reverse. + +use std::f32::consts::{FRAC_PI_2, TAU}; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +use gpui::{Animation, AnimationExt, AnyElement, App, Hsla, IntoElement, ParentElement, RenderOnce, SharedString, Styled, Window, div, ease_out_quint, px}; +use gpui_kit::assets::IconName; + +use crate::panels::theme::{self, hsla}; +use crate::panels::widgets::icon; + +/// What a session row's status icon shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SessionDot { + /// Claude Code is waiting for the user: a question or a permission. + Waiting, + /// Claude finished while the row was not being watched. + Attention, + /// The process is running and streaming output. + Working, + /// Running and idle, with the user up to date. + Active, + /// The session is not running. + Inactive, +} + +/// The icon's square, and how long one turn of the working icon takes. +const SLOT: f32 = 14.0; +const SPIN: Duration = Duration::from_millis(1600); +/// How often the working icon is redrawn (see `Workspace::start_spin`). A gpui animation would redraw the whole +/// window every frame for as long as any session works. +pub const SPIN_STEP: Duration = Duration::from_millis(40); +/// How long one icon takes to turn into the next. +const MORPH: Duration = Duration::from_millis(280); + +/// How far the working icon has turned `elapsed` into its spin, in radians; repeats every `SPIN`. +fn spin_angle(elapsed: Duration) -> f32 { + (elapsed.as_millis() % SPIN.as_millis()) as f32 / SPIN.as_millis() as f32 * TAU +} + +/// How one icon is drawn: its size and opacity as a fraction of the resting look, and an extra turn. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Look { + scale: f32, + opacity: f32, + turn: f32, +} + +impl Look { + const REST: Look = Look { scale: 1.0, opacity: 1.0, turn: 0.0 }; +} + +/// The old and the new icon `t` (0 to 1) of the way through a morph. The new one ends at `Look::REST`, so nothing +/// jumps when the morph is over and the plain icon takes its place. +fn morph_frame(t: f32) -> (Look, Look) { + let old = Look { scale: 1.0 - 0.6 * t, opacity: 1.0 - t, turn: t * FRAC_PI_2 }; + let new = Look { scale: 0.4 + 0.6 * t, opacity: t, turn: (t - 1.0) * FRAC_PI_2 }; + (old, new) +} + +/// One state's icon and color. `None` is the not-running ring, which is drawn rather than loaded. +fn icon_of(state: SessionDot) -> Option<(IconName, u32)> { + match state { + SessionDot::Waiting => Some((IconName::CircleQuestionMark, theme::WARN)), + SessionDot::Attention => Some((IconName::CircleCheck, theme::ACCENT)), + SessionDot::Working => Some((IconName::CircleDotDashed, 0xc8c8c8)), + SessionDot::Active => Some((IconName::CircleSmall, theme::TEXT_DIM)), + SessionDot::Inactive => None, + } +} + +/// `state` drawn with `look`, centered in the slot. +fn glyph(state: SessionDot, look: Look) -> AnyElement { + static START: OnceLock = OnceLock::new(); + let drawn = match icon_of(state) { + Some((name, color)) => { + let spin = if state == SessionDot::Working { spin_angle(START.get_or_init(Instant::now).elapsed()) } else { 0.0 }; + let color: Hsla = hsla(color).opacity(look.opacity); + icon(name, SLOT * look.scale).text_color(color).rotate(gpui::radians(spin + look.turn)).into_any_element() + } + None => div().size(px(7.0 * look.scale)).rounded_full().border_1().border_color(hsla(0x3d3d43).opacity(look.opacity)).into_any_element(), + }; + div().absolute().inset_0().flex().items_center().justify_center().child(drawn).into_any_element() +} + +/// What the icon showed last, kept across redraws so a change of state can be told from a redraw. +struct Memory { + shown: SessionDot, + /// The state before the last change, until `MORPH` after it. + from: Option, + changed: Instant, + /// Counts the changes, so each morph is a new animation. + epoch: u64, +} + +/// A row's status icon. `id` must be the same on every redraw of the row and differ between rows. +#[derive(IntoElement)] +pub struct StatusIcon { + id: SharedString, + state: SessionDot, +} + +impl StatusIcon { + pub fn new(id: impl Into, state: SessionDot) -> Self { + Self { id: id.into(), state } + } +} + +impl RenderOnce for StatusIcon { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let Self { id, state } = self; + let memory = window.use_keyed_state(id.clone(), cx, move |_, _| Memory { shown: state, from: None, changed: Instant::now(), epoch: 0 }); + let (from, epoch) = memory.update(cx, |m, _| { + if m.shown != state { + m.from = Some(m.shown); + m.shown = state; + m.changed = Instant::now(); + m.epoch += 1; + } + (m.from.filter(|_| m.changed.elapsed() < MORPH), m.epoch) + }); + let slot = div().relative().flex_none().size(px(SLOT)); + match from { + None => slot.child(glyph(state, Look::REST)).into_any_element(), + Some(from) => slot + .with_animation( + SharedString::from(format!("{id}-morph-{epoch}")), + Animation::new(MORPH).with_easing(ease_out_quint()), + move |slot, t| { + let (old, new) = morph_frame(t); + slot.child(glyph(from, old)).child(glyph(state, new)) + }, + ) + .into_any_element(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_morph_starts_on_the_old_icon_and_ends_on_the_new_one_at_rest() { + let (old, new) = morph_frame(0.0); + assert_eq!(old, Look::REST); + assert_eq!(new.opacity, 0.0); + let (old, new) = morph_frame(1.0); + assert_eq!(old.opacity, 0.0); + assert_eq!(new, Look::REST); + } + + #[test] + fn halfway_through_both_icons_are_partly_visible() { + let (old, new) = morph_frame(0.5); + assert!(old.opacity > 0.0 && new.opacity > 0.0); + assert!(old.scale < 1.0 && new.scale < 1.0); + } + + #[test] + fn the_working_icon_turns_once_per_spin_and_repeats() { + assert_eq!(spin_angle(Duration::ZERO), 0.0); + let quarter = spin_angle(SPIN / 4); + assert!((quarter - FRAC_PI_2).abs() < 1e-3, "a quarter of the spin is {quarter} radians"); + let (early, later) = (spin_angle(Duration::from_millis(300)), spin_angle(Duration::from_millis(300) + SPIN * 3)); + assert!((early - later).abs() < 1e-4); + } + + #[test] + fn only_a_session_that_is_not_running_draws_a_ring_instead_of_an_icon() { + for state in [SessionDot::Waiting, SessionDot::Attention, SessionDot::Working, SessionDot::Active] { + assert!(icon_of(state).is_some(), "{state:?}"); + } + assert!(icon_of(SessionDot::Inactive).is_none()); + } +} diff --git a/src/panels/workspace_view.rs b/src/panels/workspace_view.rs index f4ad9f0..befd3a5 100644 --- a/src/panels/workspace_view.rs +++ b/src/panels/workspace_view.rs @@ -31,7 +31,10 @@ impl Workspace { let hints = self.shortcuts_shown; let title = rec.as_ref().map(|r| r.display_title().to_string()).unwrap_or_else(|| "Claudiu".into()); - let branch = project.as_ref().and_then(|p| p.git.as_ref()).and_then(|g| g.branch.clone()); + // The branch and the worktree of the session's own folder, which is not the project's folder for a worktree session. + let git = project.as_ref().and_then(|p| p.git.as_ref()); + let branch = git.and_then(|g| cwd.as_deref().map_or(g.branch.as_deref(), |c| g.branch_at(c))).map(str::to_string); + let worktree = project.as_ref().zip(git).zip(cwd.as_deref()).and_then(|((p, g), c)| Some((p.id.clone(), c.to_path_buf(), crate::git::worktree::label(g, c)?))); // `.occlude()` on both groups: the bar is a Windows drag (HTCAPTION) area, which would otherwise swallow clicks on the buttons inside it. // The top bar spans the window and is drawn as the window background, not as a panel. macOS keeps its // traffic lights at the left (they are hidden in fullscreen); Windows/Linux get min/max/close at the right. @@ -107,6 +110,30 @@ impl Workspace { .child(tail) .dropdown(cx, move |ws, at, _w, cx| ws.open_branch_menu(repo.clone(), at, cx)), ) + }) + .when_some(worktree, |d, (project, cwd, label)| { + // Click: the repository's worktrees and a new one (see Workspace::open_worktree_menu). + d.child( + div() + .id("worktree") + .occlude() + .flex_none() + .flex() + .items_center() + .gap(px(4.0)) + .px(px(7.0)) + .py(px(1.0)) + .rounded(px(10.0)) + .bg(hsla(0x26262a)) + .text_size(crate::panels::scale::px(11.0)) + .text_color(hsla(theme::TEXT_DIM)) + .cursor_pointer() + .hover(|s| s.bg(hsla(0x323236)).text_color(hsla(theme::TEXT))) + .child(icon(IconName::FolderGit2, 12.0)) + .child(label) + .child(icon(IconName::ChevronDown, 12.0)) + .dropdown(cx, move |ws, at, _w, cx| ws.open_worktree_menu(project.clone(), cwd.clone(), at, cx)), + ) }), ) .child( @@ -333,7 +360,7 @@ impl Workspace { .child(button("home-claude", "New", true).dropdown( cx, |ws, at, _w, cx| { - let item = |label: String, act: Act, sep: bool| crate::app::MenuItem { label, hint: None, act, danger: false, disabled: false, separator_before: sep }; + let item = |label: String, act: Act, sep: bool| crate::app::MenuItem { label, hint: None, detail: None, act, danger: false, disabled: false, separator_before: sep, remove: None, icon: None }; let mut items: Vec<_> = ws.store.data.projects.iter().map(|p| item(p.name.clone(), Act::NewClaude { cwd: p.path.clone() }, false)).collect(); let sep = !items.is_empty(); items.push(item("Add project…".into(), Act::ImportProject, sep)); @@ -383,7 +410,7 @@ impl Workspace { let color = if item.disabled { theme::TEXT_FAINT } else if item.danger { theme::DANGER } else { theme::TEXT }; let row = div() .id(gpui::SharedString::from(format!("menu-{i}"))) - .h(px(28.0)) + .h(px(if item.detail.is_some() { 42.0 } else { 28.0 })) .px(px(10.0)) .flex() .items_center() @@ -391,8 +418,27 @@ impl Workspace { .text_size(crate::panels::scale::px(12.5)) .text_color(hsla(color)) .gap(px(8.0)) - .child(div().flex_1().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().child(item.label.clone())) - .children(item.hint.clone().map(|h| div().flex_none().text_size(crate::panels::scale::px(11.0)).text_color(hsla(theme::TEXT_FAINT)).child(h))); + .group(gpui::SharedString::from(format!("menu-row-{i}"))) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child(div().overflow_hidden().whitespace_nowrap().text_ellipsis().child(item.label.clone())) + .children(item.detail.clone().map(|d| div().overflow_hidden().whitespace_nowrap().text_ellipsis().text_size(crate::panels::scale::px(11.0)).text_color(hsla(theme::TEXT_FAINT)).child(d))), + ) + .children(item.icon.map(|name| icon(name, 12.0).text_color(hsla(theme::TEXT_FAINT)))) + .children(item.hint.clone().map(|h| div().flex_none().text_size(crate::panels::scale::px(11.0)).text_color(hsla(theme::TEXT_FAINT)).child(h))) + .children(item.remove.clone().map(|remove| { + icon_button(gpui::SharedString::from(format!("menu-remove-{i}")), IconName::X) + .invisible() + .group_hover(gpui::SharedString::from(format!("menu-row-{i}")), |s| s.visible()) + .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| { + cx.stop_propagation(); + ws.act(remove.clone(), window, cx); + })) + })); card = card.child(if item.disabled { row } else { @@ -431,7 +477,7 @@ impl Workspace { confirm.clone(), *danger, ), - Modal::Settings { .. } => ("Settings".into(), settings_body(self.settings_page, modal, &self.settings_scroll, window, cx), "Save".into(), false), + Modal::Settings { .. } => ("Settings".into(), settings_body(self.settings_page, modal, &self.worktrees_page, &self.settings_scroll, window, cx), "Save".into(), false), Modal::Advisor { input, .. } => ( "Advisor model".into(), div() @@ -459,6 +505,33 @@ impl Workspace { .into(), false, ), + Modal::NewWorktree { input, base, .. } => { + use crate::git::worktree::Base; + let choice = |id: &'static str, label: &'static str, this: Base| { + button(id, label, *base == this).on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| ws.act(Act::PickBase(this), window, cx))) + }; + ( + "New worktree".into(), + div() + .flex() + .flex_col() + .gap(px(10.0)) + .child(div().text_size(crate::panels::scale::px(12.0)).text_color(hsla(theme::TEXT_DIM)).child("The session moves into it and keeps its history. Claudiu makes a folder for it in its own data folder, outside your repository, with a new branch of this name.")) + .child(Input::new(input)) + .child( + div() + .flex() + .items_center() + .gap(px(6.0)) + .child(div().text_size(crate::panels::scale::px(12.0)).text_color(hsla(theme::TEXT_FAINT)).child("Start from")) + .child(choice("base-main", "Main", Base::Main)) + .child(choice("base-current", "Current branch", Base::Current)), + ) + .into_any_element(), + "Create and switch".into(), + false, + ) + } Modal::GoToLine { input, .. } => ("Go to line".into(), Input::new(input).into_any_element(), "Go".into(), false), Modal::Rename { input, .. } | Modal::NewBranch { input, .. } => ( if matches!(modal, Modal::NewBranch { .. }) { "New branch" } else { "Rename session" }.into(), @@ -760,7 +833,7 @@ impl Render for Workspace { } /// The Settings dialog's body: the category list on the left and the chosen page on the right. -fn settings_body(page: SettingsPage, modal: &Modal, scroll: &crate::panels::glide::Smooth, window: &mut Window, cx: &mut Context) -> AnyElement { +fn settings_body(page: SettingsPage, modal: &Modal, worktrees: &crate::app::WorktreesPage, scroll: &crate::panels::glide::Smooth, window: &mut Window, cx: &mut Context) -> AnyElement { let Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, list_focus } = modal else { return div().into_any_element(); }; @@ -856,6 +929,7 @@ fn settings_body(page: SettingsPage, modal: &Modal, scroll: &crate::panels::glid } list } + SettingsPage::Worktrees => worktrees_page(worktrees, cx), SettingsPage::About => div().child(faint(format!( "Claudiu {} · An independent project, not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic.", env!("CARGO_PKG_VERSION") @@ -881,9 +955,8 @@ fn settings_body(page: SettingsPage, modal: &Modal, scroll: &crate::panels::glid .hover(|s| s.bg(hsla(0x1f1f1f))) .child(p.label()) .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| { - ws.settings_page = p; + ws.set_settings_page(p, cx); window.focus(&focus, cx); - cx.notify(); })), ) }, @@ -898,6 +971,89 @@ fn settings_body(page: SettingsPage, modal: &Modal, scroll: &crate::panels::glid .into_any_element() } +/// The Worktrees page: the worktree folders Claudiu made, by repository, each to show in the file manager or remove. +fn worktrees_page(page: &crate::app::WorktreesPage, cx: &mut Context) -> gpui::Div { + let scaled = crate::panels::scale::px; + let faint = |text: String| div().text_size(scaled(11.0)).text_color(hsla(theme::TEXT_FAINT)).child(text); + let reveal = if cfg!(target_os = "macos") { "Show in Finder" } else { "Show in File Explorer" }; + let mut list = div().flex().flex_col().gap(px(8.0)).child(faint( + "Worktrees Claudiu made live in its own data folder, outside your repositories. Removing one here asks the same question as the x in the top-bar menu.".to_string(), + )); + let Some(stored) = &page.stored else { return list.child(faint("Looking…".to_string())) }; + if stored.is_empty() { + return list.child(faint("No worktrees yet. Make one from the worktree button in the top bar.".to_string())); + } + let mut group: Option<&std::path::Path> = None; + for (i, item) in stored.iter().enumerate() { + let repo_folder = item.folder.parent(); + if group != repo_folder { + group = repo_folder; + let heading = match &item.main_checkout { + Some(main) => main.to_string_lossy().into_owned(), + None => format!("{} (repository not found)", repo_folder.and_then(|p| p.file_name()).unwrap_or_default().to_string_lossy()), + }; + list = list.child(div().mt(px(4.0)).child(section_label(heading))); + } + let name = item.folder.file_name().unwrap_or_default().to_string_lossy().into_owned(); + let (folder, remove) = (item.folder.clone(), item.main_checkout.clone()); + let revealed = folder.clone(); + let asked = page.asking.as_ref().filter(|a| a.folder == item.folder); + let ask = match remove { + Some(main_checkout) => Act::RemoveWorktree { main_checkout, folder: folder.clone() }, + None => Act::AskDeleteUnlisted(folder.clone()), + }; + let row = div() + .flex() + .flex_col() + .gap(px(6.0)) + .px(px(10.0)) + .py(px(6.0)) + .rounded(px(6.0)) + .bg(hsla(0x111111)) + .border_1() + .border_color(hsla(0x242424)) + .child( + div() + .flex() + .items_center() + .justify_between() + .gap(px(10.0)) + .child( + div() + .flex_1() + .min_w_0() + .child(div().text_size(scaled(13.0)).child(name)) + .child(faint(item.folder.to_string_lossy().into_owned()).overflow_hidden().text_ellipsis().whitespace_nowrap()), + ) + .child( + div() + .flex() + .gap(px(6.0)) + .child(button(format!("worktree-reveal-{i}"), reveal, false).on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| ws.act(Act::Reveal(revealed.clone()), window, cx)))) + .child(button(format!("worktree-remove-{i}"), "Remove", false).on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| ws.act(ask.clone(), window, cx)))), + ), + ); + list = list.child(match asked { + None => row, + Some(asked) => { + let act = asked.act.clone(); + let confirm = if asked.danger { danger_button(format!("worktree-confirm-{i}"), asked.confirm.clone()) } else { button(format!("worktree-confirm-{i}"), asked.confirm.clone(), true) }; + row.child(faint(asked.body.clone())).child( + div() + .flex() + .gap(px(6.0)) + .child(button(format!("worktree-cancel-{i}"), "Cancel", false).on_click(cx.listener(|ws, _: &ClickEvent, _window, cx| { + ws.worktrees_page.asking = None; + cx.notify(); + }))) + .child(confirm.on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| ws.act(act.clone(), window, cx)))), + ) + } + }); + } + list +} + /// An On/Off row in the Settings modal; `field` picks the flag it flips. fn settings_toggle(id: &'static str, label: &'static str, on: bool, field: fn(&mut Modal) -> Option<&mut bool>, cx: &mut Context) -> impl IntoElement { switch_row(id, label, on, move |ws| { diff --git a/src/platform.rs b/src/platform.rs index a86ff6f..6266d47 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -369,6 +369,32 @@ pub fn is_same_or_under(child: &Path, parent: &Path) -> bool { c == p || c.starts_with(&format!("{p}/")) } +/// Whether a process with this id is running right now. +#[cfg(windows)] +pub fn process_running(pid: u32) -> bool { + use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE}; + use windows_sys::Win32::System::Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION}; + // SAFETY: the handle is checked for null before use and closed after. + unsafe { + let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if handle.is_null() { + return false; + } + let mut code = 0; + let read = GetExitCodeProcess(handle, &mut code); + CloseHandle(handle); + read != 0 && code == STILL_ACTIVE as u32 + } +} + +/// Whether a process with this id is running right now. +#[cfg(unix)] +pub fn process_running(pid: u32) -> bool { + // Signal 0 only checks; EPERM means the process exists but belongs to someone else. + // SAFETY: `kill` with signal 0 sends nothing. + unsafe { libc::kill(pid as libc::pid_t, 0) == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) } +} + #[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)] pub enum Editor { VsCode, @@ -560,6 +586,12 @@ bye assert_eq!(resolve_program("definitely-not-a-program-xyz"), None); } + #[test] + fn this_process_is_running_and_a_huge_pid_is_not() { + assert!(process_running(std::process::id())); + assert!(!process_running(u32::MAX - 1)); + } + #[test] fn containment_ignores_separator_style_and_trailing_slash() { assert!(is_same_or_under(Path::new("C:/a/b/c"), Path::new("C:/a/b"))); diff --git a/src/store.rs b/src/store.rs index 8817fdc..6f5819d 100644 --- a/src/store.rs +++ b/src/store.rs @@ -691,6 +691,12 @@ pub fn reconcile(data: &mut Data, external: &[ExternalSession], scan_ok: bool) - #[cfg(test)] mod tests { + #[test] + fn the_worktree_toggle_saved_by_an_earlier_version_is_ignored() { + let settings: Settings = serde_json::from_str(r#"{"worktree_sessions":true}"#).unwrap(); + assert_eq!(settings, Settings::default()); + } + use super::*; fn ext(id: &str, cwd: &str, title: &str, last: i64) -> ExternalSession { diff --git a/src/terminal/mod.rs b/src/terminal/mod.rs index ba6dda0..870b716 100644 --- a/src/terminal/mod.rs +++ b/src/terminal/mod.rs @@ -339,4 +339,20 @@ mod tests { std::thread::sleep(Duration::from_secs(3)); assert_ne!(unsafe { libc::kill(pid, 0) }, 0, "child must be gone"); } + + #[cfg(windows)] + #[test] + fn closing_ends_a_running_child() { + let spec = SpawnSpec { program: "ping.exe".into(), args: vec!["-n".into(), "60".into(), "127.0.0.1".into()], cwd: None, ..Default::default() }; + let (t, _rx) = Terminal::spawn(&spec, 80, 24).unwrap(); + let pid = t.process_id().unwrap(); + std::thread::sleep(Duration::from_millis(500)); + assert!(crate::platform::process_running(pid)); + drop(t); + let began = Instant::now(); + while crate::platform::process_running(pid) { + assert!(began.elapsed() < Duration::from_secs(10), "the child outlived its terminal"); + std::thread::sleep(Duration::from_millis(50)); + } + } } diff --git a/src/terminal/view/mod.rs b/src/terminal/view/mod.rs index 384731e..bc41c87 100644 --- a/src/terminal/view/mod.rs +++ b/src/terminal/view/mod.rs @@ -53,9 +53,18 @@ struct Metrics { shift: Pixels, } -/// A session moving to another account: who to, and when it began (the old process compacts first, then restarts). +/// Where a view was last drawn: its grid and cell size. +#[derive(Clone, Copy)] +pub struct Layout { + cols: u16, + rows: u16, + metrics: Metrics, +} + +/// A session being moved while its process restarts: what the skeleton says, and when the move began (an account +/// hand-off compacts the old process first, so it began earlier than the restart). pub struct Handover { - pub to: String, + pub message: String, pub since: Instant, } @@ -88,7 +97,7 @@ pub struct TerminalView { font_size: Pixels, /// Show a startup animation until the program first draws something (set for Claude sessions). pub loading: bool, - /// The skeleton says the session is handing over until the new process is ready. + /// The skeleton says what the session is being moved to until the new process is ready. pub handover: Option, /// Whether a pane currently shows this terminal (kept up to date by the workspace's render). pub visible: bool, @@ -163,6 +172,20 @@ impl TerminalView { self.terminal.start_error() } + /// `None` until the view has been drawn. + pub fn layout(&self) -> Option { + let (cols, rows) = self.terminal.size(); + self.metrics.map(|metrics| Layout { cols, rows, metrics }) + } + + /// Start on the grid of a view in the same pane. A view's first frame is drawn before it is laid out, so a new one + /// would otherwise draw that frame, and the skeleton's prompt with it, on the default 120×32 grid. + pub fn take_layout(&mut self, layout: Layout) { + let Layout { cols, rows, metrics } = layout; + self.terminal.resize(cols, rows, f32::from(metrics.cell_w), f32::from(metrics.line_h)); + self.metrics = Some(metrics); + } + pub fn new( terminal: Terminal, rx: UnboundedReceiver, @@ -407,7 +430,7 @@ impl Render for TerminalView { } } let phase = match (&self.handover, self.handing, self.last_output) { - (Some(h), _, _) => format!("Handing over to {}…", h.to), + (Some(h), _, _) => h.message.clone(), (None, true, _) => "Handing your message to Claude Code…".into(), (None, false, Some(_)) => "Loading skills, plugins and MCP servers…".into(), (None, false, None) => "Starting Claude Code…".into(), @@ -448,6 +471,11 @@ impl Render for TerminalView { } impl TerminalView { + /// The skeleton is up: Claude Code is starting, or the session is being moved. + pub fn is_loading(&self) -> bool { + self.held() + } + /// Input goes to the skeleton's draft, not the PTY: Claude Code is starting, or the session is handing over. fn held(&self) -> bool { self.loading || self.handover.is_some() diff --git a/src/terminal/view/mouse.rs b/src/terminal/view/mouse.rs index a810c9f..3e82389 100644 --- a/src/terminal/view/mouse.rs +++ b/src/terminal/view/mouse.rs @@ -2,6 +2,10 @@ use super::*; +/// A wheel notch scrolls the terminal's scrollback this many times what the system reports for it. Lower than the +/// panels' `glide::NOTCH`, because terminal lines are dense and 1.6 raced through the history. +const TERMINAL_NOTCH: f32 = 0.8; + impl TerminalView { pub(super) fn grid_point(&self, position: Point) -> Option<(GridPoint, Side, usize, usize)> { let m = self.metrics?; @@ -230,7 +234,7 @@ impl TerminalView { let top = self.terminal.term.lock().history_size() as f32; let here = self.position(); if notch { - crate::panels::glide::Glide::nudge(&mut self.glide, here, lines * crate::panels::glide::NOTCH, 0.0, top); + crate::panels::glide::Glide::nudge(&mut self.glide, here, lines * TERMINAL_NOTCH, 0.0, top); } else { self.glide = None; self.set_position((here + lines).clamp(0.0, top));