diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 5269ff55d..dc2c81e6d 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -359,6 +359,9 @@ struct TaskFile { /// `None` for a worktree task, and a task saved before these were recorded. #[serde(default, skip_serializing_if = "Option::is_none")] touched: Option>, + /// The checkout as the last turn started, its copies in the store's `.turn` folder. + #[serde(default, skip_serializing_if = "Option::is_none")] + turn: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] subagents: Vec, /// Turns to drop from the session once it is loaded (a fork of an earlier point). @@ -382,6 +385,8 @@ struct TaskState { saved: Option, /// See `TaskFile::touched`. touched: Option>>, + /// See `TaskFile::turn`. + turn: Option>, pending_rollback: u32, /// The user named the task; see `TaskFile::title_renamed`. title_renamed: bool, @@ -753,6 +758,7 @@ impl AgentManager { before: BTreeMap::new(), saved: None, touched: Some(BTreeSet::new()), + turn: None, subagents: Vec::new(), pending_rollback: 0, title_renamed: true, @@ -866,6 +872,7 @@ impl AgentManager { before, saved, touched: (req.isolation == Isolation::Local).then(BTreeSet::new), + turn: None, subagents: Vec::new(), pending_rollback: 0, title_renamed: false, @@ -1189,6 +1196,8 @@ impl AgentManager { before: (*s.before).clone(), saved: s.saved.clone(), touched: s.touched.as_deref().cloned(), + // The source's next turn replaces its copies: the fork's last turn is one of its own. + turn: None, subagents: s.conversation.saved_subagents(), pending_rollback: total - keep, title_renamed: s.title_renamed, @@ -1528,6 +1537,7 @@ impl AgentManager { self.tasks.write().remove(id); *task.deleted.lock() = true; let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json"))); + let _ = std::fs::remove_dir_all(task.turn_dir()); let saved = task.state.lock().saved.clone(); if let Some(saved) = saved && !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved)) @@ -1570,18 +1580,47 @@ impl AgentManager { .await } - /// Content of `path` (in the task's directory) when the task started. - pub async fn base_text(&self, id: &str, path: PathBuf) -> IdeResult> { - let at = self.task(id)?.base(); - blocking(move || match at.rev()? { - Some(rev) => worktree::file_at(at.cwd(), &path, &rev), - None => Ok(None), + /// The files the task's last turn changed, against the checkout as it started (while a + /// turn runs: that turn's so far). None before the task's first turn. + pub async fn turn_changes(&self, id: &str) -> IdeResult> { + let (cwd, turn, dir) = self.task(id)?.last_turn(); + let Some(turn) = turn else { return Ok(Vec::new()) }; + blocking(move || { + let changed = match &turn.changed { + Some(changed) => changed.clone(), + None => worktree::changed_in_turn(&cwd, &turn)?.1, + }; + worktree::turn_changes(&cwd, &turn, &dir, &changed) + }) + .await + } + + /// Content of `path` (in the task's directory) as `view` compares it: when the task + /// started, in `HEAD`, or when the last turn started. + pub async fn base_text(&self, id: &str, path: PathBuf, view: AgentChangesView) -> IdeResult> { + let task = self.task(id)?; + if view == AgentChangesView::LastTurn { + let (cwd, turn, dir) = task.last_turn(); + let Some(turn) = turn else { return Ok(None) }; + return blocking(move || worktree::turn_text(&cwd, &path, &turn, &dir)).await; + } + let at = task.base(); + blocking(move || { + let rev = match view { + AgentChangesView::Group => worktree::head_commit(at.cwd())?, + _ => at.rev()?, + }; + match rev { + Some(rev) => worktree::file_at(at.cwd(), &path, &rev), + None => Ok(None), + } }) .await } /// Rollback: puts the task's changed files among `rel_paths` (all with `None`) back as - /// `view` compares them: as they were when it started, or as they are in `HEAD`. + /// `view` compares them: as they were when it started, as they are in `HEAD`, or as they + /// were when its last turn started. pub async fn rollback_changes( &self, id: &str, @@ -1592,15 +1631,18 @@ impl AgentManager { if task.state.lock().busy { return Err(IdeError::invalid("the agent is working: stop it before rolling back its changes")); } + if view == AgentChangesView::LastTurn { + return self.rollback_turn(&task, rel_paths).await; + } let at = task.base(); let (before, saved, touched) = { let s = task.state.lock(); (s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)), s.touched.clone()) }; - let restamped = blocking(move || { + let (restamped, restored) = blocking(move || { let (changes, rev) = match view { AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?), - AgentChangesView::SinceStart => (at.changes(&before)?, at.rev()?), + AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before)?, at.rev()?), }; let changes = worktree::made_by_task(changes, touched.as_deref()); let sources = match rev.as_deref() { @@ -1608,6 +1650,7 @@ impl AgentManager { None => Default::default(), }; let mut restamped = Vec::new(); + let mut restored = Vec::new(); for change in changes.iter().filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path))) { // A rename goes back to its old path too; the new one is taken away first, so a // case-only rename on a case-insensitive disk ends as the old file. @@ -1617,6 +1660,58 @@ impl AgentManager { if before.contains_key(&change.rel_path) { restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0))); } + restored.push(change.rel_path.clone()); + } + } + Ok((restamped, restored)) + }) + .await?; + { + let mut s = task.state.lock(); + if !restamped.is_empty() { + let mut before = (*s.before).clone(); + before.extend(restamped); + s.before = Arc::new(before); + } + // Rolled back further than the last turn: what it changed there is gone, not the turn's to list. + if let Some(turn) = &s.turn + && let Some(changed) = &turn.changed + && restored.iter().any(|rel| changed.contains(rel)) + { + let changed = changed.iter().filter(|rel| !restored.contains(rel)).cloned().collect(); + s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(changed), ..(**turn).clone() })); + } + } + task.persist(); + Ok(()) + } + + /// Puts the last turn's changed files among `rel_paths` (all with `None`) back as they + /// were when it started. + async fn rollback_turn(&self, task: &Task, rel_paths: Option>) -> IdeResult<()> { + let (cwd, turn, dir) = task.last_turn(); + let Some(turn) = turn else { return Ok(()) }; + let (before, saved) = { + let s = task.state.lock(); + (s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name))) + }; + let restamped = blocking(move || { + let changed = match &turn.changed { + Some(changed) => changed.clone(), + None => worktree::changed_in_turn(&cwd, &turn)?.1, + }; + let mut restamped = Vec::new(); + for change in worktree::turn_changes(&cwd, &turn, &dir, &changed)? + .iter() + .filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path))) + { + worktree::restore_turn(&cwd, &turn, &dir, change)?; + // Back to the user's own edits from before the task: not a change of the task. + if let Some(Some(_)) = before.get(&change.rel_path) + && let Some(copy) = saved.as_deref().and_then(|d| worktree::saved_copy(d, &change.rel_path)) + && std::fs::read(&change.path.0).is_ok_and(|now| now == copy) + { + restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0))); } } Ok(restamped) @@ -1752,6 +1847,7 @@ impl Task { before: Arc::new(file.before), saved: file.saved, touched: file.touched.map(Arc::new), + turn: file.turn.map(Arc::new), pending_rollback: file.pending_rollback, title_renamed: file.title_renamed, busy: false, @@ -1785,31 +1881,48 @@ impl Task { (s.before.clone(), s.touched.clone()) } - /// The changed files of the checkout as a turn starts, when the task records what its turns change. - async fn checkout_before_turn(&self) -> Option { - let cwd = { - let s = self.state.lock(); - s.touched.as_ref()?; - s.task.cwd.0.clone() - }; - blocking(move || worktree::snapshot(&cwd)).await.ok() + /// Where the copies of the files already changed as the last turn started are kept. + fn turn_dir(&self) -> PathBuf { + self.shared.paths.store_dir.join(format!("{}.turn", self.id)) } - /// Records the files that changed in the checkout since `start`, as the turn ends, as the task's. - async fn record_turn_changes(&self, start: Option) { - let Some(start) = start else { return }; - let cwd = self.state.lock().task.cwd.0.clone(); - let Ok(end) = blocking(move || worktree::snapshot(&cwd)).await else { return }; - let changed = worktree::changed_between(&start, &end); - if changed.is_empty() { - return; - } + /// The checkout as the last turn started, with the folder of its copies. + fn last_turn(&self) -> (PathBuf, Option>, PathBuf) { + let s = self.state.lock(); + (s.task.cwd.0.clone(), s.turn.clone(), self.turn_dir()) + } + + /// Records the checkout as a turn starts: what the turn's changes are compared with. + async fn checkout_before_turn(&self) { + let (cwd, previous, dir) = self.last_turn(); + let turn = match blocking(move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await { + Ok(turn) => Some(Arc::new(turn)), + Err(e) => { + tracing::warn!("recording the checkout as a turn of agent task {} starts: {e}", self.id); + None + } + }; + self.state.lock().turn = turn; + self.persist(); + } + + /// Records the files that changed in the checkout while the turn ran: the turn's, and in + /// the project's own checkout also the task's. + async fn record_turn_changes(&self) { + let (cwd, turn, _) = self.last_turn(); + let Some(turn) = turn else { return }; + let start = turn.clone(); + let Ok((in_worktree, all)) = blocking(move || worktree::changed_in_turn(&cwd, &start)).await else { return }; { let mut s = self.state.lock(); - let Some(touched) = &s.touched else { return }; - let mut touched = (**touched).clone(); - touched.extend(changed); - s.touched = Some(Arc::new(touched)); + if !in_worktree.is_empty() + && let Some(touched) = &s.touched + { + let mut touched = (**touched).clone(); + touched.extend(in_worktree); + s.touched = Some(Arc::new(touched)); + } + s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() })); } self.persist(); } @@ -1926,6 +2039,7 @@ impl Task { before: (*s.before).clone(), saved: s.saved.clone(), touched: s.touched.as_deref().cloned(), + turn: s.turn.as_deref().cloned(), subagents: s.conversation.saved_subagents(), pending_rollback: s.pending_rollback, title_renamed: s.title_renamed, @@ -1977,11 +2091,11 @@ impl Task { /// the user stops one. The caller set `busy`. async fn run(self: Arc, mut prompt: AgentPrompt) { loop { - let start = self.checkout_before_turn().await; + self.checkout_before_turn().await; let result = self.turn(&prompt).await; self.cancel_pending.store(false, Ordering::Release); tokio::time::sleep(TURN_GRACE).await; - self.record_turn_changes(start).await; + self.record_turn_changes().await; let changed = self.state.lock().conversation.end_turn(Some(now_ms())); self.mark_dirty(changed); let send_now = self.send_now.swap(false, Ordering::AcqRel); diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index fa3583f92..b407bc1bd 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -672,6 +672,8 @@ pub enum AgentChangesView { SinceStart, /// The uncommitted files against `HEAD`; commits made since the start stay. Group, + /// What the last turn changed, against the checkout as that turn started. + LastTurn, } /// A task's uncommitted files and the commits made since it started. diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index e1bf94472..fb8c78872 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -2852,7 +2852,10 @@ async fn task_project_root_controls_local_and_worktree_repositories() { let changes = mgr.changes(&task.id).await.unwrap(); assert_eq!(changes.len(), 1); assert_eq!(changes[0].path.0, task.cwd.0.join("file.txt")); - assert_eq!(mgr.base_text(&task.id, changes[0].path.0.clone()).await.unwrap().as_deref(), Some("original\n")); + assert_eq!( + mgr.base_text(&task.id, changes[0].path.0.clone(), AgentChangesView::SinceStart).await.unwrap().as_deref(), + Some("original\n") + ); let saved = std::fs::read(root.join("store").join(format!("{}.json", task.id))).unwrap(); assert!(String::from_utf8(saved).unwrap().contains("projectRoot")); let mut old = serde_json::to_value(&task).unwrap(); @@ -3636,6 +3639,178 @@ async fn changed(mgr: &AgentManager, id: &str) -> Vec { mgr.changes(id).await.unwrap().into_iter().map(|c| c.rel_path).collect() } +/// Waits until the turn asks for permission, runs `work` (what the agent does), then stops it. +async fn one_turn(mgr: &AgentManager, id: &str, prompt: Option<&str>, work: impl FnOnce()) { + if let Some(prompt) = prompt { + mgr.prompt(id, text(prompt), false).await.unwrap(); + } + wait_for(mgr, id, AgentStatus::NeedsInput).await; + work(); + mgr.cancel(id, None).unwrap(); + wait_for(mgr, id, AgentStatus::Ready).await; +} + +async fn turn_changed(mgr: &AgentManager, id: &str) -> Vec<(String, ide_vcs::ChangeKind, u32, u32)> { + let changes = mgr.turn_changes(id).await.unwrap(); + changes.into_iter().map(|c| (c.rel_path, c.kind, c.added, c.removed)).collect() +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() { + use ide_vcs::ChangeKind::{Added, Deleted, Modified}; + for isolation in [Isolation::Local, Isolation::Worktree] { + for eol in EOLS { + let repo = Checkout::new(eol); + repo.write("a.txt", "base\n"); + repo.write("gone.txt", "base\n"); + repo.write("mine.txt", "base\n"); + repo.commit("init"); + let mgr = manager(&repo.dir, Arc::new(FakeAgent::default())); + let task = mgr + .create(NewAgentTask { + prompt: text("Hello"), + provider: "claude".into(), + isolation, + ..Default::default() + }) + .await + .unwrap(); + let cwd = task.cwd.0.clone(); + let write = |rel: &str, text: &str| { + let text = match eol { + Eol::Lf => text.to_owned(), + Eol::Crlf => text.replace('\n', "\r\n"), + }; + std::fs::write(cwd.join(rel), text).unwrap(); + }; + let read = |rel: &str| std::fs::read_to_string(cwd.join(rel)).unwrap().replace("\r\n", "\n"); + let case = format!("{isolation:?} {eol:?}"); + assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty(), "{case}: no turn has ended yet"); + + one_turn(&mgr, &task.id, None, || { + write("a.txt", "base\nturn 1\n"); + write("one.txt", "one\n"); + }) + .await; + // The user's own work between the turns belongs to neither. + write("mine.txt", "base\nmine\n"); + one_turn(&mgr, &task.id, Some("more"), || { + write("a.txt", "base\nturn 1\nturn 2\n"); + write("one.txt", "one\ntwo\n"); + write("two.txt", "two\n"); + std::fs::remove_file(cwd.join("gone.txt")).unwrap(); + }) + .await; + // And after the turn. + write("later.txt", "mine\n"); + + assert_eq!( + turn_changed(&mgr, &task.id).await, + [ + ("a.txt".into(), Modified, 1, 0), + ("gone.txt".into(), Deleted, 0, 1), + ("one.txt".into(), Modified, 1, 0), + ("two.txt".into(), Added, 1, 0), + ], + "{case}" + ); + let turn_base = |rel: &str| { + let path = cwd.join(rel); + let mgr = &mgr; + let id = task.id.clone(); + async move { + let text = mgr.base_text(&id, path, AgentChangesView::LastTurn).await.unwrap(); + text.map(|t| t.replace("\r\n", "\n")) + } + }; + assert_eq!(turn_base("a.txt").await.as_deref(), Some("base\nturn 1\n"), "{case}"); + assert_eq!(turn_base("gone.txt").await.as_deref(), Some("base\n"), "{case}"); + assert_eq!(turn_base("two.txt").await, None, "{case}"); + let whole: Vec = changed(&mgr, &task.id).await; + assert!(["a.txt", "one.txt"].iter().all(|f| whole.iter().any(|w| w == f)), "{case}: {whole:?}"); + + // One file, then the rest, after a restart: from the copies saved as the turn started. + mgr.rollback_changes(&task.id, Some(vec!["one.txt".into()]), AgentChangesView::LastTurn).await.unwrap(); + assert_eq!(read("one.txt"), "one\n", "{case}"); + assert_eq!(turn_changed(&mgr, &task.id).await.len(), 3, "{case}"); + mgr.shutdown(); + let mgr = manager(&repo.dir, Arc::new(FakeAgent::default())); + mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap(); + assert_eq!(read("a.txt"), "base\nturn 1\n", "{case}"); + assert_eq!(read("gone.txt"), "base\n", "{case}"); + assert!(!cwd.join("two.txt").exists(), "{case}"); + assert_eq!(read("mine.txt"), "base\nmine\n", "{case}: the user's edit between turns stays"); + assert_eq!(read("later.txt"), "mine\n", "{case}: and the one after"); + assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty(), "{case}"); + // The task's own changes from its first turn stay. + let whole: Vec = changed(&mgr, &task.id).await; + assert!(["a.txt", "one.txt"].iter().all(|f| whole.iter().any(|w| w == f)), "{case}: {whole:?}"); + + mgr.delete(&task.id, true).await.unwrap(); + assert!(!repo.dir.join("store").join(format!("{}.turn", task.id)).exists(), "{case}"); + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn rolling_back_the_whole_task_leaves_the_last_turn_nothing_to_list() { + let repo = Checkout::new(Eol::Lf); + repo.write("a.txt", "base\n"); + repo.commit("init"); + let mgr = manager(&repo.dir, Arc::new(FakeAgent::default())); + let task = mgr + .create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() }) + .await + .unwrap(); + one_turn(&mgr, &task.id, None, || repo.write("a.txt", "base\nturn 1\n")).await; + one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await; + assert_eq!(turn_changed(&mgr, &task.id).await.len(), 1); + mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap(); + assert_eq!(repo.read("a.txt"), "base\n"); + assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_commit_made_in_the_last_turn_is_among_its_changes() { + let repo = Checkout::new(Eol::Lf); + repo.write("a.txt", "base\n"); + repo.commit("init"); + let mgr = manager(&repo.dir, Arc::new(FakeAgent::default())); + let task = mgr + .create(NewAgentTask { + prompt: text("Hello"), + provider: "claude".into(), + isolation: Isolation::Worktree, + ..Default::default() + }) + .await + .unwrap(); + let cwd = task.cwd.0.clone(); + let git = |args: &[&str]| { + let ok = std::process::Command::new("git") + .args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"]) + .args(args) + .current_dir(&cwd) + .status() + .unwrap() + .success(); + assert!(ok, "{args:?}"); + }; + one_turn(&mgr, &task.id, None, || { + std::fs::write(cwd.join("a.txt"), "base\nagent\n").unwrap(); + std::fs::write(cwd.join("new.txt"), "new\n").unwrap(); + git(&["add", "."]); + git(&["commit", "-q", "-m", "agent"]); + }) + .await; + let rel: Vec = mgr.turn_changes(&task.id).await.unwrap().into_iter().map(|c| c.rel_path).collect(); + assert_eq!(rel, ["a.txt", "new.txt"]); + mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap(); + assert_eq!(std::fs::read_to_string(cwd.join("a.txt")).unwrap(), "base\n"); + assert!(!cwd.join("new.txt").exists()); + mgr.delete(&task.id, true).await.unwrap(); +} + #[tokio::test(flavor = "multi_thread")] async fn work_uncommitted_by_a_reset_during_a_local_task_is_not_rolled_back() { for eol in EOLS { @@ -3652,7 +3827,7 @@ async fn work_uncommitted_by_a_reset_during_a_local_task_is_not_rolled_back() { repo.git(&["reset", "-q", "--soft", "HEAD~1"]); assert_eq!(changed(&mgr, &task.id).await, ["a.txt"], "{eol:?}"); - let base = mgr.base_text(&task.id, repo.dir.join("a.txt")).await.unwrap(); + let base = mgr.base_text(&task.id, repo.dir.join("a.txt"), AgentChangesView::SinceStart).await.unwrap(); assert_eq!(base.map(|b| b.replace("\r\n", "\n")).as_deref(), Some("base\n"), "{eol:?}"); mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap(); assert_eq!(repo.read("a.txt"), "base\n", "{eol:?}"); @@ -3792,7 +3967,11 @@ async fn a_local_task_in_a_repository_without_commits_lists_and_rolls_back_its_c let (mgr, task) = repo.task().await; repo.write("new.txt", "agent\n"); assert_eq!(changed(&mgr, &task.id).await, ["new.txt"], "{eol:?}"); - assert_eq!(mgr.base_text(&task.id, repo.dir.join("new.txt")).await.unwrap(), None, "{eol:?}"); + assert_eq!( + mgr.base_text(&task.id, repo.dir.join("new.txt"), AgentChangesView::SinceStart).await.unwrap(), + None, + "{eol:?}" + ); mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap(); assert!(!repo.dir.join("new.txt").exists(), "{eol:?}"); diff --git a/crates/ide-agent/src/worktree.rs b/crates/ide-agent/src/worktree.rs index fa868ee4b..c9e5dc825 100644 --- a/crates/ide-agent/src/worktree.rs +++ b/crates/ide-agent/src/worktree.rs @@ -3,6 +3,7 @@ use crate::model::{AgentChange, AgentChanges, AgentCommit}; use ide_core::{IdeError, IdeResult, IpcPath}; use ide_vcs::{ChangeKind, LogQuery, Repo}; +use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use std::time::{Duration, UNIX_EPOCH}; @@ -610,7 +611,6 @@ pub(crate) fn restore( before: &BTreeMap, saved: Option<&Path>, ) -> IdeResult<()> { - let path = &change.path.0; let content = match before.get(&change.rel_path) { Some(None) => None, Some(Some(_)) => { @@ -626,11 +626,16 @@ pub(crate) fn restore( None => match rev { Some(rev) => { let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?; - repo.file_bytes_at(path, Some(rev))? + repo.file_bytes_at(&change.path.0, Some(rev))? } None => None, }, }; + put(&change.path.0, content) +} + +/// Writes `content` to `path`, or removes the file when there is none. +fn put(path: &Path, content: Option>) -> IdeResult<()> { match content { Some(bytes) => { if let Some(parent) = path.parent() { @@ -646,6 +651,187 @@ pub(crate) fn restore( Ok(()) } +/// The bytes of the copy of `rel` saved in `dir`, if there is one. +pub(crate) fn saved_copy(dir: &Path, rel: &str) -> Option> { + std::fs::read(dir.join(saved_name(rel))).ok() +} + +/// The checkout as the task's last turn started: what that turn's changes are compared with +/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed, +/// and copies of those. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct TurnStart { + /// `HEAD` then (`None` outside a repository or before its first commit). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub head: Option, + /// The files already changed then, stamped. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub before: BTreeMap, + /// The files among `before` with a copy in the task's turn folder. + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub saved: BTreeSet, + /// The files that changed while the turn ran, recorded as it ended (`None` while it runs). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub changed: Option>, +} + +/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`. +/// The copies `previous` saved of files unchanged since are kept rather than made again, so +/// starting a turn copies little more than what the turn before it changed. +pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult { + let Some(repo) = discover(cwd)? else { return Ok(TurnStart::default()) }; + let head = repo.head()?.1; + // As the turn's end is read, so the two compare. + let before = snapshot(cwd)?; + let mut saved = BTreeSet::new(); + match previous { + Some(previous) => { + for rel in &previous.saved { + let unchanged = + before.get(rel).is_some_and(|now| now.is_some() && previous.before.get(rel) == Some(now)); + if unchanged { + saved.insert(rel.clone()); + } else { + let _ = std::fs::remove_file(dir.join(saved_name(rel))); + } + } + } + None => { + let _ = std::fs::remove_dir_all(dir); + } + } + for (rel, stamp) in &before { + let path = repo.root().join(rel); + if stamp.is_none() + || saved.contains(rel) + || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) + { + continue; + } + std::fs::create_dir_all(dir)?; + // One that can't be copied is listed but can't be rolled back, as a large one. + if std::fs::copy(&path, dir.join(saved_name(rel))).is_ok() { + saved.insert(rel.clone()); + } + } + Ok(TurnStart { head, before, saved, changed: None }) +} + +/// The files that changed in `cwd` since the turn `start` began: in the working tree (as +/// `changed_between` sees them), and in the commits made since. +pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec, BTreeSet)> { + let end = snapshot(cwd)?; + let worktree = changed_between(&start.before, &end); + let mut all: BTreeSet = worktree.iter().cloned().collect(); + if let Some(repo) = discover(cwd)? + && let (Some(from), Some(to)) = (&start.head, repo.head()?.1) + && *from != to + { + for f in repo.diff_revisions(from, &to)? { + all.extend(f.old_path); + all.insert(f.path); + } + } + Ok((worktree, all)) +} + +/// The content of `rel` as the turn `start` began (`None`: no file), its copies in `dir`. +fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult>> { + match start.before.get(rel) { + Some(None) => Ok(None), + Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() { + Some(bytes) => Ok(Some(bytes)), + None => Err(IdeError::invalid(format!( + "{rel} had changes when the turn started that weren't saved; roll it back in Git instead" + ))), + }, + None => match &start.head { + Some(head) => repo.file_bytes_at(&repo.root().join(rel), Some(head)), + None => Ok(None), + }, + } +} + +/// Added and removed lines from `old` to `new`; none for binary content. +fn line_stats(old: Option<&[u8]>, new: Option<&[u8]>) -> (u32, u32) { + if [old, new].iter().flatten().any(|b| b.contains(&0)) { + return (0, 0); + } + let text = |b: Option<&[u8]>| b.map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default(); + ide_vcs::diff_hunks(&text(old), &text(new)) + .iter() + .fold((0, 0), |(added, removed), h| (added + h.lines, removed + h.old_lines)) +} + +/// The files among `changed` that differ from how they were as the turn `start` began. +pub(crate) fn turn_changes( + cwd: &Path, + start: &TurnStart, + dir: &Path, + changed: &BTreeSet, +) -> IdeResult> { + let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) }; + let mut out = Vec::new(); + for rel in changed { + let path = repo.root().join(rel); + // A folder (a submodule, say) or a file that can't be read has nothing to compare. + let Some(now) = existing(&path) else { continue }; + let (kind, (added, removed)) = match at_turn_start(&repo, rel, start, dir) { + Ok(then) if then == now => continue, + Ok(then) => { + let kind = match (&then, &now) { + (None, _) => ChangeKind::Added, + (_, None) => ChangeKind::Deleted, + _ => ChangeKind::Modified, + }; + (kind, line_stats(then.as_deref(), now.as_deref())) + } + // Its start wasn't saved: listed, without counts. + Err(_) => (ChangeKind::Modified, (0, 0)), + }; + out.push(AgentChange { path: IpcPath(path), rel_path: rel.clone(), kind, added, removed, old_path: None }); + } + Ok(out) +} + +/// The text of `path` as the turn `start` began, `None` when there was no file. +pub(crate) fn turn_text(cwd: &Path, path: &Path, start: &TurnStart, dir: &Path) -> IdeResult> { + let Some(repo) = discover(cwd)? else { return Ok(None) }; + let rel = rel_in(repo.root(), path)?; + if let (None, Some(head)) = (start.before.get(&rel), &start.head) { + return file_at(cwd, path, head); + } + let Some(bytes) = at_turn_start(&repo, &rel, start, dir)? else { return Ok(None) }; + let encoding = match ide_vfs::load_text(path) { + Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8), + Err(_) => ide_vfs::detect_encoding(&bytes, None), + }; + Ok(Some(encoding.decode(&bytes).0.into_owned())) +} + +/// `path` relative to the repository at `root`, with `/` separators. +fn rel_in(root: &Path, path: &Path) -> IdeResult { + let rel = path + .strip_prefix(root) + .map(Path::to_path_buf) + .ok() + .or_else(|| { + // Another spelling of the same place (a link, `/var` and `/private/var`); the file may be gone. + let root = dunce::canonicalize(root).ok()?; + let parent = dunce::canonicalize(path.parent()?).ok()?; + Some(parent.strip_prefix(&root).ok()?.join(path.file_name()?)) + }) + .ok_or_else(|| IdeError::invalid(format!("{} is outside the repository", path.display())))?; + Ok(rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::>().join("/")) +} + +/// Puts `change` back as it was when the turn `start` began. +pub(crate) fn restore_turn(cwd: &Path, start: &TurnStart, dir: &Path, change: &AgentChange) -> IdeResult<()> { + let repo = repo_at(cwd)?; + put(&change.path.0, at_turn_start(&repo, &change.rel_path, start, dir)?) +} + pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult> { let Some(repo) = discover(cwd)? else { return Ok(None) }; let encoding = match ide_vfs::load_text(path) { @@ -815,6 +1001,67 @@ mod tests { assert!(!created.path.exists()); } + #[test] + fn a_turn_copies_only_what_changed_since_the_last_one() { + let tmp = tempfile::tempdir().unwrap(); + let repo = tmp.path().join("repo"); + std::fs::create_dir(&repo).unwrap(); + git(&repo, &["init", "-q", "-b", "main"]); + std::fs::write(repo.join("a.txt"), "base\n").unwrap(); + git(&repo, &["add", "."]); + git(&repo, &["commit", "-q", "-m", "init"]); + let dir = tmp.path().join("turn"); + let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::>(); + + std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap(); + std::fs::write(repo.join("b.txt"), "b\n").unwrap(); + let first = start_turn(&repo, &dir, None).unwrap(); + assert_eq!(first.saved, set(&["a.txt", "b.txt"])); + // A copy made again would replace this mark. + std::fs::write(dir.join(saved_name("b.txt")), "kept\n").unwrap(); + + std::thread::sleep(std::time::Duration::from_millis(10)); + std::fs::write(repo.join("a.txt"), "turn two\n").unwrap(); + let second = start_turn(&repo, &dir, Some(&first)).unwrap(); + assert_eq!(second.saved, set(&["a.txt", "b.txt"])); + assert_eq!(saved_copy(&dir, "a.txt").as_deref(), Some(&b"turn two\n"[..])); + assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"kept\n"[..])); + + // Back as committed: nothing to keep a copy of. + git(&repo, &["checkout", "--", "a.txt"]); + let third = start_turn(&repo, &dir, Some(&second)).unwrap(); + assert_eq!(third.saved, set(&["b.txt"])); + assert_eq!(saved_copy(&dir, "a.txt"), None); + // Without a record of the last turn (a task from before), every copy is made afresh. + let fresh = start_turn(&repo, &dir, None).unwrap(); + assert_eq!(fresh.saved, set(&["b.txt"])); + assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"b\n"[..])); + } + + #[cfg(unix)] + #[test] + fn a_turns_start_is_found_through_another_spelling_of_the_checkout() { + let tmp = tempfile::tempdir().unwrap(); + let repo = dunce::canonicalize(tmp.path()).unwrap().join("repo"); + std::fs::create_dir(&repo).unwrap(); + git(&repo, &["init", "-q", "-b", "main"]); + std::fs::write(repo.join("a.txt"), "base\n").unwrap(); + git(&repo, &["add", "."]); + git(&repo, &["commit", "-q", "-m", "init"]); + std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap(); + let dir = tmp.path().join("turn"); + let start = start_turn(&repo, &dir, None).unwrap(); + std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap(); + std::fs::write(repo.join("new.txt"), "new\n").unwrap(); + let link = tmp.path().join("link"); + std::os::unix::fs::symlink(&repo, &link).unwrap(); + for at in [&repo, &link] { + assert_eq!(turn_text(&repo, &at.join("a.txt"), &start, &dir).unwrap().as_deref(), Some("turn 1\n")); + assert_eq!(turn_text(&repo, &at.join("new.txt"), &start, &dir).unwrap(), None); + } + assert!(turn_text(&repo, &tmp.path().join("elsewhere.txt"), &start, &dir).is_err()); + } + #[test] fn commits_since_the_base_are_listed_with_their_files() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index aa1146d5c..608cda7cc 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -369,10 +369,21 @@ pub async fn agent_delete(host: &Host, window: &str, task: String, remove_worktr host.project(window)?.agents.delete(&task, remove_worktree).await } +/// The task's changed files as `view` compares them (without: since it started). #[command(trust = trusted)] -pub async fn agent_changes(host: &Host, window: &str, task: String) -> IdeResult> { +pub async fn agent_changes( + host: &Host, + window: &str, + task: String, + view: Option, +) -> IdeResult> { host.require_trust(window)?; - host.project(window)?.agents.changes(&task).await + let agents = &host.project(window)?.agents; + match view.unwrap_or_default() { + AgentChangesView::SinceStart => agents.changes(&task).await, + AgentChangesView::Group => Ok(agents.grouped_changes(&task).await?.uncommitted), + AgentChangesView::LastTurn => agents.turn_changes(&task).await, + } } /// The task's uncommitted changes and the commits made since it started. @@ -382,11 +393,17 @@ pub async fn agent_grouped_changes(host: &Host, window: &str, task: String) -> I host.project(window)?.agents.grouped_changes(&task).await } -/// Content of `path` when the task started (left side of its diff). +/// Content of `path` as `view` compares it (without: when the task started), the left side of its diff. #[command(trust = trusted)] -pub async fn agent_base_text(host: &Host, window: &str, task: String, path: IpcPath) -> IdeResult> { +pub async fn agent_base_text( + host: &Host, + window: &str, + task: String, + path: IpcPath, + view: Option, +) -> IdeResult> { host.require_trust(window)?; - host.project(window)?.agents.base_text(&task, path.into_path_buf()).await + host.project(window)?.agents.base_text(&task, path.into_path_buf(), view.unwrap_or_default()).await } /// Rollback: the task's changed files among `paths` (all without) back as `view` compares them. diff --git a/docs/en/guide/agents.mdx b/docs/en/guide/agents.mdx index c96b47197..3e4848b0f 100644 --- a/docs/en/guide/agents.mdx +++ b/docs/en/guide/agents.mdx @@ -96,7 +96,7 @@ Once an agent has run a task, new tasks start in its mode that approves everythi ### Review the changes -Click **Show changes** in the task header to list the files the task changed. A task in the project's own checkout lists only the files that changed while the agent was working, not what you or another task changed while it was idle. Click a file to open a diff between the task's starting point and now. For a worktree task, the changes live on its `agent/…` branch: open a terminal there with **Open in Terminal**, and merge or cherry-pick the branch with the Git tools (see [Version control](/en/guide/vcs)) when you are happy with it. +Click **Show changes** in the task header to list the files the task changed. A task in the project's own checkout lists only the files that changed while the agent was working, not what you or another task changed while it was idle. Click a file to open a diff between the task's starting point and now. Switch the list from **Whole Task** to **Last Turn** to see only what the last turn changed, against the files as that turn started; rolling back then undoes only that turn. For a worktree task, the changes live on its `agent/…` branch: open a terminal there with **Open in Terminal**, and merge or cherry-pick the branch with the Git tools (see [Version control](/en/guide/vcs)) when you are happy with it. Drag the pane's left edge to resize it. The width applies to every task and is remembered across restarts. diff --git a/docs/zh/guide/agents.mdx b/docs/zh/guide/agents.mdx index 42d0e6145..9f0d3dab6 100644 --- a/docs/zh/guide/agents.mdx +++ b/docs/zh/guide/agents.mdx @@ -96,7 +96,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的 ### 查看改动 -在任务标题栏中单击 **显示更改**,列出任务改动过的文件。直接在项目中运行的任务只列出 agent 工作期间改动的文件,不包括它空闲时你自己或其他任务做的修改。单击文件可以打开它从任务开始到现在的 diff。worktree 任务的改动在它的 `agent/…` 分支上:用 **在终端中打开** 在那里打开终端,满意后用 Git 工具合并或 cherry-pick 这个分支(见 [版本控制](/zh/guide/vcs))。 +在任务标题栏中单击 **显示更改**,列出任务改动过的文件。直接在项目中运行的任务只列出 agent 工作期间改动的文件,不包括它空闲时你自己或其他任务做的修改。单击文件可以打开它从任务开始到现在的 diff。把列表从 **整个任务** 切换到 **最近一轮**,就只列出最近一轮的改动,对比的是这一轮开始时的文件;此时回滚也只撤销这一轮的改动。worktree 任务的改动在它的 `agent/…` 分支上:用 **在终端中打开** 在那里打开终端,满意后用 Git 工具合并或 cherry-pick 这个分支(见 [版本控制](/zh/guide/vcs))。 拖动改动面板的左边缘可以调整宽度。宽度对所有任务生效,重启后保留。 diff --git a/src/bindings.ts b/src/bindings.ts index 3accde7f8..a0ad732d2 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -15,11 +15,24 @@ export const commands = { /** Answers a non-blocking question, without cancelling the current turn. */ agentAnswerQuestion: (task: string, question: string, answer: string | null) => typedError(__TAURI_INVOKE("agent_answer_question", { task, question, answer })), agentArchive: (task: string) => typedError(__TAURI_INVOKE("agent_archive", { task })), - /** Content of `path` when the task started (left side of its diff). */ - agentBaseText: (task: string, path: IpcPath) => typedError(__TAURI_INVOKE("agent_base_text", { task, path })), + /** Content of `path` as `view` compares it (without: when the task started), the left side of its diff. */ + agentBaseText: (task: string, path: IpcPath, view: +/** Everything since the commit the task started from. */ +"sinceStart" | +/** The uncommitted files against `HEAD`; commits made since the start stay. */ +"group" | +/** What the last turn changed, against the checkout as that turn started. */ +"lastTurn" | null) => typedError(__TAURI_INVOKE("agent_base_text", { task, path, view })), /** Stops the task's current turn, or with `subagent` only that subagent's work. */ agentCancel: (task: string, subagent: string | null) => typedError(__TAURI_INVOKE("agent_cancel", { task, subagent })), - agentChanges: (task: string) => typedError(__TAURI_INVOKE("agent_changes", { task })), + /** The task's changed files as `view` compares them (without: since it started). */ + agentChanges: (task: string, view: +/** Everything since the commit the task started from. */ +"sinceStart" | +/** The uncommitted files against `HEAD`; commits made since the start stay. */ +"group" | +/** What the last turn changed, against the checkout as that turn started. */ +"lastTurn" | null) => typedError(__TAURI_INVOKE("agent_changes", { task, view })), /** * Slash commands to complete for `provider` in `task`'s directory, or in the project * before a task exists (skills and custom commands on disk included). @@ -103,7 +116,9 @@ export const commands = { /** Everything since the commit the task started from. */ "sinceStart" | /** The uncommitted files against `HEAD`; commits made since the start stay. */ -"group" | null) => typedError(__TAURI_INVOKE("agent_rollback_changes", { task, paths, view })), +"group" | +/** What the last turn changed, against the checkout as that turn started. */ +"lastTurn" | null) => typedError(__TAURI_INVOKE("agent_rollback_changes", { task, paths, view })), /** Sends a queued message now, interrupting the current turn. */ agentSendQueuedNow: (task: string, queued: string) => typedError(__TAURI_INVOKE("agent_send_queued_now", { task, queued })), /** @@ -2071,7 +2086,9 @@ export type AgentChangesView = /** Everything since the commit the task started from. */ "sinceStart" | /** The uncommitted files against `HEAD`; commits made since the start stay. */ -"group"; +"group" | +/** What the last turn changed, against the checkout as that turn started. */ +"lastTurn"; export type AgentCommand = { /** Without the leading `/`. */ diff --git a/src/features/agents/ConfigPickers.tsx b/src/features/agents/ConfigPickers.tsx index 2449be040..4bcfcfb6d 100644 --- a/src/features/agents/ConfigPickers.tsx +++ b/src/features/agents/ConfigPickers.tsx @@ -444,7 +444,7 @@ function CostBadge({ category }: { category: string | null | undefined }) { } /** Accessible segmented pill selector (`role="radiogroup"`) with Left/Right arrow navigation. */ -function SegmentedControl({ +export function SegmentedControl({ ariaLabel, options, value, diff --git a/src/features/agents/Session.module.css b/src/features/agents/Session.module.css index a4c9546d5..b6e431fea 100644 --- a/src/features/agents/Session.module.css +++ b/src/features/agents/Session.module.css @@ -1280,6 +1280,10 @@ flex: none; white-space: nowrap; } +.changesScope { + flex: none; + padding: 6px 10px 2px; +} .changesSummary { flex: none; overflow: hidden; diff --git a/src/features/agents/SessionEditor.tsx b/src/features/agents/SessionEditor.tsx index 8a9629432..7c419a61e 100644 --- a/src/features/agents/SessionEditor.tsx +++ b/src/features/agents/SessionEditor.tsx @@ -46,6 +46,8 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) { const review = useAgents((s) => s.groupedChanges.get(id)); const changes = grouped ? (review?.uncommitted ?? null) : (sinceStart ?? null); const commits = grouped ? (review?.commits ?? []) : []; + const scope = useChangesOptions((s) => s.scope); + const lastTurn = useAgents((s) => s.turnChanges.get(id)); const project = useProject((s) => s.project); const head = useLocalHead( task?.isolation === "local" ? task.status : null, @@ -189,9 +191,10 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) { {changesOpen && ( setChangesOpen(false)} diff --git a/src/features/agents/changesOptions.ts b/src/features/agents/changesOptions.ts index 3e7d876b3..255f7d238 100644 --- a/src/features/agents/changesOptions.ts +++ b/src/features/agents/changesOptions.ts @@ -1,15 +1,19 @@ /** Changes pane view options, persisted across sessions. */ import { create } from "zustand"; +/** What the pane lists: the whole task's changes, or the last turn's. */ +export type ChangesScope = "task" | "turn"; + export interface ChangesOptions { /** Files grouped by the commit that changed them; otherwise the flat list since the task started. */ groupByCommit: boolean; + scope: ChangesScope; /** Width of the pane beside the conversation, in px; `null`: the stylesheet's default. */ width: number | null; } /** IDEA-like default: the review view. */ -export const DEFAULT_CHANGES_OPTIONS: ChangesOptions = { groupByCommit: true, width: null }; +export const DEFAULT_CHANGES_OPTIONS: ChangesOptions = { groupByCommit: true, scope: "task", width: null }; const MIN_CHANGES_WIDTH = 200; const MAX_CHANGES_WIDTH = 1600; @@ -26,6 +30,7 @@ function load(): ChangesOptions { const o = raw ? (JSON.parse(raw) as Record) : {}; return { groupByCommit: typeof o.groupByCommit === "boolean" ? o.groupByCommit : DEFAULT_CHANGES_OPTIONS.groupByCommit, + scope: o.scope === "turn" ? "turn" : DEFAULT_CHANGES_OPTIONS.scope, width: typeof o.width === "number" && Number.isFinite(o.width) ? clampChangesWidth(o.width) : null, }; } catch { diff --git a/src/features/agents/session/ChangesPane.tsx b/src/features/agents/session/ChangesPane.tsx index 6eaf0f924..8d9293c86 100644 --- a/src/features/agents/session/ChangesPane.tsx +++ b/src/features/agents/session/ChangesPane.tsx @@ -10,7 +10,8 @@ import { confirm } from "@/workbench/messages"; import { useCallback, useEffect, useMemo, useState } from "react"; import { ChangesResizer } from "../ChangesResizer"; import styles from "../Session.module.css"; -import { setChangesOptions } from "../changesOptions"; +import { setChangesOptions, type ChangesScope } from "../changesOptions"; +import { SegmentedControl } from "../ConfigPickers"; import { formatSentAt } from "../conversation"; import { branchLabel } from "../model"; import { acceptChanges, refreshChanges, rollbackChanges, useAgents } from "../store"; @@ -172,6 +173,7 @@ export function ChangesPane({ changes, commits, grouped, + scope, head, docked, onHide, @@ -180,20 +182,22 @@ export function ChangesPane({ changes: AgentChange[] | null; commits: readonly AgentCommit[]; grouped: boolean; + scope: ChangesScope; head: string | null; docked: boolean; onHide: () => void; }) { - // The two views key their rows differently: a selection doesn't carry over. + // The views key their rows differently, and list different changes: a selection doesn't carry over. + const view = scope === "turn" ? "turn" : grouped ? "grouped" : "flat"; const [selection, setSelection] = useState<{ - grouped: boolean; + view: string; keys: ReadonlySet; }>(() => ({ - grouped, + view, keys: NO_SELECTION, })); - const selected = selection.grouped === grouped ? selection.keys : NO_SELECTION; - const setSelected = (keys: ReadonlySet) => setSelection({ grouped, keys }); + const selected = selection.view === view ? selection.keys : NO_SELECTION; + const setSelected = (keys: ReadonlySet) => setSelection({ view, keys }); const rows = useMemo(() => changeRows(changes ?? [], commits, grouped), [changes, commits, grouped]); // Only the working files roll back; a commit's files are history. const rollbackable = useMemo(() => { @@ -226,13 +230,17 @@ export function ChangesPane({ : tx`Roll back the changes to ${count} files?`}

- {grouped - ? tx("They go back to the last commit; changes made after it are lost.") - : task.isolation === "worktree" - ? tx("They go back to how they were when the task started, in the task's worktree.") - : tx( - "They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.", - )} + {scope === "turn" + ? tx( + "They go back to how they were when the last turn started. Edits of yours made to them since then are lost too.", + ) + : grouped + ? tx("They go back to the last commit; changes made after it are lost.") + : task.isolation === "worktree" + ? tx("They go back to how they were when the task started, in the task's worktree.") + : tx( + "They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.", + )}

), @@ -244,7 +252,7 @@ export function ChangesPane({ await rollbackChanges( task.id, picked.length ? picked.map((c) => c.relPath) : null, - grouped ? "group" : "sinceStart", + scope === "turn" ? "lastTurn" : grouped ? "group" : "sinceStart", ); setSelected(new Set()); } catch (e) { @@ -256,10 +264,11 @@ export function ChangesPane({ } }; const accept = async () => { - // Accepting brings over the task's whole work, committed or not: grouping only changes the listing. + // Accepting brings over the task's whole work, committed or not: grouping and the last turn + // only change the listing. const all = - grouped && !picked.length - ? await call(commands.agentChanges(task.id)).catch(() => changes ?? []) + (grouped || scope === "turn") && !picked.length + ? await call(commands.agentChanges(task.id, null)).catch(() => changes ?? []) : (changes ?? []); const targets = picked.length ? picked : all; const count = targets.length; @@ -334,7 +343,7 @@ export function ChangesPane({ onClick={() => void rollback()} /> void refreshChanges(task.id)} /> - {task.isolation === "worktree" && ( + {task.isolation === "worktree" && scope === "task" && ( } - {(grouped || head || task.base) && ( +
+ { + setChangesOptions({ scope: value === "turn" ? "turn" : "task" }); + void refreshChanges(task.id); + }} + /> +
+ {(scope === "turn" || grouped || head || task.base) && (
- vs {grouped ? "HEAD" : (head ?? task.base)} + {scope === "turn" ? ( + Since the last turn started + ) : ( + <> + vs {grouped ? "HEAD" : (head ?? task.base)} + + )} {changes && changes.length > 0 && ( <> {" "} @@ -373,7 +402,7 @@ export function ChangesPane({ ) : ( - key={grouped ? "grouped" : "flat"} + key={view} aria-label="Changed files" roots={rows} getKey={(n) => n.key} @@ -392,7 +421,7 @@ export function ChangesPane({ if (n.type === "file") { if (n.commit) void openCommitDiff(task, n.commit, n.change.path); else if (grouped) void openUncommittedDiff(task, n.change.path); - else void openChangeDiff(task, n.change.path); + else void openChangeDiff(task, n.change.path, scope); } else if (n.type === "commit") { void openCommitDiff(task, n.commit, n.commit.files[0]?.path ?? ""); } @@ -449,7 +478,7 @@ export function ChangesPane({ }} empty={
- No changes yet + {scope === "turn" ? The last turn changed no files : No changes yet}
} /> @@ -459,15 +488,18 @@ export function ChangesPane({ ); } -/** Opens the diff of `path` between the task's start and now. */ -export async function openChangeDiff(task: AgentTask, path: string) { - const changed = (useAgents.getState().changes.get(task.id) ?? []).map((change) => change.path); +/** Opens the diff of `path` between the task's start (or its last turn's) and now. */ +export async function openChangeDiff(task: AgentTask, path: string, scope: ChangesScope = "task") { + const { changes, turnChanges } = useAgents.getState(); + const changed = ((scope === "turn" ? turnChanges : changes).get(task.id) ?? []).map((change) => change.path); const paths = changed.includes(path) ? changed : [path]; - const baseLabel = task.base ?? "Base"; + const baseLabel = scope === "turn" ? tx("Before Last Turn") : (task.base ?? "Base"); const right = task.isolation === "worktree" ? branchLabel(task.branch) : "Working tree"; const diffs = await Promise.all( paths.map(async (file): Promise => { - const base = await call(commands.agentBaseText(task.id, file)).catch(() => null); + const base = await call(commands.agentBaseText(task.id, file, scope === "turn" ? "lastTurn" : null)).catch( + () => null, + ); return { path: file, left: { type: "text", text: base ?? "", label: baseLabel }, diff --git a/src/features/agents/sessionState.test.tsx b/src/features/agents/sessionState.test.tsx index b01e49264..1c1383a22 100644 --- a/src/features/agents/sessionState.test.tsx +++ b/src/features/agents/sessionState.test.tsx @@ -33,6 +33,7 @@ const backend = vi.hoisted(() => ({ entries: new Map(), changes: [] as AgentChange[], changesCalls: 0, + turnChanges: [] as AgentChange[], grouped: { uncommitted: [] as AgentChange[], commits: [] as AgentCommit[] }, groupedCalls: 0, rolledBack: [] as Array<[string, string[] | null, string | null]>, @@ -84,7 +85,8 @@ vi.mock("@/platform/ipc", async (original) => ({ }; return { status: "ok", data: backend.entries.get(key) ?? [] }; }, - agentChanges: async () => { + agentChanges: async (_task: string, view: string | null) => { + if (view === "lastTurn") return { status: "ok", data: backend.turnChanges }; backend.changesCalls += 1; return { status: "ok", data: backend.changes }; }, @@ -230,12 +232,13 @@ beforeEach(() => { localStorage.clear(); backend.changes = []; backend.changesCalls = 0; + backend.turnChanges = []; backend.grouped = { uncommitted: [], commits: [] }; backend.groupedCalls = 0; backend.rolledBack = []; backend.external = []; // The flat list unless a test asks for the grouped view, so counts and selections stay as before. - useChangesOptions.setState({ groupByCommit: false }); + useChangesOptions.setState({ groupByCommit: false, scope: "task" }); backend.imported = []; backend.importError = null; backend.importErrors = new Map(); @@ -2970,6 +2973,43 @@ describe("accept changes", () => { }); }); +describe("last turn changes", () => { + const change = (path: string): AgentChange => ({ + path: `/project/${path}`, + relPath: path, + kind: "modified", + added: 1, + removed: 0, + oldPath: null, + }); + + it("lists and rolls back only what the last turn changed, the session still counting the whole task", async () => { + backend.changes = [change("a.ts"), change("b.ts")]; + backend.turnChanges = [change("b.ts")]; + localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true })); + useAgents.setState({ tasks: new Map([["A", { ...task("A"), status: "ready" }]]) }); + render(); + const pane = await screen.findByRole("complementary", { name: "Changes" }); + expect(await within(pane).findByText("a.ts")).toBeInTheDocument(); + + fireEvent.click(within(pane).getByRole("radio", { name: "Last Turn" })); + await waitFor(() => expect(within(pane).queryByText("a.ts")).toBeNull()); + expect(within(pane).getByText("b.ts")).toBeInTheDocument(); + expect(within(pane).getByText("Since the last turn started")).toBeInTheDocument(); + expect(useChangesOptions.getState().scope).toBe("turn"); + expect(screen.getByRole("button", { name: /2 changed files/ })).toBeInTheDocument(); + + fireEvent.click(within(pane).getByRole("button", { name: "Rollback All Changes…" })); + await waitFor(() => expect(backend.rolledBack).toEqual([["A", null, "lastTurn"]])); + + backend.turnChanges = []; + fireEvent.click(within(pane).getByRole("button", { name: "Refresh" })); + expect(await within(pane).findByText("The last turn changed no files")).toBeInTheDocument(); + fireEvent.click(within(pane).getByRole("radio", { name: "Whole Task" })); + expect(await within(pane).findByText("a.ts")).toBeInTheDocument(); + }); +}); + describe("grouped changes", () => { const commit = (overrides: Partial = {}): AgentCommit => ({ id: "a".repeat(40), diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index b7267aeac..7cdc35378 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -98,6 +98,8 @@ interface AgentsState { changes: Map; /** The task's uncommitted changes and commits, when the Changes pane groups by commit. */ groupedChanges: Map; + /** What the task's last turn changed, when the Changes pane shows that. */ + turnChanges: Map; /** Scroll position and follow-output preference by conversation, shared by both hosts. */ scrollPositions: Map; providers: AgentProvider[]; @@ -186,6 +188,7 @@ export const useAgents = create(() => ({ entryLoads: new Map(), changes: new Map(), groupedChanges: new Map(), + turnChanges: new Map(), providers: [], limits: new Map(), modelCatalogs: new Map(), @@ -496,6 +499,7 @@ export async function connect(): Promise { entryLoads: new Map(), changes: new Map(), groupedChanges: new Map(), + turnChanges: new Map(), providers, organizeRoot, organize: pruneOrganize(loadOrganize(organizeRoot), tasks), @@ -599,12 +603,18 @@ function withoutTaskCache(s: AgentsState, taskId: string): Partial groupedChanges = new Map(s.groupedChanges); groupedChanges.delete(taskId); } - if (!entries && !entryLoads && !changes && !groupedChanges) return null; + let turnChanges: Map | undefined; + if (s.turnChanges.has(taskId)) { + turnChanges = new Map(s.turnChanges); + turnChanges.delete(taskId); + } + if (!entries && !entryLoads && !changes && !groupedChanges && !turnChanges) return null; return { ...(entries ? { entries } : {}), ...(entryLoads ? { entryLoads } : {}), ...(changes ? { changes } : {}), ...(groupedChanges ? { groupedChanges } : {}), + ...(turnChanges ? { turnChanges } : {}), }; } @@ -625,7 +635,7 @@ function isTaskOpenInUi(taskId: string): boolean { /** Whether a background trigger should reload a task's changes: only while they are shown or still cached. */ function wantsChanges(taskId: string): boolean { const s = useAgents.getState(); - return s.changes.has(taskId) || s.groupedChanges.has(taskId) || isTaskOpenInUi(taskId); + return s.changes.has(taskId) || s.groupedChanges.has(taskId) || s.turnChanges.has(taskId) || isTaskOpenInUi(taskId); } /** @@ -667,6 +677,7 @@ export function disconnect() { entryLoads: new Map(), changes: new Map(), groupedChanges: new Map(), + turnChanges: new Map(), modelCatalogs: new Map(), modelRequests: new Set(), modelRequestTargets: new Map(), @@ -846,11 +857,25 @@ export async function loadEntries(task: string, subagent: string | null = null): } export async function refreshChanges(task: string): Promise { + // Discard a result that arrives after a project switch, the task's deletion, or its cache being dropped. const gen = generation; const drops = cacheDrops.get(task); - // Discard a result that arrives after a project switch, the task's deletion, or its cache being dropped. const stillWanted = () => gen === generation && useAgents.getState().tasks.has(task) && cacheDrops.get(task) === drops; + // The whole task's changes are read in either scope: the session's summary counts them. + await Promise.all([ + refreshTaskChanges(task, stillWanted), + useChangesOptions.getState().scope === "turn" && refreshTurnChanges(task, stillWanted), + ]); +} + +async function refreshTurnChanges(task: string, stillWanted: () => boolean): Promise { + const changes = await call(commands.agentChanges(task, "lastTurn")).catch(() => []); + if (!stillWanted()) return; + useAgents.setState((s) => ({ turnChanges: new Map(s.turnChanges).set(task, changes) })); +} + +async function refreshTaskChanges(task: string, stillWanted: () => boolean): Promise { // Local tasks have no commits of their own to group: the flat list is their only view. const grouped = useChangesOptions.getState().groupByCommit && useAgents.getState().tasks.get(task)?.isolation === "worktree"; @@ -871,7 +896,7 @@ export async function refreshChanges(task: string): Promise { return; } try { - const changes = await call(commands.agentChanges(task)); + const changes = await call(commands.agentChanges(task, null)); if (!stillWanted()) return; useAgents.setState((s) => ({ changes: new Map(s.changes).set(task, changes), diff --git a/src/features/agents/unread.test.tsx b/src/features/agents/unread.test.tsx index 1e0d65e90..313a8c2bd 100644 --- a/src/features/agents/unread.test.tsx +++ b/src/features/agents/unread.test.tsx @@ -56,7 +56,10 @@ vi.mock("@/platform/ipc", async (original) => ({ agentProviders: async () => ({ status: "ok", data: [] }), agentChanges: async () => ({ status: "ok", data: [] }), agentGroupedChanges: async () => ({ status: "ok", data: { uncommitted: [], commits: [] } }), - agentBaseText: async (_task: string, path: string) => ({ status: "ok", data: `base of ${path}` }), + agentBaseText: async (_task: string, path: string, view: string | null) => ({ + status: "ok", + data: view === "lastTurn" ? `before the last turn: ${path}` : `base of ${path}`, + }), agentEntries: async () => ({ status: "ok", data: await backend.entries }), }, })); @@ -522,6 +525,21 @@ describe("the diff of an agent change", () => { expect(input.data.chain[0].left.text).toBe("base of /project/a.ts"); }); + it("in the last turn, lists that turn's files against how they were as it started", async () => { + useAgents.setState({ + changes: new Map([["one", [change("/project/a.ts"), change("/project/b.ts")]]]), + turnChanges: new Map([["one", [change("/project/b.ts")]]]), + }); + await openChangeDiff(task("one"), "/project/b.ts", "turn"); + const input = backend.openInput.mock.lastCall![0]; + expect(input.data.left).toEqual({ + type: "text", + text: "before the last turn: /project/b.ts", + label: "Before Last Turn", + }); + expect(input.data.chain).toBeUndefined(); + }); + it("opens a file outside the change list on its own", async () => { useAgents.setState({ changes: new Map([["one", [change("/project/a.ts")]]]) }); await openChangeDiff(task("one"), "/project/c.ts"); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 8f5a56c60..f5264a850 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -289,6 +289,13 @@ "They go back to how they were when the task started, in the task's worktree.": "They go back to how they were when the task started, in the task's worktree.", "They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.": "They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.", "They go back to the last commit; changes made after it are lost.": "They go back to the last commit; changes made after it are lost.", + "They go back to how they were when the last turn started. Edits of yours made to them since then are lost too.": "They go back to how they were when the last turn started. Edits of yours made to them since then are lost too.", + "Changes to show": "Changes to show", + "Whole Task": "Whole Task", + "Last Turn": "Last Turn", + "Since the last turn started": "Since the last turn started", + "The last turn changed no files": "The last turn changed no files", + "Before Last Turn": "Before Last Turn", "Cannot roll back the changes": "Cannot roll back the changes", "Cannot connect": "Cannot connect", "Rollback Selected Changes…": "Rollback Selected Changes…", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index b9fc7926b..1a63f2ad7 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -261,6 +261,13 @@ "They go back to how they were when the task started, in the task's worktree.": "它们会在任务的工作树中恢复为任务开始时的内容。", "They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.": "它们会恢复为任务开始时的内容。任务开始后你对它们做的修改也会丢失;任务开始前的修改会保留。", "They go back to the last commit; changes made after it are lost.": "它们会回到最后一次提交的状态;之后的改动会丢失。", + "They go back to how they were when the last turn started. Edits of yours made to them since then are lost too.": "它们会恢复为最近一轮开始时的内容。之后你对它们做的修改也会丢失。", + "Changes to show": "显示的更改", + "Whole Task": "整个任务", + "Last Turn": "最近一轮", + "Since the last turn started": "最近一轮开始以来", + "The last turn changed no files": "最近一轮没有改动文件", + "Before Last Turn": "最近一轮之前", "Cannot roll back the changes": "无法回滚更改", "Copy the changes to {name} into the local checkout?": "是否将对 {name} 的更改复制到本地检出?", "Copy the changes to {count} files into the local checkout?": "是否将对 {count} 个文件的更改复制到本地检出?",