Skip to content

Commit 09c7e97

Browse files
saphidgithub-actions[bot]
authored andcommitted
fix(clients): close paste-dismissal race and stale draft masking
- Track in-flight image conversions in a ref read synchronously by the dismissal guard, so a paste followed by a back gesture inside the same frame still blocks removal (review finding). - Clear a markdown-editor draft when the text returns to the remote value, so it cannot mask a later remote update (review finding). - Split the line-draft subscription so keystrokes re-render only the draft editor instead of invalidating the viewer's portal memoization on every character (review finding).
1 parent c45579c commit 09c7e97

5 files changed

Lines changed: 128 additions & 66 deletions

File tree

‎apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
22
import { TextInputWrapper } from "expo-paste-input";
33
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4-
import { useCallback, useEffect, useMemo, useState } from "react";
4+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
55
import { Platform, Pressable, ScrollView, View, useWindowDimensions } from "react-native";
66
import { KeyboardAvoidingView, KeyboardStickyView } from "react-native-keyboard-controller";
77
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -60,6 +60,13 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
6060
>({});
6161
const [attachments, setAttachments] = useState<ReadonlyArray<DraftComposerImageAttachment>>([]);
6262
const [pendingImages, setPendingImages] = useState(0);
63+
// The dismissal guard reads this ref synchronously: a paste followed by a back gesture inside
64+
// the same frame must still count the conversion React has not rendered yet.
65+
const pendingImagesRef = useRef(0);
66+
const changePendingImages = useCallback((delta: number) => {
67+
pendingImagesRef.current += delta;
68+
setPendingImages(pendingImagesRef.current);
69+
}, []);
6370
const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
6471

6572
const selectedLines = useMemo(
@@ -89,7 +96,7 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
8996
useReviewCommentDismissal({
9097
commentText,
9198
attachmentCount: attachments.length,
92-
pendingImages,
99+
pendingImages: pendingImagesRef,
93100
submitted,
94101
accepted,
95102
});
@@ -103,7 +110,7 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
103110
const dismissComposer = useCallback(() => navigation.goBack(), [navigation]);
104111
const handleNativePaste = useNativePaste((uris) => {
105112
if (submitted) return;
106-
setPendingImages((count) => count + 1);
113+
changePendingImages(1);
107114
void (async () => {
108115
try {
109116
const images = await convertPastedImagesToAttachments({
@@ -116,7 +123,7 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
116123
} catch (error) {
117124
console.error("[review comment] error converting pasted images", error);
118125
} finally {
119-
setPendingImages((count) => count - 1);
126+
changePendingImages(-1);
120127
}
121128
})();
122129
});
@@ -151,7 +158,7 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
151158

152159
async function handlePickImages(): Promise<void> {
153160
if (submitted) return;
154-
setPendingImages((count) => count + 1);
161+
changePendingImages(1);
155162
try {
156163
const result = await pickComposerImages({ existingCount: attachments.length });
157164
if (result.images.length > 0) {
@@ -161,7 +168,7 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
161168
setPendingConnectionError(result.error);
162169
}
163170
} finally {
164-
setPendingImages((count) => count - 1);
171+
changePendingImages(-1);
165172
}
166173
}
167174

‎apps/mobile/src/features/review/useReviewCommentDismissal.test.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ function render(overrides: Partial<Parameters<typeof useReviewCommentDismissal>[
3838
useReviewCommentDismissal({
3939
commentText: "",
4040
attachmentCount: 0,
41-
pendingImages: 0,
41+
pendingImages: { current: 0 },
4242
submitted: false,
4343
accepted: { current: false },
4444
...overrides,
@@ -63,7 +63,7 @@ describe("review comment removal boundary", () => {
6363
it("allows an empty editor to leave without confirmation", () => {
6464
render();
6565
remove();
66-
expect(harness.prevented).toBe(false);
66+
expect(harness.dispatch).toHaveBeenCalledExactlyOnceWith(action);
6767
expect(harness.alert).not.toHaveBeenCalled();
6868
});
6969
it.each([{ commentText: "Unsent" }, { attachmentCount: 1 }])(
@@ -90,9 +90,16 @@ describe("review comment removal boundary", () => {
9090
expect(harness.goBack).not.toHaveBeenCalled();
9191
});
9292
it("blocks removal while selected images are still being prepared", () => {
93-
render({ pendingImages: 1 });
93+
render({ pendingImages: { current: 1 } });
94+
remove();
95+
expect(harness.alert).not.toHaveBeenCalled();
96+
expect(harness.dispatch).not.toHaveBeenCalled();
97+
});
98+
it("counts a paste that has not rendered yet when dismissal races it", () => {
99+
const pendingImages = { current: 0 };
100+
render({ pendingImages });
101+
pendingImages.current = 1;
94102
remove();
95-
expect(harness.prevented).toBe(true);
96103
expect(harness.alert).not.toHaveBeenCalled();
97104
expect(harness.dispatch).not.toHaveBeenCalled();
98105
});

‎apps/mobile/src/features/review/useReviewCommentDismissal.ts‎

Lines changed: 33 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -11,45 +11,46 @@ export function useReviewCommentDismissal({
1111
}: {
1212
readonly commentText: string;
1313
readonly attachmentCount: number;
14-
readonly pendingImages: number;
14+
/** In-flight image conversions, read live: state can lag a paste that precedes dismissal. */
15+
readonly pendingImages: RefObject<number>;
1516
readonly submitted: boolean;
1617
readonly accepted: RefObject<boolean>;
1718
}) {
1819
const navigation = useNavigation();
1920
const confirmingDiscard = useRef(false);
20-
usePreventRemove(
21-
!submitted && (pendingImages > 0 || commentText.length > 0 || attachmentCount > 0),
22-
({ data }) => {
23-
// The native removal guard can lag the successful synchronous transfer.
24-
if (accepted.current) {
25-
navigation.dispatch(data.action);
26-
return;
27-
}
28-
if (pendingImages > 0 || confirmingDiscard.current) return;
29-
confirmingDiscard.current = true;
30-
Alert.alert(
31-
"Discard comment?",
32-
"Your comment and attachments have not been added to the draft.",
33-
[
34-
{
35-
text: "Keep editing",
36-
style: "cancel",
37-
onPress: () => {
38-
confirmingDiscard.current = false;
39-
},
21+
// Guard every dismissal until submission, not just the renders that already know about
22+
// content: a paste in the same frame as a back gesture must still reach this callback.
23+
usePreventRemove(!submitted, ({ data }) => {
24+
const empty = pendingImages.current === 0 && commentText.length === 0 && attachmentCount === 0;
25+
// The native removal guard can lag the successful synchronous transfer.
26+
if (accepted.current || empty) {
27+
navigation.dispatch(data.action);
28+
return;
29+
}
30+
if (pendingImages.current > 0 || confirmingDiscard.current) return;
31+
confirmingDiscard.current = true;
32+
Alert.alert(
33+
"Discard comment?",
34+
"Your comment and attachments have not been added to the draft.",
35+
[
36+
{
37+
text: "Keep editing",
38+
style: "cancel",
39+
onPress: () => {
40+
confirmingDiscard.current = false;
4041
},
41-
{
42-
text: "Discard",
43-
style: "destructive",
44-
onPress: () => {
45-
confirmingDiscard.current = false;
46-
navigation.dispatch(data.action);
47-
},
42+
},
43+
{
44+
text: "Discard",
45+
style: "destructive",
46+
onPress: () => {
47+
confirmingDiscard.current = false;
48+
navigation.dispatch(data.action);
4849
},
49-
],
50-
);
51-
},
52-
);
50+
},
51+
],
52+
);
53+
});
5354
useEffect(() => {
5455
if (!submitted) return;
5556
navigation.goBack();

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

Lines changed: 64 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
import { useAtomRefresh } from "@effect/atom-react";
2828
import * as Schema from "effect/Schema";
2929
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
30+
import { useShallow } from "zustand/react/shallow";
3031

3132
import { useLocalStorage } from "~/hooks/useLocalStorage";
3233
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
@@ -151,6 +152,47 @@ interface DraftAnchor {
151152
readonly range: SelectedLineRange;
152153
}
153154

155+
/**
156+
* The draft card subscribes to the stored text itself so a keystroke re-renders this one editor
157+
* instead of the code tab, whose renderAnnotation feeds the viewer's portal memoization.
158+
*/
159+
function LineDraftAnnotation({
160+
lineDraftKey,
161+
anchor,
162+
fileMissing,
163+
secondaryAction,
164+
onCancel,
165+
onComment,
166+
}: {
167+
readonly lineDraftKey: string;
168+
readonly anchor: DraftAnchor;
169+
readonly fileMissing: boolean;
170+
readonly secondaryAction:
171+
| { readonly label: string; readonly onAction: (text: string) => void }
172+
| undefined;
173+
readonly onCancel: () => void;
174+
readonly onComment: (text: string) => void;
175+
}) {
176+
const text = usePullRequestReviewStore((store) => store.lineDrafts[lineDraftKey]?.text ?? "");
177+
return (
178+
<DiffCommentAnnotation
179+
kind="draft"
180+
rangeLabel={`${anchor.path}:${getReviewPositionAnchor(anchor.position).line}`}
181+
text={text}
182+
onTextChange={(next) => {
183+
const store = usePullRequestReviewStore.getState();
184+
const current = store.lineDrafts[lineDraftKey];
185+
if (current) store.setLineDraft(lineDraftKey, { ...current, text: next });
186+
}}
187+
submitLabel="Add to review"
188+
submitDisabled={fileMissing}
189+
{...(secondaryAction ? { secondaryAction } : {})}
190+
onCancel={onCancel}
191+
onComment={onComment}
192+
/>
193+
);
194+
}
195+
154196
/** A range of the diff and the reader's request for the agent. */
155197
export interface PullRequestAgentSelectionInput {
156198
/** The marked lines, already in the shape the composer draws and the agent reads. */
@@ -261,21 +303,25 @@ function PullRequestCodeTab({
261303
// everything below is keyed by both.
262304
const scopeKey = commit === null ? referenceKey : `${referenceKey}@${commit}`;
263305
const lineDraftKey = JSON.stringify([environmentId, scopeKey]);
264-
const draft = usePullRequestReviewStore((store) => store.lineDrafts[lineDraftKey] ?? null);
306+
// Anchor fields only: the stored draft gets a new identity on every keystroke, and the
307+
// callbacks below feed the viewer's portal memoization, so subscribing to `text` here would
308+
// remount every visible file header on each character typed.
309+
const draft = usePullRequestReviewStore(
310+
useShallow((store) => {
311+
const current = store.lineDrafts[lineDraftKey];
312+
if (!current) return null;
313+
const { text: _text, ...anchor } = current;
314+
return anchor;
315+
}),
316+
);
265317
const setLineDraft = usePullRequestReviewStore((store) => store.setLineDraft);
266318
const setDraft = useCallback(
267319
(next: DraftAnchor | null) => {
268320
setLineDraft(lineDraftKey, next === null ? null : { ...next, text: "" });
269321
},
270322
[lineDraftKey, setLineDraft],
271323
);
272-
const setDraftText = useCallback(
273-
(text: string) => {
274-
const current = usePullRequestReviewStore.getState().lineDrafts[lineDraftKey];
275-
if (current) setLineDraft(lineDraftKey, { ...current, text });
276-
},
277-
[lineDraftKey, setLineDraft],
278-
);
324+
279325
// The editor is keyed separately; resetting the viewer must not discard its draft.
280326
useEffect(() => {
281327
setSelectedLines(null);
@@ -1017,24 +1063,21 @@ function PullRequestCodeTab({
10171063
/>
10181064
))}
10191065
{annotation.metadata.draft && draft ? (
1020-
<DiffCommentAnnotation
1021-
kind="draft"
1022-
rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}
1023-
text={draft.text}
1024-
onTextChange={setDraftText}
1025-
submitLabel="Add to review"
1026-
submitDisabled={!files.some((file) => buildFileDiffRenderKey(file) === draft.fileKey)}
1027-
{...(onAddToAgentSelection
1028-
? {
1029-
secondaryAction: {
1066+
<LineDraftAnnotation
1067+
lineDraftKey={lineDraftKey}
1068+
anchor={draft}
1069+
fileMissing={!files.some((file) => buildFileDiffRenderKey(file) === draft.fileKey)}
1070+
secondaryAction={
1071+
onAddToAgentSelection
1072+
? {
10301073
label: "Add to agent",
10311074
onAction: (text: string) =>
10321075
finishSelection(draft, text, (comment) =>
10331076
onAddToAgentSelection({ comment, request: text }),
10341077
),
1035-
},
1036-
}
1037-
: {})}
1078+
}
1079+
: undefined
1080+
}
10381081
onCancel={() => {
10391082
setDraft(null);
10401083
setSelectedLines(null);
@@ -1065,7 +1108,6 @@ function PullRequestCodeTab({
10651108
renderThreadCard,
10661109
reviewKey,
10671110
setDraft,
1068-
setDraftText,
10691111
],
10701112
);
10711113

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,13 @@ export function PullRequestMarkdownEditor({
4747
readonly onCancel: () => void;
4848
}) {
4949
const draft = usePullRequestReviewStore((store) => store.editorDrafts[draftKey] ?? value);
50-
const setDraft = (text: string) =>
51-
usePullRequestReviewStore.getState().setEditorDraft(draftKey, text);
50+
// Returning to the remote value means nothing is left to preserve — keeping that entry would
51+
// mask a later remote change behind text the reader already discarded.
52+
const setDraft = (text: string) => {
53+
const store = usePullRequestReviewStore.getState();
54+
if (text === value) store.clearEditorDraft(draftKey, draft);
55+
else store.setEditorDraft(draftKey, text);
56+
};
5257
const [preview, setPreview] = useState(false);
5358
const empty = draft.trim().length === 0;
5459
const saveDisabled = saving || (empty && !allowEmpty);

0 commit comments

Comments
 (0)