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
- {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.",
+ )}
- 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} 个文件的更改复制到本地检出?",