Skip to content

Commit 55f056b

Browse files
fix(web): keep an unfinished inline PR comment across panel switches
The draft anchor, its text and the selected lines now live in the per-PR code view state, so leaving the PR panel for another right-panel surface and coming back restores them while the file is unchanged. AI-assisted; verified with the tests and tools listed above.
1 parent 201ed64 commit 55f056b

3 files changed

Lines changed: 134 additions & 33 deletions

File tree

‎apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@ import {
88
type PullRequestDiffResult,
99
} from "@t3tools/contracts";
1010
import { expect, it, vi } from "vite-plus/test";
11+
import { userEvent } from "vite-plus/test/browser";
1112

1213
import "~/index.css";
1314
import { __setClientSettingsForTests } from "../../hooks/useSettings";
1415
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
1516

16-
const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => {
17+
const { diffAtom, firstPage, pagedDiffAtom } = await vi.hoisted(async () => {
1718
const { AsyncResult, Atom } = await import("effect/reactivity");
1819
const filePatch = (path: string) =>
1920
[
@@ -47,6 +48,7 @@ const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => {
4748
"page-2": { patch: filePatch("late.test.ts"), truncated: false, nextCursor: null },
4849
};
4950
return {
51+
firstPage,
5052
// An environment query whose refetch returns equal content hands back the previous value
5153
// itself, so a refresh publishes a new result around the very same page.
5254
diffAtom: Atom.make(() => AsyncResult.success(firstPage)),
@@ -79,6 +81,11 @@ vi.mock(import("~/state/pullRequests"), async (original) => {
7981
import { render } from "../../../test/render";
8082
import PullRequestCodeTab from "./PullRequestCodeTab";
8183
import { usePullRequestReviewStore } from "./pullRequestReviewStore";
84+
import {
85+
buildFileDiffContentVersion,
86+
buildFileDiffIdentityKey,
87+
getRenderablePatch,
88+
} from "~/lib/diffRendering";
8289

8390
const detail: PullRequestDetailView = {
8491
provider: SourceControlProviderKind.make("github"),
@@ -206,6 +213,48 @@ it("scrolls to a file asked for as the tab opens", async () => {
206213
await expectFileHeaderShown(screen, container, "early-39.ts");
207214
});
208215

216+
it("keeps an unfinished inline comment when the panel unmounts and returns", async () => {
217+
setup({ paged: false });
218+
const parsed = getRenderablePatch(firstPage.patch, "draft", { compactPartialHunkOffsets: true });
219+
if (parsed?.kind !== "files") throw new Error("fixture must parse as files");
220+
const file = parsed.files[0]!;
221+
usePullRequestReviewStore.getState().updateCodeView("code-view", (current) => ({
222+
...current,
223+
foldOverride: "expanded",
224+
draft: {
225+
fileKey: buildFileDiffIdentityKey(file),
226+
contentVersion: buildFileDiffContentVersion(file),
227+
path: "a.ts",
228+
oldPath: null,
229+
position: { kind: "context", oldLine: 2, newLine: 2, side: "right" },
230+
range: { start: 2, end: 2, side: "additions" },
231+
},
232+
}));
233+
const element = () => (
234+
<PullRequestCodeTab
235+
scrollerRef={() => {}}
236+
codeViewKey="code-view"
237+
environmentId={EnvironmentId.make("environment")}
238+
reference={detail}
239+
detail={detail}
240+
selectedCommitOid={null}
241+
onSelectedCommitChange={() => {}}
242+
onRefresh={() => {}}
243+
onAddToAgentSelection={() => {}}
244+
/>
245+
);
246+
const container = pagedContainer();
247+
{
248+
await using screen = await render(element(), { container });
249+
const composer = screen.getByRole("textbox", { name: "Comment on lines a.ts:2" });
250+
await userEvent.type(composer, "Half a thought");
251+
}
252+
await using screen = await render(element(), { container });
253+
await expect
254+
.element(screen.getByRole("textbox", { name: "Comment on lines a.ts:2" }))
255+
.toHaveValue("Half a thought");
256+
});
257+
209258
it("pages forward to a file asked for that is not loaded yet, then scrolls to it", async () => {
210259
setup({ paged: true });
211260
__setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: true });

‎apps/web/src/components/pullRequest/PullRequestCodeTab.tsx‎

Lines changed: 56 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import type {
1515
PullRequestDiffSide,
1616
PullRequestDiffResult,
1717
PullRequestRef,
18-
PullRequestReviewPosition,
1918
PullRequestReviewThread,
2019
PullRequestThreadCommentsResult,
2120
} from "@t3tools/contracts";
@@ -45,6 +44,7 @@ import {
4544
useRef,
4645
useState,
4746
type ReactNode,
47+
type ComponentProps,
4848
} from "react";
4949

5050
import { observeIntersection } from "~/lib/observeIntersection";
@@ -150,6 +150,8 @@ import {
150150
usePendingReviewComments,
151151
usePullRequestReviewStore,
152152
type PendingReviewComment,
153+
type PullRequestDraftAnchor,
154+
type PullRequestSelectedLines,
153155
} from "./pullRequestReviewStore";
154156

155157
interface ReviewAnnotationGroup {
@@ -329,14 +331,31 @@ interface MutableAnnotationGroup {
329331
draft: boolean;
330332
}
331333

332-
interface DraftAnchor {
333-
readonly fileKey: string;
334-
readonly contentVersion: number;
335-
readonly path: string;
336-
readonly oldPath: string | null;
337-
readonly position: PullRequestReviewPosition;
338-
readonly startPosition?: PullRequestReviewPosition;
339-
readonly range: SelectedLineRange;
334+
type DraftAnchor = PullRequestDraftAnchor;
335+
336+
// Subscribes to the stored text itself so typing re-renders only the composer.
337+
function StoredDraftCommentAnnotation({
338+
codeViewKey,
339+
...props
340+
}: Omit<ComponentProps<typeof DiffCommentAnnotation>, "text" | "onTextChange"> & {
341+
readonly codeViewKey: string;
342+
}) {
343+
const text = usePullRequestReviewStore(
344+
(store) => (store.codeViews[codeViewKey] ?? EMPTY_CODE_VIEW).draftText,
345+
);
346+
return (
347+
<DiffCommentAnnotation
348+
{...props}
349+
text={text}
350+
onTextChange={(next) =>
351+
usePullRequestReviewStore
352+
.getState()
353+
.updateCodeView(codeViewKey, (current) =>
354+
current.draftText === next ? current : { ...current, draftText: next },
355+
)
356+
}
357+
/>
358+
);
340359
}
341360

342361
export interface PullRequestAgentSelectionInput {
@@ -419,12 +438,21 @@ function PullRequestCodeTab({
419438
Schema.Boolean,
420439
);
421440
const [hideTestFiles, setHideTestFiles] = useHideTestFiles();
422-
const [selectedLines, setSelectedLines] = useState<{
423-
id: string;
424-
contentVersion: number;
425-
range: SelectedLineRange;
426-
} | null>(null);
427-
const [draft, setDraft] = useState<DraftAnchor | null>(null);
441+
// The panel unmounts when another right-panel surface opens; the draft outlives it.
442+
const savedSelectedLines = usePullRequestReviewStore(
443+
(store) => (store.codeViews[codeViewKey] ?? EMPTY_CODE_VIEW).selectedLines,
444+
);
445+
const savedDraft = usePullRequestReviewStore(
446+
(store) => (store.codeViews[codeViewKey] ?? EMPTY_CODE_VIEW).draft,
447+
);
448+
const setSelectedLines = (next: PullRequestSelectedLines | null) =>
449+
updateCodeView(codeViewKey, (current) =>
450+
current.selectedLines === next ? current : { ...current, selectedLines: next },
451+
);
452+
const setDraft = (next: DraftAnchor | null) =>
453+
updateCodeView(codeViewKey, (current) =>
454+
current.draft === next ? current : { ...current, draft: next, draftText: "" },
455+
);
428456
const [threadPending, setThreadPending] = useState(false);
429457
const [orphansOpen, setOrphansOpen] = useState(false);
430458
// Scope slices before reset to prevent using a previous pull request's data or cursor.
@@ -447,17 +475,14 @@ function PullRequestCodeTab({
447475
const [scrollRestoration, setScrollRestoration] = useState(
448476
() => new PullRequestCodeScrollRestoration(readPullRequestCodeView(codeViewKey)),
449477
);
450-
// The panel keeps this mounted across pull requests, so an open composer would otherwise
451-
// survive the switch and attach its comment to whichever one is on screen when it is sent.
478+
// The panel keeps this mounted across pull requests; the composer is kept per pull request.
452479
const [stateScopeKey, setStateScopeKey] = useState(scopeKey);
453480
if (stateScopeKey !== scopeKey) {
454481
setStateScopeKey(scopeKey);
455482
setLastViewedFileKey(null);
456483
setScrollRestoration(
457484
new PullRequestCodeScrollRestoration(readPullRequestCodeView(codeViewKey)),
458485
);
459-
setDraft(null);
460-
setSelectedLines(null);
461486
setVisibleCommitCount(COMMIT_PAGE_SIZE);
462487
setOrphansOpen(false);
463488
setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
@@ -662,19 +687,19 @@ function PullRequestCodeTab({
662687
const hiddenTestFileCount = loadedFiles.length - files.length;
663688
// A file on a page not read yet is not gone; only a complete diff can say it is.
664689
const diffComplete = loadedSlices.length > 0 && loadedSlices.at(-1)?.nextCursor === null;
665-
if (
666-
selectedLines !== null &&
667-
isPullRequestSelectionStale(
690+
const selectedLines =
691+
savedSelectedLines !== null &&
692+
!isPullRequestSelectionStale(
668693
loadedFiles,
669-
{ ...selectedLines, fileKey: selectedLines.id },
694+
{ ...savedSelectedLines, fileKey: savedSelectedLines.id },
670695
diffComplete,
671696
)
672-
) {
673-
setSelectedLines(null);
674-
}
675-
if (draft !== null && isPullRequestSelectionStale(loadedFiles, draft, diffComplete)) {
676-
setDraft(null);
677-
}
697+
? savedSelectedLines
698+
: null;
699+
const draft =
700+
savedDraft !== null && !isPullRequestSelectionStale(loadedFiles, savedDraft, diffComplete)
701+
? savedDraft
702+
: null;
678703
const changeSelectedLines = (selection: { id: string; range: SelectedLineRange } | null) => {
679704
const file =
680705
selection === null
@@ -1159,13 +1184,13 @@ function PullRequestCodeTab({
11591184
/>
11601185
))}
11611186
{annotation.metadata.draft && draft && canSelectLines ? (
1162-
<DiffCommentAnnotation
1187+
<StoredDraftCommentAnnotation
1188+
codeViewKey={codeViewKey}
11631189
environmentId={environmentId}
11641190
projectId={reference.projectId}
11651191
ownerKey={JSON.stringify([environmentId, reviewKey, draft])}
11661192
kind="draft"
11671193
rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}
1168-
text=""
11691194
completionScope={canCommentOnLines ? completionScope : null}
11701195
submitLabel={canCommentOnLines ? "Add to review" : "Add to agent"}
11711196
{...(canCommentOnLines && onAddToAgentSelection

‎apps/web/src/components/pullRequest/pullRequestReviewStore.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import type { PullRequestRef, PullRequestReviewCommentDraft } from "@t3tools/contracts";
1+
import type { SelectedLineRange } from "@pierre/diffs";
2+
import type {
3+
PullRequestRef,
4+
PullRequestReviewCommentDraft,
5+
PullRequestReviewPosition,
6+
} from "@t3tools/contracts";
27
import { create } from "zustand";
38
import type { DiffFoldOverride } from "./pullRequestDiff.logic";
49

@@ -21,13 +26,32 @@ export function pullRequestReviewKey(reference: PullRequestRef): string {
2126
]);
2227
}
2328

29+
export interface PullRequestDraftAnchor {
30+
readonly fileKey: string;
31+
readonly contentVersion: number;
32+
readonly path: string;
33+
readonly oldPath: string | null;
34+
readonly position: PullRequestReviewPosition;
35+
readonly startPosition?: PullRequestReviewPosition;
36+
readonly range: SelectedLineRange;
37+
}
38+
39+
export interface PullRequestSelectedLines {
40+
readonly id: string;
41+
readonly contentVersion: number;
42+
readonly range: SelectedLineRange;
43+
}
44+
2445
export interface PullRequestCodeViewState {
2546
readonly selectedCommitOid: string | null;
2647
readonly foldOverride: DiffFoldOverride;
2748
readonly toggledFiles: ReadonlySet<string>;
2849
readonly scrollTop: number;
2950
readonly loadedPageCount: number;
3051
readonly chromeCondensed: boolean;
52+
readonly selectedLines: PullRequestSelectedLines | null;
53+
readonly draft: PullRequestDraftAnchor | null;
54+
readonly draftText: string;
3155
}
3256

3357
export const EMPTY_CODE_VIEW: PullRequestCodeViewState = {
@@ -37,6 +61,9 @@ export const EMPTY_CODE_VIEW: PullRequestCodeViewState = {
3761
scrollTop: 0,
3862
loadedPageCount: 1,
3963
chromeCondensed: false,
64+
selectedLines: null,
65+
draft: null,
66+
draftText: "",
4067
};
4168

4269
export function pullRequestCodeViewKey(

0 commit comments

Comments
 (0)