diff --git a/crates/ide-agent/src/acp/mod.rs b/crates/ide-agent/src/acp/mod.rs index 7c7c7ff380..9cfe215886 100644 --- a/crates/ide-agent/src/acp/mod.rs +++ b/crates/ide-agent/src/acp/mod.rs @@ -80,6 +80,8 @@ fn client_capabilities() -> Value { "subagents": {}, // Forms the agent asks the user to fill in (`elicitation/create`); not URL mode. "elicitation": { "form": {} }, + // Ghost-text next-prompt suggestions (`prompt_suggestions_update`). + "session": { "promptSuggestions": {} }, // Cursor exposes model parameters (e.g. Composer `fast`) as separate config options // only when the client advertises this flag (undocumented Cursor ACP extension). "_meta": { "parameterizedModelPicker": true }, @@ -94,7 +96,7 @@ pub(crate) fn initialize_params(client_info: &Value) -> Value { json!({ "protocolVersion": 2, "info": client_info, - "capabilities": {}, + "capabilities": { "session": { "promptSuggestions": {} } }, "clientCapabilities": client_capabilities(), "clientInfo": client_info, }) diff --git a/crates/ide-agent/src/acp/tests.rs b/crates/ide-agent/src/acp/tests.rs index 8bfbfafa2b..4080a8fc29 100644 --- a/crates/ide-agent/src/acp/tests.rs +++ b/crates/ide-agent/src/acp/tests.rs @@ -133,11 +133,14 @@ fn the_negotiating_request_carries_both_versions() { ); // Forms only: URL mode would open pages the agent names. assert_eq!(p["clientCapabilities"]["elicitation"], json!({ "form": {} })); + assert_eq!(p["clientCapabilities"]["session"], json!({ "promptSuggestions": {} })); + assert_eq!(p["capabilities"]["session"], json!({ "promptSuggestions": {} })); // What we sent in the capture is what claude-agent-acp negotiated v2 and v1 from. let sent = frames(TURN, "out")[0]["params"]["clientCapabilities"].clone(); let mut expected = sent; expected["_meta"] = p["clientCapabilities"]["_meta"].clone(); expected["elicitation"] = p["clientCapabilities"]["elicitation"].clone(); + expected["session"] = p["clientCapabilities"]["session"].clone(); assert_eq!(expected, p["clientCapabilities"]); } diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index e0108b6025..6f6f494993 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -187,8 +187,14 @@ const STDERR_LINES: usize = 20; /// (`session/load`): the next message starts it again where it left off. const IDLE_RELEASE: Duration = Duration::from_secs(5 * 60); /// Updates of a session's state rather than its conversation. -const SESSION_STATE: [&str; 5] = - ["session_info_update", "config_option_update", "current_mode_update", "available_commands_update", "usage_update"]; +const SESSION_STATE: [&str; 6] = [ + "session_info_update", + "config_option_update", + "current_mode_update", + "available_commands_update", + "usage_update", + "prompt_suggestions_update", +]; /// A native agent's own update: it is about to retry a failed API request (see [`AgentRetry`]). pub(crate) const RETRY_UPDATE: &str = "openidea_retry"; /// A native agent's own update: the usage limits of its account (see [`AgentLimit`]). @@ -1694,6 +1700,7 @@ impl AgentManager { unread: false, recovery_window_mins: None, automation: None, + prompt_suggestions: Box::default(), }; let file = TaskFile { task: task.clone(), @@ -1791,6 +1798,7 @@ impl AgentManager { unread: false, recovery_window_mins: None, automation: None, + prompt_suggestions: Box::default(), }; let file = TaskFile { task: task.clone(), @@ -1879,10 +1887,21 @@ impl AgentManager { ))); } let dir = self.shared.paths.worktrees_dir.clone(); - let (t, b, task_id) = (title.clone(), req.base.clone(), id.clone()); - let c = vcs(&self.shared, move || worktree::create_for_task(&root, &dir, &task_id, &t, b.as_deref())) + if let Some(wt_path) = req.worktree_path.map(|p| p.0) { + let (c, before) = vcs(&self.shared, move || { + let c = worktree::reuse_for_task(&root, &dir, &wt_path)?; + let before = worktree::snapshot(&c.cwd).unwrap_or_default(); + Ok((c, before)) + }) .await?; - (c.cwd, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new()) + (c.cwd, Some(c.branch), Some(c.base), Some(c.base_commit), before) + } else { + let (t, b, task_id) = (title.clone(), req.base.clone(), id.clone()); + let c = + vcs(&self.shared, move || worktree::create_for_task(&root, &dir, &task_id, &t, b.as_deref())) + .await?; + (c.cwd, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new()) + } } Isolation::Local => { let r = root.clone(); @@ -1977,6 +1996,7 @@ impl AgentManager { unread: false, recovery_window_mins: None, automation: automation_meta.clone().map(Box::new), + prompt_suggestions: Box::default(), }; let initial_scheduled = automation_meta.as_ref().map(|m| ScheduledTurnMeta { permissions: m.permissions, @@ -2081,6 +2101,7 @@ impl AgentManager { } else { let epoch = self.shared.shutdown_epoch(); s.busy = true; + s.task.prompt_suggestions.clear(); s.pending_prompt = Some(prompt.clone()); s.active_scheduled_turn = scheduled.clone(); // A run watcher reads the status before the spawned turn shows its prompt, and @@ -2450,6 +2471,7 @@ impl AgentManager { interrupted: None, unread: false, automation: None, + prompt_suggestions: Box::default(), ..s.task.clone() }; let (session, cut) = match session { @@ -2533,6 +2555,7 @@ impl AgentManager { s.history.conversation = Conversation::default(); // The fresh session reports its own usage; nothing carries over. s.task.usage = None; + s.task.prompt_suggestions.clear(); s.pending_rollback = 0; s.task.updated_ms = now_ms(); Self::finish_rewind(&mut s, 0, restamped); @@ -2565,6 +2588,7 @@ impl AgentManager { _ => None, }; s.history.conversation.truncate(cut); + s.task.prompt_suggestions.clear(); s.task.updated_ms = now_ms(); Self::finish_rewind(&mut s, turns as usize, restamped); (first, task.turn_dir(), s.history.turns.clone()) @@ -3291,7 +3315,12 @@ impl AgentManager { if isolation != Isolation::Worktree || busy || !cwd.exists() { return Ok(false); } - let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd); + let target_root = worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &cwd); + let shared = self.tasks.read().values().any(|t| { + t.id != id + && worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &t.state.lock().task.cwd.0) + == target_root + }); if shared { return Ok(false); } @@ -3327,6 +3356,139 @@ impl AgentManager { Ok(true) } + /// Checks out (or creates and checks out) a Git branch in an idle task's working directory. + /// Rejects archived tasks, untrusted local repos, or checkouts where this task or any sibling + /// sharing the same worktree/repo is busy. Holds `BusyGuard` across the checkout to prevent + /// concurrent turns/checkouts, and updates `task.branch` (plus `base`/`base_commit` when + /// switching to an existing branch) for all worktree tasks sharing the checkout. + pub async fn checkout_branch(&self, id: &str, branch: &str, create: bool) -> IdeResult { + if !git_enabled(&self.shared) { + return Err(IdeError::invalid("Git is disabled for this project")); + } + let task = self.task(id)?; + let (isolation, raw_cwd) = { + let s = task.state.lock(); + if s.task.status == AgentStatus::Archived { + return Err(IdeError::invalid("cannot switch branches on an archived task")); + } + if s.busy || matches!(s.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput) + { + return Err(IdeError::invalid("stop the current turn before switching branches")); + } + (s.task.isolation, s.task.cwd.0.clone()) + }; + let cwd = if isolation == Isolation::Worktree { + task.verify_worktree_cwd_confined()? + } else { + if let Some(repo) = Repo::discover(&raw_cwd)? { + let canon_repo = dunce::canonicalize(repo.root())?; + if let Some(check) = self.shared.repo_trust.read().clone() + && !check(&canon_repo) + { + return Err(IdeError::invalid(format!( + "Git repository {} is not trusted: trust the repository root before switching branches", + canon_repo.display() + ))); + } + } + raw_cwd + }; + let local_repo_key = if isolation == Isolation::Local { + Repo::discover(&cwd)?.and_then(|r| dunce::canonicalize(r.root()).ok()).map(worktree::normalize_path_key) + } else { + None + }; + let wt_root_key = if isolation == Isolation::Worktree { + Some(worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &cwd)) + } else { + None + }; + // Collect all tasks sharing this checkout in deterministic BTreeMap ID order and acquire + // BusyGuard on every one so concurrent turns, rollbacks, or checkouts cannot race. + let (group, guards) = { + let tasks = self.tasks.read(); + let mut group = Vec::new(); + let mut guards = Vec::new(); + for other in tasks.values() { + let matches = if other.id == id { + true + } else { + let (other_iso, other_cwd) = { + let s = other.state.lock(); + (s.task.isolation, s.task.cwd.0.clone()) + }; + if let Some(ref target_wt) = wt_root_key { + worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &other_cwd) == *target_wt + } else if other_iso == Isolation::Local + && let Some(ref target_repo) = local_repo_key + { + Repo::discover(&other_cwd) + .ok() + .flatten() + .and_then(|r| dunce::canonicalize(r.root()).ok()) + .map(worktree::normalize_path_key) + .as_ref() + == Some(target_repo) + } else { + false + } + }; + if !matches { + continue; + } + let mut s = other.state.lock(); + if other.id == id && s.task.status == AgentStatus::Archived { + return Err(IdeError::invalid("cannot switch branches on an archived task")); + } + if s.busy + || matches!(s.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput) + { + return Err(IdeError::invalid(if other.id == id { + "stop the current turn before switching branches" + } else { + "another task sharing this checkout is currently running" + })); + } + s.busy = true; + guards.push(BusyGuard(other.clone())); + group.push(other.clone()); + } + (group, guards) + }; + let branch = branch.to_owned(); + let (current, head_commit, outcome) = + vcs(&self.shared, move || worktree::checkout_branch(&cwd, &branch, create)).await?; + let switched = matches!( + outcome, + ide_vcs::CheckoutOutcome::Done + | ide_vcs::CheckoutOutcome::Conflicts { .. } + | ide_vcs::CheckoutOutcome::RestoreFailed { .. } + ); + let mut updated = Vec::new(); + if switched && isolation == Isolation::Worktree { + for member in &group { + let mut s = member.state.lock(); + if s.task.isolation != Isolation::Worktree { + continue; + } + s.task.branch = Some(current.clone()); + if !create { + s.task.base = Some(current.clone()); + if let Some(ref commit) = head_commit { + s.task.base_commit = Some(commit.clone()); + } + } + updated.push(member.clone()); + } + } + drop(guards); + for member in updated { + member.persist(); + member.emit_task(); + } + Ok(outcome) + } + /// Forgets the task; with `remove_worktree` also deletes its worktree (the branch stays). pub async fn delete(&self, id: &str, remove_worktree: bool) -> IdeResult<()> { let task = self.task(id)?; @@ -3339,8 +3501,14 @@ impl AgentManager { s.task.project_root.clone().map(|p| p.0).unwrap_or_else(|| self.shared.paths.project_root.clone()), ) }; - // A copy of the task (a fork) may work in the same worktree. - let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd); + // A copy of the task (a fork) or a task reusing the worktree (even from a subdir) may + // work in the same physical worktree checkout root. + let target_root = worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &cwd); + let shared = self.tasks.read().values().any(|t| { + t.id != id + && worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &t.state.lock().task.cwd.0) + == target_root + }); self.tasks.write().remove(id); task.file.lock().deleted = true; let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json"))); @@ -3912,6 +4080,7 @@ impl Task { /// The task from the parts of `file` other than its history, which `history` holds. fn assemble(file: TaskFile, history: StoredHistory, adopt: bool, shared: Arc) -> Arc { let mut task = file.task; + task.prompt_suggestions.clear(); config::add_client_options(&shared.base_id(&task.provider), &mut task.config); let mut wanted = file.wanted; let mut pending_model = file.pending_switch.or_else(|| { @@ -6363,10 +6532,24 @@ impl Task { .or(s.task.usage.take()); true } + "prompt_suggestions_update" => { + if self.replaying.load(Ordering::Acquire) { + false + } else { + let next = prompt_suggestions_of(update); + let changed = *s.task.prompt_suggestions != next; + *s.task.prompt_suggestions = next; + changed + } + } _ => false, } }; if task_changed { + if kind == "prompt_suggestions_update" { + self.emit_task(); + return; + } let (config, commands, model) = { let s = self.state.lock(); ( @@ -7757,3 +7940,77 @@ fn sync_usage_context_size(task: &mut AgentTask) { usage.size = tokens; } } + +const MAX_PROMPT_SUGGESTIONS: usize = 5; + +/// Extracts plain-text prompt suggestions from an ACP `prompt_suggestions_update` payload. +fn prompt_suggestions_of(update: &Value) -> Vec { + let Some(items) = update.get("suggestions").and_then(Value::as_array) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for item in items { + let Some(blocks) = item.get("prompt").and_then(Value::as_array) else { + continue; + }; + let mut text = String::new(); + for block in blocks { + match block.get("type").and_then(Value::as_str) { + Some("text") => { + if let Some(s) = block.get("text").and_then(Value::as_str) { + text.push_str(s); + } + } + Some("resource_link") => { + let label = block + .get("name") + .and_then(Value::as_str) + .filter(|s| !s.trim().is_empty()) + .or_else(|| block.get("uri").and_then(Value::as_str).and_then(|u| u.rsplit('/').next())); + if let Some(label) = label { + if !text.is_empty() && !text.ends_with(char::is_whitespace) { + text.push(' '); + } + text.push('@'); + text.push_str(label.trim()); + } + } + _ => {} + } + } + let trimmed = text.trim(); + if !trimmed.is_empty() && !out.iter().any(|existing| existing == trimmed) { + out.push(trimmed.to_owned()); + if out.len() >= MAX_PROMPT_SUGGESTIONS { + break; + } + } + } + out +} + +#[cfg(test)] +mod prompt_suggestion_tests { + use super::prompt_suggestions_of; + use serde_json::json; + + #[test] + fn parses_text_and_resource_link_prompt_suggestions() { + let update = json!({ + "sessionUpdate": "prompt_suggestions_update", + "suggestions": [ + { "prompt": [{ "type": "text", "text": "Run the unit tests" }] }, + { + "prompt": [ + { "type": "text", "text": "Explain " }, + { "type": "resource_link", "uri": "file:///repo/src/lib.rs", "name": "src/lib.rs" } + ] + }, + { "prompt": [{ "type": "text", "text": " " }] }, + { "prompt": [{ "type": "text", "text": "Run the unit tests" }] } + ] + }); + assert_eq!(prompt_suggestions_of(&update), vec!["Run the unit tests", "Explain @src/lib.rs"]); + assert!(prompt_suggestions_of(&json!({ "suggestions": [] })).is_empty()); + } +} diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index 132fbb9187..0ab468af62 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -204,6 +204,10 @@ pub struct AgentTask { #[serde(default, skip_serializing_if = "Option::is_none")] #[specta(optional)] pub automation: Option>, + /// Ephemeral next-prompt suggestions from ACP `prompt_suggestions_update`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[specta(optional)] + pub prompt_suggestions: Box>, } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] @@ -870,6 +874,10 @@ pub struct NewAgentTask { pub isolation: Isolation, /// Branch to start the worktree from; the current branch when `None`. pub base: Option, + /// Reuse an existing managed worktree directory instead of creating a new one (`Isolation::Worktree` only). + #[serde(default)] + #[specta(optional)] + pub worktree_path: Option, /// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`). #[serde(default)] pub mcp_overrides: BTreeMap, diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index b43bb5f947..1b379236dd 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -6684,6 +6684,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() { config: Vec::new(), isolation: Isolation::Local, base: None, + worktree_path: None, mcp_overrides: BTreeMap::from([("slack".into(), false)]), idle: false, skill_overrides: BTreeMap::new(), @@ -6747,6 +6748,7 @@ async fn per_session_memory_overrides_deliver_only_for_native_claude_and_codex() config: Vec::new(), isolation: Isolation::Local, base: None, + worktree_path: None, mcp_overrides: BTreeMap::new(), skill_overrides: BTreeMap::new(), memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }), @@ -6797,6 +6799,7 @@ async fn per_session_memory_overrides_deliver_only_for_native_claude_and_codex() config: Vec::new(), isolation: Isolation::Local, base: None, + worktree_path: None, mcp_overrides: BTreeMap::new(), skill_overrides: BTreeMap::new(), memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadOnly) }), @@ -6825,6 +6828,7 @@ async fn per_session_memory_overrides_deliver_only_for_native_claude_and_codex() config: Vec::new(), isolation: Isolation::Local, base: None, + worktree_path: None, mcp_overrides: BTreeMap::new(), skill_overrides: BTreeMap::new(), memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }), @@ -6871,6 +6875,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl config: Vec::new(), isolation: Isolation::Local, base: None, + worktree_path: None, mcp_overrides: BTreeMap::new(), idle: false, skill_overrides: BTreeMap::from([ @@ -7020,6 +7025,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails() config: vec![AgentConfigChoice { id: "context_tier".into(), value: "long_context".into() }], isolation: Isolation::Local, base: None, + worktree_path: None, mcp_overrides: BTreeMap::new(), idle: false, skill_overrides: BTreeMap::new(), @@ -7048,6 +7054,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails() config: vec![], isolation: Isolation::Local, base: None, + worktree_path: None, mcp_overrides: BTreeMap::new(), idle: false, skill_overrides: BTreeMap::new(), @@ -7773,3 +7780,162 @@ async fn an_accepted_scheduled_prompt_no_longer_reads_as_ready() { assert_eq!(mgr.task_snapshot(&task.id).unwrap().status, AgentStatus::Starting); wait_for(&mgr, &task.id, AgentStatus::Ready).await; } + +#[tokio::test(flavor = "multi_thread")] +async fn shared_worktree_delete_preserves_checkout_across_subdirs() { + let repo = Checkout::new(Eol::Lf); + std::fs::create_dir_all(repo.dir.join("packages").join("app")).unwrap(); + repo.write("packages/app/a.txt", "hello\n"); + repo.commit("init"); + + let mgr = manager(&repo.dir, Arc::new(FakeAgent::default())); + let _down = ShutDown(&mgr); + + let root_task = mgr + .create(NewAgentTask { + provider: "claude".into(), + prompt: text("again"), + isolation: Isolation::Worktree, + idle: true, + ..Default::default() + }) + .await + .unwrap(); + + // Reuse the same worktree for a task rooted in a subdirectory of the repository. + let sub_task = mgr + .create(NewAgentTask { + project_root: Some(IpcPath(repo.dir.join("packages").join("app"))), + provider: "claude".into(), + prompt: text("again"), + isolation: Isolation::Worktree, + worktree_path: Some(root_task.cwd.clone()), + idle: true, + ..Default::default() + }) + .await + .unwrap(); + + assert_ne!(root_task.cwd.0, sub_task.cwd.0); + assert!(sub_task.cwd.0.starts_with(&root_task.cwd.0)); + + // Deleting the root task with `remove_worktree = true` MUST keep the shared worktree intact. + mgr.delete(&root_task.id, true).await.unwrap(); + assert!(sub_task.cwd.0.exists(), "shared worktree was deleted while subdir sibling still exists"); + + // Deleting the final surviving task removes the worktree. + mgr.delete(&sub_task.id, true).await.unwrap(); + assert!(!root_task.cwd.0.exists(), "worktree should be removed once no tasks share it"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn checkout_branch_guards_archived_untrusted_busy_siblings_and_updates_base_commit() { + let repo = Checkout::new(Eol::Lf); + repo.write("a.txt", "base\n"); + repo.commit("init"); + // Create a diverged branch with its own commit. + repo.git(&["checkout", "-q", "-b", "feat/diverged"]); + repo.write("diverged.txt", "from diverged\n"); + repo.commit("diverged commit"); + let diverged_head = worktree::head_of(&repo.dir).unwrap().1; + repo.git(&["checkout", "-q", "main"]); + + let mgr = manager(&repo.dir, Arc::new(FakeAgent::default())); + let _down = ShutDown(&mgr); + + let wt_a = mgr + .create(NewAgentTask { + provider: "claude".into(), + prompt: text("again"), + isolation: Isolation::Worktree, + idle: true, + ..Default::default() + }) + .await + .unwrap(); + let wt_b = mgr + .create(NewAgentTask { + provider: "claude".into(), + prompt: text("again"), + isolation: Isolation::Worktree, + worktree_path: Some(wt_a.cwd.clone()), + idle: true, + ..Default::default() + }) + .await + .unwrap(); + let original_base_commit = wt_a.base_commit.clone(); + + // 1. Busy sibling blocks checkout on the shared worktree. + mgr.task(&wt_b.id).unwrap().state.lock().busy = true; + let err = mgr.checkout_branch(&wt_a.id, "feat/diverged", false).await.unwrap_err(); + assert!(err.to_string().contains("running"), "unexpected error: {err}"); + mgr.task(&wt_b.id).unwrap().state.lock().busy = false; + + // 2. Creating a new branch (`create == true`) updates `branch` on both siblings while preserving `base_commit`. + let out = mgr.checkout_branch(&wt_a.id, "feat/new-from-wt", true).await.unwrap(); + assert_eq!(out, ide_vcs::CheckoutOutcome::Done); + let snap_a = mgr.task_snapshot(&wt_a.id).unwrap(); + let snap_b = mgr.task_snapshot(&wt_b.id).unwrap(); + assert_eq!(snap_a.branch.as_deref(), Some("feat/new-from-wt")); + assert_eq!(snap_b.branch.as_deref(), Some("feat/new-from-wt")); + assert_eq!(snap_a.base_commit, original_base_commit); + assert_eq!(snap_b.base_commit, original_base_commit); + + // 3. Switching to an existing diverged branch (`create == false`) updates `branch`, `base`, + // and `base_commit` on both siblings so unrelated commits don't pollute Changes. + let out = mgr.checkout_branch(&wt_a.id, "feat/diverged", false).await.unwrap(); + assert_eq!(out, ide_vcs::CheckoutOutcome::Done); + let snap_a = mgr.task_snapshot(&wt_a.id).unwrap(); + let snap_b = mgr.task_snapshot(&wt_b.id).unwrap(); + assert_eq!(snap_a.branch.as_deref(), Some("feat/diverged")); + assert_eq!(snap_b.branch.as_deref(), Some("feat/diverged")); + assert_eq!(snap_a.base.as_deref(), Some("feat/diverged")); + assert_eq!(snap_a.base_commit.as_deref(), Some(diverged_head.as_str())); + assert_eq!(snap_b.base_commit.as_deref(), Some(diverged_head.as_str())); + let grouped = mgr.grouped_changes(&wt_a.id).await.unwrap(); + assert!(grouped.commits.is_empty(), "unrelated commits on switched branch leaked into Changes"); + assert!(grouped.uncommitted.is_empty()); + + // 4. Archived task rejects branch checkout. + mgr.archive(&wt_a.id).unwrap(); + let err = mgr.checkout_branch(&wt_a.id, "feat/new-from-wt", false).await.unwrap_err(); + assert!(err.to_string().contains("archived"), "unexpected error: {err}"); + + // 5. Untrusted local repo rejects `checkout_branch`. + let local_task = mgr + .create(NewAgentTask { + provider: "claude".into(), + prompt: text("again"), + isolation: Isolation::Local, + idle: true, + ..Default::default() + }) + .await + .unwrap(); + mgr.set_repo_trust_hook(Arc::new(|_| false)); + let err = mgr.checkout_branch(&local_task.id, "feat/diverged", false).await.unwrap_err(); + assert!(err.to_string().contains("not trusted"), "unexpected error: {err}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn rollback_clears_prompt_suggestions() { + let tmp = tempfile::tempdir().unwrap(); + let mgr = manager(tmp.path(), Arc::new(FakeAgent::default())); + let _down = ShutDown(&mgr); + + let task = mgr + .create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() }) + .await + .unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + + { + let handle = mgr.task(&task.id).unwrap(); + *handle.state.lock().task.prompt_suggestions = vec!["Follow up".into()]; + } + assert_eq!(mgr.task_snapshot(&task.id).unwrap().prompt_suggestions.as_slice(), ["Follow up"]); + + mgr.rollback(&task.id, 0, false).await.unwrap(); + assert!(mgr.task_snapshot(&task.id).unwrap().prompt_suggestions.is_empty()); +} diff --git a/crates/ide-agent/src/worktree.rs b/crates/ide-agent/src/worktree.rs index 59f158bf64..82d919c8ca 100644 --- a/crates/ide-agent/src/worktree.rs +++ b/crates/ide-agent/src/worktree.rs @@ -287,6 +287,88 @@ pub(crate) fn create_for_task( Ok(Created { path, cwd: canon_cwd, branch, base, base_commit }) } +/// Validates and opens an existing managed worktree under `worktrees_dir` so a new task can +/// reuse it. Rejects paths outside `worktrees_dir`, non-directories, non-linked repositories, +/// or worktrees belonging to a different Git repository than `project_root`. Preserves any +/// project-relative subdirectory inside `project_root` just like [`create_for_task`]. +pub(crate) fn reuse_for_task(project_root: &Path, worktrees_dir: &Path, worktree_path: &Path) -> IdeResult { + let canon_input = verify_confined_worktree_cwd(worktrees_dir, worktree_path)?; + if !canon_input.is_dir() { + return Err(IdeError::not_found(format!("worktree {} does not exist", worktree_path.display()))); + } + let project_repo = repo_at(project_root)?; + let wt_repo = repo_at(&canon_input)?; + let [_, project_common] = project_repo.metadata_dirs()?; + let [wt_git_dir, wt_common] = wt_repo.metadata_dirs()?; + let canon_wt_git_dir = dunce::canonicalize(&wt_git_dir)?; + let canon_wt_common = dunce::canonicalize(&wt_common)?; + let canon_project_common = dunce::canonicalize(&project_common)?; + if canon_wt_git_dir == canon_wt_common || canon_wt_common != canon_project_common { + return Err(IdeError::invalid(format!( + "worktree {} is not a linked worktree of this repository", + worktree_path.display() + ))); + } + let canon_wt_root = dunce::canonicalize(wt_repo.root())?; + let canon_wt_dir = dunce::canonicalize(worktrees_dir)?; + if !canon_wt_root.starts_with(&canon_wt_dir) + || canon_wt_root == canon_wt_dir + || canon_wt_root.parent() != Some(canon_wt_dir.as_path()) + { + return Err(IdeError::invalid("worktree root does not match managed worktrees directory")); + } + let canon_repo = dunce::canonicalize(project_repo.root())?; + let canon_proj = dunce::canonicalize(project_root)?; + let rel_subdir = if canon_proj != canon_repo { + canon_proj + .strip_prefix(&canon_repo) + .map_err(|_| { + IdeError::invalid(format!( + "{} is outside git repository {}", + canon_proj.display(), + canon_repo.display() + )) + })? + .to_path_buf() + } else { + PathBuf::new() + }; + let raw_cwd = + if rel_subdir.as_os_str().is_empty() { canon_wt_root.clone() } else { canon_wt_root.join(&rel_subdir) }; + if !raw_cwd.is_dir() { + return Err(IdeError::invalid(format!( + "project folder {} does not exist in worktree {}", + rel_subdir.display(), + canon_wt_root.display() + ))); + } + let canon_cwd = verify_confined_worktree_subdir(&canon_wt_root, &raw_cwd)?; + let (branch, base_commit) = head_of(&canon_cwd)?; + Ok(Created { path: canon_wt_root, cwd: canon_cwd, branch: branch.clone(), base: branch, base_commit }) +} + +/// Checks out (or creates and checks out) `branch` in `cwd` using Smart checkout so uncommitted +/// edits are stashed and restored across the switch. Returns the resulting branch name, HEAD +/// commit (when available), and checkout outcome. +pub(crate) fn checkout_branch( + cwd: &Path, + branch: &str, + create: bool, +) -> IdeResult<(String, Option, ide_vcs::CheckoutOutcome)> { + let name = branch.trim(); + if name.is_empty() { + return Err(IdeError::invalid("branch name cannot be empty")); + } + let repo = repo_at(cwd)?; + let options = ide_vcs::CheckoutOptions { mode: ide_vcs::CheckoutMode::Smart, ..Default::default() }; + let outcome = repo.checkout_with(name, create, &options)?; + let (current, head_commit) = match head_of(cwd) { + Ok((b, commit)) => (b, Some(commit)), + Err(_) => (name.to_owned(), None), + }; + Ok((current, head_commit, outcome)) +} + fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult { let canon_cwd = dunce::canonicalize(target_cwd)?; let real_wt = ide_core::real_path::resolve_real(canon_wt_root); @@ -327,23 +409,60 @@ pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) -> verify_confined_worktree_subdir(&canon_wt_root, cwd) } -fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) { - if let Ok(rel) = path.strip_prefix(worktrees_dir) +/// Returns a canonical comparison key for the managed worktree checkout root containing `path`, +/// so two tasks pointing to different subdirs or path casings of the same worktree match. +pub(crate) fn shared_worktree_root(worktrees_dir: &Path, path: &Path) -> PathBuf { + let (root, _) = worktree_checkout_root(worktrees_dir, path); + let resolved = dunce::canonicalize(&root).unwrap_or(root); + normalize_path_key(resolved) +} + +pub(crate) fn normalize_path_key(path: PathBuf) -> PathBuf { + #[cfg(windows)] + { + PathBuf::from(path.to_string_lossy().replace('/', "\\").to_lowercase()) + } + #[cfg(not(windows))] + { + path + } +} + +fn first_child_under(base: &Path, path: &Path) -> Option { + if let Ok(rel) = path.strip_prefix(base) && let Some(first) = rel.components().next() { - return (worktrees_dir.join(first), worktrees_dir.to_path_buf()); + return Some(base.join(first)); + } + #[cfg(windows)] + { + let base_comps: Vec = + base.components().map(|c| c.as_os_str().to_string_lossy().to_lowercase()).collect(); + let path_comps: Vec> = path.components().collect(); + if path_comps.len() > base_comps.len() + && base_comps + .iter() + .zip(path_comps.iter()) + .all(|(a, b)| a == &b.as_os_str().to_string_lossy().to_lowercase()) + { + return Some(base.join(path_comps[base_comps.len()])); + } + } + None +} + +fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) { + if let Some(child) = first_child_under(worktrees_dir, path) { + return (child, worktrees_dir.to_path_buf()); } if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) { - if let Ok(rel) = path.strip_prefix(&canon_wt_dir) - && let Some(first) = rel.components().next() - { - return (canon_wt_dir.join(first), canon_wt_dir); + if let Some(child) = first_child_under(&canon_wt_dir, path) { + return (child, canon_wt_dir); } if let Ok(canon_path) = dunce::canonicalize(path) - && let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir) - && let Some(first) = rel.components().next() + && let Some(child) = first_child_under(&canon_wt_dir, &canon_path) { - return (canon_wt_dir.join(first), canon_wt_dir); + return (child, canon_wt_dir); } } (path.to_path_buf(), worktrees_dir.to_path_buf()) @@ -2314,4 +2433,109 @@ mod tests { "symlink swap on worktree reuse must be rejected: {reuse_err}" ); } + + #[test] + fn reuse_for_task_validates_confinement_and_repo_membership() { + let tmp = tempfile::tempdir().unwrap(); + let repo = tmp.path().join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + git(&repo, &["init", "-q", "-b", "main"]); + std::fs::write(repo.join("a.txt"), "hello\n").unwrap(); + git(&repo, &["add", "."]); + git(&repo, &["commit", "-q", "-m", "init"]); + + let other = tmp.path().join("other"); + std::fs::create_dir_all(&other).unwrap(); + git(&other, &["init", "-q", "-b", "main"]); + std::fs::write(other.join("b.txt"), "world\n").unwrap(); + git(&other, &["add", "."]); + git(&other, &["commit", "-q", "-m", "init other"]); + + let wt_dir = tmp.path().join("wt"); + let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap(); + + // Reusing a managed worktree of the same repository succeeds and reports its live branch. + let reused = super::reuse_for_task(&repo, &wt_dir, &created.cwd).unwrap(); + assert_eq!(reused.cwd, created.cwd); + assert_eq!(reused.branch, created.branch); + assert_eq!(reused.base_commit, created.base_commit); + + // Paths outside `worktrees_dir` are rejected. + assert!(super::reuse_for_task(&repo, &wt_dir, &repo).is_err()); + + // Worktrees belonging to a different repository are rejected. + let other_wt = create_for_task(&other, &wt_dir, "task-2", "Other work", None).unwrap(); + assert!(super::reuse_for_task(&repo, &wt_dir, &other_wt.cwd).is_err()); + } + + #[test] + fn checkout_branch_creates_and_switches_branches_in_worktree() { + let tmp = tempfile::tempdir().unwrap(); + let repo = tmp.path().join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + git(&repo, &["init", "-q", "-b", "main"]); + std::fs::write(repo.join("a.txt"), "hello\n").unwrap(); + git(&repo, &["add", "."]); + git(&repo, &["commit", "-q", "-m", "init"]); + + let wt_dir = tmp.path().join("wt"); + let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap(); + + let (branch, head_commit, outcome) = super::checkout_branch(&created.cwd, "feat/follow-up", true).unwrap(); + assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done); + assert_eq!(branch, "feat/follow-up"); + assert_eq!(head_commit.as_deref(), Some(created.base_commit.as_str())); + + let (back, back_commit, outcome) = super::checkout_branch(&created.cwd, &created.branch, false).unwrap(); + assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done); + assert_eq!(back, created.branch); + assert_eq!(back_commit.as_deref(), Some(created.base_commit.as_str())); + } + + #[test] + fn reuse_for_task_resolves_subdir_consistently_and_rejects_standalone_repo() { + let tmp = tempfile::tempdir().unwrap(); + let repo = tmp.path().join("repo"); + let sub = repo.join("packages").join("app"); + std::fs::create_dir_all(&sub).unwrap(); + git(&repo, &["init", "-q", "-b", "main"]); + std::fs::write(sub.join("a.txt"), "hello\n").unwrap(); + git(&repo, &["add", "."]); + git(&repo, &["commit", "-q", "-m", "init"]); + + let wt_dir = tmp.path().join("wt"); + let created = create_for_task(&sub, &wt_dir, "task-sub", "Subdir work", None).unwrap(); + assert!(created.cwd.ends_with(Path::new("packages").join("app"))); + + // Passing either the worktree root or the subdir cwd resolves to the same subdir cwd. + let reused_from_root = super::reuse_for_task(&sub, &wt_dir, &created.path).unwrap(); + assert_eq!(reused_from_root.cwd, created.cwd); + assert_eq!(reused_from_root.path, dunce::canonicalize(&created.path).unwrap()); + + let reused_from_sub = super::reuse_for_task(&sub, &wt_dir, &created.cwd).unwrap(); + assert_eq!(reused_from_sub.cwd, created.cwd); + + // `shared_worktree_root` matches root and subdir (and mixed casing on Windows). + assert_eq!( + super::shared_worktree_root(&wt_dir, &created.path), + super::shared_worktree_root(&wt_dir, &created.cwd) + ); + #[cfg(windows)] + { + let upper = PathBuf::from(created.cwd.to_string_lossy().to_uppercase()); + assert_eq!( + super::shared_worktree_root(&wt_dir, &created.path), + super::shared_worktree_root(&wt_dir, &upper) + ); + } + + // A standalone repo placed directly inside `worktrees_dir` (not a linked worktree) is rejected. + let standalone = wt_dir.join("standalone"); + std::fs::create_dir_all(&standalone).unwrap(); + git(&standalone, &["init", "-q", "-b", "main"]); + std::fs::write(standalone.join("x.txt"), "x\n").unwrap(); + git(&standalone, &["add", "."]); + git(&standalone, &["commit", "-q", "-m", "standalone"]); + assert!(super::reuse_for_task(&standalone, &wt_dir, &standalone).is_err()); + } } diff --git a/crates/ide-host/src/automations/mod.rs b/crates/ide-host/src/automations/mod.rs index 34ee1fb049..ed79d22dad 100644 --- a/crates/ide-host/src/automations/mod.rs +++ b/crates/ide-host/src/automations/mod.rs @@ -1999,6 +1999,7 @@ impl AutomationService { config: auto.config.clone(), isolation, base, + worktree_path: None, mcp_overrides: auto.mcp_overrides.clone(), skill_overrides: auto.skill_overrides.clone(), memory_overrides: auto.memory_overrides.clone(), diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index c0b96c7990..f1215208a4 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -543,6 +543,19 @@ pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> I project.agents.create(request).await } +/// Checks out (or creates and checks out) a Git branch in an idle task's working directory. +#[command(trust = trusted)] +pub async fn agent_checkout_branch( + host: &Host, + window: &str, + task: String, + branch: String, + create: bool, +) -> IdeResult { + host.require_trust(window)?; + host.project(window)?.agents.checkout_branch(&task, &branch, create).await +} + /// Sends a message; while the agent works it is queued, or with `now` it interrupts the turn. #[command(trust = trusted)] pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> { @@ -2941,6 +2954,7 @@ ide_command::domain!( agent_automation_save, agent_automation_set_enabled, agent_automation_snapshot, + agent_checkout_branch, agent_cli_update_check, agent_commands, agent_copilot_auth_status, diff --git a/crates/ide-host/tests/agent_automations.rs b/crates/ide-host/tests/agent_automations.rs index 715ae55173..8a207cc6bc 100644 --- a/crates/ide-host/tests/agent_automations.rs +++ b/crates/ide-host/tests/agent_automations.rs @@ -2155,6 +2155,7 @@ async fn ceiling_rejection_persist_rollback_cross_owner_auth_queued_trust_and_wo prompt: AgentPrompt { text: "initial interactive turn".into(), files: vec![], images: vec![] }, isolation: Isolation::Local, base: None, + worktree_path: None, project_root: Some(IpcPath(root_a.clone())), config: vec![], idle: false, @@ -3471,6 +3472,7 @@ async fn local_host_keep_alive_respects_keep_alive_setting_without_auto_start_se prompt: AgentPrompt { text: "seed task".into(), files: vec![], images: vec![] }, isolation: Isolation::Local, base: None, + worktree_path: None, project_root: Some(IpcPath(root.clone())), config: vec![], idle: false, diff --git a/e2e/agentAutomations.spec.ts b/e2e/agentAutomations.spec.ts index 3e939273a3..b8480a2c04 100644 --- a/e2e/agentAutomations.spec.ts +++ b/e2e/agentAutomations.spec.ts @@ -665,7 +665,7 @@ test("supports SameTask rolling continuity, NeedsInput approval flow, and sideba await expect(taskTree.locator('[data-tree-key="g:automated"]')).toHaveCount(0); }); -test("running composer replaces Send with Stop and keeps the Agents header focused", async ({ +test("running composer keeps Stop dedicated alongside Queue and keeps the Agents header focused", async ({ workbench: page, }, testInfo) => { await page.setViewportSize({ width: 1280, height: 840 }); @@ -693,12 +693,10 @@ test("running composer replaces Send with Stop and keeps the Agents header focus await page.getByRole("textbox", { name: "Message" }).fill("Follow up"); const queue = page.getByRole("button", { name: "Queue", exact: true }); await expect(queue).toBeEnabled(); - await expect(stop).toHaveCount(0); - const after = (await queue.boundingBox())!; + await expect(stop).toBeEnabled(); + const after = (await stop.boundingBox())!; expect(after.x).toBeCloseTo(before.x, 0); expect(after.width).toBeCloseTo(before.width, 0); - await page.getByRole("button", { name: "Message Actions" }).click(); - await expect(page.getByRole("menuitem", { name: "Stop", exact: true })).toBeVisible(); }); test("opens persistent automation scheduling directly from a new agent task", async ({ workbench: page }) => { @@ -713,9 +711,10 @@ test("opens persistent automation scheduling directly from a new agent task", as const composer = page.getByRole("textbox", { name: "Message", exact: true }); await composer.fill("Review the weekly changelog"); - const clock = page.getByRole("button", { name: "New Agent Automation…" }); - await expect(clock).toBeVisible(); - await clock.click(); + await page.getByRole("button", { name: "Add Context", exact: true }).click(); + const automate = page.getByRole("menuitem", { name: "New Agent Automation…", exact: true }); + await expect(automate).toBeVisible(); + await automate.click(); const dialog = page.getByRole("dialog", { name: "New Automation" }); await expect(dialog).toBeVisible(); await expect(dialog.getByLabel("Prompt Instructions")).toHaveValue("Review the weekly changelog"); @@ -740,11 +739,12 @@ test("schedules in-session Send Later, /loop recurring prompts, and /automate fr const composerBox = page.getByRole("textbox", { name: "Message" }); await expect(composerBox).toBeVisible(); - // 1) Type a message and schedule via the clock menu ("Send in 15 minutes") + // 1) Type a message and schedule via the Add Context › Schedule submenu ("Send in 15 minutes") await composerBox.click(); await page.keyboard.type("Verify staging deployment health"); - await page.getByRole("button", { name: "Schedule or Loop Message" }).click(); - await page.getByRole("menuitem", { name: "Send in 15 minutes" }).click(); + await page.getByRole("button", { name: "Add Context", exact: true }).click(); + await page.getByRole("menuitem", { name: "Schedule or Loop Message", exact: true }).hover(); + await page.getByRole("menuitem", { name: "Send in 15 minutes", exact: true }).click(); const strip = page.getByTestId("session-schedule-strip"); await expect(strip).toBeVisible(); diff --git a/e2e/agentComposerPopup.spec.ts b/e2e/agentComposerPopup.spec.ts index d2f6cbbf84..5734a3142e 100644 --- a/e2e/agentComposerPopup.spec.ts +++ b/e2e/agentComposerPopup.spec.ts @@ -117,7 +117,9 @@ test("erasing the @ filter restores the popup's fitting side and height", async await editor.pressSequentially("a"); await expect(list.getByText("a.ts", { exact: true })).toBeVisible(); - await expect.poll(() => geometry(list)).toMatchObject({ side: "below", footerVisible: true }); + await expect.poll(() => geometry(list)).toMatchObject({ side: "above", inViewport: true, footerVisible: true }); + const narrowed = await geometry(list); + expect(narrowed.height).toBeLessThan(initial.height); await editor.press("Backspace"); await expect(list.getByText("file0.ts", { exact: true })).toBeVisible(); await expect.poll(() => geometry(list)).toEqual(initial); @@ -133,7 +135,7 @@ test("first-open @ results can grow and flip after asynchronous file search", as await editor.press("ArrowUp"); await editor.pressSequentially("@"); await expect(list.getByRole("option").first()).toBeVisible(); - await expect.poll(() => geometry(list)).toMatchObject({ side: "below", footerVisible: true }); + await expect.poll(() => geometry(list)).toMatchObject({ side: "above", inViewport: true, footerVisible: true }); await expect(list.getByText("file0.ts", { exact: true })).toHaveCount(0); await page.evaluate(() => window.dispatchEvent(new Event("test:release-composer-files"))); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 1fdaf04d94..7667a69832 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -17,6 +17,7 @@ agent_automation_snapshot always project_host bin agent_base_text trusted project_host bindings async agent_cancel always project_host bindings sync agent_changes trusted project_host bindings async +agent_checkout_branch trusted project_host bindings async agent_cli_install trusted project_host bindings async agent_cli_update trusted project_host bindings async agent_cli_update_check trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index b572678a27..f1841efaba 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -58,6 +58,8 @@ export const commands = { "group" | /** What the last turn changed, against the checkout as that turn started. */ "lastTurn" | null) => typedError(__TAURI_INVOKE("agent_changes", { task, view })), + /** Checks out (or creates and checks out) a Git branch in an idle task's working directory. */ + agentCheckoutBranch: (task: string, branch: string, create: boolean) => typedError(__TAURI_INVOKE("agent_checkout_branch", { task, branch, create })), /** Installs a missing built-in CLI on the project host using the command shown in Agent Setup. */ agentCliInstall: (provider: string, approvedCommand: string, request: RequestId) => typedError(__TAURI_INVOKE("agent_cli_install", { provider, approvedCommand, request })), /** Installs the exact version offered if the selected installation still matches. */ @@ -5189,6 +5191,8 @@ export type AgentTask_Deserialize = { recoveryWindowMins?: number | null, /** Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`]. */ automation?: AgentTaskAutomation_Deserialize | null, + /** Ephemeral next-prompt suggestions from ACP `prompt_suggestions_update`. */ + promptSuggestions?: string[], }; export type AgentTask_Serialize = { @@ -5254,6 +5258,8 @@ export type AgentTask_Serialize = { recoveryWindowMins?: number | null, /** Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`]. */ automation?: AgentTaskAutomation_Serialize | null, + /** Ephemeral next-prompt suggestions from ACP `prompt_suggestions_update`. */ + promptSuggestions?: string[], }; /** Token pricing (Credits per 1M tokens) and context window capacity for one tier. */ @@ -13837,6 +13843,8 @@ export type NewAgentTask_Deserialize = { isolation: Isolation, /** Branch to start the worktree from; the current branch when `None`. */ base: string | null, + /** Reuse an existing managed worktree directory instead of creating a new one (`Isolation::Worktree` only). */ + worktreePath?: IpcPath | null, /** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`). */ mcpOverrides?: { [key in string]: boolean }, /** Per-session skill modes (`skill name` -> mode). */ @@ -13865,6 +13873,8 @@ export type NewAgentTask_Serialize = { isolation: Isolation, /** Branch to start the worktree from; the current branch when `None`. */ base: string | null, + /** Reuse an existing managed worktree directory instead of creating a new one (`Isolation::Worktree` only). */ + worktreePath?: IpcPath | null, /** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`). */ mcpOverrides: { [key in string]: boolean }, /** Per-session skill modes (`skill name` -> mode). */ diff --git a/src/features/agents/AgentBranchPicker.module.css b/src/features/agents/AgentBranchPicker.module.css new file mode 100644 index 0000000000..f08e59b102 --- /dev/null +++ b/src/features/agents/AgentBranchPicker.module.css @@ -0,0 +1,33 @@ +.picker { + display: inline-flex; + align-items: center; + min-width: 0; + max-width: 100%; +} + +.trigger { + min-width: 0; + max-width: 100%; + color: inherit; + font-size: inherit; +} + +.branchTrigger { + display: inline-flex; + align-items: center; + gap: var(--space-1); + min-width: 0; + max-width: 100%; +} + +.branchPrefix { + flex: none; + color: var(--fg-faint); +} + +.branchName { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} diff --git a/src/features/agents/AgentBranchPicker.test.tsx b/src/features/agents/AgentBranchPicker.test.tsx new file mode 100644 index 0000000000..aa27e578e1 --- /dev/null +++ b/src/features/agents/AgentBranchPicker.test.tsx @@ -0,0 +1,145 @@ +import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { Branch } from "@/bindings"; +import { commands } from "@/platform/ipc"; +import { AgentBranchPicker } from "./AgentBranchPicker"; + +const branch = (name: string, opts: Partial = {}): Branch => ({ + name, + remote: false, + current: false, + upstream: null, + ahead: 0, + behind: 0, + lastCommitMs: 0, + ...opts, +}); + +describe("AgentBranchPicker", () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + it("groups local and remote branches and switches locally with smart checkout", async () => { + const checkout = vi.spyOn(commands, "vcsCheckout").mockResolvedValue({ + status: "ok", + data: { kind: "done" }, + }); + const onCheckedOut = vi.fn(); + render( + , + ); + + const trigger = screen.getByRole("button", { name: "Branch" }); + expect(trigger).toHaveTextContent("main"); + fireEvent.click(trigger); + + const listbox = screen.getByRole("listbox"); + expect(within(listbox).getByText("Local")).toBeVisible(); + expect(within(listbox).getByText("Remote")).toBeVisible(); + expect(within(listbox).queryByRole("option", { name: "origin/HEAD" })).not.toBeInTheDocument(); + + fireEvent.click(within(listbox).getByRole("option", { name: "feat/ui" })); + await waitFor(() => expect(onCheckedOut).toHaveBeenCalledWith("feat/ui")); + expect(checkout).toHaveBeenCalledWith(null, "feat/ui", false, { mode: "smart", diverged: null }, null); + }); + + it("strips the remote prefix when reporting a checked-out remote branch", async () => { + const checkout = vi.spyOn(commands, "vcsCheckout").mockResolvedValue({ + status: "ok", + data: { kind: "done" }, + }); + const onCheckedOut = vi.fn(); + render( + , + ); + + fireEvent.click(screen.getByRole("button", { name: "Branch" })); + fireEvent.click(screen.getByRole("option", { name: "origin/feat/remote" })); + await waitFor(() => expect(onCheckedOut).toHaveBeenCalledWith("feat/remote")); + expect(checkout).toHaveBeenCalledWith(null, "origin/feat/remote", false, { mode: "smart", diverged: null }, null); + }); + + it("creates and checks out a new branch typed into the search field", async () => { + const checkout = vi.spyOn(commands, "vcsCheckout").mockResolvedValue({ + status: "ok", + data: { kind: "done" }, + }); + const onCheckedOut = vi.fn(); + render( + , + ); + + fireEvent.click(screen.getByRole("button", { name: "Branch" })); + const search = screen.getByPlaceholderText("Search…"); + fireEvent.change(search, { target: { value: "feat/new-branch" } }); + fireEvent.click(screen.getByRole("option", { name: 'Create branch "feat/new-branch"' })); + + await waitFor(() => expect(onCheckedOut).toHaveBeenCalledWith("feat/new-branch")); + expect(checkout).toHaveBeenCalledWith(null, "feat/new-branch", true, { mode: "smart", diverged: null }, null); + }); + + it("shows base-branch semantics and supports remote branches without inline branch creation", () => { + const onSelectBase = vi.fn(); + render( + , + ); + + const trigger = screen.getByRole("button", { name: "Base branch" }); + expect(trigger).toHaveTextContent("frommain"); + fireEvent.click(trigger); + + const search = screen.getByPlaceholderText("Search…"); + fireEvent.change(search, { target: { value: "origin/main" } }); + expect(screen.queryByRole("option", { name: /Create branch/ })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("option", { name: "origin/main" })); + expect(onSelectBase).toHaveBeenCalledExactlyOnceWith("origin/main"); + }); + + it("switches a worktree session branch via agentCheckoutBranch", async () => { + const checkout = vi.spyOn(commands, "agentCheckoutBranch").mockResolvedValue({ + status: "ok", + data: { kind: "done" }, + }); + const onCheckedOut = vi.fn(); + render( + , + ); + + fireEvent.click(screen.getByRole("button", { name: "Branch" })); + fireEvent.click(screen.getByRole("option", { name: "feat/bar" })); + await waitFor(() => expect(onCheckedOut).toHaveBeenCalledWith("feat/bar")); + expect(checkout).toHaveBeenCalledWith("task-42", "feat/bar", false); + }); +}); diff --git a/src/features/agents/AgentBranchPicker.tsx b/src/features/agents/AgentBranchPicker.tsx new file mode 100644 index 0000000000..6a0e31246c --- /dev/null +++ b/src/features/agents/AgentBranchPicker.tsx @@ -0,0 +1,219 @@ +/** + * Searchable Git branch selector shared by the New Task page (Local checkout switching and + * Worktree base-branch selection) and active session status bars (Local & Worktree sessions). + */ +import clsx from "clsx"; +import { useMemo, useState } from "react"; +import type { Branch, CheckoutOutcome } from "@/bindings"; +import { executeAction } from "@/platform/actions"; +import { useTx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { Icon, Select, showContextMenu, type SelectOption } from "@/ui"; +import { notifications } from "@/workbench/contributions"; +import styles from "./AgentBranchPicker.module.css"; + +const CREATE_PREFIX = "__create__:"; + +/** Rejects whitespace and Git ref-name meta characters before offering inline branch creation. */ +function isValidNewBranchName(name: string): boolean { + if (!name || name.startsWith("-") || name.startsWith("/") || name.endsWith("/") || name.endsWith(".")) return false; + if (name.includes("..") || name.includes("//") || name.includes("@{") || name.endsWith(".lock")) return false; + return !/[\s~^:?*[\\]/.test(name); +} + +export interface AgentBranchPickerProps { + /** `"checkout"` switches or creates branches in place; `"base"` picks the base ref for a new worktree. */ + mode: "checkout" | "base"; + branches: readonly Branch[]; + value: string | null; + /** Repository root for local checkouts (`null` = primary repository). */ + repo?: string | null; + /** Active task id when switching inside an existing agent session. */ + taskId?: string; + disabled?: boolean; + title?: string; + "aria-label"?: string; + className?: string; + onOpen?: () => void; + onSelectBase?: (branch: string) => void; + onCheckedOut?: (branch: string) => void; +} + +export function AgentBranchPicker({ + mode, + branches, + value, + repo = null, + taskId, + disabled = false, + title, + "aria-label": ariaLabel, + className, + onOpen, + onSelectBase, + onCheckedOut, +}: AgentBranchPickerProps) { + const tx = useTx(); + const [switching, setSwitching] = useState(false); + + const options = useMemo(() => { + const local = branches.filter((b) => !b.remote); + const remote = branches.filter((b) => b.remote && !b.name.endsWith("/HEAD")); + const toOption = (b: Branch): SelectOption => ({ + value: b.name, + label: b.name, + verbatim: true, + icon: "branch", + }); + const out: SelectOption[] = []; + if (local.length > 0 && remote.length > 0) { + out.push({ value: "__local__", label: "Local", section: true }, ...local.map(toOption)); + out.push({ value: "__remote__", label: "Remote", section: true }, ...remote.map(toOption)); + } else { + out.push(...local.map(toOption), ...remote.map(toOption)); + } + return out; + }, [branches]); + + const reportOutcome = (target: string, outcome: CheckoutOutcome) => { + switch (outcome.kind) { + case "done": + onCheckedOut?.(target); + return; + case "conflicts": + onCheckedOut?.(target); + notifications().notify({ + level: "warning", + title: tx("Switched branch with conflicts"), + body: outcome.files.join(", "), + }); + return; + case "restoreFailed": + onCheckedOut?.(target); + notifications().notify({ + level: "warning", + title: tx("Switched branch, but local changes could not be restored"), + body: outcome.message, + }); + return; + case "checkedOutInWorktree": + notifications().notify({ + level: "warning", + title: tx("Branch is already checked out in another worktree"), + body: outcome.path, + }); + return; + case "localChanges": + case "untrackedFiles": + notifications().notify({ + level: "warning", + title: tx("Local changes prevented switching branches"), + body: outcome.files.join(", "), + }); + return; + case "localBranchAhead": + notifications().notify({ + level: "warning", + title: tx("Local branch has commits not on the remote branch"), + body: `${outcome.local} → ${outcome.remote}`, + }); + return; + } + }; + + const handleChange = (selected: string) => { + if (mode === "base") { + onSelectBase?.(selected); + return; + } + const create = selected.startsWith(CREATE_PREFIX); + const target = create ? selected.slice(CREATE_PREFIX.length) : selected; + if (!target || (!create && target === value) || switching) return; + + const isRemote = !create && branches.some((b) => b.remote && b.name === target); + const localTarget = isRemote && target.includes("/") ? target.slice(target.indexOf("/") + 1) : target; + + setSwitching(true); + const run = taskId + ? call(commands.agentCheckoutBranch(taskId, target, create)) + : call(commands.vcsCheckout(repo, target, create, { mode: "smart", diverged: null }, null)); + void run + .then((outcome) => reportOutcome(localTarget, outcome)) + .catch((e: unknown) => + notifications().notify({ + level: "error", + title: tx("Couldn't switch branch"), + body: String(e), + }), + ) + .finally(() => setSwitching(false)); + }; + + const customOption = + mode === "checkout" + ? (query: string): SelectOption => { + const trimmed = query.trim(); + const valid = isValidNewBranchName(trimmed); + return { + value: `${CREATE_PREFIX}${trimmed}`, + label: tx`Create branch "${trimmed}"`, + verbatim: true, + icon: "plus", + disabled: !valid, + }; + } + : undefined; + + const displayLabel = value ?? tx("Branch"); + const triggerTitle = title ?? (mode === "base" ? tx`Base branch: ${displayLabel}` : tx`Branch: ${displayLabel}`); + + return ( + { + if (mode !== "checkout" || !value) return; + e.preventDefault(); + e.stopPropagation(); + showContextMenu(e, [ + { + id: "copy-branch", + label: "Copy Branch Name", + icon: "copy", + run: () => void navigator.clipboard?.writeText(value), + }, + ...(!taskId + ? [ + { + id: "all-branches", + label: "All Branches…", + icon: "branch", + run: () => void executeAction("vcs.branches"), + }, + ] + : []), + ]); + }} + > + + {props.toolbar &&