Skip to content

Commit 3c2945e

Browse files
Ziyad Aklclaude
authored andcommitted
fix(web): gate file-restore on the undone span + normalize agent paths
Gate computeRevertTurnCountByUserMessageId on the union of the span's agent edit sets (ADR-0004 decision 4), not a single turn; normalize web agent paths to repo-relative and match the checkpoint diff by equality instead of a suffix heuristic. Review findings: spec gating, quality #4/#5. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 92d960a commit 3c2945e

3 files changed

Lines changed: 163 additions & 36 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1867,8 +1867,12 @@ export default function ChatView(props: ChatViewProps) {
18671867
return byMessageId;
18681868
}, [turnDiffSummaries]);
18691869
const agentEditSetByTurnIdMap = useMemo(
1870-
() => agentEditSetByTurnId(activeThread?.activities ?? []),
1871-
[activeThread?.activities],
1870+
() =>
1871+
agentEditSetByTurnId(
1872+
activeThread?.activities ?? [],
1873+
activeThread?.worktreePath ?? activeProject?.cwd ?? null,
1874+
),
1875+
[activeThread?.activities, activeThread?.worktreePath, activeProject?.cwd],
18721876
);
18731877
const revertTurnCountByUserMessageId = useMemo(
18741878
() =>

‎apps/web/src/session-logic.test.ts‎

Lines changed: 82 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
computeRevertTurnCountByUserMessageId,
2525
agentEditSetByTurnId,
2626
pathIsInAgentEditSet,
27+
toRepoRelativePath,
2728
type TimelineEntry,
2829
} from "./session-logic";
2930
import { type TurnDiffSummary } from "./types";
@@ -1656,30 +1657,59 @@ describe("agentEditSetByTurnId", () => {
16561657
});
16571658
});
16581659

1660+
describe("toRepoRelativePath", () => {
1661+
it("strips the root prefix from an absolute path under the repo root", () => {
1662+
expect(toRepoRelativePath("/repo/src/foo.ts", "/repo")).toBe("src/foo.ts");
1663+
});
1664+
1665+
it("strips trailing slash from root before matching", () => {
1666+
expect(toRepoRelativePath("/repo/src/foo.ts", "/repo/")).toBe("src/foo.ts");
1667+
});
1668+
1669+
it("leaves an already-relative path unchanged", () => {
1670+
expect(toRepoRelativePath("src/bar.ts", "/repo")).toBe("src/bar.ts");
1671+
});
1672+
1673+
it("leaves a path that is absolute but outside the root unchanged", () => {
1674+
expect(toRepoRelativePath("/other/src/foo.ts", "/repo")).toBe("/other/src/foo.ts");
1675+
});
1676+
1677+
it("strips a leading ./ before processing", () => {
1678+
expect(toRepoRelativePath("./src/foo.ts", "/repo")).toBe("src/foo.ts");
1679+
});
1680+
1681+
it("returns the path unchanged when root is null", () => {
1682+
expect(toRepoRelativePath("src/foo.ts", null)).toBe("src/foo.ts");
1683+
});
1684+
1685+
it("returns the path unchanged when root is undefined", () => {
1686+
expect(toRepoRelativePath("/repo/src/foo.ts", undefined)).toBe("/repo/src/foo.ts");
1687+
});
1688+
});
1689+
16591690
describe("pathIsInAgentEditSet", () => {
1660-
it("matches when absolute agent path ends with /diffPath", () => {
1661-
expect(pathIsInAgentEditSet("src/foo.ts", ["/abs/repo/src/foo.ts"])).toBe(true);
1691+
// Agent paths are now pre-normalized to repo-relative by agentEditSetByTurnId.
1692+
// pathIsInAgentEditSet uses exact equality after stripping a leading ./ from diffPath.
1693+
1694+
it("matches when both are repo-relative and equal", () => {
1695+
expect(pathIsInAgentEditSet("src/foo.ts", ["src/foo.ts"])).toBe(true);
16621696
});
16631697

16641698
it("matches when agent path equals diffPath exactly (relative-to-relative)", () => {
16651699
expect(pathIsInAgentEditSet("src/bar.ts", ["src/bar.ts"])).toBe(true);
16661700
});
16671701

1668-
it("strips a leading ./ from diffPath before matching", () => {
1669-
expect(pathIsInAgentEditSet("./src/foo.ts", ["/abs/repo/src/foo.ts"])).toBe(true);
1702+
it("strips a leading ./ from diffPath before exact matching", () => {
1703+
expect(pathIsInAgentEditSet("./src/foo.ts", ["src/foo.ts"])).toBe(true);
16701704
});
16711705

1672-
it("requires a / boundary — bare suffix without separator does NOT match", () => {
1673-
// diff path "foo.ts" should not match agent "/repo/src/foo.ts" only via trailing substring
1674-
// because the boundary check uses endsWith("/" + diffPath), so "foo.ts" hits the boundary
1675-
// correctly; but "oo.ts" must NOT match "foo.ts"
1676-
expect(pathIsInAgentEditSet("oo.ts", ["/abs/repo/src/foo.ts"])).toBe(false);
1706+
it("does NOT match a bare suffix without full path equality", () => {
1707+
// agent paths are repo-relative; "oo.ts" should not match "src/foo.ts"
1708+
expect(pathIsInAgentEditSet("oo.ts", ["src/foo.ts"])).toBe(false);
16771709
});
16781710

16791711
it("returns false when diffPath is not in agentPaths", () => {
1680-
expect(pathIsInAgentEditSet("src/other.ts", ["/abs/repo/src/foo.ts", "src/bar.ts"])).toBe(
1681-
false,
1682-
);
1712+
expect(pathIsInAgentEditSet("src/other.ts", ["src/foo.ts", "src/bar.ts"])).toBe(false);
16831713
});
16841714

16851715
it("returns false for an empty agent set", () => {
@@ -1731,8 +1761,47 @@ describe("computeRevertTurnCountByUserMessageId — agent edit set gate", () =>
17311761
[MessageId.make("a1"), summary("turn-1", [{ path: "src/x.ts" }], 3)],
17321762
]),
17331763
inferredCheckpointTurnCountByTurnId: {},
1734-
agentEditSetByTurnId: new Map([[TurnId.make("turn-1"), ["/repo/src/x.ts"]]]),
1764+
agentEditSetByTurnId: new Map([[TurnId.make("turn-1"), ["src/x.ts"]]]),
17351765
});
17361766
expect(result.get(MessageId.make("u1"))).toBe(2);
17371767
});
1768+
1769+
it("per-span: shows affordance when matched turn is empty but a later turn in span has edits", () => {
1770+
// turn-1 (checkpointTurnCount 1) → matched turn for u1, restoreTarget = 0
1771+
// turn-2 (checkpointTurnCount 2) → in the span (> restoreTarget 0), non-empty agent edit set
1772+
// The affordance should be offered because the SPAN has agent edits.
1773+
// Current single-turn code gates on turn-1's empty set → does NOT offer → this test is RED.
1774+
const result = computeRevertTurnCountByUserMessageId({
1775+
timelineEntries: [messageEntry("u1", "user"), messageEntry("a1", "assistant")],
1776+
turnDiffSummaryByAssistantMessageId: new Map([
1777+
[MessageId.make("a1"), summary("turn-1", [{ path: "src/x.ts" }], 1)],
1778+
// turn-2 exists in the summary map even though it's not in the timeline (it could be
1779+
// from a prior segment); the gate must scan ALL summaries to build the span union.
1780+
[MessageId.make("a2"), summary("turn-2", [{ path: "src/y.ts" }], 2)],
1781+
]),
1782+
inferredCheckpointTurnCountByTurnId: {},
1783+
agentEditSetByTurnId: new Map([
1784+
[TurnId.make("turn-1"), []], // matched turn — empty
1785+
[TurnId.make("turn-2"), ["src/y.ts"]], // in span (checkpointTurnCount 2 > restoreTarget 0) — non-empty
1786+
]),
1787+
});
1788+
expect(result.has(MessageId.make("u1"))).toBe(true);
1789+
expect(result.get(MessageId.make("u1"))).toBe(0); // Math.max(0, 1 - 1)
1790+
});
1791+
1792+
it("per-span: hides affordance when all turns in span have empty agent edit sets", () => {
1793+
const result = computeRevertTurnCountByUserMessageId({
1794+
timelineEntries: [messageEntry("u1", "user"), messageEntry("a1", "assistant")],
1795+
turnDiffSummaryByAssistantMessageId: new Map([
1796+
[MessageId.make("a1"), summary("turn-1", [{ path: "src/x.ts" }], 1)],
1797+
[MessageId.make("a2"), summary("turn-2", [{ path: "src/y.ts" }], 2)],
1798+
]),
1799+
inferredCheckpointTurnCountByTurnId: {},
1800+
agentEditSetByTurnId: new Map([
1801+
[TurnId.make("turn-1"), []], // empty
1802+
[TurnId.make("turn-2"), []], // also empty
1803+
]),
1804+
});
1805+
expect(result.has(MessageId.make("u1"))).toBe(false);
1806+
});
17381807
});

‎apps/web/src/session-logic.ts‎

Lines changed: 75 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1228,16 +1228,39 @@ export function inferCheckpointTurnCountByTurnId(
12281228
return result;
12291229
}
12301230

1231+
/**
1232+
* Strips an absolute path down to repo-relative by removing the repo root
1233+
* prefix. If the path is already relative (does not start with "/"), or the
1234+
* root is unknown, the path is returned as-is (after stripping a leading "./").
1235+
*
1236+
* No `node:path` dependency — intentionally pure string ops so it is safe in
1237+
* both Node and browser contexts.
1238+
*/
1239+
export function toRepoRelativePath(
1240+
p: string,
1241+
root: string | null | undefined,
1242+
): string {
1243+
const stripped = p.startsWith("./") ? p.slice(2) : p;
1244+
if (!root || !stripped.startsWith("/")) return stripped;
1245+
const base = root.endsWith("/") ? root : root + "/";
1246+
return stripped.startsWith(base) ? stripped.slice(base.length) : stripped;
1247+
}
1248+
12311249
/**
12321250
* Groups activities by `turnId` and, per turn, returns the agent edit set
12331251
* (the files the agent itself edited via file_change tool activities).
12341252
* Activities with `turnId === null` are skipped.
12351253
*
1254+
* When `root` (the repo/worktree root) is provided, absolute paths emitted by
1255+
* Claude are normalized to repo-relative so they match the repo-relative paths
1256+
* in checkpoint diffs. See ADR-0004.
1257+
*
12361258
* This is the single source of truth for "what the agent edited per turn" on
12371259
* the web side. See ADR-0004.
12381260
*/
12391261
export function agentEditSetByTurnId(
12401262
activities: ReadonlyArray<OrchestrationThreadActivity>,
1263+
root?: string | null,
12411264
): Map<TurnId, ReadonlyArray<string>> {
12421265
const byTurn = new Map<TurnId, OrchestrationThreadActivity[]>();
12431266
for (const activity of activities) {
@@ -1251,43 +1274,65 @@ export function agentEditSetByTurnId(
12511274
}
12521275
const result = new Map<TurnId, ReadonlyArray<string>>();
12531276
for (const [turnId, turnActivities] of byTurn) {
1254-
result.set(turnId, agentEditSet(turnActivities));
1277+
const rawPaths = agentEditSet(turnActivities);
1278+
result.set(
1279+
turnId,
1280+
root ? rawPaths.map((p) => toRepoRelativePath(p, root)) : rawPaths,
1281+
);
12551282
}
12561283
return result;
12571284
}
12581285

12591286
/**
12601287
* Returns true when `diffPath` (a repo-relative or `./`-prefixed path from the
1261-
* checkpoint diff) is attributable to the agent, i.e. some path in `agentPaths`
1262-
* equals `diffPath` exactly, or ends with `"/" + diffPath` (so that Claude's
1263-
* absolute `/abs/repo/src/foo.ts` matches the diff's `src/foo.ts`).
1288+
* checkpoint diff) matches an entry in `agentPaths` exactly (after stripping a
1289+
* leading `./` from `diffPath`).
12641290
*
1265-
* A leading `./` is stripped from `diffPath` before matching.
1291+
* Agent paths are expected to be pre-normalized to repo-relative by
1292+
* `agentEditSetByTurnId` (see `toRepoRelativePath`), so a simple exact-equality
1293+
* check is sufficient and avoids the fragile `endsWith` suffix heuristic.
12661294
*
1267-
* NOTE: The boundary check uses `endsWith("/" + diffPath)`, which requires a
1268-
* directory separator. A bare filename like `"foo.ts"` will NOT match an agent
1269-
* path like `"/repo/src/barfoo.ts"` — the `/` in `"/foo.ts"` is the guard.
1270-
* It WILL match `"/repo/src/foo.ts"` correctly. This is the intended behaviour.
1295+
* A leading `./` is stripped from `diffPath` before matching.
12711296
*/
12721297
export function pathIsInAgentEditSet(
12731298
diffPath: string,
12741299
agentPaths: ReadonlyArray<string>,
12751300
): boolean {
12761301
// Strip a leading "./" that some tools emit.
12771302
const normalized = diffPath.startsWith("./") ? diffPath.slice(2) : diffPath;
1278-
for (const h of agentPaths) {
1279-
if (h === normalized || h.endsWith("/" + normalized)) return true;
1280-
}
1281-
return false;
1303+
return agentPaths.some((h) => h === normalized);
12821304
}
12831305

12841306
// Maps each user prompt to the number of turns its rewind would restore, BUT only
1285-
// when the rewound turn had agent-edited files — so the "also restore files" rewind
1286-
// affordance (inline banner, ESC-ESC picker, per-row action) is offered only when
1287-
// the agent actually edited something the restore would revert. A checkpoint where
1288-
// the agent made no file changes (empty agent edit set for that turn) is treated as
1289-
// a no-op restore and the affordance is hidden. See ADR-0004.
1307+
// when the span of turns being undone contains agent-edited files — so the "also
1308+
// restore files" rewind affordance (inline banner, ESC-ESC picker, per-row action)
1309+
// is offered only when the agent actually edited something the restore would revert.
1310+
// A checkpoint span where the agent made no file changes (all agent edit sets in the
1311+
// span are empty) is treated as a no-op restore and the affordance is hidden.
1312+
// See ADR-0004 (decision 4: gate is per-SPAN, not per single turn).
12901313
// Presence in the returned map == "a file-restore is offerable for this prompt".
1314+
1315+
/**
1316+
* Returns true when ANY turn whose effective checkpointTurnCount is strictly
1317+
* greater than `restoreTarget` has a non-empty agent edit set. This is the
1318+
* span-union check used by `computeRevertTurnCountByUserMessageId`.
1319+
*/
1320+
function spanHasAgentEdits(
1321+
restoreTarget: number,
1322+
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>,
1323+
inferredCheckpointTurnCountByTurnId: Record<TurnId, number>,
1324+
agentEditSetMap: ReadonlyMap<TurnId, ReadonlyArray<string>>,
1325+
): boolean {
1326+
for (const s of turnDiffSummaryByAssistantMessageId.values()) {
1327+
const tc = s.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[s.turnId];
1328+
if (typeof tc !== "number") continue;
1329+
if (tc > restoreTarget) {
1330+
if ((agentEditSetMap.get(s.turnId)?.length ?? 0) > 0) return true;
1331+
}
1332+
}
1333+
return false;
1334+
}
1335+
12911336
export function computeRevertTurnCountByUserMessageId(input: {
12921337
timelineEntries: ReadonlyArray<TimelineEntry>;
12931338
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
@@ -1324,9 +1369,18 @@ export function computeRevertTurnCountByUserMessageId(input: {
13241369
if (typeof turnCount !== "number") {
13251370
break;
13261371
}
1327-
// Only offer a file restore when the agent itself edited files in this turn.
1328-
if ((agentEditSetMap.get(summary.turnId)?.length ?? 0) > 0) {
1329-
byUserMessageId.set(entry.message.id, Math.max(0, turnCount - 1));
1372+
const restoreTarget = Math.max(0, turnCount - 1);
1373+
// Only offer a file restore when the span of turns being undone (all turns
1374+
// with checkpointTurnCount > restoreTarget) contains agent-edited files.
1375+
if (
1376+
spanHasAgentEdits(
1377+
restoreTarget,
1378+
turnDiffSummaryByAssistantMessageId,
1379+
inferredCheckpointTurnCountByTurnId,
1380+
agentEditSetMap,
1381+
)
1382+
) {
1383+
byUserMessageId.set(entry.message.id, restoreTarget);
13301384
}
13311385
break;
13321386
}

0 commit comments

Comments
 (0)