From 808c7a082dabb2f994b1ca69b51c4e5b19d963f7 Mon Sep 17 00:00:00 2001 From: Angel-Mario Savin Date: Thu, 5 Nov 2026 10:31:03 +0200 Subject: [PATCH] Switch worktrees before the first message and let Claude switch them A session with no conversation yet can now move to another worktree: it starts over in the target folder under the same session id, where it used to be refused for having no transcript to resume. Claude can ask for a switch with the new switch_worktree tool (main, a listed worktree, or a new name). The user is always asked first. The answer goes back at once and the switch runs when the session's turn ends, so the restart never cuts off the call that asked for it. --- README.md | 2 +- src/app/background.rs | 1 + src/app/cross.rs | 89 +++++++++++++++++++++++++++++++++++++------ src/app/mod.rs | 8 +++- src/app/sessions.rs | 41 ++++++++++++++------ src/app/switch.rs | 39 +++++++++++-------- src/claude/mcp.rs | 26 +++++++++---- src/git/worktree.rs | 47 +++++++++++++++++++++++ 8 files changed, 205 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 5141136..62f9088 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ 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. 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. +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 (a session that has no conversation yet starts over in the new folder). Claude can switch the session itself with the `switch_worktree` tool, after you approve it and once its turn ends. In the menu, the 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. diff --git a/src/app/background.rs b/src/app/background.rs index 49fdfcc..bb5e555 100644 --- a/src/app/background.rs +++ b/src/app/background.rs @@ -112,6 +112,7 @@ impl Workspace { let update = this.update_in(cx, |ws, window, cx| { ws.serve_requests(requests, window, cx); ws.finish_handoffs(window, cx); + ws.run_pending_switches(&statuses, window, cx); ws.check_open_files(window, cx); ws.update_activity(window, cx, &statuses) }); diff --git a/src/app/cross.rs b/src/app/cross.rs index f42eb9b..c8e4a86 100644 --- a/src/app/cross.rs +++ b/src/app/cross.rs @@ -18,6 +18,19 @@ pub struct PendingStart { shown: bool, } +/// A worktree switch the user approved, waiting for the turn in which the session asked for it to end: the switch restarts +/// the process that made the call. +pub struct PendingSwitch { + id: Id, + folder: PathBuf, + base: crate::git::worktree::Base, + /// Unix seconds when the user approved it. + approved: i64, +} + +/// How long an approved switch waits for the turn to end before it is given up. +const SWITCH_PATIENCE_SECS: i64 = 300; + /// Longest part of the first message the dialog quotes. const SHOWN_PROMPT: usize = 600; @@ -28,6 +41,13 @@ fn start_question(asker: &str, folder: &std::path::Path, prompt: &str) -> String format!("“{asker}” wants to open a new Claude Code session in {} with this first message:\n\n{quoted}{more}", folder.to_string_lossy()) } +/// What the dialog says about the worktree a session wants to move into. +fn switch_question(asker: &str, folder: &std::path::Path, new: bool) -> String { + let name = folder.file_name().map_or_else(|| folder.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()); + let what = if new { format!("a new worktree, {name}") } else { format!("the worktree {name}") }; + format!("“{asker}” wants to switch to {what}. Its process restarts once its turn ends, and the conversation continues there.") +} + /// `2026-10-22 09:10 UTC` for a Unix time (days since 1970 turned into a calendar date, no time crate needed). fn utc(ts: i64) -> String { let (days, secs) = (ts.div_euclid(86_400), ts.rem_euclid(86_400)); @@ -124,14 +144,13 @@ impl Workspace { let requester = p.req.from.split_once(':').map_or(p.req.from.as_str(), |(_, id)| id); let asker = self.store.session(requester).map_or_else(|| "A session".to_string(), |s| s.display_title().to_string()); let folder = PathBuf::from(p.req.args["folder"].as_str().unwrap_or_default()); - let prompt = p.req.args["prompt"].as_str().unwrap_or_default().trim().to_string(); - self.modal = Some(Modal::Confirm { - title: "Start a Claude Code session?".into(), - body: start_question(&asker, &folder, &prompt), - confirm: "Start session".into(), - danger: false, - act: Act::ConfirmStartSession(p.req.id.clone()), - }); + let (title, body, confirm) = if p.req.tool == "switch_worktree" { + ("Switch worktree?", switch_question(&asker, &folder, p.req.args["new"].as_bool().unwrap_or(false)), "Switch") + } else { + let prompt = p.req.args["prompt"].as_str().unwrap_or_default().trim().to_string(); + ("Start a Claude Code session?", start_question(&asker, &folder, &prompt), "Start session") + }; + self.modal = Some(Modal::Confirm { title: title.into(), body, confirm: confirm.into(), danger: false, act: Act::ConfirmStartSession(p.req.id.clone()) }); window.focus(&self.modal_focus, cx); cx.notify(); } @@ -146,8 +165,11 @@ impl Workspace { answer(&req, ok, result.unwrap_or_else(|e| e)); } - /// Check what starting a session needs and resolve the folder into `req.args["folder"]`. + /// Check what the request needs. A new session's folder, or the worktree to switch to, is resolved into `req.args["folder"]`. fn prepare(&self, req: &mut Request) -> Result<(), String> { + if req.tool == "switch_worktree" { + return self.prepare_switch(req); + } if req.tool != "start_code_session" { return Ok(()); } @@ -162,6 +184,42 @@ impl Workspace { Ok(()) } + fn prepare_switch(&self, req: &mut Request) -> Result<(), String> { + let id = req.from.split_once(':').map_or(req.from.as_str(), |(_, id)| id); + let rec = self.store.session(id).ok_or("Claudiu doesn't know this session.")?; + let git = rec.project_id.as_ref().and_then(|p| self.store.project(p)).and_then(|p| p.git.as_ref()).ok_or("This session's project is not a git repository.")?; + let wanted = req.args["worktree"].as_str().unwrap_or_default(); + let listed = crate::git::worktree::folders(git).into_iter().skip(1).filter_map(|f| f.file_name().map(|n| n.to_string_lossy().into_owned())).collect::>(); + let target = crate::git::worktree::resolve(git, &rec.cwd, wanted).map_err(|why| format!("{why} Worktrees: main{}{}.", if listed.is_empty() { "" } else { ", " }, listed.join(", ")))?; + req.args["folder"] = target.folder.to_string_lossy().into_owned().into(); + req.args["new"] = target.new.into(); + Ok(()) + } + + /// Start the approved switches whose session has ended its turn. Looks at Claude Code's own status, as a switch from + /// the menu does, so the call that asked is finished and answered first. + pub(super) fn run_pending_switches(&mut self, statuses: &std::collections::HashMap, window: &mut Window, cx: &mut Context) { + let now = crate::store::now(); + let pending = std::mem::take(&mut self.pending_switches); + for p in pending { + let claude_id = self.store.session(&p.id).and_then(|r| r.claude_id()); + // Without a registry entry (older Claude Code) the terminal's own activity decides, as in `switch::inspect`. + let idle = match claude_id.and_then(|c| statuses.get(c)) { + Some(status) => status == "idle", + None => self.live_view(&p.id).is_some_and(|v| !v.read(cx).is_working()), + }; + if now - p.approved > SWITCH_PATIENCE_SECS { + self.toast("The worktree switch was dropped: the session's turn did not end.", true, cx); + } else if !self.is_running(&p.id, cx) { + // Closed in the meantime: nothing to move. + } else if idle { + self.switch_session(p.id, p.folder, p.base, false, window, cx); + } else { + self.pending_switches.push(p); + } + } + } + /// Do what was asked. pub(super) fn run_request(&mut self, req: &Request, window: &mut Window, cx: &mut Context) -> Result { let id = req.args["id"].as_str().unwrap_or_default().to_string(); @@ -241,6 +299,13 @@ impl Workspace { None => Err("The session could not be started (is the `claude` CLI installed?).".into()), } } + "switch_worktree" => { + let folder = folder.ok_or("No folder.")?; + let base = if req.args["base"].as_str() == Some("current") { crate::git::worktree::Base::Current } else { crate::git::worktree::Base::Main }; + let name = folder.file_name().map_or_else(|| "the main checkout".into(), |n| n.to_string_lossy().into_owned()); + self.pending_switches.push(PendingSwitch { id: requester_id.to_string(), folder, base, approved: crate::store::now() }); + Ok(format!("Approved. Claudiu switches this session to {name} as soon as your turn ends, so end your turn now: reply in one line and make no more tool calls. The user's next message continues the same conversation there.")) + } other => Err(format!("unknown tool {other}")), } } @@ -258,9 +323,10 @@ mod tests { } } -/// A new session with a first message of its own is a prompt the user did not write. +/// A new session with a first message of its own is a prompt the user did not write, and a worktree switch restarts the +/// session: both wait for the user's yes. fn wants_confirmation(req: &Request) -> bool { - req.tool == "start_code_session" && req.args["prompt"].as_str().is_some_and(|p| !p.trim().is_empty()) + req.tool == "switch_worktree" || (req.tool == "start_code_session" && req.args["prompt"].as_str().is_some_and(|p| !p.trim().is_empty())) } #[cfg(test)] @@ -278,6 +344,7 @@ mod start_tests { assert!(!wants_confirmation(&request("start_code_session", json!({"folder": "/p"}))), "no prompt, nothing to approve"); assert!(!wants_confirmation(&request("start_code_session", json!({"folder": "/p", "prompt": " "})))); assert!(!wants_confirmation(&request("read_code_session", json!({"prompt": "x"})))); + assert!(wants_confirmation(&request("switch_worktree", json!({"worktree": "fix"}))), "a switch always asks"); } #[test] diff --git a/src/app/mod.rs b/src/app/mod.rs index 99310e7..1c21561 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -125,6 +125,7 @@ pub enum Act { }, /// `SwitchWorktree`, after the user agreed to leave uncommitted files behind. ConfirmSwitch { + id: Id, folder: PathBuf, base: Base, }, @@ -500,6 +501,8 @@ pub struct Workspace { pub config_sync: config_sync::Runner, /// Sessions asked to open another with a first message; each waits for the user's yes (`cross.rs`). pub pending_starts: Vec, + /// Worktree switches the user approved that a session asked for; each waits for the session's turn to end (`cross.rs`). + pub pending_switches: Vec, pub drag_pos: Option>, pub update: UpdateState, pub scanning: bool, @@ -604,6 +607,7 @@ impl Workspace { attached_sync: Default::default(), config_sync: Default::default(), pending_starts: vec![], + pending_switches: vec![], update: UpdateState::default(), scanning: false, quitting: false, @@ -667,9 +671,9 @@ impl Workspace { } } Act::SwitchWorktree { folder, base } => self.switch_shown(folder, base, false, window, cx), - Act::ConfirmSwitch { folder, base } => { + Act::ConfirmSwitch { id, folder, base } => { self.modal = None; - self.switch_shown(folder, base, true, window, cx) + self.switch_session(id, 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), diff --git a/src/app/sessions.rs b/src/app/sessions.rs index b31040f..5088fb9 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -106,22 +106,13 @@ 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) { + pub(super) fn new_claude_with(&mut self, cwd: PathBuf, 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; - }; let session_id = new_id(); let record_id = new_id(); - let mut spec = claude::new_session_spec(&exe, &cwd, &session_id); - let settings = &self.store.data.settings; - let defaults = claude::defaults::flags(&settings.new_session, settings.trimmed_tools.contains(&claude::trim::Trim::PlanMode), &leading, by); - leading.extend(defaults); - spec.args.splice(0..0, leading); let chrome = self.store.data.settings.chrome_default; - let spec = self.with_helpers(spec, &session_id, &record_id, chrome, cx); + let Some(spec) = self.fresh_spec(&cwd, &session_id, &record_id, chrome, leading, by, cx) else { return }; let record = SessionRecord { id: record_id, kind: SessionKind::Claude, @@ -143,6 +134,34 @@ impl Workspace { self.start(record, spec, true, window, cx); } + /// `claude --session-id` in `cwd` with the new-session defaults. None, with a toast, when `claude` isn't installed. + #[allow(clippy::too_many_arguments)] + fn fresh_spec(&mut self, cwd: &std::path::Path, session_id: &str, record_id: &str, chrome: bool, mut leading: Vec, by: Starter, cx: &mut Context) -> Option { + 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 None; + }; + let mut spec = claude::new_session_spec(&exe, cwd, session_id); + let settings = &self.store.data.settings; + let defaults = claude::defaults::flags(&settings.new_session, settings.trimmed_tools.contains(&claude::trim::Trim::PlanMode), &leading, by); + leading.extend(defaults); + spec.args.splice(0..0, leading); + Some(self.with_helpers(spec, session_id, record_id, chrome, cx)) + } + + /// Start the session over under its own id in its folder. For a session with no conversation yet: `--resume` has + /// nothing to find, and nothing is lost. A running view of it is replaced, which ends its process. + pub(super) fn relaunch_empty(&mut self, id: &str, window: &mut Window, cx: &mut Context) { + let Some(rec) = self.store.session(id).cloned() else { return }; + let Some(meta) = rec.claude.clone() else { return }; + let cwd = self.resume_cwd(&rec, cx); + let Some(mut spec) = self.fresh_spec(&cwd, &meta.session_id, &rec.id, meta.chrome, vec![], Starter::User, cx) else { return }; + if let Some(name) = rec.chosen_title() { + spec.args.extend(["--name".into(), name.into()]); + } + self.start(rec, spec, false, 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()); diff --git a/src/app/switch.rs b/src/app/switch.rs index 30c3233..deb48d7 100644 --- a/src/app/switch.rs +++ b/src/app/switch.rs @@ -47,11 +47,12 @@ fn inspect(claude_id: &str, folder: &Path, quiet: bool) -> Checked { /// 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> { +fn prepare(main_checkout: &Path, folder: &Path, base: Base, transcript: Option<&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) + // Without a conversation there is nothing recorded to clear. + transcript.map_or(Ok(()), |t| clear_worktree_record(t, claude_id)) } fn clear_worktree_record(transcript: &Path, claude_id: &str) -> Result<(), String> { @@ -66,6 +67,11 @@ impl Workspace { /// 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 }; + self.switch_session(id, folder, base, asked, window, cx); + } + + /// Switch session `id` (shown or not) into `folder`. + pub(super) fn switch_session(&mut self, id: Id, folder: PathBuf, base: Base, asked: bool, window: &mut Window, cx: &mut Context) { 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 }; @@ -98,11 +104,6 @@ impl Workspace { 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) }; @@ -112,24 +113,26 @@ impl Workspace { body: format!("{files} in {name}. Your shell restarts."), confirm: "Switch".into(), danger: false, - act: Act::ConfirmSwitch { folder, base }, + act: Act::ConfirmSwitch { id, folder, base }, }); return; } - self.perform_switch(id, folder, base, transcript, window, cx); + self.perform_switch(id, folder, base, checked.transcript, window, cx); } - fn perform_switch(&mut self, id: Id, folder: PathBuf, base: Base, transcript: PathBuf, window: &mut Window, cx: &mut Context) { + /// `transcript` is None for a session that has no conversation yet: it starts over in the folder, as a new session. + fn perform_switch(&mut self, id: Id, folder: PathBuf, base: Base, transcript: Option, 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); + let fresh = transcript.is_none(); 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 ready = cx.background_executor().spawn(async move { prepare(&main_checkout, &target, base, transcript.as_deref(), &claude_id) }).await; let _ = this.update_in(cx, |ws, window, cx| match ready { - Ok(()) => ws.move_into(&id, folder, message, window, cx), + Ok(()) => ws.move_into(&id, folder, message, fresh, window, cx), Err(why) => { ws.set_handover(&id, None, cx); ws.toast(format!("Couldn't switch: {why}."), true, cx); @@ -139,8 +142,9 @@ impl Workspace { .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) { + /// The old process ends and a new one resumes the conversation in `folder`, as a restart does; `fresh` when there is + /// no conversation to resume. + fn move_into(&mut self, id: &str, folder: PathBuf, message: String, fresh: bool, window: &mut Window, cx: &mut Context) { // Closed while the target was readied. if !self.is_running(id, cx) { return; @@ -151,7 +155,12 @@ impl Workspace { if let Some(r) = self.store.session_mut(id) { r.cwd = folder; } - self.relaunch(id, window, cx); // replacing the view ends the old process + // Replacing the view ends the old process. + if fresh { + self.relaunch_empty(id, window, cx); + } else { + self.relaunch(id, window, cx); + } self.set_handover(id, Some(Handover { message, since: Instant::now() }), cx); self.restore_shell(id, shell, window, cx); if was_shown { diff --git a/src/claude/mcp.rs b/src/claude/mcp.rs index 0503c99..5d8b7cc 100644 --- a/src/claude/mcp.rs +++ b/src/claude/mcp.rs @@ -93,7 +93,7 @@ fn is_off(off: &[&str], tool: &str) -> bool { const OWN_TOOLS: [&str; 6] = ["set_tab_title", "attach_github", "detach_github", "link_session", "unlink_session", "show_visual"]; /// Tools that reach other sessions (`claude/bridge.rs`). -const BRIDGE_TOOLS: [&str; 5] = ["list_code_sessions", "read_code_session", "search_sessions", "search_projects", "start_code_session"]; +const BRIDGE_TOOLS: [&str; 6] = ["list_code_sessions", "read_code_session", "search_sessions", "search_projects", "start_code_session", "switch_worktree"]; /// `mcp____` names allowed per process so Claude Code adds no prompt of its own: renaming the tab is /// harmless, and the cross-session tools are limited to what the user asks of the model. @@ -103,7 +103,9 @@ pub fn allowed_tools(off: &[&str]) -> Vec { const BRIDGE_INSTRUCTIONS: &str = " Claudiu also has tools that reach your other sessions: list_code_sessions, read_code_session, \ search_sessions, search_projects and start_code_session. They act at once. Use them only when the user asks you to look at, hand \ -work to or continue in another session, or to work in a project; search_sessions may also be used unasked to find a session to link."; +work to or continue in another session, or to work in a project; search_sessions may also be used unasked to find a session to link. \ +switch_worktree moves this session into another git worktree of its project; call it only when the user asks for a worktree, and \ +end your turn once it is approved."; const LINK_INSTRUCTIONS: &str = " Claudiu shows related sessions together. When this work continues or builds on another \ Claude Code session (the user says so, or you recognise it), find it with search_sessions and call link_session once per pair; \ @@ -368,6 +370,14 @@ fn bridge_tools() -> Vec { json!({ "query": { "type": "string", "description": "Words to look for (optional: without it, every project)" } }), ), tool("start_code_session", format!("Open a new Claude Code session, optionally with a first prompt. With a prompt, the user is asked to approve it first; without one, it opens at once.{CONFIRM}"), target), + tool( + "switch_worktree", + "Move this session into another git worktree of its project: `main` for the main checkout, the name of a worktree the project has, or a new name to make one. The user is asked to approve it first. Claudiu then restarts this session in that folder once your turn ends and the conversation continues there, so after the approval end your turn without more tool calls.".to_string(), + json!({ + "worktree": { "type": "string", "description": "`main`, a worktree's name, or a new name (letters, digits, - and _)" }, + "base": { "type": "string", "enum": ["main", "current"], "description": "For a new worktree: start from origin's default branch (main, the default) or from the commit the main checkout is on (current)" }, + }), + ), ] } @@ -616,7 +626,7 @@ mod tests { let names: Vec<_> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); assert_eq!( names, - ["set_tab_title", "attach_github", "detach_github", "set_model", "link_session", "unlink_session", "show_visual", "list_code_sessions", "read_code_session", "search_sessions", "search_projects", "start_code_session"] + ["set_tab_title", "attach_github", "detach_github", "set_model", "link_session", "unlink_session", "show_visual", "list_code_sessions", "read_code_session", "search_sessions", "search_projects", "start_code_session", "switch_worktree"] ); let upfront: Vec<_> = tools.iter().filter(|t| t["_meta"]["anthropic/alwaysLoad"] == true).map(|t| t["name"].as_str().unwrap()).collect(); assert_eq!(upfront, ["set_tab_title", "attach_github", "detach_github", "link_session", "unlink_session"], "show_visual and the session-reaching tools stay deferred"); @@ -775,7 +785,7 @@ mod tests { #[test] fn with_nothing_off_the_server_offers_every_tool_and_all_the_text() { let (names, text) = offer(&[]); - assert_eq!(names.len(), 12); + assert_eq!(names.len(), 13); for part in [TITLE_INSTRUCTIONS, GITHUB_INSTRUCTIONS, LINK_INSTRUCTIONS, VISUAL_INSTRUCTIONS, BRIDGE_INSTRUCTIONS] { assert!(text.contains(part)); } @@ -785,22 +795,22 @@ mod tests { #[test] fn each_feature_takes_its_tools_and_its_text_away() { let (names, text) = offer(&["visual"]); - assert!(!names.contains(&"show_visual".to_string()) && names.len() == 11); + assert!(!names.contains(&"show_visual".to_string()) && names.len() == 12); assert!(!text.contains("Visual:") && !text.contains("show_visual")); let (names, text) = offer(&["github"]); - assert!(!names.iter().any(|n| n.ends_with("_github")) && names.len() == 10); + assert!(!names.iter().any(|n| n.ends_with("_github")) && names.len() == 11); assert!(!text.contains("attach_github")); let (names, text) = offer(&["sessions"]); - for gone in ["link_session", "unlink_session", "list_code_sessions", "read_code_session", "search_sessions", "search_projects", "start_code_session"] { + for gone in ["link_session", "unlink_session", "list_code_sessions", "read_code_session", "search_sessions", "search_projects", "start_code_session", "switch_worktree"] { assert!(!names.contains(&gone.to_string()), "{gone}"); } assert_eq!(names.len(), 5); assert!(!text.contains("link_session") && !text.contains("start_code_session")); let (names, text) = offer(&["model"]); - assert!(!names.contains(&"set_model".to_string()) && names.len() == 11); + assert!(!names.contains(&"set_model".to_string()) && names.len() == 12); assert!(!text.contains("set_model") && !text.contains("Never switch models")); } diff --git a/src/git/worktree.rs b/src/git/worktree.rs index a8981bd..27dd4cf 100644 --- a/src/git/worktree.rs +++ b/src/git/worktree.rs @@ -173,6 +173,35 @@ pub fn check_unused(main_checkout: &Path, name: &str) -> Result<(), String> { } } +/// Where a name given by the model leads. +#[derive(Debug, PartialEq, Eq)] +pub struct Target { + pub folder: PathBuf, + /// The folder does not exist yet; switching makes it. + pub new: bool, +} + +/// What `wanted` names, seen from a session in `cwd`: `main`, a working tree of the repository by its folder name, or a +/// new name. Switching to the tree the session is in is an error: it would only restart the process. +pub fn resolve(git: &GitInfo, cwd: &Path, wanted: &str) -> Result { + let wanted = wanted.trim(); + let listed = folders(git); + let existing = if wanted.eq_ignore_ascii_case("main") { listed.first().copied() } else { listed.into_iter().skip(1).find(|f| f.file_name().is_some_and(|n| n.to_string_lossy() == wanted)) }; + let target = match existing { + Some(folder) => Target { folder: folder.to_path_buf(), new: false }, + None => { + check_name(wanted)?; + let main = source(Some(git)).map_err(|why| format!("A new worktree can't be made: the project {why}."))?; + check_unused(main, wanted)?; + Target { folder: folder(main, wanted), new: true } + } + }; + if git.folder_of(cwd).is_some_and(|here| path_key(here) == path_key(&target.folder)) { + return Err("This session is already in that worktree.".into()); + } + Ok(target) +} + /// 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(); @@ -382,6 +411,24 @@ mod tests { assert_eq!(source(Some(&info("/p/.claude/worktrees/a", "/p", &["/p"], false))), Ok(Path::new("/p"))); } + #[test] + fn a_name_from_the_model_leads_to_main_a_listed_tree_or_a_new_one() { + use_throwaway_data_folder(); + let git = info("/p", "/p", &["/p/.claude/worktrees/fix"], false); + let main = Path::new("/p/src"); + let ok = |wanted| resolve(&git, main, wanted); + assert_eq!(ok("fix"), Ok(Target { folder: "/p/.claude/worktrees/fix".into(), new: false })); + assert_eq!(ok("fresh"), Ok(Target { folder: folder(Path::new("/p"), "fresh"), new: true })); + // From inside `fix`, main is a real move and `fix` is not. + let in_fix = Path::new("/p/.claude/worktrees/fix/src"); + assert_eq!(resolve(&git, in_fix, "MAIN"), Ok(Target { folder: "/p".into(), new: false })); + assert!(resolve(&git, in_fix, "fix").unwrap_err().contains("already in")); + assert!(ok("main").unwrap_err().contains("already in")); + // A name git would refuse is refused before anything is made, and a repository without commits has no source. + assert!(ok("bad name").is_err() && ok("").is_err()); + assert!(resolve(&info("/p", "/p", &[], true), main, "fresh").unwrap_err().contains("no commits yet")); + } + #[test] fn the_pill_names_the_working_tree_a_session_is_in() { let git = info("/p", "/p", &["/p/.claude/worktrees/fix"], false);