Skip to content

Commit 5d2406b

Browse files
saphidcodexgithub-actions[bot]juliusmarminge
authored
fix(web): release orphaned diff comment drafts (pingdotgg#18430)
Co-authored-by: SAPHID <[email protected]> Co-authored-by: GPT-6.1 Sol <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Julius Marminge <[email protected]>
1 parent 04ab2fc commit 5d2406b

3 files changed

Lines changed: 239 additions & 5 deletions

File tree

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,7 @@ export default function DiffPanel({
542542
collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,
543543
}));
544544
const codeViewFileKeys = codeViewFiles.map((file) => file.fileKey);
545+
const pendingFiles = renderableFiles.filter((file) => file.cacheKey?.endsWith(":pending"));
545546
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
546547
const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles);
547548
const fileTreeEntries = diffFileTreeEntries(renderableFiles);
@@ -1085,6 +1086,7 @@ export default function DiffPanel({
10851086
codeViewKey={`${codeViewMountKey}:${lazySource ? filePatchScope : "preview"}`}
10861087
className="h-full min-h-0 overflow-auto"
10871088
files={codeViewFiles}
1089+
pendingFiles={pendingFiles}
10881090
renderCodeViewFooter={renderLoadingBoundary}
10891091
sectionId={reviewSectionId}
10901092
sectionTitle={reviewSectionTitle}
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import type { ScopedThreadRef } from "@t3tools/contracts";
1111
import { useState, type ReactNode, type Ref } from "react";
1212

1313
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
14-
import { fnv1a32, resolveFileDiffPath } from "~/lib/diffRendering";
14+
import { fnv1a32, resolveFileDiffPath, resolveFileDiffPreviousPath } from "~/lib/diffRendering";
1515
import {
1616
buildDiffReviewComment,
1717
restoreDiffReviewCommentRange,
@@ -80,6 +80,7 @@ interface AnnotatableCodeViewProps {
8080
fileVersion: number;
8181
collapsed: boolean;
8282
}>;
83+
pendingFiles: ReadonlyArray<FileDiffMetadata>;
8384
sectionId: string;
8485
sectionTitle: string;
8586
composerDraftTarget: ScopedThreadRef | DraftId;
@@ -105,6 +106,7 @@ interface DiffSelectionContext {
105106
export function AnnotatableCodeView({
106107
codeViewKey,
107108
files,
109+
pendingFiles,
108110
sectionId,
109111
sectionTitle,
110112
composerDraftTarget,
@@ -129,11 +131,27 @@ export function AnnotatableCodeView({
129131
} | null>(null);
130132
const [draft, setDraft] = useState<{
131133
fileKey: string;
134+
filePath: string;
135+
previousFilePath: string;
132136
annotation: DiffCommentLineAnnotation;
133137
} | null>(null);
134138
const [draftText, setDraftText] = useState("");
135139

136140
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+
}
137155
const items: CodeViewDiffItem<DiffCommentAnnotationGroup>[] = files.map(
138156
({ fileDiff, filePath, fileKey, fileVersion, collapsed }) => {
139157
const persisted = reviewComments
@@ -210,11 +228,12 @@ export function AnnotatableCodeView({
210228
// Read from the item, not the file list, so the compiled callback keeps its identity
211229
// as patches arrive; the viewer re-applies its options whenever it changes.
212230
const id = nextFileCommentId();
231+
const filePath = resolveFileDiffPath(item.fileDiff);
213232
const comment = buildDiffReviewComment({
214233
id,
215234
sectionId,
216235
sectionTitle,
217-
filePath: resolveFileDiffPath(item.fileDiff),
236+
filePath,
218237
fileDiff: item.fileDiff,
219238
range,
220239
text: "",
@@ -223,6 +242,8 @@ export function AnnotatableCodeView({
223242
setDraftText("");
224243
setDraft({
225244
fileKey: item.id,
245+
filePath,
246+
previousFilePath: resolveFileDiffPreviousPath(item.fileDiff),
226247
annotation: {
227248
side: annotationSide(range),
228249
lineNumber: range.end,
@@ -233,7 +254,6 @@ export function AnnotatableCodeView({
233254
});
234255
};
235256

236-
const hasOpenComment = draft !== null;
237257
return (
238258
<StyledDiffCodeView<DiffCommentAnnotationGroup>
239259
key={codeViewKey}
@@ -253,8 +273,8 @@ export function AnnotatableCodeView({
253273
onRevealSearchMatch={(item) => onRevealSearchMatch(item.id)}
254274
options={{
255275
...options,
256-
enableGutterUtility: !hasOpenComment,
257-
enableLineSelection: !hasOpenComment,
276+
enableGutterUtility: draft === null,
277+
enableLineSelection: draft === null,
258278
onGutterUtilityClick: beginComment,
259279
}}
260280
renderHeaderFilenameSuffix={(item) =>

0 commit comments

Comments
 (0)