diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 3d2803803..1b019a016 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -419,9 +419,13 @@ 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")] + /// The checkout as the last turn started, in task files saved before every turn's was kept. + #[serde(default, skip_serializing)] turn: Option, + /// The checkout as each turn of the conversation started (by turn, `None` where it wasn't + /// recorded), the copies in the store's `.turn` folder. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + turns: Vec>, #[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). @@ -455,6 +459,16 @@ impl PendingModel { /// The changed files of a checkout, stamped. type Snapshot = BTreeMap; +/// What rolling back to an earlier message does to the files. +enum Rewind { + /// They stay as they are. + None, + /// Back as they were when the task started. + TaskStart, + /// These files back as they were. + Files(Vec), +} + struct TaskState { task: AgentTask, session_id: Option, @@ -467,8 +481,8 @@ struct TaskState { saved: Option, /// See `TaskFile::touched`. touched: Option>>, - /// See `TaskFile::turn`. - turn: Option>, + /// See `TaskFile::turns`. + turns: Vec>>, pending_rollback: u32, /// The user named the task; see `TaskFile::title_renamed`. title_renamed: bool, @@ -989,6 +1003,7 @@ impl AgentManager { saved: None, touched: Some(BTreeSet::new()), turn: None, + turns: Vec::new(), subagents: Vec::new(), pending_rollback: 0, title_renamed: true, @@ -1116,6 +1131,7 @@ impl AgentManager { saved, touched: (req.isolation == Isolation::Local).then(BTreeSet::new), turn: None, + turns: Vec::new(), subagents: Vec::new(), pending_rollback: 0, title_renamed: false, @@ -1478,8 +1494,9 @@ 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. + // The copies are the source's: the fork's turns are recorded as it runs them. turn: None, + turns: Vec::new(), subagents: s.conversation.saved_subagents(), pending_rollback: total - keep, title_renamed: s.title_renamed, @@ -1496,15 +1513,18 @@ impl AgentManager { } /// Drops the task's turns after its first `turns`, in the agent's session and in the - /// conversation; returns the message that started the first dropped turn. Files the - /// agent changed stay as they are. - pub async fn rollback(&self, id: &str, turns: u32) -> IdeResult> { + /// conversation; returns the message that started the first dropped turn. With `files`, + /// the files the dropped turns changed go back as they were when the first of them + /// started; otherwise they stay as they are. + pub async fn rollback(&self, id: &str, turns: u32, files: bool) -> IdeResult> { let task = self.task(id)?; if task.state.lock().busy { return Err(IdeError::invalid("wait until the agent is done")); } let starts = turn_starts(&task.state.lock().conversation.main.entries); let Some(&cut) = starts.get(turns as usize) else { return Ok(None) }; + // Read and checked before anything changes: a file that can't go back stops it all. + let rewind = if files { self.plan_rewind(&task, turns as usize).await? } else { Rewind::None }; // Dropping every turn starts the conversation over, which needs no agent-side // rewind — and some agents cannot rewind past their first turn (a resumed // Claude Code session). A fresh session avoids both. @@ -1533,6 +1553,7 @@ impl AgentManager { task.persist(); self.shared.emit(AgentEvent::Truncated { task: id.to_owned(), length: 0 }); task.emit_task(); + self.put_back(&task, rewind, 0).await?; return Ok(first); } let live = task.ensure_session().await.map_err(IdeError::internal)?; @@ -1558,6 +1579,7 @@ impl AgentManager { task.streamed.lock().clear(); task.persist(); self.shared.emit(AgentEvent::Truncated { task: id.to_owned(), length: cut as u32 }); + self.put_back(&task, rewind, turns as usize).await?; task.emit_task(); // Undoing may have started the agent: it stops again once idle. task.release_when_idle(); @@ -1916,6 +1938,78 @@ impl AgentManager { .await } + /// What rolling the task's files back to the start of its turn `turn` writes. + async fn plan_rewind(&self, task: &Arc, turn: usize) -> IdeResult { + let (cwd, start, touched) = { + let s = task.state.lock(); + (s.task.cwd.0.clone(), s.turns.get(turn).cloned().flatten(), s.touched.clone()) + }; + let Some(start) = start else { + // The task's own start is the first turn's. + if turn == 0 { + return Ok(Rewind::TaskStart); + } + return Err(IdeError::invalid( + "the files weren't recorded as this message was sent: roll them back in the Changes view instead", + )); + }; + let dir = task.turn_dir(); + let planned = vcs(&self.shared, move || { + let mut changed = worktree::changed_in_turn(&cwd, &start)?.1; + // In the project's own checkout, the files the user changed are theirs. + if let Some(touched) = &touched { + changed.retain(|rel| touched.contains(rel)); + } + worktree::rewind(&cwd, &start, &dir, &changed) + }) + .await?; + Ok(Rewind::Files(planned)) + } + + /// Writes what `plan_rewind` read, and drops the records of the turns from `turn` on. + async fn put_back(&self, task: &Arc, rewind: Rewind, turn: usize) -> IdeResult<()> { + let written = match rewind { + Rewind::None => Vec::new(), + Rewind::TaskStart => { + self.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await?; + Vec::new() + } + Rewind::Files(planned) => { + let written: Vec<(String, PathBuf)> = planned.iter().map(|f| (f.rel.clone(), f.path.clone())).collect(); + vcs(&self.shared, move || worktree::put_back(planned)).await?; + written + } + }; + let (dir, kept) = { + let mut s = task.state.lock(); + s.turns.truncate(turn); + // Back to the user's own edits from before the task: not a change of the task. + let saved = s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)); + let mut before = (*s.before).clone(); + let mut restamped = false; + for (rel, path) in &written { + if let Some(Some(_)) = before.get(rel) + && let Some(copy) = saved.as_deref().and_then(|d| worktree::saved_copy(d, rel)) + && std::fs::read(path).is_ok_and(|now| now == copy) + { + before.insert(rel.clone(), worktree::stamp(path)); + restamped = true; + } + } + if restamped { + s.before = Arc::new(before); + } + (task.turn_dir(), s.turns.clone()) + }; + task.persist(); + let _ = vcs(&self.shared, move || { + worktree::prune_turn_copies(&dir, kept.iter().flatten().map(|t| &**t)); + Ok(()) + }) + .await; + Ok(()) + } + /// Rollback: puts the task's changed files among `rel_paths` (all with `None`) back as /// `view` compares them: as they were when it started, as they are in `HEAD`, or as they /// were when its last turn started. @@ -1972,12 +2066,12 @@ impl AgentManager { 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 + if let Some(Some(turn)) = s.turns.last_mut() && 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() })); + *turn = Arc::new(worktree::TurnStart { changed: Some(changed), ..(**turn).clone() }); } } task.persist(); @@ -2224,6 +2318,14 @@ impl Task { config::add_client_options(&task.provider, &mut task.config); let adopt = file.entries.is_empty() && file.session_id.is_some(); let conversation = Conversation::restore(file.entries, file.subagents); + let mut turns: Vec<_> = file.turns.into_iter().map(|t| t.map(Arc::new)).collect(); + // Saved with the last turn's only: the turns before it have none. + if turns.is_empty() + && let Some(last) = file.turn + { + turns.resize(turn_starts(&conversation.main.entries).len().saturating_sub(1), None); + turns.push(Some(Arc::new(last))); + } let mut wanted = file.wanted; let pending_model = file.pending_switch.or_else(|| { let id = file.pending_model?; @@ -2256,7 +2358,7 @@ impl Task { before: Arc::new(file.before), saved: file.saved, touched: file.touched.map(Arc::new), - turn: file.turn.map(Arc::new), + turns, pending_rollback: file.pending_rollback, title_renamed: file.title_renamed, busy: false, @@ -2295,7 +2397,7 @@ impl Task { (s.before.clone(), s.touched.clone()) } - /// Where the copies of the files already changed as the last turn started are kept. + /// Where the copies of the files already changed as the turns started are kept. fn turn_dir(&self) -> PathBuf { self.shared.paths.store_dir.join(format!("{}.turn", self.id)) } @@ -2303,20 +2405,38 @@ impl Task { /// 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()) + (s.task.cwd.0.clone(), s.turns.last().cloned().flatten(), self.turn_dir()) } - /// Records the checkout as a turn starts: what the turn's changes are compared with. + /// Records the checkout as a turn starts (its message shown): what the turn's changes are + /// compared with, and what rolling back to its message puts back. async fn checkout_before_turn(self: &Arc) { - let (cwd, previous, dir) = self.last_turn(); - let turn = match vcs(&self.shared, move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await { + let (cwd, dir, index, earlier) = { + let s = self.state.lock(); + let index = turn_starts(&s.conversation.main.entries).len().saturating_sub(1); + let earlier: Vec<_> = s.turns.iter().take(index).cloned().collect(); + (s.task.cwd.0.clone(), self.turn_dir(), index, earlier) + }; + let kept = earlier.clone(); + let turn = match vcs(&self.shared, move || { + let turn = worktree::start_turn(&cwd, &dir)?; + worktree::prune_turn_copies(&dir, kept.iter().flatten().map(|t| &**t).chain([&turn])); + Ok(turn) + }) + .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; + { + let mut s = self.state.lock(); + s.turns = earlier; + s.turns.resize(index, None); + s.turns.push(turn); + } self.persist_soon(); } @@ -2338,7 +2458,9 @@ impl Task { touched.extend(in_worktree); s.touched = Some(Arc::new(touched)); } - s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() })); + if let Some(last) = s.turns.last_mut() { + *last = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() })); + } } self.persist_soon(); } @@ -2509,7 +2631,8 @@ impl Task { before: (*s.before).clone(), saved: s.saved.clone(), touched: s.touched.as_deref().cloned(), - turn: s.turn.as_deref().cloned(), + turn: None, + turns: s.turns.iter().map(|t| t.as_deref().cloned()).collect(), subagents: s.conversation.saved_subagents(), pending_rollback: s.pending_rollback, title_renamed: s.title_renamed, diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index e811db3da..a993d5b6f 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -2688,7 +2688,7 @@ async fn forks_rollbacks_and_steering() { } // Undoing the last turn hands its message back. - let undone = mgr.rollback(&task.id, 1).await.unwrap().unwrap(); + let undone = mgr.rollback(&task.id, 1, false).await.unwrap().unwrap(); assert_eq!(undone.text, "again"); assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1); assert!(agent.calls.lock().iter().any(|c| c == "_openidea/rollback 1")); @@ -2715,7 +2715,7 @@ async fn forks_rollbacks_and_steering() { } handle.state.lock().conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() }); let rewinds = agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count(); - let first = mgr.rollback(&task.id, 0).await.unwrap().unwrap(); + let first = mgr.rollback(&task.id, 0, false).await.unwrap().unwrap(); assert_eq!(first.text, "again"); assert!(mgr.entries(&task.id, None).unwrap().is_empty()); assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_none()); @@ -3654,7 +3654,7 @@ async fn idle_agents_stop_and_resume_their_session_on_the_next_message() { wait_for(&mgr, &task.id, AgentStatus::Ready).await; tokio::time::sleep(Duration::from_millis(600)).await; assert!(!live(&mgr, &task.id)); - mgr.rollback(&task.id, 1).await.unwrap(); + mgr.rollback(&task.id, 1, false).await.unwrap(); assert!(live(&mgr, &task.id)); tokio::time::sleep(Duration::from_millis(600)).await; assert!(!live(&mgr, &task.id), "an agent started to undo turns stops too"); @@ -4665,6 +4665,94 @@ async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() { } } +#[tokio::test(flavor = "multi_thread")] +async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() { + for isolation in [Isolation::Local, Isolation::Worktree] { + let repo = Checkout::new(Eol::Lf); + repo.write("a.txt", "base\n"); + repo.write("gone.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| std::fs::write(cwd.join(rel), text).unwrap(); + let read = |rel: &str| std::fs::read_to_string(cwd.join(rel)).ok(); + let case = format!("{isolation:?}"); + + one_turn(&mgr, &task.id, None, || write("a.txt", "base\nturn 1\n")).await; + // The user's own work between the turns. + write("mine.txt", "mine\n"); + one_turn(&mgr, &task.id, Some("more"), || { + write("a.txt", "base\nturn 1\nturn 2\n"); + write("two.txt", "two\n"); + }) + .await; + one_turn(&mgr, &task.id, Some("last"), || { + write("a.txt", "base\nturn 1\nturn 2\nturn 3\n"); + std::fs::remove_file(cwd.join("gone.txt")).unwrap(); + }) + .await; + // And after the last one. + write("later.txt", "later\n"); + + // After a restart: the turns' records are kept with the task. + mgr.shutdown(); + let mgr = manager(&repo.dir, Arc::new(FakeAgent::default())); + let undone = mgr.rollback(&task.id, 1, true).await.unwrap().unwrap(); + assert_eq!(undone.text, "more", "{case}"); + assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1, "{case}"); + assert_eq!(read("a.txt").as_deref(), Some("base\nturn 1\n"), "{case}"); + assert_eq!(read("gone.txt").as_deref(), Some("base\n"), "{case}"); + assert_eq!(read("two.txt"), None, "{case}"); + // There before the message was sent. + assert_eq!(read("mine.txt").as_deref(), Some("mine\n"), "{case}"); + let later = match isolation { + // In the project's own checkout, a file no turn of the task changed is the user's. + Isolation::Local => Some("later\n"), + // In its own worktree, everything changed there since is the task's. + Isolation::Worktree => None, + }; + assert_eq!(read("later.txt").as_deref(), later, "{case}"); + assert_eq!(mgr.task(&task.id).unwrap().state.lock().turns.len(), 1, "{case}"); + + // Without `files` they stay; the first message takes the task back to its start. + one_turn(&mgr, &task.id, Some("retry"), || write("a.txt", "again\n")).await; + mgr.rollback(&task.id, 1, false).await.unwrap(); + assert_eq!(read("a.txt").as_deref(), Some("again\n"), "{case}"); + mgr.rollback(&task.id, 0, true).await.unwrap(); + assert_eq!(read("a.txt").as_deref(), Some("base\n"), "{case}"); + assert!(mgr.task(&task.id).unwrap().state.lock().turns.is_empty(), "{case}"); + let left = std::fs::read_dir(repo.dir.join("store").join(format!("{}.turn", task.id))); + assert!(left.map_or(true, |mut d| d.next().is_none()), "{case}: no copies left"); + mgr.delete(&task.id, true).await.unwrap(); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_message_sent_before_turns_were_recorded_cannot_take_the_files_back() { + 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; + one_turn(&mgr, &task.id, Some("last"), || repo.write("a.txt", "base\nturn 1\nturn 2\nturn 3\n")).await; + // As a task saved with its last turn's record only. + mgr.task(&task.id).unwrap().state.lock().turns[1] = None; + assert!(mgr.rollback(&task.id, 1, true).await.is_err()); + assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 3, "nothing changed"); + assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\nturn 3\n"); + mgr.rollback(&task.id, 2, true).await.unwrap(); + assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\n"); +} + #[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); diff --git a/crates/ide-agent/src/worktree.rs b/crates/ide-agent/src/worktree.rs index 8a1ffab8b..2d46aeb04 100644 --- a/crates/ide-agent/src/worktree.rs +++ b/crates/ide-agent/src/worktree.rs @@ -819,7 +819,7 @@ 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 +/// The checkout as one of the task's turns 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)] @@ -840,13 +840,40 @@ pub(crate) struct TurnStart { /// 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>, + /// The copies are named by file and stamp, so the turns share them; the turn recorded + /// before that named them by file alone. + #[serde(default, skip_serializing_if = "is_false")] + pub stamped: bool, +} + +fn is_false(b: &bool) -> bool { + !*b +} + +/// The name of the copy of `rel` as stamped `stamp`: the same while the file is unchanged. +fn turn_copy_name(rel: &str, stamp: &Stamp) -> String { + use std::hash::{DefaultHasher, Hash, Hasher}; + let mut hash = DefaultHasher::new(); + rel.hash(&mut hash); + stamp.hash(&mut hash); + format!("t{:016x}", hash.finish()) +} + +impl TurnStart { + /// The name of the copy saved of `rel` as the turn began. + fn copy_name(&self, rel: &str) -> Option { + if !self.stamped { + return Some(saved_name(rel)); + } + Some(turn_copy_name(rel, self.before.get(rel)?)) + } } /// 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 +/// A copy an earlier turn saved of a file unchanged since is used 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(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) }; +pub(crate) fn start_turn(cwd: &Path, dir: &Path) -> IdeResult { + let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart { stamped: true, ..Default::default() }) }; let mut heads = BTreeMap::new(); let head = if at.nested { for repo in &at.repos { @@ -859,37 +886,72 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) - // 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 = at.base.join(rel); - if stamp.is_none() - || saved.contains(rel) - || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) - { + if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) { + continue; + } + let copy = dir.join(turn_copy_name(rel, stamp)); + if copy.is_file() { + saved.insert(rel.clone()); 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() { + if std::fs::copy(&path, ©).is_ok() { saved.insert(rel.clone()); } } - Ok(TurnStart { head, heads, before, saved, changed: None }) + Ok(TurnStart { head, heads, before, saved, changed: None, stamped: true }) +} + +/// Removes the copies in `dir` that none of `turns` uses any more. +pub(crate) fn prune_turn_copies<'a>(dir: &Path, turns: impl IntoIterator) { + let used: BTreeSet = + turns.into_iter().flat_map(|t| t.saved.iter().filter_map(move |rel| t.copy_name(rel))).collect(); + let Ok(read) = std::fs::read_dir(dir) else { return }; + for entry in read.flatten() { + if !used.contains(&*entry.file_name().to_string_lossy()) { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +/// A file to put back as it was. +pub(crate) struct PutBack { + /// Relative to the checkout, as the task names it. + pub rel: String, + pub path: PathBuf, + /// `None`: there was no file. + pub content: Option>, +} + +/// The files among `rels` that differ from how they were as the turn `start` began, with what +/// to put back. Fails, changing nothing, when one can't be put back. +pub(crate) fn rewind(cwd: &Path, start: &TurnStart, dir: &Path, rels: &BTreeSet) -> IdeResult> { + let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) }; + let mut out = Vec::new(); + for rel in rels { + let path = at.base.join(rel); + // A folder (a submodule, say) has nothing to put back. + if path.is_dir() { + continue; + } + let then = at_turn_start(&at, rel, start, dir)?; + if existing(&path).is_some_and(|now| now == then) { + continue; + } + out.push(PutBack { rel: rel.clone(), path, content: then }); + } + Ok(out) +} + +/// Writes what `rewind` planned. +pub(crate) fn put_back(planned: Vec) -> IdeResult<()> { + for file in planned { + put(&file.path, file.content)?; + } + Ok(()) } /// The files that changed in `cwd` since the turn `start` began: in the working tree (as @@ -919,7 +981,12 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec IdeResult>> { match start.before.get(rel) { Some(None) => Ok(None), - Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() { + Some(Some(_)) => match start + .saved + .contains(rel) + .then(|| start.copy_name(rel).and_then(|name| std::fs::read(dir.join(name)).ok())) + .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" @@ -1312,30 +1379,37 @@ mod tests { git(&repo, &["commit", "-q", "-m", "init"]); let dir = tmp.path().join("turn"); let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::>(); + let copy = |turn: &TurnStart, rel: &str| std::fs::read(dir.join(turn.copy_name(rel).unwrap())).ok(); + let at = |turn: &TurnStart, rel: &str| { + at_turn_start(&TurnRepos::of(&repo).unwrap().unwrap(), rel, turn, &dir).unwrap() + }; 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(); + let first = start_turn(&repo, &dir).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::fs::write(dir.join(first.copy_name("b.txt").unwrap()), "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(); + let second = start_turn(&repo, &dir).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"[..])); + assert_eq!(copy(&second, "a.txt").as_deref(), Some(&b"turn two\n"[..])); + assert_eq!(copy(&second, "b.txt").as_deref(), Some(&b"kept\n"[..])); + // The first turn keeps its own copy of the file changed since. + assert_eq!(at(&first, "a.txt").as_deref(), Some(&b"turn 1\n"[..])); - // Back as committed: nothing to keep a copy of. + // Back as committed: nothing to keep a copy of, and the committed text is the start. git(&repo, &["checkout", "--", "a.txt"]); - let third = start_turn(&repo, &dir, Some(&second)).unwrap(); + let third = start_turn(&repo, &dir).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"[..])); + assert_eq!(at(&third, "a.txt").as_deref(), Some(&b"base\n"[..])); + + // Dropping the earlier turns drops the copies only they used. + prune_turn_copies(&dir, [&third]); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); + assert_eq!(copy(&third, "b.txt").as_deref(), Some(&b"kept\n"[..])); } #[cfg(unix)] @@ -1350,7 +1424,7 @@ mod tests { 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(); + let start = start_turn(&repo, &dir).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"); diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index 2d607afd5..ccbb28630 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -360,10 +360,17 @@ pub async fn agent_fork(host: &Host, window: &str, task: String, turns: Option IdeResult> { +pub async fn agent_rollback( + host: &Host, + window: &str, + task: String, + turns: u32, + files: bool, +) -> IdeResult> { host.require_trust(window)?; - host.project(window)?.agents.rollback(&task, turns).await + host.project(window)?.agents.rollback(&task, turns, files).await } /// Checks the selected installation without modifying it. diff --git a/docs/en/guide/agents.mdx b/docs/en/guide/agents.mdx index bbf2d0ba9..f01ea3550 100644 --- a/docs/en/guide/agents.mdx +++ b/docs/en/guide/agents.mdx @@ -79,7 +79,7 @@ The task tab shows the conversation: your messages, the agent's replies, its rea - **Stop** ends the current turn. - `⌘F` / `Ctrl+F` finds text in the conversation. -On your own messages you can **Edit** (the messages after it are replaced; files already changed stay as they are) or **Retract Message**. On replies you can **Copy Markdown**, **Quote Reply**, **Regenerate Response** and **Branch Conversation from Here**, which starts a new task from that point. +On your own messages you can **Edit** (the messages after it are replaced, and the files the agent changed since go back to how they were before it was sent) or **Roll Back to Here**, which removes the message and the ones after it, puts the files the agent changed since back as they were before it was sent, and returns the message to the composer. On replies you can **Copy Markdown**, **Quote Reply**, **Regenerate Response** and **Branch Conversation from Here**, which starts a new task from that point. In an existing chat, open **Model › Refresh models** to discover newly available models without sending a message or changing the selection. If the agent can't switch in place, the choice stays pending. You can choose an effort level as soon as the provider reports the new model's options. On your next message, OpenIDEA reopens the same session and applies the model and any effort you selected before sending. If the session can't be reopened or rejects either choice, OpenIDEA restores the previous selection and reports the error without sending the message. diff --git a/docs/zh/guide/agents.mdx b/docs/zh/guide/agents.mdx index f2087b8c3..420725a5f 100644 --- a/docs/zh/guide/agents.mdx +++ b/docs/zh/guide/agents.mdx @@ -79,7 +79,7 @@ Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex - **停止** 结束当前这一轮。 - `⌘F` / `Ctrl+F` 在对话中查找。 -在你自己的消息上可以 **编辑**(其后的消息会被替换,已经改动的文件保持不变)或 **撤回消息**。在回复上可以 **复制 Markdown**、**引用回复**、**重新生成回复**,以及 **从此处创建分支对话**,从这一点开始一个新任务。 +在你自己的消息上可以 **编辑**(其后的消息会被替换,Agent 在此之后改动的文件会恢复到这条消息发送前的状态)或 **回滚到这里**:移除这条消息及之后的消息,把 Agent 在此之后改动的文件恢复到这条消息发送前的状态,并把消息放回输入框。在回复上可以 **复制 Markdown**、**引用回复**、**重新生成回复**,以及 **从此处创建分支对话**,从这一点开始一个新任务。 在已有对话中,打开**模型 › 刷新模型**即可查找新上线的模型,不会发送消息或更改当前选择。如果 agent 无法直接切换,所选模型会保持待应用状态。提供商返回新模型支持的思考强度后,你就可以选择强度。发送下一条消息时,OpenIDEA 会先恢复原会话并应用所选模型和思考强度,再发送消息。如果无法恢复会话,或原会话不接受其中任何一项,OpenIDEA 会还原之前的选择并提示错误,不会发送该消息。 diff --git a/src/bindings.ts b/src/bindings.ts index 7a67e7c9f..d9db5a19d 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -120,12 +120,15 @@ export const commands = { agentRename: (task: string, title: string) => typedError(__TAURI_INVOKE("agent_rename", { task, title })), /** Answers a permission request; `option: null` cancels it. */ agentRespond: (task: string, permission: number, option: string | null) => typedError(__TAURI_INVOKE("agent_respond", { task, permission, option })), - /** Drops the task's turns after its first `turns`; returns the message of the first dropped one. */ - agentRollback: (task: string, turns: number) => typedError<{ + /** + * Drops the task's turns after its first `turns`; returns the message of the first dropped one. + * With `files`, the files those turns changed go back as they were before them. + */ + agentRollback: (task: string, turns: number, files: boolean) => typedError<{ text: string, files: IpcPath[], images: AgentImage[], -} | null, IdeError>(__TAURI_INVOKE("agent_rollback", { task, turns })), +} | null, IdeError>(__TAURI_INVOKE("agent_rollback", { task, turns, files })), /** Rollback: the task's changed files among `paths` (all without) back as `view` compares them. */ agentRollbackChanges: (task: string, paths: string[] | null, view: /** Everything since the commit the task started from. */ diff --git a/src/features/agents/messageEditing.test.tsx b/src/features/agents/messageEditing.test.tsx index c8f7e02bc..36388f042 100644 --- a/src/features/agents/messageEditing.test.tsx +++ b/src/features/agents/messageEditing.test.tsx @@ -46,7 +46,7 @@ vi.mock("@tauri-apps/api/webview", () => ({ import { SessionEditor } from "./SessionEditor"; import { textOf, typeIn } from "./composerTesting"; import { registerActions } from "@/platform/actions"; -import { composerDraft, retractFrom, rerunFrom, sendMessage, updateComposer, useAgents } from "./store"; +import { composerDraft, rollBackTo, rerunFrom, sendMessage, updateComposer, useAgents } from "./store"; import { replyActions } from "./replyActions"; const task: AgentTask = { @@ -107,19 +107,19 @@ it("keeps the transcript and running session when a fresh-session rerun is cance expect(useAgents.getState().entries.get(task.id)).toEqual(entries); }); -describe("retracting a turn", () => { +describe("rolling back to a message", () => { it.each([0, 1])("stops before rollback and restores text/images without sending (turn %s)", async (turn) => { const image = { mimeType: "image/png", data: "AAA", name: "shot.png" }; useAgents.setState({ tasks: new Map([[task.id, { ...task, status: "running" }]]), }); updateComposer(task.id, { text: "Draft" }); - const running = retractFrom(task.id, turn, "Original", [image]); + const running = rollBackTo(task.id, turn, "Original", [image]); await waitFor(() => expect(ipc.cancel).toHaveBeenCalledTimes(1)); expect(ipc.rollback).not.toHaveBeenCalled(); useAgents.setState({ tasks: new Map([[task.id, task]]) }); await running; - expect(ipc.rollback).toHaveBeenCalledExactlyOnceWith(task.id, turn); + expect(ipc.rollback).toHaveBeenCalledExactlyOnceWith(task.id, turn, true); expect(ipc.prompt).not.toHaveBeenCalled(); expect(composerDraft(task.id)).toEqual({ text: "Original\nDraft", @@ -135,7 +135,7 @@ describe("retracting a turn", () => { useAgents.setState({ tasks: new Map([[task.id, { ...task, status: "running" }]]), }); - const result = expect(retractFrom(task.id, 1, "Original")).rejects.toThrow("The agent is still stopping"); + const result = expect(rollBackTo(task.id, 1, "Original")).rejects.toThrow("The agent is still stopping"); await vi.advanceTimersByTimeAsync(15_000); await result; expect(ipc.rollback).not.toHaveBeenCalled(); @@ -150,12 +150,12 @@ describe("retracting a turn", () => { status: "error", error: { kind: "internal", message: "Rollback failed" }, }); - await expect(retractFrom(task.id, 1, "Original")).rejects.toThrow("Rollback failed"); + await expect(rollBackTo(task.id, 1, "Original")).rejects.toThrow("Rollback failed"); expect(composerDraft(task.id).text).toBe("Original"); expect(ipc.prompt).not.toHaveBeenCalled(); }); - it("confirms before retracting a turn with later messages and guards repeated clicks", async () => { + it("confirms before rolling back and guards repeated clicks", async () => { const transcript = [...entries, { ...entries[0]!, text: "Follow up" } as AgentEntry, entries[1]!]; useAgents.setState({ entries: new Map([[task.id, transcript]]) }); let answer!: (ok: boolean) => void; @@ -167,7 +167,7 @@ describe("retracting a turn", () => { render(); const user = userEvent.setup(); const retract = screen.getAllByRole("button", { - name: "Retract Message", + name: "Roll Back to Here", })[0]!; await user.click(retract); await user.click(retract); @@ -177,7 +177,7 @@ describe("retracting a turn", () => { expect(useAgents.getState().entries.get(task.id)).toEqual(transcript); ipc.confirm.mockResolvedValue(true); await user.click(retract); - await waitFor(() => expect(ipc.rollback).toHaveBeenCalledExactlyOnceWith(task.id, 0)); + await waitFor(() => expect(ipc.rollback).toHaveBeenCalledExactlyOnceWith(task.id, 0, true)); expect(composerDraft(task.id).text).toBe("Original message"); }); }); @@ -371,7 +371,7 @@ describe("editing a sent agent message", () => { ); const { user, box, send } = await edit(); await user.click(send); - expect(ipc.rollback).toHaveBeenCalledWith(task.id, 0); + expect(ipc.rollback).toHaveBeenCalledWith(task.id, 0, true); expect(ipc.prompt).not.toHaveBeenCalled(); expect(send).toBeDisabled(); expect(send).toHaveAccessibleName("Send"); diff --git a/src/features/agents/replyActions.ts b/src/features/agents/replyActions.ts index b19b1aabc..f76836a92 100644 --- a/src/features/agents/replyActions.ts +++ b/src/features/agents/replyActions.ts @@ -4,7 +4,7 @@ import { tx } from "@/platform/i18n"; import { confirm } from "@/workbench/messages"; import { notifications } from "@/workbench/contributions"; import { replyOperations, replyTurns, turnNumbers } from "./model"; -import { forkTask, quoteInComposer, rerunFrom, retractFrom, useAgents } from "./store"; +import { forkTask, quoteInComposer, rerunFrom, rollBackTo, useAgents } from "./store"; export interface CopyReply { text: string; @@ -72,8 +72,8 @@ export const replyActions: Action[] = [ }, }, { - id: "agents.retractMessage", - title: "Retract Message", + id: "agents.rollBackToMessage", + title: "Roll Back to Here", category: "Agents", icon: "diff-revert", hidden: true, @@ -87,18 +87,19 @@ export const replyActions: Action[] = [ const index = [...turns].find(([, turn]) => turn === target.turn)?.[0]; const prompt = index === undefined ? undefined : entries[index]; if (prompt?.type !== "user") return; - return runReplyOperation(task.id, "Couldn't retract the message", async () => { + return runReplyOperation(task.id, "Couldn't roll back", async () => { if ( - target.turn < turns.size - 1 && !(await confirm({ - title: "Retract Message", - message: tx("The messages after this one are replaced. Files the agent changed stay as they are."), - ok: "Retract", + title: "Roll Back to Here", + message: tx( + "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.", + ), + ok: "Roll Back", icon: "warning", })) ) return; - await retractFrom(task.id, target.turn, prompt.text, prompt.images ?? []); + await rollBackTo(task.id, target.turn, prompt.text, prompt.images ?? []); }); }, }, diff --git a/src/features/agents/session/messages.tsx b/src/features/agents/session/messages.tsx index 1112c52cb..39ec3e182 100644 --- a/src/features/agents/session/messages.tsx +++ b/src/features/agents/session/messages.tsx @@ -307,8 +307,8 @@ function UserMessage({ size="small" icon="diff-revert" iconSize={14} - title="Retract Message" - action="agents.retractMessage" + title="Roll Back to Here" + action="agents.rollBackToMessage" actionArg={{ task: task.id, turn }} /> )} @@ -430,11 +430,16 @@ function MessageEditor({ )}
- {later && ( - - The messages after this one are replaced. Files the agent changed stay as they are. - - )} + + {later ? ( + + The messages after this one are replaced, and the files the agent changed since go back to how they were + before this message was sent. + + ) : ( + The files the agent changed since go back to how they were before this message was sent. + )} + { @@ -1560,7 +1561,7 @@ export async function rerunFrom(task: string, turn: number, text: string, images !(await confirm({ title: "Start a Fresh Agent Session", message: - "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.", + "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.", ok: "Start Fresh", icon: "warning", })) @@ -1568,7 +1569,7 @@ export async function rerunFrom(task: string, turn: number, text: string, images return false; try { await stopForEdit(task); - await call(commands.agentRollback(task, turn)); + await call(commands.agentRollback(task, turn, true)); await call(commands.agentPrompt(task, { text, files: [], images }, false)); } catch (e) { restoreComposer(task, text, images); @@ -1577,11 +1578,14 @@ export async function rerunFrom(task: string, turn: number, text: string, images return true; } -/** Drops `turn` and the later turns, and puts the message back in the composer to edit. */ -export async function retractFrom(task: string, turn: number, text: string, images: AgentImage[] = []): Promise { +/** + * Rolls back to before `turn`: drops it and the later turns, puts back the files they changed, + * and puts the message back in the composer to edit. + */ +export async function rollBackTo(task: string, turn: number, text: string, images: AgentImage[] = []): Promise { try { await stopForEdit(task); - const prompt = await call(commands.agentRollback(task, turn)); + const prompt = await call(commands.agentRollback(task, turn, true)); // The agent only hands back the text; the images come from the message itself. restoreComposer(task, prompt?.text ?? text, images); } catch (e) { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index af20fb412..11537aa7e 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1458,7 +1458,7 @@ "Couldn't rename the task": "Couldn't rename the task", "Start a Fresh Agent Session": "Start a Fresh Agent Session", "Start Fresh": "Start Fresh", - "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.", + "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.", "Copy Path From Source Root": "Copy Path From Source Root", "Copy Path From Repository Root": "Copy Path From Repository Root", "Escape text on paste in string literals": "Escape text on paste in string literals", @@ -1497,9 +1497,6 @@ "Ask": "Ask", "You": "You", "Jump to Latest": "Jump to Latest", - "Retract Message": "Retract Message", - "Retract": "Retract", - "Couldn't retract the message": "Couldn't retract the message", "The agent is still stopping. Try again once it has stopped.": "The agent is still stopping. Try again once it has stopped.", "Uninstall incomplete; retry Uninstall to finish cleanup.": "Uninstall incomplete; retry Uninstall to finish cleanup.", "refusing symlink in plugin cleanup path": "refusing symlink in plugin cleanup path", @@ -3963,5 +3960,10 @@ "Resize hover card from the right": "Resize hover card from the right", "Resize hover card from the bottom": "Resize hover card from the bottom", "Resize hover card from the left": "Resize hover card from the left", - "Resize hover card from the corner": "Resize hover card from the corner" + "Resize hover card from the corner": "Resize hover card from the corner", + "Roll Back to Here": "Roll Back to Here", + "Couldn't roll back": "Couldn't roll back", + "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.", + "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.": "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.", + "The files the agent changed since go back to how they were before this message was sent.": "The files the agent changed since go back to how they were before this message was sent." } diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 756cdd75c..46ffc8be5 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -4859,7 +4859,8 @@ "{provider} didn't start: {error}": "{provider} no se inició: {error}", "resets {resetsMs}": "se restablece en {resetsMs}", "Run Again From Here": "Volver a ejecutar desde aquí", - "The messages after this one are replaced. Files the agent changed stay as they are.": "Los mensajes posteriores a este se reemplazan. Los archivos que el agente modificó permanecen tal como están.", + "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.": "Los mensajes posteriores a este se reemplazan, y los archivos que el agente modificó desde entonces vuelven a como estaban antes de enviar este mensaje.", + "The files the agent changed since go back to how they were before this message was sent.": "Los archivos que el agente modificó desde entonces vuelven a como estaban antes de enviar este mensaje.", "Cancelling…": "Cancelando…", "Code insight needs the index; it can't be stopped": "El análisis de código necesita el índice; no se puede detener", "Waiting for other tasks": "Esperando otras tareas", @@ -6103,5 +6104,9 @@ "This version is signed with a different key than the installed one, and the publisher's earlier key doesn't vouch for it. Only continue if you know the publisher changed keys.": "Esta versión está firmada con una clave diferente a la instalada y la clave anterior del editor no la avala. Continúe solo si sabe que el editor cambió de clave.", "Select files in the Project view, Commit tool window, or open a file in the editor": "Seleccione archivos en la vista Proyecto, la ventana de Confirmación, o abra un archivo en el editor", "Agent Reference": "Referencia del agente", - "Copy Agent Reference": "Copiar referencia del agente" + "Copy Agent Reference": "Copiar referencia del agente", + "Roll Back to Here": "Revertir hasta aquí", + "Couldn't roll back": "No se pudo revertir", + "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Este mensaje y los posteriores se eliminan, y los archivos que el agente modificó desde entonces vuelven a como estaban antes de enviarlo. El mensaje vuelve al cuadro de texto.", + "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "Esto borra toda la conversación, devuelve los archivos que el agente modificó a como estaban al empezar la tarea e inicia una nueva sesión del agente con este mensaje." } diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index f98cd6fdb..a1053b084 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -4714,7 +4714,8 @@ "{provider} didn't start: {error}": "{provider} n'a pas démarré : {error}", "resets {resetsMs}": "réinitialisation {resetsMs}", "Run Again From Here": "Réexécuter à partir d'ici", - "The messages after this one are replaced. Files the agent changed stay as they are.": "Les messages suivants sont remplacés. Les fichiers modifiés par l'agent restent en l'état.", + "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.": "Les messages suivants sont remplacés, et les fichiers modifiés par l'agent depuis reviennent à leur état d'avant l'envoi de ce message.", + "The files the agent changed since go back to how they were before this message was sent.": "Les fichiers modifiés par l'agent depuis reviennent à leur état d'avant l'envoi de ce message.", "Cancelling…": "Annulation…", "Code insight needs the index; it can't be stopped": "L'analyse du code nécessite l'index ; il ne peut pas être arrêté", "Waiting for other tasks": "En attente d'autres tâches", @@ -5746,5 +5747,9 @@ "Replace preview": "Aperçu du remplacement", "Select files in the Project view, Commit tool window, or open a file in the editor": "Sélectionnez des fichiers dans la vue Projet, la fenêtre Commit, ou ouvrez un fichier dans l'éditeur", "Agent Reference": "Référence d'agent", - "Copy Agent Reference": "Copier la référence d'agent" + "Copy Agent Reference": "Copier la référence d'agent", + "Roll Back to Here": "Revenir à ce point", + "Couldn't roll back": "Impossible de revenir en arrière", + "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Ce message et les suivants sont supprimés, et les fichiers modifiés par l'agent depuis reviennent à leur état d'avant l'envoi. Le message revient dans la zone de saisie.", + "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "Cela efface toute la conversation, remet les fichiers modifiés par l'agent dans leur état du début de la tâche et démarre une nouvelle session de l'agent avec ce message." } diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 5657f0c68..99f2132f8 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -4932,7 +4932,8 @@ "{provider} didn't start: {error}": "{provider}이(가) 시작되지 않았습니다: {error}", "resets {resetsMs}": "{resetsMs}에 재설정", "Run Again From Here": "여기부터 다시 실행", - "The messages after this one are replaced. Files the agent changed stay as they are.": "이 메시지 이후의 메시지가 대체됩니다. 에이전트가 변경한 파일은 그대로 유지됩니다.", + "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.": "이 메시지 이후의 메시지가 대체되고, 그 이후 에이전트가 변경한 파일은 이 메시지를 보내기 전 상태로 돌아갑니다.", + "The files the agent changed since go back to how they were before this message was sent.": "그 이후 에이전트가 변경한 파일은 이 메시지를 보내기 전 상태로 돌아갑니다.", "Cancelling…": "취소 중…", "Code insight needs the index; it can't be stopped": "코드 인사이트에는 색인이 필요하므로 중지할 수 없습니다", "Waiting for other tasks": "다른 작업 대기 중", @@ -6213,5 +6214,9 @@ "Run as the image's user, not the project folder's owner (Linux)": "프로젝트 폴더 소유자가 아닌 이미지의 사용자로 실행(Linux)", "Select files in the Project view, Commit tool window, or open a file in the editor": "프로젝트 뷰나 커밋 도구 창에서 파일을 선택하거나 편집기에서 파일을 여세요", "Agent Reference": "에이전트 참조", - "Copy Agent Reference": "에이전트 참조 복사" + "Copy Agent Reference": "에이전트 참조 복사", + "Roll Back to Here": "여기로 롤백", + "Couldn't roll back": "롤백할 수 없습니다", + "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "이 메시지와 이후 메시지가 제거되고, 그 이후 에이전트가 변경한 파일은 메시지를 보내기 전 상태로 돌아갑니다. 메시지는 입력란으로 돌아갑니다.", + "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "전체 대화를 지우고, 에이전트가 변경한 파일을 작업 시작 시점의 상태로 되돌린 뒤, 이 메시지로 새 에이전트 세션을 시작합니다." } diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 24dae7ea0..2d1740a1f 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -4810,7 +4810,8 @@ "{provider} didn't start: {error}": "Dostawca {provider} nie uruchomił się: {error}", "resets {resetsMs}": "resetuje się za {resetsMs}", "Run Again From Here": "Uruchom ponownie od tego miejsca", - "The messages after this one are replaced. Files the agent changed stay as they are.": "Wiadomości po tej zostaną zastąpione. Pliki zmienione przez agenta pozostają bez zmian.", + "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.": "Wiadomości po tej zostaną zastąpione, a pliki zmienione od tego czasu przez agenta wrócą do stanu sprzed wysłania tej wiadomości.", + "The files the agent changed since go back to how they were before this message was sent.": "Pliki zmienione od tego czasu przez agenta wrócą do stanu sprzed wysłania tej wiadomości.", "Cancelling…": "Anulowanie…", "Code insight needs the index; it can't be stopped": "Analiza kodu wymaga indeksu; proces ten nie może zostać zatrzymany", "Waiting for other tasks": "Oczekiwanie na inne zadania", @@ -5911,5 +5912,9 @@ "Find by main class": "Znajdź według klasy głównej", "Select files in the Project view, Commit tool window, or open a file in the editor": "Wybierz pliki w widoku Projektu, oknie Commit lub otwórz plik w edytorze", "Agent Reference": "Odwołanie do agenta", - "Copy Agent Reference": "Kopiuj odwołanie do agenta" + "Copy Agent Reference": "Kopiuj odwołanie do agenta", + "Roll Back to Here": "Wycofaj do tego miejsca", + "Couldn't roll back": "Nie udało się wycofać", + "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Ta wiadomość i kolejne zostaną usunięte, a pliki zmienione od tego czasu przez agenta wrócą do stanu sprzed jej wysłania. Wiadomość wróci do pola tekstowego.", + "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "To wyczyści całą rozmowę, przywróci pliki zmienione przez agenta do stanu z początku zadania i rozpocznie nową sesję agenta z tą wiadomością." } diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 41d2a0374..20541cd27 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -4825,7 +4825,8 @@ "{provider} didn't start: {error}": "{provider} não iniciou: {error}", "resets {resetsMs}": "reinicia em {resetsMs}", "Run Again From Here": "Executar novamente a partir daqui", - "The messages after this one are replaced. Files the agent changed stay as they are.": "As mensagens após esta são substituídas. Os arquivos que o agente alterou permanecem como estão.", + "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.": "As mensagens após esta são substituídas, e os arquivos que o agente alterou desde então voltam a como estavam antes do envio desta mensagem.", + "The files the agent changed since go back to how they were before this message was sent.": "Os arquivos que o agente alterou desde então voltam a como estavam antes do envio desta mensagem.", "Cancelling…": "Cancelando…", "Code insight needs the index; it can't be stopped": "A análise de código precisa do índice; ela não pode ser interrompida", "Waiting for other tasks": "Aguardando outras tarefas", @@ -5926,5 +5927,9 @@ "Find by main class": "Localizar por classe principal", "Select files in the Project view, Commit tool window, or open a file in the editor": "Selecione arquivos na visualização do projeto, na janela Commit, ou abra um arquivo no editor", "Agent Reference": "Referência do agente", - "Copy Agent Reference": "Copiar referência do agente" + "Copy Agent Reference": "Copiar referência do agente", + "Roll Back to Here": "Reverter até aqui", + "Couldn't roll back": "Não foi possível reverter", + "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Esta mensagem e as seguintes são removidas, e os arquivos que o agente alterou desde então voltam a como estavam antes do envio. A mensagem volta para a caixa de texto.", + "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "Isso limpa toda a conversa, devolve os arquivos que o agente alterou a como estavam no início da tarefa e inicia uma nova sessão do agente com esta mensagem." } diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index be282c986..cd45d3aea 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -6381,7 +6381,8 @@ "{provider} didn't start: {error}": "Не удалось запустить {provider}: {error}", "resets {resetsMs}": "сброс {resetsMs}", "Run Again From Here": "Запустить снова с этого места", - "The messages after this one are replaced. Files the agent changed stay as they are.": "Сообщения после этого будут заменены. Файлы, изменённые агентом, останутся без изменений.", + "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.": "Сообщения после этого будут заменены, а файлы, изменённые агентом с тех пор, вернутся к состоянию до отправки этого сообщения.", + "The files the agent changed since go back to how they were before this message was sent.": "Файлы, изменённые агентом с тех пор, вернутся к состоянию до отправки этого сообщения.", "Cancelling…": "Отмена…", "Code insight needs the index; it can't be stopped": "Для анализа кода требуется индекс; его нельзя остановить", "Waiting for other tasks": "Ожидание других задач", @@ -7931,7 +7932,7 @@ "Couldn't rename the task": "Не удалось переименовать задачу", "Start a Fresh Agent Session": "Начать новую сессию агента", "Start Fresh": "Начать заново", - "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "Это очистит всю беседу и начнёт новую сессию агента с этого сообщения. Изменённые агентом файлы останутся без изменений.", + "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "Весь разговор будет очищен, файлы, изменённые агентом, вернутся к состоянию на начало задачи, и с этим сообщением начнётся новый сеанс агента.", "Path From Source Root": "Путь от корня исходного кода", "Path From Repository Root": "Путь от корня репозитория", "Agent Reference": "Ссылка для агента", @@ -7958,9 +7959,6 @@ "Insert imports on paste": "Добавлять импорты при вставке", "You": "Вы", "Jump to Latest": "Перейти к последнему", - "Retract Message": "Отозвать сообщение", - "Retract": "Отозвать", - "Couldn't retract the message": "Не удалось отозвать сообщение", "The agent is still stopping. Try again once it has stopped.": "Агент всё ещё останавливается. Повторите попытку после его остановки.", "Uninstall incomplete; retry Uninstall to finish cleanup.": "Удаление не завершено; повторите удаление, чтобы завершить очистку.", "refusing symlink in plugin cleanup path": "отклонена символическая ссылка в пути очистки плагина", @@ -10113,5 +10111,8 @@ "Mark as Unread": "Отметить как непрочитанное", "Archive All Below": "Архивировать всё ниже", "Mark Agent Tasks as Unread": "Отметить задачи агента как непрочитанные", - "Mark Agent Tasks as Read": "Отметить задачи агента как прочитанные" + "Mark Agent Tasks as Read": "Отметить задачи агента как прочитанные", + "Roll Back to Here": "Откатить до этого места", + "Couldn't roll back": "Не удалось откатить", + "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Это сообщение и все последующие будут удалены, а файлы, изменённые агентом с тех пор, вернутся к состоянию до его отправки. Сообщение вернётся в поле ввода." } diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 5c26b81e0..7fbe8b6bb 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -930,7 +930,7 @@ "Couldn't rename the task": "Görev yeniden adlandırılamadı", "Start a Fresh Agent Session": "Yeni Bir Ajan Oturumu Başlat", "Start Fresh": "Yeni Oturum Başlat", - "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "Bu işlem tüm konuşmayı temizler ve bu mesajla yeni bir ajan oturumu başlatır. Ajanın değiştirdiği dosyalar olduğu gibi kalır.", + "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "Bu, tüm konuşmayı temizler, ajanın değiştirdiği dosyaları görevin başladığı andaki hâline döndürür ve bu mesajla yeni bir ajan oturumu başlatır.", "Copy Path From Source Root": "Kaynak Kökünden Yolu Kopyala", "Copy Path From Repository Root": "Depo Kökünden Yolu Kopyala", "Escape text on paste in string literals": "Dize sabitlerine yapıştırırken metindeki özel karakterleri kaçır", @@ -967,9 +967,6 @@ "Ask": "Sor", "You": "Siz", "Jump to Latest": "En Sona Git", - "Retract Message": "Mesajı Geri Çek", - "Retract": "Geri Çek", - "Couldn't retract the message": "Mesaj geri çekilemedi", "The agent is still stopping. Try again once it has stopped.": "Ajan hâlâ durduruluyor. Tamamen durduktan sonra yeniden deneyin.", "Uninstall incomplete; retry Uninstall to finish cleanup.": "Kaldırma işlemi tamamlanmadı; temizliği bitirmek için Kaldır'ı yeniden deneyin.", "refusing symlink in plugin cleanup path": "eklenti temizleme yolundaki sembolik bağlantı reddedildi", @@ -7537,7 +7534,8 @@ "{provider} didn't start: {error}": "{provider} başlatılamadı: {error}", "resets {resetsMs}": "{resetsMs} sonra sıfırlanır", "Run Again From Here": "Buradan Yeniden Çalıştır", - "The messages after this one are replaced. Files the agent changed stay as they are.": "Bu mesajdan sonraki mesajlar değiştirilir. Ajanın değiştirdiği dosyalar olduğu gibi kalır.", + "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.": "Bu mesajdan sonraki mesajlar değiştirilir; ajanın o zamandan beri değiştirdiği dosyalar bu mesaj gönderilmeden önceki hâline döner.", + "The files the agent changed since go back to how they were before this message was sent.": "Ajanın o zamandan beri değiştirdiği dosyalar bu mesaj gönderilmeden önceki hâline döner.", "Cancelling…": "İptal ediliyor…", "Code insight needs the index; it can't be stopped": "Kod desteği dizine ihtiyaç duyuyor; durdurulamaz", "Waiting for other tasks": "Diğer görevler bekleniyor", @@ -8766,5 +8764,8 @@ "Plugin update available": "Eklenti güncellemesi mevcut", "{length} plugin updates available": "{length} eklenti güncellemesi mevcut", "Updated {updated} plugins": "{updated} eklenti güncellendi", - "This version is signed with a different key than the installed one, and the publisher's earlier key doesn't vouch for it. Only continue if you know the publisher changed keys.": "Bu sürüm, yüklü olandan farklı bir anahtarla imzalanmış ve yayıncının önceki anahtarı bunu doğrulamıyor. Yalnızca yayıncının anahtar değiştirdiğinden eminseniz devam edin." + "This version is signed with a different key than the installed one, and the publisher's earlier key doesn't vouch for it. Only continue if you know the publisher changed keys.": "Bu sürüm, yüklü olandan farklı bir anahtarla imzalanmış ve yayıncının önceki anahtarı bunu doğrulamıyor. Yalnızca yayıncının anahtar değiştirdiğinden eminseniz devam edin.", + "Roll Back to Here": "Buraya Geri Al", + "Couldn't roll back": "Geri alınamadı", + "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Bu mesaj ve sonrakiler kaldırılır; ajanın o zamandan beri değiştirdiği dosyalar mesaj gönderilmeden önceki hâline döner. Mesaj yazma alanına geri konur." } diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index f2493fce2..ef0b93e3d 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -5863,7 +5863,8 @@ "{provider} didn't start: {error}": "{provider} 未能啟動:{error}", "resets {resetsMs}": "{resetsMs} 重設", "Run Again From Here": "從此處重新執行", - "The messages after this one are replaced. Files the agent changed stay as they are.": "這條之後的訊息會被取代。Agent 改動過的檔案保持不變。", + "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.": "這條之後的訊息會被取代,Agent 在此之後改動的檔案會恢復到這條訊息傳送前的狀態。", + "The files the agent changed since go back to how they were before this message was sent.": "Agent 在此之後改動的檔案會恢復到這條訊息傳送前的狀態。", "Cancelling…": "正在取消…", "Code insight needs the index; it can't be stopped": "程式碼洞察依賴索引,無法停止", "Waiting for other tasks": "正在等待其他任務", @@ -7402,7 +7403,7 @@ "Couldn't rename the task": "無法重新命名任務", "Start a Fresh Agent Session": "啟動全新的代理工作階段", "Start Fresh": "重新開始", - "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "這會清空整個對話,並使用此訊息啟動全新的代理對話。代理已修改的檔案保持不變。", + "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "這會清空整個對話,把 Agent 改動過的檔案恢復到任務開始時的狀態,並用這條訊息開始一個新的 Agent 工作階段。", "Path From Source Root": "相對於源根的路徑", "Path From Repository Root": "相對於存放庫根的路徑", "Agent Reference": "智能體引用", @@ -7429,9 +7430,6 @@ "Insert imports on paste": "貼上時插入匯入", "You": "你", "Jump to Latest": "跳轉到最新位置", - "Retract Message": "撤回訊息", - "Retract": "撤回", - "Couldn't retract the message": "無法撤回訊息", "The agent is still stopping. Try again once it has stopped.": "代理仍在停止中。請在停止後重試。", "Uninstall incomplete; retry Uninstall to finish cleanup.": "解除安裝未完成;請重試解除安裝以完成清理。", "refusing symlink in plugin cleanup path": "拒絕清理路徑中包含符號連結的外掛", @@ -9277,5 +9275,8 @@ "Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project.": "Gradle 無法同步 {project}。建置同步成功前,Java 程式碼分析可能無法正常運作。請修正建置,然後重新載入 Gradle 專案。", "Fill Paragraph": "填充段落", "Convert Indents to Spaces": "將縮排轉換為空格", - "Convert Indents to Tabs": "將縮排轉換為定位字元" + "Convert Indents to Tabs": "將縮排轉換為定位字元", + "Roll Back to Here": "回滾到這裡", + "Couldn't roll back": "無法回滾", + "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "這條訊息及之後的訊息會被移除,Agent 在此之後改動的檔案會恢復到這條訊息傳送前的狀態。訊息會放回輸入框。" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index fa9b5f0ab..c31aa95ee 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -6437,7 +6437,8 @@ "{provider} didn't start: {error}": "{provider} 未能启动:{error}", "resets {resetsMs}": "{resetsMs} 重置", "Run Again From Here": "从此处重新运行", - "The messages after this one are replaced. Files the agent changed stay as they are.": "这条之后的消息会被替换。Agent 改动过的文件保持不变。", + "The messages after this one are replaced, and the files the agent changed since go back to how they were before this message was sent.": "这条之后的消息会被替换,Agent 在此之后改动的文件会恢复到这条消息发送前的状态。", + "The files the agent changed since go back to how they were before this message was sent.": "Agent 在此之后改动的文件会恢复到这条消息发送前的状态。", "Cancelling…": "正在取消…", "Code insight needs the index; it can't be stopped": "代码洞察依赖索引,无法停止", "Waiting for other tasks": "正在等待其他任务", @@ -7999,7 +8000,7 @@ "Couldn't rename the task": "无法重命名任务", "Start a Fresh Agent Session": "启动全新的智能体会话", "Start Fresh": "重新开始", - "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "这会清空整个对话,并使用此消息启动全新的智能体会话。智能体已修改的文件保持不变。", + "This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "这会清空整个对话,把 Agent 改动过的文件恢复到任务开始时的状态,并用这条消息开始一个新的 Agent 会话。", "Path From Source Root": "相对于源根的路径", "Path From Repository Root": "相对于仓库根的路径", "Agent Reference": "智能体引用", @@ -8026,9 +8027,6 @@ "Insert imports on paste": "粘贴时插入导入", "You": "你", "Jump to Latest": "跳转到最新位置", - "Retract Message": "撤回消息", - "Retract": "撤回", - "Couldn't retract the message": "无法撤回消息", "The agent is still stopping. Try again once it has stopped.": "智能体仍在停止中。请在停止后重试。", "Uninstall incomplete; retry Uninstall to finish cleanup.": "卸载未完成;请重试卸载以完成清理。", "refusing symlink in plugin cleanup path": "拒绝清理路径中包含符号链接的插件", @@ -10248,5 +10246,8 @@ "Find where this component is imported and used": "查找此组件被导入和使用的位置", "Gradle project sync failed": "Gradle 项目同步失败", "Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project. Cause: {cause}": "Gradle 无法同步 {project}。构建同步成功前,Java 代码分析可能无法正常工作。请修复构建,然后重新加载 Gradle 项目。原因:{cause}", - "Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project.": "Gradle 无法同步 {project}。构建同步成功前,Java 代码分析可能无法正常工作。请修复构建,然后重新加载 Gradle 项目。" + "Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project.": "Gradle 无法同步 {project}。构建同步成功前,Java 代码分析可能无法正常工作。请修复构建,然后重新加载 Gradle 项目。", + "Roll Back to Here": "回滚到这里", + "Couldn't roll back": "无法回滚", + "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "这条消息及之后的消息会被移除,Agent 在此之后改动的文件会恢复到这条消息发送前的状态。消息会放回输入框。" }