Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: a turn's changes include edits made around a compaction

ogsamratb195cba3abba
diff --git a/apps/app/src/react-app/domains/session/commands/changes-panel.tsx b/apps/app/src/react-app/domains/session/commands/changes-panel.tsx
index a6755945..b65ebdea 100644
--- a/apps/app/src/react-app/domains/session/commands/changes-panel.tsx
+++ b/apps/app/src/react-app/domains/session/commands/changes-panel.tsx
@@ -13,6 +13,7 @@ import {
CHANGES_EMPTY,
CHANGES_SOURCE_LABEL,
changeTotals,
+ mergeTurnChanges,
normalizeChanges,
MAX_DIFF_LINES,
patchLineCount,
@@ -24,6 +25,7 @@ import {
} from "./changes";
import { useSessionCommandBridge, useSessionCommandsStore } from "./session-commands-store";
import { latestUserMessageId, useCachedQueryData, useOpencodeClient, type SessionCommandTarget } from "./use-session-commands";
+import { turnUserMessageIds } from "./turn-messages";
const SOURCES: ChangesSource[] = ["chat", "turn", "tree"];
@@ -201,16 +203,24 @@ function ChangesBody(props: SessionCommandTarget & {
const lastUserId = props.turnId ?? latestUserMessageId(snapshot?.session.id === props.sessionId ? snapshot : null);
const revertId = snapshot?.session.revert?.messageID ?? null;
const running = (status?.type ?? "idle") !== "idle";
+ // The whole turn: the person's prompt and the user messages a compaction added in it (turn-messages.ts).
+ const turnIds = useMemo(() => {
+ if (!lastUserId) return [];
+ const ids = turnUserMessageIds(snapshot?.session.id === props.sessionId ? snapshot.messages : [], lastUserId);
+ return ids.length ? ids : [lastUserId];
+ }, [snapshot, props.sessionId, lastUserId]);
const query = useQuery({
- queryKey: ["session-commands-changes", props.workspaceId, props.sessionId, source, source === "turn" ? lastUserId : null, revertId],
+ queryKey: ["session-commands-changes", props.workspaceId, props.sessionId, source, source === "turn" ? turnIds.join(",") : null, revertId],
queryFn: async () => {
if (source === "tree") {
return normalizeChanges(unwrap(await client.vcs.diff({ mode: "git", directory: props.workspaceRoot || undefined })));
}
if (source === "turn") {
if (!lastUserId) return [];
- return normalizeChanges(unwrap(await client.session.diff({ sessionID: props.sessionId, messageID: lastUserId })));
+ const parts = await Promise.all(turnIds.map(async (messageID) =>
+ normalizeChanges(unwrap(await client.session.diff({ sessionID: props.sessionId, messageID })))));
+ return mergeTurnChanges(parts);
}
return normalizeChanges(unwrap(await client.session.diff({ sessionID: props.sessionId })));
},
diff --git a/apps/app/src/react-app/domains/session/commands/changes.ts b/apps/app/src/react-app/domains/session/commands/changes.ts
index 5eded0d5..ebdb23f4 100644
--- a/apps/app/src/react-app/domains/session/commands/changes.ts
+++ b/apps/app/src/react-app/domains/session/commands/changes.ts
@@ -38,7 +38,7 @@ export function changeTotals(files: readonly ChangedFile[]) {
export const CHANGES_EMPTY: Record<ChangesSource, string> = {
chat: "This chat has not changed any files yet.",
- turn: "The last turn changed no files.",
+ turn: "No files changed in this turn.",
tree: "No changes.",
};
@@ -126,3 +126,23 @@ export function splitRows(lines: readonly PatchLine[]): SplitRow[] {
flush();
return rows;
}
+
+/**
+ * One turn's changes from the engine's per-message diffs (a turn split by a compaction has one list per user
+ * message, oldest first): a file changed in several parts keeps every part's hunks in order and the summed counts.
+ */
+export function mergeTurnChanges(lists: readonly ChangedFile[][]): ChangedFile[] {
+ const byPath = new Map<string, ChangedFile>();
+ for (const list of lists) {
+ for (const file of list) {
+ const seen = byPath.get(file.path);
+ if (!seen) { byPath.set(file.path, { ...file }); continue; }
+ seen.additions += file.additions;
+ seen.deletions += file.deletions;
+ seen.patch = [seen.patch, file.patch].filter((patch) => patch.trim()).join("\n");
+ // Added earlier in the turn stays added; deleted at the end is deleted.
+ seen.status = seen.status === "added" ? (file.status === "deleted" ? "modified" : "added") : file.status === "deleted" ? "deleted" : "modified";
+ }
+ }
+ return [...byPath.values()].sort((a, b) => a.path.localeCompare(b.path));
+}
diff --git a/apps/app/src/react-app/domains/session/commands/turn-messages.ts b/apps/app/src/react-app/domains/session/commands/turn-messages.ts
index 7f0bd60e..5f971c25 100644
--- a/apps/app/src/react-app/domains/session/commands/turn-messages.ts
+++ b/apps/app/src/react-app/domains/session/commands/turn-messages.ts
@@ -48,3 +48,22 @@ export function personUserMessages<T extends MessageLike>(messages: readonly T[]
return !text || text !== promptText(earlier);
});
}
+
+/**
+ * The ids of the user messages that make up the turn `anchorId` belongs to, oldest first: the person's prompt that
+ * started it, then the compaction requests, automatic continues and replays the engine added before the next
+ * person's prompt. Each keeps its own part of the turn's file changes (the engine diffs per user message).
+ * Empty when the anchor is not a user message of `messages`.
+ */
+export function turnUserMessageIds<T extends MessageLike & { info: unknown }>(messages: readonly T[], anchorId: string): string[] {
+ const idOf = (message: T) => (message.info as { id?: unknown } | null)?.id;
+ const users = messages.filter((message) => isUser(message));
+ const at = users.findIndex((message) => idOf(message) === anchorId);
+ if (at < 0) return [];
+ const starts = new Set(personUserMessages(users));
+ let start = at;
+ while (start > 0 && !starts.has(users[start] as T)) start -= 1;
+ let end = at + 1;
+ while (end < users.length && !starts.has(users[end] as T)) end += 1;
+ return users.slice(start, end).map((message) => String(idOf(message)));
+}
diff --git a/apps/app/tests/turn-changes.test.ts b/apps/app/tests/turn-changes.test.ts
new file mode 100644
index 00000000..3561a1ae
--- /dev/null
+++ b/apps/app/tests/turn-changes.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, test } from "bun:test";
+
+import { mergeTurnChanges, type ChangedFile } from "../src/react-app/domains/session/commands/changes";
+import { turnUserMessageIds } from "../src/react-app/domains/session/commands/turn-messages";
+
+const user = (id: string, parts: unknown[]) => ({ info: { id, role: "user" }, parts });
+const assistant = (id: string) => ({ info: { id, role: "assistant" }, parts: [] });
+const prompt = (id: string, text: string) => user(id, [{ type: "text", text }]);
+const compaction = (id: string) => user(id, [{ type: "compaction" }]);
+const resume = (id: string) => user(id, [{ type: "text", text: "Continue", synthetic: true, metadata: { compaction_continue: true } }]);
+
+// Turn A: edits, a mid-turn compaction, more edits. Turn B after it.
+const chat = [
+ prompt("u1", "fix the parser"), assistant("a1"),
+ compaction("u2"), assistant("a2"),
+ resume("u3"), assistant("a3"),
+ prompt("u4", "now the tests"), assistant("a4"),
+];
+
+describe("turnUserMessageIds", () => {
+ test("a turn split by a compaction covers its prompt, the compaction and the continue, not the next turn", () => {
+ expect(turnUserMessageIds(chat, "u1")).toEqual(["u1", "u2", "u3"]);
+ // Opened from the reply after the continue: the same turn.
+ expect(turnUserMessageIds(chat, "u3")).toEqual(["u1", "u2", "u3"]);
+ expect(turnUserMessageIds(chat, "u4")).toEqual(["u4"]);
+ });
+
+ test("a prompt the engine replayed after a compaction belongs to the turn it repeats", () => {
+ const replayed = [prompt("p1", "build it"), assistant("x1"), compaction("c1"), assistant("x2"), prompt("p2", "build it"), assistant("x3"), prompt("p3", "next")];
+ expect(turnUserMessageIds(replayed, "p2")).toEqual(["p1", "c1", "p2"]);
+ expect(turnUserMessageIds(replayed, "p3")).toEqual(["p3"]);
+ });
+
+ test("an unknown anchor gives nothing", () => {
+ expect(turnUserMessageIds(chat, "a1")).toEqual([]);
+ expect(turnUserMessageIds(chat, "nope")).toEqual([]);
+ });
+});
+
+describe("mergeTurnChanges", () => {
+ const file = (path: string, patch: string, additions: number, deletions: number, status: ChangedFile["status"] = "modified"): ChangedFile => ({ path, patch, additions, deletions, status });
+
+ test("edits before and after the compaction both show, each file once", () => {
+ const before = [file("src/parser.ts", "@@ -1 +1 @@\n-a\n+b", 1, 1), file("src/new.ts", "@@ -0,0 +1 @@\n+x", 1, 0, "added")];
+ const after = [file("src/parser.ts", "@@ -5 +5 @@\n-c\n+d", 1, 1), file("README.md", "@@ -1 +1 @@\n-r\n+R", 1, 1)];
+ const merged = mergeTurnChanges([before, [], after]);
+ expect(merged.map((f) => f.path)).toEqual(["README.md", "src/new.ts", "src/parser.ts"]);
+ const parser = merged.find((f) => f.path === "src/parser.ts");
+ expect(parser?.patch).toBe("@@ -1 +1 @@\n-a\n+b\n@@ -5 +5 @@\n-c\n+d");
+ expect([parser?.additions, parser?.deletions]).toEqual([2, 2]);
+ expect(merged.find((f) => f.path === "src/new.ts")?.status).toBe("added");
+ });
+
+ test("added then deleted in one turn reads as modified; deleted last is deleted", () => {
+ expect(mergeTurnChanges([[file("a", "p1", 1, 0, "added")], [file("a", "p2", 0, 1, "deleted")]])[0]?.status).toBe("modified");
+ expect(mergeTurnChanges([[file("b", "p1", 1, 1)], [file("b", "p2", 0, 3, "deleted")]])[0]?.status).toBe("deleted");
+ });
+});