@devries-cameron20 / t3code-1 / commits / a2589f22d3
Fork 0

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

fix(mobile): review opens on Changes and keeps the section you picked (#25223)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 25, 2026 at 20:59 UTC a2589f22d3b63c927c386721efa5eaf562ca3b1e
17 files changed +606 -454
apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
+14 -15
@@ -30,6 +30,8 @@ import { changeTone, DiffTokenText, ReviewChangeBar } from "./reviewDiffRenderin
30 import { highlightReviewSelectedLines } from "./highlightReviewSelectedLines";
31
32 const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;
33 +const NO_LINES: ReturnType<typeof getSelectedReviewCommentLines> = [];
34 +const NO_HIGHLIGHTS: ReturnType<typeof highlightReviewSelectedLines> = {};
35
36 type ReviewCommentComposerSheetProps = StaticScreenProps<{
37 readonly environmentId: EnvironmentId;
@@ -49,21 +51,18 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
51 const [attachments, setAttachments] = useState<ReadonlyArray<DraftComposerImageAttachment>>([]);
52 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
53
52 - const selectedLines = useMemo(
53 - () => (target ? getSelectedReviewCommentLines(target) : []),
54 - [target],
55 - );
56 - const highlightedLinesById = useMemo(
57 - () =>
58 - target
59 - ? highlightReviewSelectedLines({
60 - filePath: target.filePath,
61 - lines: selectedLines,
62 - theme: selectedTheme,
63 - })
64 - : {},
65 - [selectedLines, selectedTheme, target],
66 - );
54 + const { selectedLines, highlightedLinesById } = useMemo(() => {
55 + if (!target) return { selectedLines: NO_LINES, highlightedLinesById: NO_HIGHLIGHTS };
56 + const lines = getSelectedReviewCommentLines(target);
57 + return {
58 + selectedLines: lines,
59 + highlightedLinesById: highlightReviewSelectedLines({
60 + filePath: target.filePath,
61 + lines,
62 + theme: selectedTheme,
63 + }),
64 + };
65 + }, [selectedTheme, target]);
66 const firstLine = selectedLines[0] ?? null;
67 const lastLine = selectedLines[selectedLines.length - 1] ?? null;
68 const firstNumber = firstLine ? getReviewUnifiedLineNumber(firstLine) : null;
apps/mobile/src/features/review/ReviewSheet.tsx
-2
@@ -461,7 +461,6 @@ export function ReviewSheet(props: ReviewSheetProps) {
461 refreshSelectedSection,
462 selectSection,
463 isSelectedSectionPending,
464 - diffPreviewRevision,
464 } = useReviewSections({
465 enabled: isEnvironmentReady,
466 environmentId,
@@ -485,7 +484,6 @@ export function ReviewSheet(props: ReviewSheetProps) {
484 environmentId,
485 cwd: selectedThreadCwd,
486 selectedSection,
488 - revision: diffPreviewRevision,
487 draftMessage,
488 });
489 // Expo may return null before registration or in older binaries; use the fallback.
apps/mobile/src/features/review/reviewCommentSelection.test.ts
+90
@@ -1,11 +1,19 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 import {
4 + clearReviewCommentTarget,
5 + completeReviewCommentRange,
6 formatReviewCommentContext,
7 + getReviewCommentSelection,
8 + reviewCommentSelectionScope,
9 + selectReviewCommentSelection,
10 + setReviewCommentTarget,
11 + startReviewCommentRange,
12 parseReviewCommentMessageSegments,
13 parseReviewInlineComments,
14 type ReviewCommentTarget,
15 } from "./reviewCommentSelection";
16 +import { setReviewSelectedSectionId } from "./reviewState";
17
18 function makeTarget(): ReviewCommentTarget {
19 return {
@@ -143,3 +151,85 @@ describe("review comment serialization", () => {
151 expect(comment?.sectionTitle).toBe("Changes > 5");
152 });
153 });
154 +
155 +describe("review comment selection store", () => {
156 + const changes = { id: "git:branch-range", content: "hash-1" };
157 + const scope = reviewCommentSelectionScope(1, "env:thread", changes)!;
158 + const otherScope = reviewCommentSelectionScope(1, "env:thread", {
159 + id: "turn:2",
160 + content: "diff",
161 + })!;
162 + const target = makeTarget();
163 + const pending = {
164 + sectionId: target.sectionId,
165 + sectionTitle: target.sectionTitle,
166 + filePath: target.filePath,
167 + lines: target.lines,
168 + lineIndex: 0,
169 + rowId: "row-1",
170 + };
171 +
172 + it("keeps a long-pressed range start when replacing an earlier target", () => {
173 + setReviewCommentTarget(scope, target);
174 + startReviewCommentRange(scope, pending);
175 +
176 + expect(getReviewCommentSelection()).toEqual({ scope, target: null, pending });
177 + });
178 +
179 + it("keeps the range start after a same-line range end and drops it on a plain tap", () => {
180 + startReviewCommentRange(scope, pending);
181 + const sameLine = { ...target, startIndex: 0, endIndex: 0 };
182 + completeReviewCommentRange(scope, sameLine);
183 + expect(getReviewCommentSelection().pending).toEqual(pending);
184 +
185 + setReviewCommentTarget(scope, sameLine);
186 + expect(getReviewCommentSelection().pending).toBeNull();
187 + });
188 +
189 + it("clears the target and the range start together", () => {
190 + startReviewCommentRange(scope, pending);
191 + clearReviewCommentTarget();
192 +
193 + expect(getReviewCommentSelection()).toEqual({ scope: null, target: null, pending: null });
194 + });
195 +
196 + it("reads as empty from another thread or section", () => {
197 + setReviewCommentTarget(scope, target);
198 +
199 + expect(selectReviewCommentSelection(getReviewCommentSelection(), scope).target).toBe(target);
200 + expect(selectReviewCommentSelection(getReviewCommentSelection(), otherScope).target).toBeNull();
201 + expect(selectReviewCommentSelection(getReviewCommentSelection(), null).target).toBeNull();
202 + });
203 +
204 + it("reads as empty in a reopened review sheet", () => {
205 + setReviewCommentTarget(scope, target);
206 + const reopenedScope = reviewCommentSelectionScope(2, "env:thread", changes);
207 +
208 + expect(
209 + selectReviewCommentSelection(getReviewCommentSelection(), reopenedScope).target,
210 + ).toBeNull();
211 + });
212 +
213 + it("reads as empty when the section disappears and comes back over a different diff", () => {
214 + setReviewCommentTarget(scope, target);
215 + // The working tree went clean, so the default showed; the section later returns.
216 + const returned = reviewCommentSelectionScope(1, "env:thread", {
217 + ...changes,
218 + content: "hash-2",
219 + });
220 + const unchanged = reviewCommentSelectionScope(1, "env:thread", { ...changes });
221 +
222 + expect(selectReviewCommentSelection(getReviewCommentSelection(), returned).target).toBeNull();
223 + expect(selectReviewCommentSelection(getReviewCommentSelection(), unchanged).target).toBe(
224 + target,
225 + );
226 + });
227 +
228 + it("drops the selection when the section changes, so switching back starts empty", () => {
229 + setReviewCommentTarget(scope, target);
230 + setReviewSelectedSectionId("env:thread", "turn:2");
231 + setReviewSelectedSectionId("env:thread", "git:branch-range");
232 +
233 + expect(selectReviewCommentSelection(getReviewCommentSelection(), scope).target).toBeNull();
234 + });
235 +});
apps/mobile/src/features/review/reviewCommentSelection.ts
+107 -14
@@ -36,43 +36,136 @@ export type ReviewCommentMessageSegment =
36 readonly comment: ReviewInlineComment;
37 };
38
39 -let currentTarget: ReviewCommentTarget | null = null;
39 +/** The first line of a range picked with a long press, waiting for its other end. */
40 +export interface PendingReviewCommentRange extends Pick<
41 + ReviewCommentTarget,
42 + "sectionId" | "sectionTitle" | "filePath" | "lines"
43 +> {
44 + readonly lineIndex: number;
45 + readonly rowId: string;
46 +}
47 +
48 +/** The sheet, thread and section a selection was made in, and the diff it was made over. */
49 +export interface ReviewCommentSelectionScope {
50 + readonly key: string;
51 + /** Compared by `===`: a git section's diff hash, or a turn's diff as answered. */
52 + readonly content: string | null;
53 +}
54 +
55 +export interface ReviewCommentSelection {
56 + readonly scope: ReviewCommentSelectionScope | null;
57 + readonly target: ReviewCommentTarget | null;
58 + readonly pending: PendingReviewCommentRange | null;
59 +}
60 +
61 +const EMPTY_SELECTION: ReviewCommentSelection = { scope: null, target: null, pending: null };
62 +let selection = EMPTY_SELECTION;
63 const listeners = new Set<() => void>();
64 const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
65 const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
66 const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
67
45 -function emitChange() {
68 +function setSelection(next: ReviewCommentSelection) {
69 + selection = next;
70 listeners.forEach((listener) => listener());
71 }
72
49 -export function subscribeReviewCommentTarget(listener: () => void): () => void {
73 +function subscribeReviewCommentSelection(listener: () => void): () => void {
74 listeners.add(listener);
75 return () => {
76 listeners.delete(listener);
77 };
78 }
79
56 -export function getReviewCommentTarget(): ReviewCommentTarget | null {
57 - return currentTarget;
80 +export function getReviewCommentSelection(): ReviewCommentSelection {
81 + return selection;
82 }
83
60 -export function setReviewCommentTarget(target: ReviewCommentTarget | null) {
61 - currentTarget = target;
62 - emitChange();
84 +let lastReviewSheetId = 0;
85 +
86 +/** A fresh id per mounted review sheet, so reopening the sheet starts without a selection. */
87 +export function nextReviewSheetId(): number {
88 + lastReviewSheetId += 1;
89 + return lastReviewSheetId;
90 +}
91 +
92 +export function reviewCommentSelectionScope(
93 + sheetId: number,
94 + threadKey: string | null,
95 + section: { readonly id: string; readonly content: string | null } | null,
96 +): ReviewCommentSelectionScope | null {
97 + return threadKey === null || section === null
98 + ? null
99 + : { key: JSON.stringify([sheetId, threadKey, section.id]), content: section.content };
100 +}
101 +
102 +function isSameScope(
103 + a: ReviewCommentSelectionScope | null,
104 + b: ReviewCommentSelectionScope | null,
105 +): boolean {
106 + return a !== null && b !== null && a.key === b.key && a.content === b.content;
107 +}
108 +
109 +export function setReviewCommentTarget(
110 + scope: ReviewCommentSelectionScope,
111 + target: ReviewCommentTarget,
112 +) {
113 + setSelection({ scope, target, pending: null });
114 +}
115 +
116 +/**
117 + * Keeps the pending range: when both ends are the same line the target is a single line, and
118 + * the range still waits for a different end.
119 + */
120 +export function completeReviewCommentRange(
121 + scope: ReviewCommentSelectionScope,
122 + target: ReviewCommentTarget,
123 +) {
124 + setSelection({
125 + scope,
126 + target,
127 + pending: isSameScope(selection.scope, scope) ? selection.pending : null,
128 + });
129 +}
130 +
131 +export function startReviewCommentRange(
132 + scope: ReviewCommentSelectionScope,
133 + pending: PendingReviewCommentRange,
134 +) {
135 + setSelection({ scope, target: null, pending });
136 }
137
138 export function clearReviewCommentTarget() {
66 - currentTarget = null;
67 - emitChange();
139 + setSelection(EMPTY_SELECTION);
140 +}
141 +
142 +/** A selection made in another sheet, thread or section, or over another diff, reads as empty. */
143 +export function selectReviewCommentSelection(
144 + current: ReviewCommentSelection,
145 + scope: ReviewCommentSelectionScope | null,
146 +): ReviewCommentSelection {
147 + return isSameScope(current.scope, scope) ? current : EMPTY_SELECTION;
148 +}
149 +
150 +export function useReviewCommentSelection(
151 + scope: ReviewCommentSelectionScope | null,
152 +): ReviewCommentSelection {
153 + return selectReviewCommentSelection(
154 + useSyncExternalStore(
155 + subscribeReviewCommentSelection,
156 + getReviewCommentSelection,
157 + getReviewCommentSelection,
158 + ),
159 + scope,
160 + );
161 }
162
163 export function useReviewCommentTarget(): ReviewCommentTarget | null {
164 return useSyncExternalStore(
72 - subscribeReviewCommentTarget,
73 - getReviewCommentTarget,
74 - getReviewCommentTarget,
75 - );
165 + subscribeReviewCommentSelection,
166 + getReviewCommentSelection,
167 + getReviewCommentSelection,
168 + ).target;
169 }
170
171 export function getSelectedReviewCommentLines(
apps/mobile/src/features/review/reviewModel.test.ts
+31 -1
@@ -1,6 +1,36 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { applyReviewDiffMetadata, buildReviewParsedDiff } from "./reviewModel";
3 +import {
4 + applyReviewDiffMetadata,
5 + buildReviewParsedDiff,
6 + resolveReviewSelectedSectionId,
7 + type ReviewSectionItem,
8 +} from "./reviewModel";
9 +
10 +function makeSection(id: string): ReviewSectionItem {
11 + return {
12 + id,
13 + kind: id.startsWith("turn:") ? "turn" : "branch-range",
14 + title: id,
15 + subtitle: null,
16 + diff: null,
17 + isLoading: false,
18 + };
19 +}
20 +
21 +describe("resolveReviewSelectedSectionId", () => {
22 + const turn = makeSection("turn:2");
23 + const changes = makeSection("git:branch-range");
24 +
25 + it("shows Changes before anything is picked, not the first section", () => {
26 + expect(resolveReviewSelectedSectionId([turn, changes], null)).toBe("git:branch-range");
27 + });
28 +
29 + it("shows the default while the picked section loads and returns to the pick once it does", () => {
30 + expect(resolveReviewSelectedSectionId([changes], "turn:2")).toBe("git:branch-range");
31 + expect(resolveReviewSelectedSectionId([turn, changes], "turn:2")).toBe("turn:2");
32 + });
33 +});
34
35 describe("buildReviewParsedDiff", () => {
36 it("keeps UI identities compact, stable, and isolated from parser cache keys", () => {
apps/mobile/src/features/review/reviewModel.ts
+27 -2
@@ -499,11 +499,22 @@ export function getReadyReviewCheckpoints(
499 );
500 }
501
502 +export function reviewTurnDiffsBySectionId(
503 + checkpoints: ReadonlyArray<Pick<ThreadCheckpointSummary, "checkpointTurnCount">>,
504 + diffByTurnCount: Readonly<Record<number, string | undefined>>,
505 +): Readonly<Record<string, string | undefined>> {
506 + return Object.fromEntries(
507 + checkpoints.map((checkpoint) => [
508 + getReviewSectionIdForCheckpoint(checkpoint),
509 + diffByTurnCount[checkpoint.checkpointTurnCount],
510 + ]),
511 + );
512 +}
513 +
514 export function buildReviewSectionItems(input: {
515 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
516 readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
517 readonly turnDiffById: Readonly<Record<string, string | undefined>>;
506 - readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
518 readonly loadingGitSections: boolean;
519 }): ReadonlyArray<ReviewSectionItem> {
520 const turnItems = getReadyReviewCheckpoints(input.checkpoints).map<ReviewSectionItem>(
@@ -515,7 +526,7 @@ export function buildReviewSectionItems(input: {
526 title: checkpointTitle(checkpoint),
527 subtitle: checkpointSubtitle(checkpoint),
528 diff: input.turnDiffById[id] ?? null,
518 - isLoading: input.loadingTurnIds[id] === true,
529 + isLoading: false,
530 };
531 },
532 );
@@ -556,6 +567,20 @@ export function getDefaultReviewSectionId(
567 return (sections.find((section) => section.id === CHANGES_SECTION_ID) ?? sections[0])?.id ?? null;
568 }
569
570 +/**
571 + * The store holds only the user's pick. While that section is missing (still loading, or the
572 + * working tree went clean) the default shows, and the pick returns once the section does: the
573 + * thread-feed entry relies on this, as it selects a section before the sections have loaded.
574 + */
575 +export function resolveReviewSelectedSectionId(
576 + sections: ReadonlyArray<ReviewSectionItem>,
577 + storedSectionId: string | null,
578 +): string | null {
579 + return storedSectionId !== null && sections.some((section) => section.id === storedSectionId)
580 + ? storedSectionId
581 + : getDefaultReviewSectionId(sections);
582 +}
583 +
584 export function buildReviewParsedDiff(
585 diff: string | null | undefined,
586 cacheScope: string,
apps/mobile/src/features/review/reviewState.ts
+5 -115
@@ -1,57 +1,25 @@
1 import { useAtomValue } from "@effect/atom-react";
2
3 -import type { EnvironmentId, ReviewDiffPreviewSource, ThreadId } from "@t3tools/contracts";
3 +import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4 import { Atom } from "effect/reactivity";
5
6 import { scopedThreadKey } from "../../lib/scopedEntities";
7 import { appAtomRegistry } from "../../state/atom-registry";
8 +import { clearReviewCommentTarget } from "./reviewCommentSelection";
9 import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";
10
10 -const EMPTY_GIT_REVIEW_SECTIONS = Object.freeze<ReadonlyArray<ReviewDiffPreviewSource>>([]);
11 -const EMPTY_REVIEW_TURN_DIFFS = Object.freeze<Readonly<Record<string, string>>>({});
12 -const EMPTY_REVIEW_LOADING_TURN_IDS = Object.freeze<Readonly<Record<string, boolean>>>({});
13 -const EMPTY_REVIEW_ASYNC_STATE = Object.freeze<ReviewAsyncState>({
14 - loadingTurnIds: EMPTY_REVIEW_LOADING_TURN_IDS,
15 - error: null,
16 -});
11 const EMPTY_REVIEW_SECTION_FILE_IDS = Object.freeze<
12 Readonly<Record<string, ReadonlyArray<string> | undefined>>
13 >({});
20 -const EMPTY_REVIEW_GIT_SECTIONS_ATOM = Atom.make(EMPTY_GIT_REVIEW_SECTIONS).pipe(
21 - Atom.keepAlive,
22 - Atom.withLabel("mobile:review:git-sections:null"),
23 -);
24 -const EMPTY_REVIEW_TURN_DIFFS_ATOM = Atom.make(EMPTY_REVIEW_TURN_DIFFS).pipe(
25 - Atom.keepAlive,
26 - Atom.withLabel("mobile:review:turn-diffs:null"),
27 -);
14 const EMPTY_REVIEW_SELECTED_SECTION_ID_ATOM = Atom.make<string | null>(null).pipe(
15 Atom.keepAlive,
16 Atom.withLabel("mobile:review:selected-section-id:null"),
17 );
32 -const EMPTY_REVIEW_ASYNC_STATE_ATOM = Atom.make(EMPTY_REVIEW_ASYNC_STATE).pipe(
33 - Atom.keepAlive,
34 - Atom.withLabel("mobile:review:async-state:null"),
35 -);
18 const EMPTY_REVIEW_SECTION_FILE_IDS_ATOM = Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
19 Atom.keepAlive,
20 Atom.withLabel("mobile:review:section-file-ids:null"),
21 );
22
41 -const reviewGitSectionsByThreadKeyAtom = Atom.family((threadKey: string) =>
42 - Atom.make(EMPTY_GIT_REVIEW_SECTIONS).pipe(
43 - Atom.keepAlive,
44 - Atom.withLabel(`mobile:review:git-sections:${threadKey}`),
45 - ),
46 -);
47 -
48 -const reviewTurnDiffByThreadKeyAtom = Atom.family((threadKey: string) =>
49 - Atom.make(EMPTY_REVIEW_TURN_DIFFS).pipe(
50 - Atom.keepAlive,
51 - Atom.withLabel(`mobile:review:turn-diffs:${threadKey}`),
52 - ),
53 -);
54 -
23 const reviewSelectedSectionIdByThreadKeyAtom = Atom.family((threadKey: string) =>
24 Atom.make<string | null>(null).pipe(
25 Atom.keepAlive,
@@ -59,13 +27,6 @@ const reviewSelectedSectionIdByThreadKeyAtom = Atom.family((threadKey: string) =
27 ),
28 );
29
62 -const reviewAsyncStateByThreadKeyAtom = Atom.family((threadKey: string) =>
63 - Atom.make(EMPTY_REVIEW_ASYNC_STATE).pipe(
64 - Atom.keepAlive,
65 - Atom.withLabel(`mobile:review:async-state:${threadKey}`),
66 - ),
67 -);
68 -
30 const reviewExpandedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>
31 Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
32 Atom.keepAlive,
@@ -104,10 +65,7 @@ const reviewParsedDiffCacheAtom = Atom.make(() => ({
65
66 export interface ReviewCacheForThread {
67 readonly threadKey: string | null;
107 - readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
108 - readonly turnDiffById: Readonly<Record<string, string>>;
68 readonly selectedSectionId: string | null;
110 - readonly asyncState: ReviewAsyncState;
69 readonly expandedFileIdsBySection: Readonly<Record<string, ReadonlyArray<string> | undefined>>;
70 readonly revealedLargeFileIdsBySection: Readonly<
71 Record<string, ReadonlyArray<string> | undefined>
@@ -115,11 +73,6 @@ export interface ReviewCacheForThread {
73 readonly viewedFileIdsBySection: Readonly<Record<string, ReadonlyArray<string> | undefined>>;
74 }
75
118 -export interface ReviewAsyncState {
119 - readonly loadingTurnIds: Readonly<Record<string, boolean>>;
120 - readonly error: string | null;
121 -}
122 -
76 function buildThreadKey(input: {
77 readonly environmentId?: EnvironmentId;
78 readonly threadId?: ThreadId;
@@ -138,20 +91,11 @@ export function useReviewCacheForThread(input: {
91 readonly threadId?: ThreadId;
92 }): ReviewCacheForThread {
93 const threadKey = buildThreadKey(input);
141 - const gitSections = useAtomValue(
142 - threadKey ? reviewGitSectionsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_GIT_SECTIONS_ATOM,
143 - );
144 - const turnDiffById = useAtomValue(
145 - threadKey ? reviewTurnDiffByThreadKeyAtom(threadKey) : EMPTY_REVIEW_TURN_DIFFS_ATOM,
146 - );
94 const selectedSectionId = useAtomValue(
95 threadKey
96 ? reviewSelectedSectionIdByThreadKeyAtom(threadKey)
97 : EMPTY_REVIEW_SELECTED_SECTION_ID_ATOM,
98 );
152 - const asyncState = useAtomValue(
153 - threadKey ? reviewAsyncStateByThreadKeyAtom(threadKey) : EMPTY_REVIEW_ASYNC_STATE_ATOM,
154 - );
99 const expandedFileIdsBySection = useAtomValue(
100 threadKey
101 ? reviewExpandedFileIdsByThreadKeyAtom(threadKey)
@@ -168,74 +112,20 @@ export function useReviewCacheForThread(input: {
112
113 return {
114 threadKey,
171 - gitSections,
172 - turnDiffById,
115 selectedSectionId,
174 - asyncState,
116 expandedFileIdsBySection,
117 revealedLargeFileIdsBySection,
118 viewedFileIdsBySection,
119 };
120 }
121
181 -export function setReviewGitSections(
182 - threadKey: string,
183 - sections: ReadonlyArray<ReviewDiffPreviewSource>,
184 -): void {
185 - appAtomRegistry.set(reviewGitSectionsByThreadKeyAtom(threadKey), sections);
186 -}
187 -
188 -export function setReviewTurnDiff(threadKey: string, sectionId: string, diff: string): void {
189 - const atom = reviewTurnDiffByThreadKeyAtom(threadKey);
190 - const current = appAtomRegistry.get(atom);
191 - appAtomRegistry.set(atom, {
192 - ...current,
193 - [sectionId]: diff,
194 - });
195 -}
196 -
122 export function setReviewSelectedSectionId(threadKey: string, sectionId: string | null): void {
123 + // A line selection belongs to the section it was made in; switching away drops it, so
124 + // switching back does not bring back a range over lines that may have changed.
125 + clearReviewCommentTarget();
126 appAtomRegistry.set(reviewSelectedSectionIdByThreadKeyAtom(threadKey), sectionId);
127 }
128
201 -function updateReviewAsyncState(
202 - threadKey: string,
203 - update: (current: ReviewAsyncState) => ReviewAsyncState,
204 -): void {
205 - const atom = reviewAsyncStateByThreadKeyAtom(threadKey);
206 - appAtomRegistry.set(atom, update(appAtomRegistry.get(atom)));
207 -}
208 -
209 -export function setReviewTurnDiffLoading(
210 - threadKey: string,
211 - sectionId: string,
212 - isLoading: boolean,
213 -): void {
214 - updateReviewAsyncState(threadKey, (current) => {
215 - const loadingTurnIds = { ...current.loadingTurnIds };
216 - if (isLoading) {
217 - loadingTurnIds[sectionId] = true;
218 - } else {
219 - delete loadingTurnIds[sectionId];
220 - }
221 - return {
222 - ...current,
223 - loadingTurnIds,
224 - };
225 - });
226 -}
227 -
228 -export function setReviewAsyncError(threadKey: string, error: string | null): void {
229 - updateReviewAsyncState(threadKey, (current) => ({
230 - ...current,
231 - error,
232 - }));
233 -}
234 -
235 -export function getReviewAsyncStateSnapshot(threadKey: string): ReviewAsyncState {
236 - return appAtomRegistry.get(reviewAsyncStateByThreadKeyAtom(threadKey));
237 -}
238 -
129 export function updateReviewExpandedFileIds(
130 threadKey: string,
131 sectionId: string,
apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
+3
@@ -48,6 +48,8 @@ export function useNativeReviewDiffHighlighting(input: {
48 ),
49 );
50
51 + // Effect on purpose: the native highlighter's token stream and the scheduler's timers must
52 + // reset with the diff the view shows, and be cancelled when it unmounts.
53 useEffect(() => {
54 traceDiffHighlight("viewport-reset", {
55 reset: diffHighlightTraceId(resetKey),
@@ -65,6 +67,7 @@ export function useNativeReviewDiffHighlighting(input: {
67 return () => scheduler.cancel();
68 }, [enabled, resetKey, rows.length, scheduler, viewportScope]);
69
70 + // Effect on purpose: abortable async highlighting tied to the visible range's lifetime.
71 useEffect(() => {
72 if (!enabled || rows.length === 0 || !viewport.range || viewport.scope !== viewportScope) {
73 return;
apps/mobile/src/features/review/useReviewCommentSelectionController.ts
+79 -138
@@ -1,4 +1,4 @@
1 -import { useCallback, useEffect, useMemo, useState } from "react";
1 +import { useState } from "react";
2 import type { NativeSyntheticEvent } from "react-native";
3 import { useNavigation } from "@react-navigation/native";
4 import * as Arr from "effect/Array";
@@ -6,26 +6,22 @@ import { pipe } from "effect/Function";
6 import * as Result from "effect/Result";
7
8 import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
9 +import { scopedThreadKey } from "../../lib/scopedEntities";
10 import {
11 buildReviewCommentTarget,
12 clearReviewCommentTarget,
13 + completeReviewCommentRange,
14 formatReviewSelectedRangeLabel,
15 getSelectedReviewCommentLines,
16 + nextReviewSheetId,
17 + reviewCommentSelectionScope,
18 setReviewCommentTarget,
15 - useReviewCommentTarget,
19 + startReviewCommentRange,
20 + useReviewCommentSelection,
21 } from "./reviewCommentSelection";
17 -import type {
18 - NativeReviewDiffData,
19 - NativeReviewDiffCommentTarget,
20 -} from "./nativeReviewDiffAdapter";
22 +import type { NativeReviewDiffData } from "./nativeReviewDiffAdapter";
23 import type { ReviewSectionItem } from "./reviewModel";
24
23 -interface PendingNativeCommentSelection extends NativeReviewDiffCommentTarget {
24 - readonly sectionId: string;
25 - readonly sectionTitle: string;
26 - readonly rowId: string;
27 -}
28 -
25 export function useReviewCommentSelectionController(input: {
26 readonly environmentId?: EnvironmentId;
27 readonly threadId?: ThreadId;
@@ -34,11 +30,24 @@ export function useReviewCommentSelectionController(input: {
30 }) {
31 const { environmentId, nativeReviewDiffData, selectedSection, threadId } = input;
32 const navigation = useNavigation();
37 - const activeCommentTarget = useReviewCommentTarget();
38 - const [pendingNativeCommentSelection, setPendingNativeCommentSelection] =
39 - useState<PendingNativeCommentSelection | null>(null);
33 + const [sheetId] = useState(nextReviewSheetId);
34 + // Scoping the selection to this sheet, thread, section and diff drops it when the sheet
35 + // reopens, either changes, or a section comes back with different lines.
36 + const scope = reviewCommentSelectionScope(
37 + sheetId,
38 + environmentId && threadId ? scopedThreadKey(environmentId, threadId) : null,
39 + selectedSection === null
40 + ? null
41 + : {
42 + id: selectedSection.id,
43 + content: selectedSection.source?.diffHash ?? selectedSection.diff,
44 + },
45 + );
46 + const { target: activeCommentTarget, pending: pendingRange } = useReviewCommentSelection(scope);
47 + const hasRangeTarget =
48 + activeCommentTarget !== null && activeCommentTarget.startIndex !== activeCommentTarget.endIndex;
49
41 - const openReviewCommentSheet = useCallback(() => {
50 + const openReviewCommentSheet = () => {
51 if (!environmentId || !threadId) {
52 return;
53 }
@@ -47,152 +56,84 @@ export function useReviewCommentSelectionController(input: {
56 environmentId,
57 threadId,
58 });
50 - }, [environmentId, navigation, threadId]);
59 + };
60
52 - const selectedRowIds = useMemo(() => {
53 - if (
54 - activeCommentTarget &&
55 - activeCommentTarget.sectionTitle === selectedSection?.title &&
56 - activeCommentTarget.startIndex !== activeCommentTarget.endIndex
57 - ) {
58 - return pipe(
61 + const selectedRowIds = hasRangeTarget
62 + ? pipe(
63 getSelectedReviewCommentLines(activeCommentTarget),
64 Arr.filterMap((line) => {
65 const rowId = nativeReviewDiffData.rowIdByCommentLineId.get(line.id);
66 return rowId ? Result.succeed(rowId) : Result.failVoid;
67 }),
64 - );
65 - }
66 -
67 - return pendingNativeCommentSelection ? [pendingNativeCommentSelection.rowId] : [];
68 - }, [
69 - activeCommentTarget,
70 - nativeReviewDiffData.rowIdByCommentLineId,
71 - pendingNativeCommentSelection,
72 - selectedSection?.title,
73 - ]);
68 + )
69 + : pendingRange
70 + ? [pendingRange.rowId]
71 + : [];
72
75 - const selectionAction = useMemo(() => {
76 - if (
77 - activeCommentTarget &&
78 - activeCommentTarget.sectionTitle === selectedSection?.title &&
79 - activeCommentTarget.startIndex !== activeCommentTarget.endIndex
80 - ) {
81 - return {
73 + const selectionAction = hasRangeTarget
74 + ? {
75 title: `Comment on ${formatReviewSelectedRangeLabel(activeCommentTarget)}`,
76 onOpenComment: openReviewCommentSheet,
84 - };
77 + }
78 + : pendingRange
79 + ? { title: "Select range end", onOpenComment: null }
80 + : null;
81 +
82 + const onPressLine = (
83 + event: NativeSyntheticEvent<{
84 + readonly rowId?: string;
85 + readonly gesture?: "tap" | "longPress";
86 + }>,
87 + ) => {
88 + if (!selectedSection || scope === null) {
89 + return;
90 }
91
87 - if (
88 - pendingNativeCommentSelection &&
89 - pendingNativeCommentSelection.sectionTitle === selectedSection?.title
90 - ) {
91 - return {
92 - title: "Select range end",
93 - onOpenComment: null,
94 - };
92 + const { rowId, gesture } = event.nativeEvent;
93 + if (!rowId) {
94 + return;
95 }
96
97 - return null;
98 - }, [
99 - activeCommentTarget,
100 - openReviewCommentSheet,
101 - pendingNativeCommentSelection,
102 - selectedSection?.title,
103 - ]);
104 -
105 - useEffect(() => {
106 - clearReviewCommentTarget();
107 - setPendingNativeCommentSelection(null);
108 - }, [selectedSection?.id]);
109 -
110 - useEffect(() => {
111 - if (activeCommentTarget === null) {
112 - setPendingNativeCommentSelection(null);
97 + const target = nativeReviewDiffData.commentTargetsByRowId.get(rowId);
98 + if (!target) {
99 + return;
100 }
114 - }, [activeCommentTarget]);
115 -
116 - const onPressLine = useCallback(
117 - (
118 - event: NativeSyntheticEvent<{
119 - readonly rowId?: string;
120 - readonly gesture?: "tap" | "longPress";
121 - }>,
122 - ) => {
123 - if (!selectedSection) {
124 - return;
125 - }
126 -
127 - const { rowId, gesture } = event.nativeEvent;
128 - if (!rowId) {
129 - return;
130 - }
101
132 - const target = nativeReviewDiffData.commentTargetsByRowId.get(rowId);
133 - if (!target) {
134 - return;
135 - }
136 -
137 - if (gesture === "longPress") {
138 - clearReviewCommentTarget();
139 - setPendingNativeCommentSelection({
140 - ...target,
141 - sectionId: selectedSection.id,
142 - sectionTitle: selectedSection.title,
143 - rowId,
144 - });
145 - return;
146 - }
147 -
148 - if (
149 - pendingNativeCommentSelection &&
150 - pendingNativeCommentSelection.sectionTitle === selectedSection.title &&
151 - pendingNativeCommentSelection.filePath === target.filePath
152 - ) {
153 - setReviewCommentTarget(
154 - buildReviewCommentTarget(
155 - {
156 - sectionTitle: pendingNativeCommentSelection.sectionTitle,
157 - sectionId: pendingNativeCommentSelection.sectionId,
158 - filePath: pendingNativeCommentSelection.filePath,
159 - lines: pendingNativeCommentSelection.lines,
160 - },
161 - pendingNativeCommentSelection.lineIndex,
162 - target.lineIndex,
163 - ),
164 - );
165 - return;
166 - }
167 -
168 - setPendingNativeCommentSelection(null);
169 - setReviewCommentTarget({
170 - sectionTitle: selectedSection.title,
102 + if (gesture === "longPress") {
103 + startReviewCommentRange(scope, {
104 sectionId: selectedSection.id,
105 + sectionTitle: selectedSection.title,
106 filePath: target.filePath,
107 lines: target.lines,
174 - startIndex: target.lineIndex,
175 - endIndex: target.lineIndex,
108 + lineIndex: target.lineIndex,
109 + rowId,
110 });
177 - openReviewCommentSheet();
178 - },
179 - [
180 - nativeReviewDiffData.commentTargetsByRowId,
181 - openReviewCommentSheet,
182 - pendingNativeCommentSelection,
183 - selectedSection,
184 - ],
185 - );
111 + return;
112 + }
113 +
114 + if (pendingRange && pendingRange.filePath === target.filePath) {
115 + completeReviewCommentRange(
116 + scope,
117 + buildReviewCommentTarget(pendingRange, pendingRange.lineIndex, target.lineIndex),
118 + );
119 + return;
120 + }
121
187 - const clearSelection = useCallback(() => {
188 - clearReviewCommentTarget();
189 - setPendingNativeCommentSelection(null);
190 - }, []);
122 + setReviewCommentTarget(scope, {
123 + sectionTitle: selectedSection.title,
124 + sectionId: selectedSection.id,
125 + filePath: target.filePath,
126 + lines: target.lines,
127 + startIndex: target.lineIndex,
128 + endIndex: target.lineIndex,
129 + });
130 + openReviewCommentSheet();
131 + };
132
133 return {
134 selectedRowIds,
135 selectionAction,
136 onPressLine,
196 - clearSelection,
137 + clearSelection: clearReviewCommentTarget,
138 };
139 }
apps/mobile/src/features/review/useReviewDiffData.ts
+3 -20
@@ -1,4 +1,4 @@
1 -import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
1 +import { useCallback, useContext, useEffect, useMemo, useState } from "react";
2 import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
3
4 import { countReviewCommentContexts, parseReviewInlineComments } from "./reviewCommentSelection";
@@ -126,7 +126,6 @@ export function useReviewDiffData(input: {
126 readonly environmentId: EnvironmentId | undefined;
127 readonly cwd: string | null;
128 readonly selectedSection: ReviewSectionItem | null;
129 - readonly revision: string | undefined;
129 readonly draftMessage: string;
130 }) {
131 const { draftMessage, selectedSection, threadKey } = input;
@@ -170,6 +169,8 @@ export function useReviewDiffData(input: {
169 environmentId,
170 input: {
171 cacheKey: scope,
172 + // Newer preview revisions refresh patches read under an older one.
173 + preview: { cwd },
174 request: {
175 cwd,
176 ...(lazySource.baseRef ? { baseRef: lazySource.baseRef } : {}),
@@ -203,24 +204,6 @@ export function useReviewDiffData(input: {
204 [queries, parsedQuery],
205 ),
206 );
206 - const previousPreview = useRef({
207 - scope,
208 - revision: input.revision,
209 - queries: [] as typeof queries,
210 - });
211 - useEffect(() => {
212 - const previous = previousPreview.current;
213 - previousPreview.current = { scope, revision: input.revision, queries };
214 - for (const query of queries) {
215 - if (!query) continue;
216 - const changed = previous.scope === scope && previous.revision !== input.revision;
217 - const cached =
218 - !previous.queries.includes(query) &&
219 - registry.get(query)._tag !== "Initial" &&
220 - !registry.get(query).waiting;
221 - if (changed || cached) registry.refresh(query);
222 - }
223 - }, [input.revision, queries, registry, scope]);
207 const loadVisibleFile = useCallback(
208 (fileId: string | null, retry = false) => {
209 const index =
apps/mobile/src/features/review/useReviewSections.ts
+70 -138
@@ -1,34 +1,36 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
2 -import { environmentSession } from "../../state/session";
3 -import { useCallback, useEffect, useMemo } from "react";
4 -import * as DateTime from "effect/DateTime";
3 +import { Atom } from "effect/reactivity";
4
6 -import {
7 - deriveThreadCheckpointSummaries,
8 - type ThreadCheckpointSummary,
9 -} from "@t3tools/client-runtime/state/thread-checkpoints";
10 -import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
5 +import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints";
6 +import type { EnvironmentId, ReviewDiffPreviewSource, ThreadId } from "@t3tools/contracts";
7
8 import { useCheckpointDiff } from "../../state/queries";
9 import { useEnvironmentQuery } from "../../state/query";
10 import { useEnvironmentPresentation } from "../../state/presentation";
15 -import { reviewEnvironment } from "../../state/review";
11 +import { lastReviewGitSectionsAtom, reviewEnvironment } from "../../state/review";
12 +import { lastReviewTurnDiffsAtom } from "../../state/reviewTurnDiffs";
13 +import { environmentSession } from "../../state/session";
14 import { useSelectedThreadProjection } from "../../state/use-thread-detail";
15 import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
16 import {
17 buildReviewSectionItems,
20 - getDefaultReviewSectionId,
18 getReadyReviewCheckpoints,
19 getReviewSectionIdForCheckpoint,
20 + resolveReviewSelectedSectionId,
21 + reviewTurnDiffsBySectionId,
22 + type ReviewSectionItem,
23 } from "./reviewModel";
24 -import {
25 - setReviewAsyncError,
26 - setReviewGitSections,
27 - setReviewSelectedSectionId,
28 - setReviewTurnDiff,
29 - setReviewTurnDiffLoading,
30 - type ReviewCacheForThread,
31 -} from "./reviewState";
24 +import { setReviewSelectedSectionId, type ReviewCacheForThread } from "./reviewState";
25 +
26 +const NO_GIT_SECTIONS_ATOM = Atom.make<ReadonlyArray<ReviewDiffPreviewSource>>([]).pipe(
27 + Atom.keepAlive,
28 + Atom.withLabel("mobile:review:git-sections:null"),
29 +);
30 +const NO_TURN_DIFFS_ATOM = Atom.make<Readonly<Record<number, string>>>({}).pipe(
31 + Atom.keepAlive,
32 + Atom.withLabel("mobile:review:turn-diffs:null"),
33 +);
34
35 export function useReviewSections(input: {
36 readonly enabled?: boolean;
@@ -59,97 +61,41 @@ export function useReviewSections(input: {
61 })
62 : null,
63 );
62 - const { loadingTurnIds } = reviewCache.asyncState;
63 -
64 - useEffect(() => {
65 - if (reviewCache.threadKey && diffPreview.data) {
66 - setReviewGitSections(reviewCache.threadKey, diffPreview.data.sources);
67 - }
68 - }, [diffPreview.data, reviewCache.threadKey]);
69 -
70 - const readyCheckpoints = useMemo(
71 - () =>
72 - getReadyReviewCheckpoints(
73 - selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
74 - ),
75 - [selectedThread],
76 - );
77 - const checkpointBySectionId = useMemo(
78 - () =>
79 - Object.fromEntries(
80 - readyCheckpoints.map((checkpoint) => [
81 - getReviewSectionIdForCheckpoint(checkpoint),
82 - checkpoint,
83 - ]),
84 - ) as Record<string, ThreadCheckpointSummary>,
85 - [readyCheckpoints],
64 + const lastGitSections = useAtomValue(
65 + environmentId !== undefined && selectedThreadCwd !== null
66 + ? lastReviewGitSectionsAtom(environmentId, selectedThreadCwd)
67 + : NO_GIT_SECTIONS_ATOM,
68 );
87 - const reviewSections = useMemo(() => {
88 - const sections = buildReviewSectionItems({
89 - checkpoints: readyCheckpoints,
90 - gitSections:
91 - canReadFiles || fileAccess.isPending
92 - ? (diffPreview.data?.sources ?? reviewCache.gitSections)
93 - : [],
94 - turnDiffById: reviewCache.turnDiffById,
95 - loadingTurnIds,
96 - loadingGitSections: fileAccess.isPending || diffPreview.isPending,
97 - });
98 - // Keep the selected section while its grant loads, without displaying cached host files.
99 - return fileAccess.isPending
100 - ? sections.map((section) =>
101 - section.kind === "turn" ? section : { ...section, diff: null, isLoading: true },
102 - )
103 - : sections;
104 - }, [
105 - canReadFiles,
106 - diffPreview.data?.sources,
107 - diffPreview.isPending,
108 - fileAccess.isPending,
109 - loadingTurnIds,
110 - readyCheckpoints,
111 - reviewCache.gitSections,
112 - reviewCache.turnDiffById,
113 - ]);
114 - const selectedSection = useMemo(
115 - () =>
116 - reviewSections.find((section) => section.id === reviewCache.selectedSectionId) ??
117 - reviewSections[0] ??
118 - null,
119 - [reviewCache.selectedSectionId, reviewSections],
69 +
70 + const lastTurnDiffs = useAtomValue(
71 + environmentId !== undefined && threadId !== undefined
72 + ? lastReviewTurnDiffsAtom(environmentId, threadId)
73 + : NO_TURN_DIFFS_ATOM,
74 );
121 - const fallbackSectionId = useMemo(
122 - () => getDefaultReviewSectionId(reviewSections),
123 - [reviewSections],
75 +
76 + const readyCheckpoints = getReadyReviewCheckpoints(
77 + selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
78 );
125 - const selectedSectionIdExists = useMemo(
126 - () =>
127 - reviewCache.selectedSectionId
128 - ? reviewSections.some((section) => section.id === reviewCache.selectedSectionId)
129 - : false,
130 - [reviewCache.selectedSectionId, reviewSections],
79 + const checkpointBySectionId = new Map(
80 + readyCheckpoints.map((checkpoint) => [getReviewSectionIdForCheckpoint(checkpoint), checkpoint]),
81 );
132 -
133 - useEffect(() => {
134 - if (
135 - reviewSections.length > 0 &&
136 - reviewCache.threadKey &&
137 - (!reviewCache.selectedSectionId || !selectedSectionIdExists)
138 - ) {
139 - setReviewSelectedSectionId(reviewCache.threadKey, fallbackSectionId);
140 - }
141 - }, [
142 - fallbackSectionId,
82 + // Turns show their last answered diff; the active turn's live query below overrides it.
83 + // Section ids and the selection do not depend on the live query, so they are resolved first.
84 + const cachedSections = buildReviewSectionItems({
85 + checkpoints: readyCheckpoints,
86 + gitSections:
87 + canReadFiles || fileAccess.isPending ? (diffPreview.data?.sources ?? lastGitSections) : [],
88 + turnDiffById: reviewTurnDiffsBySectionId(readyCheckpoints, lastTurnDiffs),
89 + loadingGitSections: fileAccess.isPending || diffPreview.isPending,
90 + });
91 + const selectedSectionId = resolveReviewSelectedSectionId(
92 + cachedSections,
93 reviewCache.selectedSectionId,
144 - reviewCache.threadKey,
145 - reviewSections.length,
146 - selectedSectionIdExists,
147 - ]);
94 + );
95
149 - let activeCheckpoint = readyCheckpoints[0] ?? null;
150 - if (selectedSection?.kind === "turn") {
151 - activeCheckpoint = checkpointBySectionId[selectedSection.id] ?? activeCheckpoint;
152 - }
96 + const selectedCheckpoint =
97 + selectedSectionId === null ? undefined : checkpointBySectionId.get(selectedSectionId);
98 + const activeCheckpoint = selectedCheckpoint ?? readyCheckpoints[0] ?? null;
99 const activeSectionId = activeCheckpoint
100 ? getReviewSectionIdForCheckpoint(activeCheckpoint)
101 : null;
@@ -162,28 +108,23 @@ export function useReviewSections(input: {
108 ignoreWhitespace: false,
109 });
110
165 - useEffect(() => {
166 - if (!reviewCache.threadKey || !activeSectionId) {
167 - return;
168 - }
169 - setReviewTurnDiffLoading(reviewCache.threadKey, activeSectionId, activeTurnDiff.isPending);
170 - }, [activeSectionId, activeTurnDiff.isPending, reviewCache.threadKey]);
171 -
172 - useEffect(() => {
173 - if (!reviewCache.threadKey || !activeSectionId || !activeTurnDiff.data) {
174 - return;
175 - }
176 - setReviewTurnDiff(reviewCache.threadKey, activeSectionId, activeTurnDiff.data.diff);
177 - setReviewAsyncError(reviewCache.threadKey, null);
178 - }, [activeSectionId, activeTurnDiff.data, reviewCache.threadKey]);
179 -
180 - useEffect(() => {
181 - if (reviewCache.threadKey && activeTurnDiff.error) {
182 - setReviewAsyncError(reviewCache.threadKey, activeTurnDiff.error);
111 + const reviewSections = cachedSections.map((section): ReviewSectionItem => {
112 + if (section.kind === "turn") {
113 + return section.id === activeSectionId
114 + ? {
115 + ...section,
116 + diff: activeTurnDiff.data?.diff ?? section.diff,
117 + isLoading: activeTurnDiff.isPending,
118 + }
119 + : section;
120 }
184 - }, [activeTurnDiff.error, reviewCache.threadKey]);
121 + // Keep the selected section while its grant loads, without displaying cached host files.
122 + return fileAccess.isPending ? { ...section, diff: null, isLoading: true } : section;
123 + });
124 + const selectedSection =
125 + reviewSections.find((section) => section.id === selectedSectionId) ?? null;
126
186 - const refreshSelectedSection = useCallback(async () => {
127 + const refreshSelectedSection = async () => {
128 if (!enabled) {
129 return;
130 }
@@ -192,32 +133,23 @@ export function useReviewSections(input: {
133 return;
134 }
135 diffPreview.refresh();
195 - }, [activeTurnDiff, diffPreview, enabled, selectedSection?.kind]);
136 + };
137
197 - const selectSection = useCallback(
198 - (sectionId: string) => {
199 - if (reviewCache.threadKey) {
200 - setReviewSelectedSectionId(reviewCache.threadKey, sectionId);
201 - }
202 - },
203 - [reviewCache.threadKey],
204 - );
138 + const selectSection = (sectionId: string) => {
139 + if (reviewCache.threadKey) {
140 + setReviewSelectedSectionId(reviewCache.threadKey, sectionId);
141 + }
142 + };
143
144 return {
145 error:
146 diffPreview.error ??
147 activeTurnDiff.error ??
210 - reviewCache.asyncState.error ??
148 (selectedSection === null && !fileAccess.isPending && !canReadFiles
149 ? (fileAccess.error ?? "This connection cannot read local diffs.")
150 : null),
151 isSelectedSectionPending:
152 selectedSection?.kind === "turn" ? activeTurnDiff.isPending : diffPreview.isPending,
216 - loadingGitDiffs: fileAccess.isPending || diffPreview.isPending,
217 - diffPreviewRevision: diffPreview.data
218 - ? DateTime.formatIso(diffPreview.data.generatedAt)
219 - : undefined,
220 - loadingTurnIds,
153 reviewSections,
154 selectedSection,
155 refreshSelectedSection,
apps/mobile/src/state/orchestration.ts
+4 -1
@@ -1,5 +1,8 @@
1 import { createOrchestrationEnvironmentAtoms } from "@t3tools/client-runtime/state/orchestration";
2
3 import { connectionAtomRuntime } from "../connection/runtime";
4 +import { recordReviewTurnDiffAnswer } from "./reviewTurnDiffs";
5
5 -export const orchestrationEnvironment = createOrchestrationEnvironmentAtoms(connectionAtomRuntime);
6 +export const orchestrationEnvironment = createOrchestrationEnvironmentAtoms(connectionAtomRuntime, {
7 + onCheckpointDiffAnswer: recordReviewTurnDiffAnswer,
8 +});
apps/mobile/src/state/review.ts
+27 -1
@@ -1,5 +1,31 @@
1 import { createReviewEnvironmentAtoms } from "@t3tools/client-runtime/state/review";
2 +import type { EnvironmentId, ReviewDiffPreviewSource } from "@t3tools/contracts";
3 +import * as Effect from "effect/Effect";
4 +import { Atom } from "effect/reactivity";
5
6 import { connectionAtomRuntime } from "../connection/runtime";
7
5 -export const reviewEnvironment = createReviewEnvironmentAtoms(connectionAtomRuntime);
8 +const EMPTY_GIT_SECTIONS = Object.freeze<ReadonlyArray<ReviewDiffPreviewSource>>([]);
9 +
10 +// The last answered preview per worktree, so review keeps showing git sections while the live
11 +// query is not mounted. useReviewSections still hides them unless the session grants file reads.
12 +const lastGitSectionsFamily = Atom.family((key: string) =>
13 + Atom.make(EMPTY_GIT_SECTIONS).pipe(
14 + Atom.keepAlive,
15 + Atom.withLabel(`mobile:review:git-sections:${key}`),
16 + ),
17 +);
18 +
19 +export function lastReviewGitSectionsAtom(environmentId: EnvironmentId, cwd: string) {
20 + return lastGitSectionsFamily(JSON.stringify([environmentId, cwd]));
21 +}
22 +
23 +export const reviewEnvironment = createReviewEnvironmentAtoms(connectionAtomRuntime, {
24 + onDiffPreviewAnswer: (target, value, registry) =>
25 + Effect.sync(() =>
26 + registry.set(
27 + lastReviewGitSectionsAtom(target.environmentId, target.input.cwd),
28 + value.sources,
29 + ),
30 + ),
31 +});
apps/mobile/src/state/reviewTurnDiffs.test.ts new
+52
@@ -0,0 +1,52 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +import { EnvironmentId, ThreadId } from "@t3tools/contracts";
3 +import * as Effect from "effect/Effect";
4 +import { AtomRegistry } from "effect/reactivity";
5 +
6 +import { reviewTurnDiffsBySectionId } from "../features/review/reviewModel";
7 +import { lastReviewTurnDiffsAtom, recordReviewTurnDiffAnswer } from "./reviewTurnDiffs";
8 +
9 +const environmentId = EnvironmentId.make("env-1");
10 +const threadId = ThreadId.make("thread-1");
11 +
12 +const answer = (
13 + registry: AtomRegistry.AtomRegistry,
14 + range: { fromTurnCount: number; toTurnCount: number; diff: string },
15 + ignoreWhitespace = false,
16 +) =>
17 + recordReviewTurnDiffAnswer(
18 + { environmentId, input: { ignoreWhitespace } },
19 + { threadId, ...range },
20 + registry,
21 + );
22 +
23 +describe("recordReviewTurnDiffAnswer", () => {
24 + it.effect("keeps loaded turn diffs for review after their queries are gone", () =>
25 + Effect.gen(function* () {
26 + const registry = AtomRegistry.make();
27 + yield* answer(registry, { fromTurnCount: 0, toTurnCount: 1, diff: "turn one" });
28 + yield* answer(registry, { fromTurnCount: 1, toTurnCount: 2, diff: "turn two" });
29 +
30 + // A disconnected sheet mounts no turn query; every loaded turn still has its diff.
31 + const cached = registry.get(lastReviewTurnDiffsAtom(environmentId, threadId));
32 + expect(
33 + reviewTurnDiffsBySectionId(
34 + [{ checkpointTurnCount: 1 }, { checkpointTurnCount: 2 }, { checkpointTurnCount: 3 }],
35 + cached,
36 + ),
37 + ).toEqual({ "turn:1": "turn one", "turn:2": "turn two", "turn:3": undefined });
38 + registry.dispose();
39 + }),
40 + );
41 +
42 + it.effect("ignores ranges and whitespace-ignoring reads, which no review section shows", () =>
43 + Effect.gen(function* () {
44 + const registry = AtomRegistry.make();
45 + yield* answer(registry, { fromTurnCount: 0, toTurnCount: 3, diff: "whole thread" });
46 + yield* answer(registry, { fromTurnCount: 1, toTurnCount: 2, diff: "no whitespace" }, true);
47 +
48 + expect(registry.get(lastReviewTurnDiffsAtom(environmentId, threadId))).toEqual({});
49 + registry.dispose();
50 + }),
51 + );
52 +});
apps/mobile/src/state/reviewTurnDiffs.ts new
+38
@@ -0,0 +1,38 @@
1 +import type { EnvironmentId, OrchestrationGetTurnDiffResult, ThreadId } from "@t3tools/contracts";
2 +import * as Effect from "effect/Effect";
3 +import { Atom, type AtomRegistry } from "effect/reactivity";
4 +
5 +const EMPTY_TURN_DIFFS = Object.freeze<Readonly<Record<number, string>>>({});
6 +
7 +// The last answered diff of each single turn, keyed by its turn count, so review keeps showing
8 +// turns it already loaded while the environment is disconnected and no turn query is mounted.
9 +const lastTurnDiffsFamily = Atom.family((key: string) =>
10 + Atom.make(EMPTY_TURN_DIFFS).pipe(
11 + Atom.keepAlive,
12 + Atom.withLabel(`mobile:review:turn-diffs:${key}`),
13 + ),
14 +);
15 +
16 +export function lastReviewTurnDiffsAtom(environmentId: EnvironmentId, threadId: ThreadId) {
17 + return lastTurnDiffsFamily(JSON.stringify([environmentId, threadId]));
18 +}
19 +
20 +export const recordReviewTurnDiffAnswer = (
21 + target: {
22 + readonly environmentId: EnvironmentId;
23 + readonly input: { readonly ignoreWhitespace?: boolean };
24 + },
25 + value: OrchestrationGetTurnDiffResult,
26 + registry: AtomRegistry.AtomRegistry,
27 +) =>
28 + Effect.sync(() => {
29 + // Review shows one turn with whitespace changes; other ranges and whitespace-ignoring
30 + // reads are not what a review section displays.
31 + if (target.input.ignoreWhitespace === true || value.fromTurnCount !== value.toTurnCount - 1) {
32 + return;
33 + }
34 + const atom = lastReviewTurnDiffsAtom(target.environmentId, value.threadId);
35 + const current = registry.get(atom);
36 + if (current[value.toTurnCount] === value.diff) return;
37 + registry.set(atom, { ...current, [value.toTurnCount]: value.diff });
38 + });
packages/client-runtime/src/state/orchestration.ts
+19 -1
@@ -1,4 +1,8 @@
1 -import { ORCHESTRATION_V2_WS_METHODS, type ThreadId } from "@t3tools/contracts";
1 +import {
2 + ORCHESTRATION_V2_WS_METHODS,
3 + type ThreadId,
4 + type OrchestrationGetTurnDiffResult,
5 +} from "@t3tools/contracts";
6 import * as Effect from "effect/Effect";
7 import * as Option from "effect/Option";
8 import * as Stream from "effect/Stream";
@@ -13,6 +17,7 @@ import {
17 createEnvironmentRpcQueryAtomFamily,
18 createEnvironmentRpcSubscriptionAtomFamily,
19 createEnvironmentCommand,
20 + type QueryAnswerHandler,
21 } from "./runtime.ts";
22 import type { EnvironmentRegistry } from "../connection/registry.ts";
23 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
@@ -23,7 +28,18 @@ import { fetchEnvironmentThreadTranscript } from "./threadTranscriptHttp.ts";
28
29 export function createOrchestrationEnvironmentAtoms<R, E>(
30 runtime: Atom.AtomRuntime<EnvironmentRegistry | HttpClient.HttpClient | R, E>,
31 + options: {
32 + /** Runs on each turn-range and full-thread diff the server answers. */
33 + readonly onCheckpointDiffAnswer?: QueryAnswerHandler<
34 + { readonly ignoreWhitespace?: boolean },
35 + OrchestrationGetTurnDiffResult
36 + >;
37 + } = {},
38 ) {
39 + const onCheckpointDiffAnswer =
40 + options.onCheckpointDiffAnswer === undefined
41 + ? {}
42 + : { onAnswer: options.onCheckpointDiffAnswer };
43 return {
44 threadTranscript: createEnvironmentCommand(runtime, {
45 label: "environment-data:orchestration:thread-transcript",
@@ -85,6 +101,7 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
101 turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
102 label: "environment-data:orchestration:turn-diff",
103 tag: ORCHESTRATION_V2_WS_METHODS.getTurnDiff,
104 + ...onCheckpointDiffAnswer,
105 }),
106 workflowScript: createEnvironmentRpcQueryAtomFamily(runtime, {
107 label: "environment-data:orchestration:workflow-script",
@@ -105,6 +122,7 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
122 fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
123 label: "environment-data:orchestration:full-thread-diff",
124 tag: ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff,
125 + ...onCheckpointDiffAnswer,
126 }),
127 threadFind: createEnvironmentRpcQueryAtomFamily(runtime, {
128 label: "environment-data:orchestration:thread-find",
packages/client-runtime/src/state/review.ts
+37 -6
@@ -1,38 +1,69 @@
1 import {
2 type ReviewDiffPreviewInput,
3 + type ReviewDiffPreviewResult,
4 VcsUnsupportedOperationError,
5 WS_METHODS,
6 } from "@t3tools/contracts";
7 +import * as DateTime from "effect/DateTime";
8 import * as Effect from "effect/Effect";
9 +import * as Option from "effect/Option";
10 import * as Semaphore from "effect/Semaphore";
11 import { request } from "../rpc/client.ts";
9 -import { Atom } from "effect/reactivity";
12 +import { AsyncResult, Atom } from "effect/reactivity";
13
14 import {
15 createAtomCommandScheduler,
16 createEnvironmentRpcCommand,
17 createEnvironmentQueryAtomFamily,
18 createEnvironmentRpcQueryAtomFamily,
19 + type QueryAnswerHandler,
20 } from "./runtime.ts";
21 import type { EnvironmentRegistry } from "../connection/registry.ts";
22
23 export function createReviewEnvironmentAtoms<R, E>(
24 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
25 + options: {
26 + readonly onDiffPreviewAnswer?: QueryAnswerHandler<
27 + ReviewDiffPreviewInput,
28 + ReviewDiffPreviewResult
29 + >;
30 + } = {},
31 ) {
32 const patchReads = Semaphore.makeUnsafe(4);
33 const diffFileScheduler = createAtomCommandScheduler();
34 + const diffPreview = createEnvironmentRpcQueryAtomFamily(runtime, {
35 + label: "environment-data:review:diff-preview",
36 + tag: WS_METHODS.reviewGetDiffPreview,
37 + staleTimeMs: 5_000,
38 + ...(options.onDiffPreviewAnswer === undefined ? {} : { onAnswer: options.onDiffPreviewAnswer }),
39 + });
40 + // A file patch is a slice of the comparison its preview generated, so a newer preview
41 + // revision makes every patch read under the old one stale.
42 + const previewRevisionFamily = Atom.family((key: string) => {
43 + const target = JSON.parse(key) as Parameters<typeof diffPreview>[0];
44 + return Atom.make((get) => {
45 + // A failed refresh keeps the last revision, so an error does not refresh every patch.
46 + // Reading the preview here keeps its query mounted while any of its patches is read.
47 + return Option.match(AsyncResult.value(get(diffPreview(target))), {
48 + onNone: () => null,
49 + onSome: (preview) => DateTime.formatIso(preview.generatedAt),
50 + });
51 + });
52 + });
53 return {
25 - diffPreview: createEnvironmentRpcQueryAtomFamily(runtime, {
26 - label: "environment-data:review:diff-preview",
27 - tag: WS_METHODS.reviewGetDiffPreview,
28 - staleTimeMs: 5_000,
29 - }),
54 + diffPreview,
55 diffFilePatch: createEnvironmentQueryAtomFamily(runtime, {
56 label: "environment-data:review:diff-file-patch",
57 staleTimeMs: 5 * 60_000,
58 + refreshTrigger: ({ environmentId, input }) =>
59 + input.preview === undefined
60 + ? undefined
61 + : previewRevisionFamily(JSON.stringify({ environmentId, input: input.preview })),
62 execute: (input: {
63 request: ReviewDiffPreviewInput & { file: NonNullable<ReviewDiffPreviewInput["file"]> };
64 cacheKey: string;
65 + /** The preview this patch belongs to; its revisions refresh the patch. */
66 + preview?: ReviewDiffPreviewInput;
67 }) =>
68 request(WS_METHODS.reviewGetDiffPreview, input.request).pipe(
69 patchReads.withPermit,