@devries-cameron20 / t3code-1 / commits / 5d2406bb3b
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): release orphaned diff comment drafts (#18430)

Co-authored-by: SAPHID <saphid@users.noreply.github.com> Co-authored-by: GPT-6.1 Sol <noreply@openai.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Alex Southwell committed Oct 20, 2026 at 06:24 UTC 5d2406bb3b2f495e19ca4764c0efc265659a031f
3 files changed +239 -5
apps/web/src/components/DiffPanel.tsx
+2
@@ -542,6 +542,7 @@ export default function DiffPanel({
542 collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,
543 }));
544 const codeViewFileKeys = codeViewFiles.map((file) => file.fileKey);
545 + const pendingFiles = renderableFiles.filter((file) => file.cacheKey?.endsWith(":pending"));
546 const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
547 const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles);
548 const fileTreeEntries = diffFileTreeEntries(renderableFiles);
@@ -1085,6 +1086,7 @@ export default function DiffPanel({
1086 codeViewKey={`${codeViewMountKey}:${lazySource ? filePatchScope : "preview"}`}
1087 className="h-full min-h-0 overflow-auto"
1088 files={codeViewFiles}
1089 + pendingFiles={pendingFiles}
1090 renderCodeViewFooter={renderLoadingBoundary}
1091 sectionId={reviewSectionId}
1092 sectionTitle={reviewSectionTitle}
apps/web/src/components/diffs/AnnotatableCodeView.browser.test.tsx new
+212
@@ -0,0 +1,212 @@
1 +import type { CodeViewDiffItem, FileDiffMetadata, SelectedLineRange } from "@pierre/diffs";
2 +import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
3 +import { act, StrictMode, type ComponentProps } from "react";
4 +import { createRoot, type Root } from "react-dom/client";
5 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6 +
7 +import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
8 +import { buildFileDiffIdentityKey } from "~/lib/diffRendering";
9 +
10 +type ViewerProps = Omit<ComponentProps<typeof StyledDiffCodeView<unknown>>, "options"> & {
11 + options: {
12 + enableLineSelection: boolean;
13 + enableGutterUtility: boolean;
14 + onGutterUtilityClick: (
15 + range: SelectedLineRange,
16 + context: { item: CodeViewDiffItem<unknown> },
17 + ) => void;
18 + };
19 +};
20 +
21 +// Replace only the virtualized viewer; comment editing and submission use the real components.
22 +vi.mock("./StyledDiffCodeView", () => ({
23 + StyledDiffCodeView: (props: ViewerProps) =>
24 + props.items
25 + ?.filter((item) => item.type === "diff")
26 + .map((item) => (
27 + <section key={item.id}>
28 + <button
29 + disabled={!props.options?.enableLineSelection || !props.options?.enableGutterUtility}
30 + onClick={() => {
31 + props.onSelectedLinesChange?.({ id: item.id, range });
32 + props.options?.onGutterUtilityClick?.(range, { item });
33 + }}
34 + >
35 + Comment on {item.fileDiff.name}
36 + </button>
37 + {props.selectedLines?.id === item.id ? (
38 + <mark>Line {props.selectedLines.range.start}</mark>
39 + ) : null}
40 + {item.annotations?.map((annotation) => (
41 + <div key={`${annotation.side}:${annotation.lineNumber}`}>
42 + {props.renderAnnotation?.(annotation, item)}
43 + </div>
44 + ))}
45 + </section>
46 + )),
47 +}));
48 +
49 +import { AnnotatableCodeView } from "./AnnotatableCodeView";
50 +import type { StyledDiffCodeView } from "./StyledDiffCodeView";
51 +
52 +const target = DraftId.make("diff-draft-test");
53 +const range: SelectedLineRange = { start: 1, end: 1, side: "additions" };
54 +let root: Root;
55 +let container: HTMLDivElement;
56 +
57 +function file(
58 + name: string,
59 + fileVersion = 1,
60 + type: FileDiffMetadata["type"] = "change",
61 + prevName?: string,
62 +) {
63 + const fileDiff = parsePatchFiles(
64 + `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n@@ -1 +1 @@\n-old\n+new\n`,
65 + name,
66 + )[0]!.files[0]!;
67 + fileDiff.type = type;
68 + if (prevName) fileDiff.prevName = prevName;
69 + return {
70 + fileDiff,
71 + filePath: name,
72 + fileKey: buildFileDiffIdentityKey(fileDiff),
73 + fileVersion,
74 + collapsed: false,
75 + };
76 +}
77 +
78 +function render(
79 + files: ReturnType<typeof file>[],
80 + codeViewKey = "initial",
81 + pendingFiles: FileDiffMetadata[] = [],
82 +) {
83 + act(() =>
84 + root.render(
85 + <StrictMode>
86 + <AnnotatableCodeView
87 + codeViewKey={codeViewKey}
88 + files={files}
89 + pendingFiles={pendingFiles}
90 + sectionId="unstaged"
91 + sectionTitle="Uncommitted"
92 + composerDraftTarget={target}
93 + options={{}}
94 + renderHeaderFilenameSuffix={() => null}
95 + renderHeaderPrefix={() => null}
96 + onRevealSearchMatch={() => {}}
97 + />
98 + </StrictMode>,
99 + ),
100 + );
101 +}
102 +
103 +function click(label: string) {
104 + const button = Array.from(container.querySelectorAll("button")).find(
105 + (node) => node.textContent === label,
106 + );
107 + if (!button) throw new Error(`Missing button: ${label}`);
108 + act(() => button.click());
109 +}
110 +
111 +function editor() {
112 + const textarea = container.querySelector("textarea");
113 + if (!textarea) throw new Error("Comment editor is not available");
114 + return textarea;
115 +}
116 +
117 +function typeComment(text: string) {
118 + act(() => {
119 + Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(
120 + editor(),
121 + text,
122 + );
123 + editor().dispatchEvent(new Event("input", { bubbles: true }));
124 + });
125 +}
126 +
127 +beforeEach(() => {
128 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
129 + useComposerDraftStore.setState(useComposerDraftStore.getInitialState(), true);
130 + container = document.createElement("div");
131 + document.body.append(container);
132 + root = createRoot(container);
133 +});
134 +
135 +afterEach(() => {
136 + act(() => root.unmount());
137 + container.remove();
138 + useComposerDraftStore.setState(useComposerDraftStore.getInitialState(), true);
139 + vi.unstubAllGlobals();
140 +});
141 +
142 +describe("diff comment drafts", () => {
143 + it.each(["removed file", "replaced rename"] as const)(
144 + "allows a fresh comment after a %s loses its draft",
145 + (scenario) => {
146 + const original =
147 + scenario === "removed file"
148 + ? file("a.ts")
149 + : file("shared.ts", 1, "rename-changed", "old.ts");
150 + render([original, file("b.ts")]);
151 + click(`Comment on ${original.filePath}`);
152 + typeComment("Discard this draft");
153 + const pending =
154 + scenario === "removed file"
155 + ? []
156 + : [
157 + {
158 + ...file("shared.ts", 2, "rename-changed", "other.ts").fileDiff,
159 + hunks: [],
160 + cacheKey: "replacement:pending",
161 + },
162 + ];
163 +
164 + render([file("b.ts")], "refreshed", pending);
165 + expect(container.querySelector("textarea")).toBeNull();
166 + click("Comment on b.ts");
167 + expect(editor().value).toBe("");
168 + typeComment(" Review b.ts ");
169 + click("Comment");
170 +
171 + expect(useComposerDraftStore.getState().getComposerDraft(target)?.reviewComments).toEqual([
172 + expect.objectContaining({
173 + filePath: "b.ts",
174 + text: "Review b.ts",
175 + selection: { ...range, endSide: "additions" },
176 + }),
177 + ]);
178 + render([original, file("b.ts")], "returned");
179 + expect(container.querySelector("textarea")).toBeNull();
180 + expect(container.querySelector("mark")).toBeNull();
181 + expect(container.querySelector("p")?.textContent).toBe("Review b.ts");
182 + },
183 + );
184 +
185 + it("keeps the text and selected line through refresh and a provisional lazy patch", () => {
186 + const original = file("shared.ts", 1, "rename-pure", "old.ts");
187 + render([original]);
188 + click("Comment on shared.ts");
189 + typeComment("Keep this draft");
190 + const refreshed = file("shared.ts", 2, "rename-pure", "old.ts");
191 + render([refreshed], "refreshed");
192 + expect(editor().value).toBe("Keep this draft");
193 + expect(container.querySelector("mark")?.textContent).toBe("Line 1");
194 +
195 + render([], "loading", [
196 + { ...refreshed.fileDiff, type: "rename-changed", hunks: [], cacheKey: "shared:pending" },
197 + ]);
198 + expect(container.querySelector("textarea")).toBeNull();
199 + render([refreshed], "loaded");
200 + expect(editor().value).toBe("Keep this draft");
201 + expect(container.querySelector("mark")?.textContent).toBe("Line 1");
202 + click("Comment");
203 + expect(useComposerDraftStore.getState().getComposerDraft(target)?.reviewComments).toEqual([
204 + expect.objectContaining({
205 + filePath: "shared.ts",
206 + text: "Keep this draft",
207 + selection: { ...range, endSide: "additions" },
208 + }),
209 + ]);
210 + expect(container.querySelector("p")?.textContent).toBe("Keep this draft");
211 + });
212 +});
apps/web/src/components/diffs/AnnotatableCodeView.tsx
+25 -5
@@ -11,7 +11,7 @@ import type { ScopedThreadRef } from "@t3tools/contracts";
11 import { useState, type ReactNode, type Ref } from "react";
12
13 import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
14 -import { fnv1a32, resolveFileDiffPath } from "~/lib/diffRendering";
14 +import { fnv1a32, resolveFileDiffPath, resolveFileDiffPreviousPath } from "~/lib/diffRendering";
15 import {
16 buildDiffReviewComment,
17 restoreDiffReviewCommentRange,
@@ -80,6 +80,7 @@ interface AnnotatableCodeViewProps {
80 fileVersion: number;
81 collapsed: boolean;
82 }>;
83 + pendingFiles: ReadonlyArray<FileDiffMetadata>;
84 sectionId: string;
85 sectionTitle: string;
86 composerDraftTarget: ScopedThreadRef | DraftId;
@@ -105,6 +106,7 @@ interface DiffSelectionContext {
106 export function AnnotatableCodeView({
107 codeViewKey,
108 files,
109 + pendingFiles,
110 sectionId,
111 sectionTitle,
112 composerDraftTarget,
@@ -129,11 +131,27 @@ export function AnnotatableCodeView({
131 } | null>(null);
132 const [draft, setDraft] = useState<{
133 fileKey: string;
134 + filePath: string;
135 + previousFilePath: string;
136 annotation: DiffCommentLineAnnotation;
137 } | null>(null);
138 const [draftText, setDraftText] = useState("");
139
140 const filesByKey = new Map(files.map((file) => [file.fileKey, file]));
141 + if (
142 + draft !== null &&
143 + !filesByKey.has(draft.fileKey) &&
144 + // Lazy placeholders have provisional change types, so match both paths instead.
145 + !pendingFiles.some(
146 + (file) =>
147 + resolveFileDiffPath(file) === draft.filePath &&
148 + resolveFileDiffPreviousPath(file) === draft.previousFilePath,
149 + )
150 + ) {
151 + setDraft(null);
152 + setDraftText("");
153 + setSelectedLines(null);
154 + }
155 const items: CodeViewDiffItem<DiffCommentAnnotationGroup>[] = files.map(
156 ({ fileDiff, filePath, fileKey, fileVersion, collapsed }) => {
157 const persisted = reviewComments
@@ -210,11 +228,12 @@ export function AnnotatableCodeView({
228 // Read from the item, not the file list, so the compiled callback keeps its identity
229 // as patches arrive; the viewer re-applies its options whenever it changes.
230 const id = nextFileCommentId();
231 + const filePath = resolveFileDiffPath(item.fileDiff);
232 const comment = buildDiffReviewComment({
233 id,
234 sectionId,
235 sectionTitle,
217 - filePath: resolveFileDiffPath(item.fileDiff),
236 + filePath,
237 fileDiff: item.fileDiff,
238 range,
239 text: "",
@@ -223,6 +242,8 @@ export function AnnotatableCodeView({
242 setDraftText("");
243 setDraft({
244 fileKey: item.id,
245 + filePath,
246 + previousFilePath: resolveFileDiffPreviousPath(item.fileDiff),
247 annotation: {
248 side: annotationSide(range),
249 lineNumber: range.end,
@@ -233,7 +254,6 @@ export function AnnotatableCodeView({
254 });
255 };
256
236 - const hasOpenComment = draft !== null;
257 return (
258 <StyledDiffCodeView<DiffCommentAnnotationGroup>
259 key={codeViewKey}
@@ -253,8 +273,8 @@ export function AnnotatableCodeView({
273 onRevealSearchMatch={(item) => onRevealSearchMatch(item.id)}
274 options={{
275 ...options,
256 - enableGutterUtility: !hasOpenComment,
257 - enableLineSelection: !hasOpenComment,
276 + enableGutterUtility: draft === null,
277 + enableLineSelection: draft === null,
278 onGutterUtilityClick: beginComment,
279 }}
280 renderHeaderFilenameSuffix={(item) =>