Skip to content
TypeScript

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

Julius Marmingea2589f22d3b6
diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
index 8e2e5f185e1..5288929ed89 100644
--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
@@ -30,6 +30,8 @@ import { changeTone, DiffTokenText, ReviewChangeBar } from "./reviewDiffRenderin
import { highlightReviewSelectedLines } from "./highlightReviewSelectedLines";
const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;
+const NO_LINES: ReturnType<typeof getSelectedReviewCommentLines> = [];
+const NO_HIGHLIGHTS: ReturnType<typeof highlightReviewSelectedLines> = {};
type ReviewCommentComposerSheetProps = StaticScreenProps<{
readonly environmentId: EnvironmentId;
@@ -49,21 +51,18 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
const [attachments, setAttachments] = useState<ReadonlyArray<DraftComposerImageAttachment>>([]);
const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
- const selectedLines = useMemo(
- () => (target ? getSelectedReviewCommentLines(target) : []),
- [target],
- );
- const highlightedLinesById = useMemo(
- () =>
- target
- ? highlightReviewSelectedLines({
- filePath: target.filePath,
- lines: selectedLines,
- theme: selectedTheme,
- })
- : {},
- [selectedLines, selectedTheme, target],
- );
+ const { selectedLines, highlightedLinesById } = useMemo(() => {
+ if (!target) return { selectedLines: NO_LINES, highlightedLinesById: NO_HIGHLIGHTS };
+ const lines = getSelectedReviewCommentLines(target);
+ return {
+ selectedLines: lines,
+ highlightedLinesById: highlightReviewSelectedLines({
+ filePath: target.filePath,
+ lines,
+ theme: selectedTheme,
+ }),
+ };
+ }, [selectedTheme, target]);
const firstLine = selectedLines[0] ?? null;
const lastLine = selectedLines[selectedLines.length - 1] ?? null;
const firstNumber = firstLine ? getReviewUnifiedLineNumber(firstLine) : null;
diff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx
index 54e94eab05b..2694d306207 100644
--- a/apps/mobile/src/features/review/ReviewSheet.tsx
+++ b/apps/mobile/src/features/review/ReviewSheet.tsx
@@ -461,7 +461,6 @@ export function ReviewSheet(props: ReviewSheetProps) {
refreshSelectedSection,
selectSection,
isSelectedSectionPending,
- diffPreviewRevision,
} = useReviewSections({
enabled: isEnvironmentReady,
environmentId,
@@ -485,7 +484,6 @@ export function ReviewSheet(props: ReviewSheetProps) {
environmentId,
cwd: selectedThreadCwd,
selectedSection,
- revision: diffPreviewRevision,
draftMessage,
});
// Expo may return null before registration or in older binaries; use the fallback.
diff --git a/apps/mobile/src/features/review/reviewCommentSelection.test.ts b/apps/mobile/src/features/review/reviewCommentSelection.test.ts
index a5a9503b904..59a0bb6bcb6 100644
--- a/apps/mobile/src/features/review/reviewCommentSelection.test.ts
+++ b/apps/mobile/src/features/review/reviewCommentSelection.test.ts
@@ -1,11 +1,19 @@
import { describe, expect, it } from "vite-plus/test";
import {
+ clearReviewCommentTarget,
+ completeReviewCommentRange,
formatReviewCommentContext,
+ getReviewCommentSelection,
+ reviewCommentSelectionScope,
+ selectReviewCommentSelection,
+ setReviewCommentTarget,
+ startReviewCommentRange,
parseReviewCommentMessageSegments,
parseReviewInlineComments,
type ReviewCommentTarget,
} from "./reviewCommentSelection";
+import { setReviewSelectedSectionId } from "./reviewState";
function makeTarget(): ReviewCommentTarget {
return {
@@ -143,3 +151,85 @@ describe("review comment serialization", () => {
expect(comment?.sectionTitle).toBe("Changes > 5");
});
});
+
+describe("review comment selection store", () => {
+ const changes = { id: "git:branch-range", content: "hash-1" };
+ const scope = reviewCommentSelectionScope(1, "env:thread", changes)!;
+ const otherScope = reviewCommentSelectionScope(1, "env:thread", {
+ id: "turn:2",
+ content: "diff",
+ })!;
+ const target = makeTarget();
+ const pending = {
+ sectionId: target.sectionId,
+ sectionTitle: target.sectionTitle,
+ filePath: target.filePath,
+ lines: target.lines,
+ lineIndex: 0,
+ rowId: "row-1",
+ };
+
+ it("keeps a long-pressed range start when replacing an earlier target", () => {
+ setReviewCommentTarget(scope, target);
+ startReviewCommentRange(scope, pending);
+
+ expect(getReviewCommentSelection()).toEqual({ scope, target: null, pending });
+ });
+
+ it("keeps the range start after a same-line range end and drops it on a plain tap", () => {
+ startReviewCommentRange(scope, pending);
+ const sameLine = { ...target, startIndex: 0, endIndex: 0 };
+ completeReviewCommentRange(scope, sameLine);
+ expect(getReviewCommentSelection().pending).toEqual(pending);
+
+ setReviewCommentTarget(scope, sameLine);
+ expect(getReviewCommentSelection().pending).toBeNull();
+ });
+
+ it("clears the target and the range start together", () => {
+ startReviewCommentRange(scope, pending);
+ clearReviewCommentTarget();
+
+ expect(getReviewCommentSelection()).toEqual({ scope: null, target: null, pending: null });
+ });
+
+ it("reads as empty from another thread or section", () => {
+ setReviewCommentTarget(scope, target);
+
+ expect(selectReviewCommentSelection(getReviewCommentSelection(), scope).target).toBe(target);
+ expect(selectReviewCommentSelection(getReviewCommentSelection(), otherScope).target).toBeNull();
+ expect(selectReviewCommentSelection(getReviewCommentSelection(), null).target).toBeNull();
+ });
+
+ it("reads as empty in a reopened review sheet", () => {
+ setReviewCommentTarget(scope, target);
+ const reopenedScope = reviewCommentSelectionScope(2, "env:thread", changes);
+
+ expect(
+ selectReviewCommentSelection(getReviewCommentSelection(), reopenedScope).target,
+ ).toBeNull();
+ });
+
+ it("reads as empty when the section disappears and comes back over a different diff", () => {
+ setReviewCommentTarget(scope, target);
+ // The working tree went clean, so the default showed; the section later returns.
+ const returned = reviewCommentSelectionScope(1, "env:thread", {
+ ...changes,
+ content: "hash-2",
+ });
+ const unchanged = reviewCommentSelectionScope(1, "env:thread", { ...changes });
+
+ expect(selectReviewCommentSelection(getReviewCommentSelection(), returned).target).toBeNull();
+ expect(selectReviewCommentSelection(getReviewCommentSelection(), unchanged).target).toBe(
+ target,
+ );
+ });
+
+ it("drops the selection when the section changes, so switching back starts empty", () => {
+ setReviewCommentTarget(scope, target);
+ setReviewSelectedSectionId("env:thread", "turn:2");
+ setReviewSelectedSectionId("env:thread", "git:branch-range");
+
+ expect(selectReviewCommentSelection(getReviewCommentSelection(), scope).target).toBeNull();
+ });
+});
diff --git a/apps/mobile/src/features/review/reviewCommentSelection.ts b/apps/mobile/src/features/review/reviewCommentSelection.ts
index c8917b4af00..59a3cc5b1db 100644
--- a/apps/mobile/src/features/review/reviewCommentSelection.ts
+++ b/apps/mobile/src/features/review/reviewCommentSelection.ts
@@ -36,43 +36,136 @@ export type ReviewCommentMessageSegment =
readonly comment: ReviewInlineComment;
};
-let currentTarget: ReviewCommentTarget | null = null;
+/** The first line of a range picked with a long press, waiting for its other end. */
+export interface PendingReviewCommentRange extends Pick<
+ ReviewCommentTarget,
+ "sectionId" | "sectionTitle" | "filePath" | "lines"
+> {
+ readonly lineIndex: number;
+ readonly rowId: string;
+}
+
+/** The sheet, thread and section a selection was made in, and the diff it was made over. */
+export interface ReviewCommentSelectionScope {
+ readonly key: string;
+ /** Compared by `===`: a git section's diff hash, or a turn's diff as answered. */
+ readonly content: string | null;
+}
+
+export interface ReviewCommentSelection {
+ readonly scope: ReviewCommentSelectionScope | null;
+ readonly target: ReviewCommentTarget | null;
+ readonly pending: PendingReviewCommentRange | null;
+}
+
+const EMPTY_SELECTION: ReviewCommentSelection = { scope: null, target: null, pending: null };
+let selection = EMPTY_SELECTION;
const listeners = new Set<() => void>();
const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
-function emitChange() {
+function setSelection(next: ReviewCommentSelection) {
+ selection = next;
listeners.forEach((listener) => listener());
}
-export function subscribeReviewCommentTarget(listener: () => void): () => void {
+function subscribeReviewCommentSelection(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
-export function getReviewCommentTarget(): ReviewCommentTarget | null {
- return currentTarget;
+export function getReviewCommentSelection(): ReviewCommentSelection {
+ return selection;
}
-export function setReviewCommentTarget(target: ReviewCommentTarget | null) {
- currentTarget = target;
- emitChange();
+let lastReviewSheetId = 0;
+
+/** A fresh id per mounted review sheet, so reopening the sheet starts without a selection. */
+export function nextReviewSheetId(): number {
+ lastReviewSheetId += 1;
+ return lastReviewSheetId;
+}
+
+export function reviewCommentSelectionScope(
+ sheetId: number,
+ threadKey: string | null,
+ section: { readonly id: string; readonly content: string | null } | null,
+): ReviewCommentSelectionScope | null {
+ return threadKey === null || section === null
+ ? null
+ : { key: JSON.stringify([sheetId, threadKey, section.id]), content: section.content };
+}
+
+function isSameScope(
+ a: ReviewCommentSelectionScope | null,
+ b: ReviewCommentSelectionScope | null,
+): boolean {
+ return a !== null && b !== null && a.key === b.key && a.content === b.content;
+}
+
+export function setReviewCommentTarget(
+ scope: ReviewCommentSelectionScope,
+ target: ReviewCommentTarget,
+) {
+ setSelection({ scope, target, pending: null });
+}
+
+/**
+ * Keeps the pending range: when both ends are the same line the target is a single line, and
+ * the range still waits for a different end.
+ */
+export function completeReviewCommentRange(
+ scope: ReviewCommentSelectionScope,
+ target: ReviewCommentTarget,
+) {
+ setSelection({
+ scope,
+ target,
+ pending: isSameScope(selection.scope, scope) ? selection.pending : null,
+ });
+}
+
+export function startReviewCommentRange(
+ scope: ReviewCommentSelectionScope,
+ pending: PendingReviewCommentRange,
+) {
+ setSelection({ scope, target: null, pending });
}
export function clearReviewCommentTarget() {
- currentTarget = null;
- emitChange();
+ setSelection(EMPTY_SELECTION);
+}
+
+/** A selection made in another sheet, thread or section, or over another diff, reads as empty. */
+export function selectReviewCommentSelection(
+ current: ReviewCommentSelection,
+ scope: ReviewCommentSelectionScope | null,
+): ReviewCommentSelection {
+ return isSameScope(current.scope, scope) ? current : EMPTY_SELECTION;
+}
+
+export function useReviewCommentSelection(
+ scope: ReviewCommentSelectionScope | null,
+): ReviewCommentSelection {
+ return selectReviewCommentSelection(
+ useSyncExternalStore(
+ subscribeReviewCommentSelection,
+ getReviewCommentSelection,
+ getReviewCommentSelection,
+ ),
+ scope,
+ );
}
export function useReviewCommentTarget(): ReviewCommentTarget | null {
return useSyncExternalStore(
- subscribeReviewCommentTarget,
- getReviewCommentTarget,
- getReviewCommentTarget,
- );
+ subscribeReviewCommentSelection,
+ getReviewCommentSelection,
+ getReviewCommentSelection,
+ ).target;
}
export function getSelectedReviewCommentLines(
diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts
index 39d27de3d6d..ef366dc33d4 100644
--- a/apps/mobile/src/features/review/reviewModel.test.ts
+++ b/apps/mobile/src/features/review/reviewModel.test.ts
@@ -1,6 +1,36 @@
import { describe, expect, it } from "vite-plus/test";
-import { applyReviewDiffMetadata, buildReviewParsedDiff } from "./reviewModel";
+import {
+ applyReviewDiffMetadata,
+ buildReviewParsedDiff,
+ resolveReviewSelectedSectionId,
+ type ReviewSectionItem,
+} from "./reviewModel";
+
+function makeSection(id: string): ReviewSectionItem {
+ return {
+ id,
+ kind: id.startsWith("turn:") ? "turn" : "branch-range",
+ title: id,
+ subtitle: null,
+ diff: null,
+ isLoading: false,
+ };
+}
+
+describe("resolveReviewSelectedSectionId", () => {
+ const turn = makeSection("turn:2");
+ const changes = makeSection("git:branch-range");
+
+ it("shows Changes before anything is picked, not the first section", () => {
+ expect(resolveReviewSelectedSectionId([turn, changes], null)).toBe("git:branch-range");
+ });
+
+ it("shows the default while the picked section loads and returns to the pick once it does", () => {
+ expect(resolveReviewSelectedSectionId([changes], "turn:2")).toBe("git:branch-range");
+ expect(resolveReviewSelectedSectionId([turn, changes], "turn:2")).toBe("turn:2");
+ });
+});
describe("buildReviewParsedDiff", () => {
it("keeps UI identities compact, stable, and isolated from parser cache keys", () => {
diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts
index a5b077e139a..bc0e23b3365 100644
--- a/apps/mobile/src/features/review/reviewModel.ts
+++ b/apps/mobile/src/features/review/reviewModel.ts
@@ -499,11 +499,22 @@ export function getReadyReviewCheckpoints(
);
}
+export function reviewTurnDiffsBySectionId(
+ checkpoints: ReadonlyArray<Pick<ThreadCheckpointSummary, "checkpointTurnCount">>,
+ diffByTurnCount: Readonly<Record<number, string | undefined>>,
+): Readonly<Record<string, string | undefined>> {
+ return Object.fromEntries(
+ checkpoints.map((checkpoint) => [
+ getReviewSectionIdForCheckpoint(checkpoint),
+ diffByTurnCount[checkpoint.checkpointTurnCount],
+ ]),
+ );
+}
+
export function buildReviewSectionItems(input: {
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
- readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
readonly loadingGitSections: boolean;
}): ReadonlyArray<ReviewSectionItem> {
const turnItems = getReadyReviewCheckpoints(input.checkpoints).map<ReviewSectionItem>(
@@ -515,7 +526,7 @@ export function buildReviewSectionItems(input: {
title: checkpointTitle(checkpoint),
subtitle: checkpointSubtitle(checkpoint),
diff: input.turnDiffById[id] ?? null,
- isLoading: input.loadingTurnIds[id] === true,
+ isLoading: false,
};
},
);
@@ -556,6 +567,20 @@ export function getDefaultReviewSectionId(
return (sections.find((section) => section.id === CHANGES_SECTION_ID) ?? sections[0])?.id ?? null;
}
+/**
+ * The store holds only the user's pick. While that section is missing (still loading, or the
+ * working tree went clean) the default shows, and the pick returns once the section does: the
+ * thread-feed entry relies on this, as it selects a section before the sections have loaded.
+ */
+export function resolveReviewSelectedSectionId(
+ sections: ReadonlyArray<ReviewSectionItem>,
+ storedSectionId: string | null,
+): string | null {
+ return storedSectionId !== null && sections.some((section) => section.id === storedSectionId)
+ ? storedSectionId
+ : getDefaultReviewSectionId(sections);
+}
+
export function buildReviewParsedDiff(
diff: string | null | undefined,
cacheScope: string,
diff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts
index 4242f5525e8..55a43a64fa4 100644
--- a/apps/mobile/src/features/review/reviewState.ts
+++ b/apps/mobile/src/features/review/reviewState.ts
@@ -1,57 +1,25 @@
import { useAtomValue } from "@effect/atom-react";
-import type { EnvironmentId, ReviewDiffPreviewSource, ThreadId } from "@t3tools/contracts";
+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { appAtomRegistry } from "../../state/atom-registry";
+import { clearReviewCommentTarget } from "./reviewCommentSelection";
import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";
-const EMPTY_GIT_REVIEW_SECTIONS = Object.freeze<ReadonlyArray<ReviewDiffPreviewSource>>([]);
-const EMPTY_REVIEW_TURN_DIFFS = Object.freeze<Readonly<Record<string, string>>>({});
-const EMPTY_REVIEW_LOADING_TURN_IDS = Object.freeze<Readonly<Record<string, boolean>>>({});
-const EMPTY_REVIEW_ASYNC_STATE = Object.freeze<ReviewAsyncState>({
- loadingTurnIds: EMPTY_REVIEW_LOADING_TURN_IDS,
- error: null,
-});
const EMPTY_REVIEW_SECTION_FILE_IDS = Object.freeze<
Readonly<Record<string, ReadonlyArray<string> | undefined>>
>({});
-const EMPTY_REVIEW_GIT_SECTIONS_ATOM = Atom.make(EMPTY_GIT_REVIEW_SECTIONS).pipe(
- Atom.keepAlive,
- Atom.withLabel("mobile:review:git-sections:null"),
-);
-const EMPTY_REVIEW_TURN_DIFFS_ATOM = Atom.make(EMPTY_REVIEW_TURN_DIFFS).pipe(
- Atom.keepAlive,
- Atom.withLabel("mobile:review:turn-diffs:null"),
-);
const EMPTY_REVIEW_SELECTED_SECTION_ID_ATOM = Atom.make<string | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("mobile:review:selected-section-id:null"),
);
-const EMPTY_REVIEW_ASYNC_STATE_ATOM = Atom.make(EMPTY_REVIEW_ASYNC_STATE).pipe(
- Atom.keepAlive,
- Atom.withLabel("mobile:review:async-state:null"),
-);
const EMPTY_REVIEW_SECTION_FILE_IDS_ATOM = Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
Atom.keepAlive,
Atom.withLabel("mobile:review:section-file-ids:null"),
);
-const reviewGitSectionsByThreadKeyAtom = Atom.family((threadKey: string) =>
- Atom.make(EMPTY_GIT_REVIEW_SECTIONS).pipe(
- Atom.keepAlive,
- Atom.withLabel(`mobile:review:git-sections:${threadKey}`),
- ),
-);
-
-const reviewTurnDiffByThreadKeyAtom = Atom.family((threadKey: string) =>
- Atom.make(EMPTY_REVIEW_TURN_DIFFS).pipe(
- Atom.keepAlive,
- Atom.withLabel(`mobile:review:turn-diffs:${threadKey}`),
- ),
-);
-
const reviewSelectedSectionIdByThreadKeyAtom = Atom.family((threadKey: string) =>
Atom.make<string | null>(null).pipe(
Atom.keepAlive,
@@ -59,13 +27,6 @@ const reviewSelectedSectionIdByThreadKeyAtom = Atom.family((threadKey: string) =
),
);
-const reviewAsyncStateByThreadKeyAtom = Atom.family((threadKey: string) =>
- Atom.make(EMPTY_REVIEW_ASYNC_STATE).pipe(
- Atom.keepAlive,
- Atom.withLabel(`mobile:review:async-state:${threadKey}`),
- ),
-);
-
const reviewExpandedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>
Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
Atom.keepAlive,
@@ -104,10 +65,7 @@ const reviewParsedDiffCacheAtom = Atom.make(() => ({
export interface ReviewCacheForThread {
readonly threadKey: string | null;
- readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
- readonly turnDiffById: Readonly<Record<string, string>>;
readonly selectedSectionId: string | null;
- readonly asyncState: ReviewAsyncState;
readonly expandedFileIdsBySection: Readonly<Record<string, ReadonlyArray<string> | undefined>>;
readonly revealedLargeFileIdsBySection: Readonly<
Record<string, ReadonlyArray<string> | undefined>
@@ -115,11 +73,6 @@ export interface ReviewCacheForThread {
readonly viewedFileIdsBySection: Readonly<Record<string, ReadonlyArray<string> | undefined>>;
}
-export interface ReviewAsyncState {
- readonly loadingTurnIds: Readonly<Record<string, boolean>>;
- readonly error: string | null;
-}
-
function buildThreadKey(input: {
readonly environmentId?: EnvironmentId;
readonly threadId?: ThreadId;
@@ -138,20 +91,11 @@ export function useReviewCacheForThread(input: {
readonly threadId?: ThreadId;
}): ReviewCacheForThread {
const threadKey = buildThreadKey(input);
- const gitSections = useAtomValue(
- threadKey ? reviewGitSectionsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_GIT_SECTIONS_ATOM,
- );
- const turnDiffById = useAtomValue(
- threadKey ? reviewTurnDiffByThreadKeyAtom(threadKey) : EMPTY_REVIEW_TURN_DIFFS_ATOM,
- );
const selectedSectionId = useAtomValue(
threadKey
? reviewSelectedSectionIdByThreadKeyAtom(threadKey)
: EMPTY_REVIEW_SELECTED_SECTION_ID_ATOM,
);
- const asyncState = useAtomValue(
- threadKey ? reviewAsyncStateByThreadKeyAtom(threadKey) : EMPTY_REVIEW_ASYNC_STATE_ATOM,
- );
const expandedFileIdsBySection = useAtomValue(
threadKey
? reviewExpandedFileIdsByThreadKeyAtom(threadKey)
@@ -168,74 +112,20 @@ export function useReviewCacheForThread(input: {
return {
threadKey,
- gitSections,
- turnDiffById,
selectedSectionId,
- asyncState,
expandedFileIdsBySection,
revealedLargeFileIdsBySection,
viewedFileIdsBySection,
};
}
-export function setReviewGitSections(
- threadKey: string,
- sections: ReadonlyArray<ReviewDiffPreviewSource>,
-): void {
- appAtomRegistry.set(reviewGitSectionsByThreadKeyAtom(threadKey), sections);
-}
-
-export function setReviewTurnDiff(threadKey: string, sectionId: string, diff: string): void {
- const atom = reviewTurnDiffByThreadKeyAtom(threadKey);
- const current = appAtomRegistry.get(atom);
- appAtomRegistry.set(atom, {
- ...current,
- [sectionId]: diff,
- });
-}
-
export function setReviewSelectedSectionId(threadKey: string, sectionId: string | null): void {
+ // A line selection belongs to the section it was made in; switching away drops it, so
+ // switching back does not bring back a range over lines that may have changed.
+ clearReviewCommentTarget();
appAtomRegistry.set(reviewSelectedSectionIdByThreadKeyAtom(threadKey), sectionId);
}
-function updateReviewAsyncState(
- threadKey: string,
- update: (current: ReviewAsyncState) => ReviewAsyncState,
-): void {
- const atom = reviewAsyncStateByThreadKeyAtom(threadKey);
- appAtomRegistry.set(atom, update(appAtomRegistry.get(atom)));
-}
-
-export function setReviewTurnDiffLoading(
- threadKey: string,
- sectionId: string,
- isLoading: boolean,
-): void {
- updateReviewAsyncState(threadKey, (current) => {
- const loadingTurnIds = { ...current.loadingTurnIds };
- if (isLoading) {
- loadingTurnIds[sectionId] = true;
- } else {
- delete loadingTurnIds[sectionId];
- }
- return {
- ...current,
- loadingTurnIds,
- };
- });
-}
-
-export function setReviewAsyncError(threadKey: string, error: string | null): void {
- updateReviewAsyncState(threadKey, (current) => ({
- ...current,
- error,
- }));
-}
-
-export function getReviewAsyncStateSnapshot(threadKey: string): ReviewAsyncState {
- return appAtomRegistry.get(reviewAsyncStateByThreadKeyAtom(threadKey));
-}
-
export function updateReviewExpandedFileIds(
threadKey: string,
sectionId: string,
diff --git a/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts b/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
index 6c454d94a6b..652b03682b1 100644
--- a/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
+++ b/apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
@@ -48,6 +48,8 @@ export function useNativeReviewDiffHighlighting(input: {
),
);
+ // Effect on purpose: the native highlighter's token stream and the scheduler's timers must
+ // reset with the diff the view shows, and be cancelled when it unmounts.
useEffect(() => {
traceDiffHighlight("viewport-reset", {
reset: diffHighlightTraceId(resetKey),
@@ -65,6 +67,7 @@ export function useNativeReviewDiffHighlighting(input: {
return () => scheduler.cancel();
}, [enabled, resetKey, rows.length, scheduler, viewportScope]);
+ // Effect on purpose: abortable async highlighting tied to the visible range's lifetime.
useEffect(() => {
if (!enabled || rows.length === 0 || !viewport.range || viewport.scope !== viewportScope) {
return;
diff --git a/apps/mobile/src/features/review/useReviewCommentSelectionController.ts b/apps/mobile/src/features/review/useReviewCommentSelectionController.ts
index 923369a5e9e..4a68af28ca8 100644
--- a/apps/mobile/src/features/review/useReviewCommentSelectionController.ts
+++ b/apps/mobile/src/features/review/useReviewCommentSelectionController.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useState } from "react";
import type { NativeSyntheticEvent } from "react-native";
import { useNavigation } from "@react-navigation/native";
import * as Arr from "effect/Array";
@@ -6,26 +6,22 @@ import { pipe } from "effect/Function";
import * as Result from "effect/Result";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { scopedThreadKey } from "../../lib/scopedEntities";
import {
buildReviewCommentTarget,
clearReviewCommentTarget,
+ completeReviewCommentRange,
formatReviewSelectedRangeLabel,
getSelectedReviewCommentLines,
+ nextReviewSheetId,
+ reviewCommentSelectionScope,
setReviewCommentTarget,
- useReviewCommentTarget,
+ startReviewCommentRange,
+ useReviewCommentSelection,
} from "./reviewCommentSelection";
-import type {
- NativeReviewDiffData,
- NativeReviewDiffCommentTarget,
-} from "./nativeReviewDiffAdapter";
+import type { NativeReviewDiffData } from "./nativeReviewDiffAdapter";
import type { ReviewSectionItem } from "./reviewModel";
-interface PendingNativeCommentSelection extends NativeReviewDiffCommentTarget {
- readonly sectionId: string;
- readonly sectionTitle: string;
- readonly rowId: string;
-}
-
export function useReviewCommentSelectionController(input: {
readonly environmentId?: EnvironmentId;
readonly threadId?: ThreadId;
@@ -34,11 +30,24 @@ export function useReviewCommentSelectionController(input: {
}) {
const { environmentId, nativeReviewDiffData, selectedSection, threadId } = input;
const navigation = useNavigation();
- const activeCommentTarget = useReviewCommentTarget();
- const [pendingNativeCommentSelection, setPendingNativeCommentSelection] =
- useState<PendingNativeCommentSelection | null>(null);
+ const [sheetId] = useState(nextReviewSheetId);
+ // Scoping the selection to this sheet, thread, section and diff drops it when the sheet
+ // reopens, either changes, or a section comes back with different lines.
+ const scope = reviewCommentSelectionScope(
+ sheetId,
+ environmentId && threadId ? scopedThreadKey(environmentId, threadId) : null,
+ selectedSection === null
+ ? null
+ : {
+ id: selectedSection.id,
+ content: selectedSection.source?.diffHash ?? selectedSection.diff,
+ },
+ );
+ const { target: activeCommentTarget, pending: pendingRange } = useReviewCommentSelection(scope);
+ const hasRangeTarget =
+ activeCommentTarget !== null && activeCommentTarget.startIndex !== activeCommentTarget.endIndex;
- const openReviewCommentSheet = useCallback(() => {
+ const openReviewCommentSheet = () => {
if (!environmentId || !threadId) {
return;
}
@@ -47,152 +56,84 @@ export function useReviewCommentSelectionController(input: {
environmentId,
threadId,
});
- }, [environmentId, navigation, threadId]);
+ };
- const selectedRowIds = useMemo(() => {
- if (
- activeCommentTarget &&
- activeCommentTarget.sectionTitle === selectedSection?.title &&
- activeCommentTarget.startIndex !== activeCommentTarget.endIndex
- ) {
- return pipe(
+ const selectedRowIds = hasRangeTarget
+ ? pipe(
getSelectedReviewCommentLines(activeCommentTarget),
Arr.filterMap((line) => {
const rowId = nativeReviewDiffData.rowIdByCommentLineId.get(line.id);
return rowId ? Result.succeed(rowId) : Result.failVoid;
}),
- );
- }
-
- return pendingNativeCommentSelection ? [pendingNativeCommentSelection.rowId] : [];
- }, [
- activeCommentTarget,
- nativeReviewDiffData.rowIdByCommentLineId,
- pendingNativeCommentSelection,
- selectedSection?.title,
- ]);
+ )
+ : pendingRange
+ ? [pendingRange.rowId]
+ : [];
- const selectionAction = useMemo(() => {
- if (
- activeCommentTarget &&
- activeCommentTarget.sectionTitle === selectedSection?.title &&
- activeCommentTarget.startIndex !== activeCommentTarget.endIndex
- ) {
- return {
+ const selectionAction = hasRangeTarget
+ ? {
title: `Comment on ${formatReviewSelectedRangeLabel(activeCommentTarget)}`,
onOpenComment: openReviewCommentSheet,
- };
+ }
+ : pendingRange
+ ? { title: "Select range end", onOpenComment: null }
+ : null;
+
+ const onPressLine = (
+ event: NativeSyntheticEvent<{
+ readonly rowId?: string;
+ readonly gesture?: "tap" | "longPress";
+ }>,
+ ) => {
+ if (!selectedSection || scope === null) {
+ return;
}
- if (
- pendingNativeCommentSelection &&
- pendingNativeCommentSelection.sectionTitle === selectedSection?.title
- ) {
- return {
- title: "Select range end",
- onOpenComment: null,
- };
+ const { rowId, gesture } = event.nativeEvent;
+ if (!rowId) {
+ return;
}
- return null;
- }, [
- activeCommentTarget,
- openReviewCommentSheet,
- pendingNativeCommentSelection,
- selectedSection?.title,
- ]);
-
- useEffect(() => {
- clearReviewCommentTarget();
- setPendingNativeCommentSelection(null);
- }, [selectedSection?.id]);
-
- useEffect(() => {
- if (activeCommentTarget === null) {
- setPendingNativeCommentSelection(null);
+ const target = nativeReviewDiffData.commentTargetsByRowId.get(rowId);
+ if (!target) {
+ return;
}
- }, [activeCommentTarget]);
-
- const onPressLine = useCallback(
- (
- event: NativeSyntheticEvent<{
- readonly rowId?: string;
- readonly gesture?: "tap" | "longPress";
- }>,
- ) => {
- if (!selectedSection) {
- return;
- }
-
- const { rowId, gesture } = event.nativeEvent;
- if (!rowId) {
- return;
- }
- const target = nativeReviewDiffData.commentTargetsByRowId.get(rowId);
- if (!target) {
- return;
- }
-
- if (gesture === "longPress") {
- clearReviewCommentTarget();
- setPendingNativeCommentSelection({
- ...target,
- sectionId: selectedSection.id,
- sectionTitle: selectedSection.title,
- rowId,
- });
- return;
- }
-
- if (
- pendingNativeCommentSelection &&
- pendingNativeCommentSelection.sectionTitle === selectedSection.title &&
- pendingNativeCommentSelection.filePath === target.filePath
- ) {
- setReviewCommentTarget(
- buildReviewCommentTarget(
- {
- sectionTitle: pendingNativeCommentSelection.sectionTitle,
- sectionId: pendingNativeCommentSelection.sectionId,
- filePath: pendingNativeCommentSelection.filePath,
- lines: pendingNativeCommentSelection.lines,
- },
- pendingNativeCommentSelection.lineIndex,
- target.lineIndex,
- ),
- );
- return;
- }
-
- setPendingNativeCommentSelection(null);
- setReviewCommentTarget({
- sectionTitle: selectedSection.title,
+ if (gesture === "longPress") {
+ startReviewCommentRange(scope, {
sectionId: selectedSection.id,
+ sectionTitle: selectedSection.title,
filePath: target.filePath,
lines: target.lines,
- startIndex: target.lineIndex,
- endIndex: target.lineIndex,
+ lineIndex: target.lineIndex,
+ rowId,
});
- openReviewCommentSheet();
- },
- [
- nativeReviewDiffData.commentTargetsByRowId,
- openReviewCommentSheet,
- pendingNativeCommentSelection,
- selectedSection,
- ],
- );
+ return;
+ }
+
+ if (pendingRange && pendingRange.filePath === target.filePath) {
+ completeReviewCommentRange(
+ scope,
+ buildReviewCommentTarget(pendingRange, pendingRange.lineIndex, target.lineIndex),
+ );
+ return;
+ }
- const clearSelection = useCallback(() => {
- clearReviewCommentTarget();
- setPendingNativeCommentSelection(null);
- }, []);
+ setReviewCommentTarget(scope, {
+ sectionTitle: selectedSection.title,
+ sectionId: selectedSection.id,
+ filePath: target.filePath,
+ lines: target.lines,
+ startIndex: target.lineIndex,
+ endIndex: target.lineIndex,
+ });
+ openReviewCommentSheet();
+ };
return {
selectedRowIds,
selectionAction,
onPressLine,
- clearSelection,
+ clearSelection: clearReviewCommentTarget,
};
}
diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts
index 7ffd694077f..21cec36eca5 100644
--- a/apps/mobile/src/features/review/useReviewDiffData.ts
+++ b/apps/mobile/src/features/review/useReviewDiffData.ts
@@ -1,4 +1,4 @@
-import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
import { countReviewCommentContexts, parseReviewInlineComments } from "./reviewCommentSelection";
@@ -126,7 +126,6 @@ export function useReviewDiffData(input: {
readonly environmentId: EnvironmentId | undefined;
readonly cwd: string | null;
readonly selectedSection: ReviewSectionItem | null;
- readonly revision: string | undefined;
readonly draftMessage: string;
}) {
const { draftMessage, selectedSection, threadKey } = input;
@@ -170,6 +169,8 @@ export function useReviewDiffData(input: {
environmentId,
input: {
cacheKey: scope,
+ // Newer preview revisions refresh patches read under an older one.
+ preview: { cwd },
request: {
cwd,
...(lazySource.baseRef ? { baseRef: lazySource.baseRef } : {}),
@@ -203,24 +204,6 @@ export function useReviewDiffData(input: {
[queries, parsedQuery],
),
);
- const previousPreview = useRef({
- scope,
- revision: input.revision,
- queries: [] as typeof queries,
- });
- useEffect(() => {
- const previous = previousPreview.current;
- previousPreview.current = { scope, revision: input.revision, queries };
- for (const query of queries) {
- if (!query) continue;
- const changed = previous.scope === scope && previous.revision !== input.revision;
- const cached =
- !previous.queries.includes(query) &&
- registry.get(query)._tag !== "Initial" &&
- !registry.get(query).waiting;
- if (changed || cached) registry.refresh(query);
- }
- }, [input.revision, queries, registry, scope]);
const loadVisibleFile = useCallback(
(fileId: string | null, retry = false) => {
const index =
diff --git a/apps/mobile/src/features/review/useReviewSections.ts b/apps/mobile/src/features/review/useReviewSections.ts
index d7c91941abc..4fd506732e5 100644
--- a/apps/mobile/src/features/review/useReviewSections.ts
+++ b/apps/mobile/src/features/review/useReviewSections.ts
@@ -1,34 +1,36 @@
+import { useAtomValue } from "@effect/atom-react";
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
-import { environmentSession } from "../../state/session";
-import { useCallback, useEffect, useMemo } from "react";
-import * as DateTime from "effect/DateTime";
+import { Atom } from "effect/reactivity";
-import {
- deriveThreadCheckpointSummaries,
- type ThreadCheckpointSummary,
-} from "@t3tools/client-runtime/state/thread-checkpoints";
-import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints";
+import type { EnvironmentId, ReviewDiffPreviewSource, ThreadId } from "@t3tools/contracts";
import { useCheckpointDiff } from "../../state/queries";
import { useEnvironmentQuery } from "../../state/query";
import { useEnvironmentPresentation } from "../../state/presentation";
-import { reviewEnvironment } from "../../state/review";
+import { lastReviewGitSectionsAtom, reviewEnvironment } from "../../state/review";
+import { lastReviewTurnDiffsAtom } from "../../state/reviewTurnDiffs";
+import { environmentSession } from "../../state/session";
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import {
buildReviewSectionItems,
- getDefaultReviewSectionId,
getReadyReviewCheckpoints,
getReviewSectionIdForCheckpoint,
+ resolveReviewSelectedSectionId,
+ reviewTurnDiffsBySectionId,
+ type ReviewSectionItem,
} from "./reviewModel";
-import {
- setReviewAsyncError,
- setReviewGitSections,
- setReviewSelectedSectionId,
- setReviewTurnDiff,
- setReviewTurnDiffLoading,
- type ReviewCacheForThread,
-} from "./reviewState";
+import { setReviewSelectedSectionId, type ReviewCacheForThread } from "./reviewState";
+
+const NO_GIT_SECTIONS_ATOM = Atom.make<ReadonlyArray<ReviewDiffPreviewSource>>([]).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:review:git-sections:null"),
+);
+const NO_TURN_DIFFS_ATOM = Atom.make<Readonly<Record<number, string>>>({}).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:review:turn-diffs:null"),
+);
export function useReviewSections(input: {
readonly enabled?: boolean;
@@ -59,97 +61,41 @@ export function useReviewSections(input: {
})
: null,
);
- const { loadingTurnIds } = reviewCache.asyncState;
-
- useEffect(() => {
- if (reviewCache.threadKey && diffPreview.data) {
- setReviewGitSections(reviewCache.threadKey, diffPreview.data.sources);
- }
- }, [diffPreview.data, reviewCache.threadKey]);
-
- const readyCheckpoints = useMemo(
- () =>
- getReadyReviewCheckpoints(
- selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
- ),
- [selectedThread],
- );
- const checkpointBySectionId = useMemo(
- () =>
- Object.fromEntries(
- readyCheckpoints.map((checkpoint) => [
- getReviewSectionIdForCheckpoint(checkpoint),
- checkpoint,
- ]),
- ) as Record<string, ThreadCheckpointSummary>,
- [readyCheckpoints],
+ const lastGitSections = useAtomValue(
+ environmentId !== undefined && selectedThreadCwd !== null
+ ? lastReviewGitSectionsAtom(environmentId, selectedThreadCwd)
+ : NO_GIT_SECTIONS_ATOM,
);
- const reviewSections = useMemo(() => {
- const sections = buildReviewSectionItems({
- checkpoints: readyCheckpoints,
- gitSections:
- canReadFiles || fileAccess.isPending
- ? (diffPreview.data?.sources ?? reviewCache.gitSections)
- : [],
- turnDiffById: reviewCache.turnDiffById,
- loadingTurnIds,
- loadingGitSections: fileAccess.isPending || diffPreview.isPending,
- });
- // Keep the selected section while its grant loads, without displaying cached host files.
- return fileAccess.isPending
- ? sections.map((section) =>
- section.kind === "turn" ? section : { ...section, diff: null, isLoading: true },
- )
- : sections;
- }, [
- canReadFiles,
- diffPreview.data?.sources,
- diffPreview.isPending,
- fileAccess.isPending,
- loadingTurnIds,
- readyCheckpoints,
- reviewCache.gitSections,
- reviewCache.turnDiffById,
- ]);
- const selectedSection = useMemo(
- () =>
- reviewSections.find((section) => section.id === reviewCache.selectedSectionId) ??
- reviewSections[0] ??
- null,
- [reviewCache.selectedSectionId, reviewSections],
+
+ const lastTurnDiffs = useAtomValue(
+ environmentId !== undefined && threadId !== undefined
+ ? lastReviewTurnDiffsAtom(environmentId, threadId)
+ : NO_TURN_DIFFS_ATOM,
);
- const fallbackSectionId = useMemo(
- () => getDefaultReviewSectionId(reviewSections),
- [reviewSections],
+
+ const readyCheckpoints = getReadyReviewCheckpoints(
+ selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
);
- const selectedSectionIdExists = useMemo(
- () =>
- reviewCache.selectedSectionId
- ? reviewSections.some((section) => section.id === reviewCache.selectedSectionId)
- : false,
- [reviewCache.selectedSectionId, reviewSections],
+ const checkpointBySectionId = new Map(
+ readyCheckpoints.map((checkpoint) => [getReviewSectionIdForCheckpoint(checkpoint), checkpoint]),
);
-
- useEffect(() => {
- if (
- reviewSections.length > 0 &&
- reviewCache.threadKey &&
- (!reviewCache.selectedSectionId || !selectedSectionIdExists)
- ) {
- setReviewSelectedSectionId(reviewCache.threadKey, fallbackSectionId);
- }
- }, [
- fallbackSectionId,
+ // Turns show their last answered diff; the active turn's live query below overrides it.
+ // Section ids and the selection do not depend on the live query, so they are resolved first.
+ const cachedSections = buildReviewSectionItems({
+ checkpoints: readyCheckpoints,
+ gitSections:
+ canReadFiles || fileAccess.isPending ? (diffPreview.data?.sources ?? lastGitSections) : [],
+ turnDiffById: reviewTurnDiffsBySectionId(readyCheckpoints, lastTurnDiffs),
+ loadingGitSections: fileAccess.isPending || diffPreview.isPending,
+ });
+ const selectedSectionId = resolveReviewSelectedSectionId(
+ cachedSections,
reviewCache.selectedSectionId,
- reviewCache.threadKey,
- reviewSections.length,
- selectedSectionIdExists,
- ]);
+ );
- let activeCheckpoint = readyCheckpoints[0] ?? null;
- if (selectedSection?.kind === "turn") {
- activeCheckpoint = checkpointBySectionId[selectedSection.id] ?? activeCheckpoint;
- }
+ const selectedCheckpoint =
+ selectedSectionId === null ? undefined : checkpointBySectionId.get(selectedSectionId);
+ const activeCheckpoint = selectedCheckpoint ?? readyCheckpoints[0] ?? null;
const activeSectionId = activeCheckpoint
? getReviewSectionIdForCheckpoint(activeCheckpoint)
: null;
@@ -162,28 +108,23 @@ export function useReviewSections(input: {
ignoreWhitespace: false,
});
- useEffect(() => {
- if (!reviewCache.threadKey || !activeSectionId) {
- return;
- }
- setReviewTurnDiffLoading(reviewCache.threadKey, activeSectionId, activeTurnDiff.isPending);
- }, [activeSectionId, activeTurnDiff.isPending, reviewCache.threadKey]);
-
- useEffect(() => {
- if (!reviewCache.threadKey || !activeSectionId || !activeTurnDiff.data) {
- return;
- }
- setReviewTurnDiff(reviewCache.threadKey, activeSectionId, activeTurnDiff.data.diff);
- setReviewAsyncError(reviewCache.threadKey, null);
- }, [activeSectionId, activeTurnDiff.data, reviewCache.threadKey]);
-
- useEffect(() => {
- if (reviewCache.threadKey && activeTurnDiff.error) {
- setReviewAsyncError(reviewCache.threadKey, activeTurnDiff.error);
+ const reviewSections = cachedSections.map((section): ReviewSectionItem => {
+ if (section.kind === "turn") {
+ return section.id === activeSectionId
+ ? {
+ ...section,
+ diff: activeTurnDiff.data?.diff ?? section.diff,
+ isLoading: activeTurnDiff.isPending,
+ }
+ : section;
}
- }, [activeTurnDiff.error, reviewCache.threadKey]);
+ // Keep the selected section while its grant loads, without displaying cached host files.
+ return fileAccess.isPending ? { ...section, diff: null, isLoading: true } : section;
+ });
+ const selectedSection =
+ reviewSections.find((section) => section.id === selectedSectionId) ?? null;
- const refreshSelectedSection = useCallback(async () => {
+ const refreshSelectedSection = async () => {
if (!enabled) {
return;
}
@@ -192,32 +133,23 @@ export function useReviewSections(input: {
return;
}
diffPreview.refresh();
- }, [activeTurnDiff, diffPreview, enabled, selectedSection?.kind]);
+ };
- const selectSection = useCallback(
- (sectionId: string) => {
- if (reviewCache.threadKey) {
- setReviewSelectedSectionId(reviewCache.threadKey, sectionId);
- }
- },
- [reviewCache.threadKey],
- );
+ const selectSection = (sectionId: string) => {
+ if (reviewCache.threadKey) {
+ setReviewSelectedSectionId(reviewCache.threadKey, sectionId);
+ }
+ };
return {
error:
diffPreview.error ??
activeTurnDiff.error ??
- reviewCache.asyncState.error ??
(selectedSection === null && !fileAccess.isPending && !canReadFiles
? (fileAccess.error ?? "This connection cannot read local diffs.")
: null),
isSelectedSectionPending:
selectedSection?.kind === "turn" ? activeTurnDiff.isPending : diffPreview.isPending,
- loadingGitDiffs: fileAccess.isPending || diffPreview.isPending,
- diffPreviewRevision: diffPreview.data
- ? DateTime.formatIso(diffPreview.data.generatedAt)
- : undefined,
- loadingTurnIds,
reviewSections,
selectedSection,
refreshSelectedSection,
diff --git a/apps/mobile/src/state/orchestration.ts b/apps/mobile/src/state/orchestration.ts
index 8c6e1738857..766185f2a71 100644
--- a/apps/mobile/src/state/orchestration.ts
+++ b/apps/mobile/src/state/orchestration.ts
@@ -1,5 +1,8 @@
import { createOrchestrationEnvironmentAtoms } from "@t3tools/client-runtime/state/orchestration";
import { connectionAtomRuntime } from "../connection/runtime";
+import { recordReviewTurnDiffAnswer } from "./reviewTurnDiffs";
-export const orchestrationEnvironment = createOrchestrationEnvironmentAtoms(connectionAtomRuntime);
+export const orchestrationEnvironment = createOrchestrationEnvironmentAtoms(connectionAtomRuntime, {
+ onCheckpointDiffAnswer: recordReviewTurnDiffAnswer,
+});
diff --git a/apps/mobile/src/state/review.ts b/apps/mobile/src/state/review.ts
index e4289d1f1d5..2f4a1a5efe0 100644
--- a/apps/mobile/src/state/review.ts
+++ b/apps/mobile/src/state/review.ts
@@ -1,5 +1,31 @@
import { createReviewEnvironmentAtoms } from "@t3tools/client-runtime/state/review";
+import type { EnvironmentId, ReviewDiffPreviewSource } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import { Atom } from "effect/reactivity";
import { connectionAtomRuntime } from "../connection/runtime";
-export const reviewEnvironment = createReviewEnvironmentAtoms(connectionAtomRuntime);
+const EMPTY_GIT_SECTIONS = Object.freeze<ReadonlyArray<ReviewDiffPreviewSource>>([]);
+
+// The last answered preview per worktree, so review keeps showing git sections while the live
+// query is not mounted. useReviewSections still hides them unless the session grants file reads.
+const lastGitSectionsFamily = Atom.family((key: string) =>
+ Atom.make(EMPTY_GIT_SECTIONS).pipe(
+ Atom.keepAlive,
+ Atom.withLabel(`mobile:review:git-sections:${key}`),
+ ),
+);
+
+export function lastReviewGitSectionsAtom(environmentId: EnvironmentId, cwd: string) {
+ return lastGitSectionsFamily(JSON.stringify([environmentId, cwd]));
+}
+
+export const reviewEnvironment = createReviewEnvironmentAtoms(connectionAtomRuntime, {
+ onDiffPreviewAnswer: (target, value, registry) =>
+ Effect.sync(() =>
+ registry.set(
+ lastReviewGitSectionsAtom(target.environmentId, target.input.cwd),
+ value.sources,
+ ),
+ ),
+});
diff --git a/apps/mobile/src/state/reviewTurnDiffs.test.ts b/apps/mobile/src/state/reviewTurnDiffs.test.ts
new file mode 100644
index 00000000000..9fea5264428
--- /dev/null
+++ b/apps/mobile/src/state/reviewTurnDiffs.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "@effect/vitest";
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import { AtomRegistry } from "effect/reactivity";
+
+import { reviewTurnDiffsBySectionId } from "../features/review/reviewModel";
+import { lastReviewTurnDiffsAtom, recordReviewTurnDiffAnswer } from "./reviewTurnDiffs";
+
+const environmentId = EnvironmentId.make("env-1");
+const threadId = ThreadId.make("thread-1");
+
+const answer = (
+ registry: AtomRegistry.AtomRegistry,
+ range: { fromTurnCount: number; toTurnCount: number; diff: string },
+ ignoreWhitespace = false,
+) =>
+ recordReviewTurnDiffAnswer(
+ { environmentId, input: { ignoreWhitespace } },
+ { threadId, ...range },
+ registry,
+ );
+
+describe("recordReviewTurnDiffAnswer", () => {
+ it.effect("keeps loaded turn diffs for review after their queries are gone", () =>
+ Effect.gen(function* () {
+ const registry = AtomRegistry.make();
+ yield* answer(registry, { fromTurnCount: 0, toTurnCount: 1, diff: "turn one" });
+ yield* answer(registry, { fromTurnCount: 1, toTurnCount: 2, diff: "turn two" });
+
+ // A disconnected sheet mounts no turn query; every loaded turn still has its diff.
+ const cached = registry.get(lastReviewTurnDiffsAtom(environmentId, threadId));
+ expect(
+ reviewTurnDiffsBySectionId(
+ [{ checkpointTurnCount: 1 }, { checkpointTurnCount: 2 }, { checkpointTurnCount: 3 }],
+ cached,
+ ),
+ ).toEqual({ "turn:1": "turn one", "turn:2": "turn two", "turn:3": undefined });
+ registry.dispose();
+ }),
+ );
+
+ it.effect("ignores ranges and whitespace-ignoring reads, which no review section shows", () =>
+ Effect.gen(function* () {
+ const registry = AtomRegistry.make();
+ yield* answer(registry, { fromTurnCount: 0, toTurnCount: 3, diff: "whole thread" });
+ yield* answer(registry, { fromTurnCount: 1, toTurnCount: 2, diff: "no whitespace" }, true);
+
+ expect(registry.get(lastReviewTurnDiffsAtom(environmentId, threadId))).toEqual({});
+ registry.dispose();
+ }),
+ );
+});
diff --git a/apps/mobile/src/state/reviewTurnDiffs.ts b/apps/mobile/src/state/reviewTurnDiffs.ts
new file mode 100644
index 00000000000..1816ade56f3
--- /dev/null
+++ b/apps/mobile/src/state/reviewTurnDiffs.ts
@@ -0,0 +1,38 @@
+import type { EnvironmentId, OrchestrationGetTurnDiffResult, ThreadId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import { Atom, type AtomRegistry } from "effect/reactivity";
+
+const EMPTY_TURN_DIFFS = Object.freeze<Readonly<Record<number, string>>>({});
+
+// The last answered diff of each single turn, keyed by its turn count, so review keeps showing
+// turns it already loaded while the environment is disconnected and no turn query is mounted.
+const lastTurnDiffsFamily = Atom.family((key: string) =>
+ Atom.make(EMPTY_TURN_DIFFS).pipe(
+ Atom.keepAlive,
+ Atom.withLabel(`mobile:review:turn-diffs:${key}`),
+ ),
+);
+
+export function lastReviewTurnDiffsAtom(environmentId: EnvironmentId, threadId: ThreadId) {
+ return lastTurnDiffsFamily(JSON.stringify([environmentId, threadId]));
+}
+
+export const recordReviewTurnDiffAnswer = (
+ target: {
+ readonly environmentId: EnvironmentId;
+ readonly input: { readonly ignoreWhitespace?: boolean };
+ },
+ value: OrchestrationGetTurnDiffResult,
+ registry: AtomRegistry.AtomRegistry,
+) =>
+ Effect.sync(() => {
+ // Review shows one turn with whitespace changes; other ranges and whitespace-ignoring
+ // reads are not what a review section displays.
+ if (target.input.ignoreWhitespace === true || value.fromTurnCount !== value.toTurnCount - 1) {
+ return;
+ }
+ const atom = lastReviewTurnDiffsAtom(target.environmentId, value.threadId);
+ const current = registry.get(atom);
+ if (current[value.toTurnCount] === value.diff) return;
+ registry.set(atom, { ...current, [value.toTurnCount]: value.diff });
+ });
diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts
index 24ec67e5b38..5b36e4b2d6d 100644
--- a/packages/client-runtime/src/state/orchestration.ts
+++ b/packages/client-runtime/src/state/orchestration.ts
@@ -1,4 +1,8 @@
-import { ORCHESTRATION_V2_WS_METHODS, type ThreadId } from "@t3tools/contracts";
+import {
+ ORCHESTRATION_V2_WS_METHODS,
+ type ThreadId,
+ type OrchestrationGetTurnDiffResult,
+} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
@@ -13,6 +17,7 @@ import {
createEnvironmentRpcQueryAtomFamily,
createEnvironmentRpcSubscriptionAtomFamily,
createEnvironmentCommand,
+ type QueryAnswerHandler,
} from "./runtime.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
@@ -23,7 +28,18 @@ import { fetchEnvironmentThreadTranscript } from "./threadTranscriptHttp.ts";
export function createOrchestrationEnvironmentAtoms<R, E>(
runtime: Atom.AtomRuntime<EnvironmentRegistry | HttpClient.HttpClient | R, E>,
+ options: {
+ /** Runs on each turn-range and full-thread diff the server answers. */
+ readonly onCheckpointDiffAnswer?: QueryAnswerHandler<
+ { readonly ignoreWhitespace?: boolean },
+ OrchestrationGetTurnDiffResult
+ >;
+ } = {},
) {
+ const onCheckpointDiffAnswer =
+ options.onCheckpointDiffAnswer === undefined
+ ? {}
+ : { onAnswer: options.onCheckpointDiffAnswer };
return {
threadTranscript: createEnvironmentCommand(runtime, {
label: "environment-data:orchestration:thread-transcript",
@@ -85,6 +101,7 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:turn-diff",
tag: ORCHESTRATION_V2_WS_METHODS.getTurnDiff,
+ ...onCheckpointDiffAnswer,
}),
workflowScript: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:workflow-script",
@@ -105,6 +122,7 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:full-thread-diff",
tag: ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff,
+ ...onCheckpointDiffAnswer,
}),
threadFind: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:thread-find",
diff --git a/packages/client-runtime/src/state/review.ts b/packages/client-runtime/src/state/review.ts
index d96181dd70f..691212aedd5 100644
--- a/packages/client-runtime/src/state/review.ts
+++ b/packages/client-runtime/src/state/review.ts
@@ -1,38 +1,69 @@
import {
type ReviewDiffPreviewInput,
+ type ReviewDiffPreviewResult,
VcsUnsupportedOperationError,
WS_METHODS,
} from "@t3tools/contracts";
+import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
import * as Semaphore from "effect/Semaphore";
import { request } from "../rpc/client.ts";
-import { Atom } from "effect/reactivity";
+import { AsyncResult, Atom } from "effect/reactivity";
import {
createAtomCommandScheduler,
createEnvironmentRpcCommand,
createEnvironmentQueryAtomFamily,
createEnvironmentRpcQueryAtomFamily,
+ type QueryAnswerHandler,
} from "./runtime.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
export function createReviewEnvironmentAtoms<R, E>(
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
+ options: {
+ readonly onDiffPreviewAnswer?: QueryAnswerHandler<
+ ReviewDiffPreviewInput,
+ ReviewDiffPreviewResult
+ >;
+ } = {},
) {
const patchReads = Semaphore.makeUnsafe(4);
const diffFileScheduler = createAtomCommandScheduler();
+ const diffPreview = createEnvironmentRpcQueryAtomFamily(runtime, {
+ label: "environment-data:review:diff-preview",
+ tag: WS_METHODS.reviewGetDiffPreview,
+ staleTimeMs: 5_000,
+ ...(options.onDiffPreviewAnswer === undefined ? {} : { onAnswer: options.onDiffPreviewAnswer }),
+ });
+ // A file patch is a slice of the comparison its preview generated, so a newer preview
+ // revision makes every patch read under the old one stale.
+ const previewRevisionFamily = Atom.family((key: string) => {
+ const target = JSON.parse(key) as Parameters<typeof diffPreview>[0];
+ return Atom.make((get) => {
+ // A failed refresh keeps the last revision, so an error does not refresh every patch.
+ // Reading the preview here keeps its query mounted while any of its patches is read.
+ return Option.match(AsyncResult.value(get(diffPreview(target))), {
+ onNone: () => null,
+ onSome: (preview) => DateTime.formatIso(preview.generatedAt),
+ });
+ });
+ });
return {
- diffPreview: createEnvironmentRpcQueryAtomFamily(runtime, {
- label: "environment-data:review:diff-preview",
- tag: WS_METHODS.reviewGetDiffPreview,
- staleTimeMs: 5_000,
- }),
+ diffPreview,
diffFilePatch: createEnvironmentQueryAtomFamily(runtime, {
label: "environment-data:review:diff-file-patch",
staleTimeMs: 5 * 60_000,
+ refreshTrigger: ({ environmentId, input }) =>
+ input.preview === undefined
+ ? undefined
+ : previewRevisionFamily(JSON.stringify({ environmentId, input: input.preview })),
execute: (input: {
request: ReviewDiffPreviewInput & { file: NonNullable<ReviewDiffPreviewInput["file"]> };
cacheKey: string;
+ /** The preview this patch belongs to; its revisions refresh the patch. */
+ preview?: ReviewDiffPreviewInput;
}) =>
request(WS_METHODS.reviewGetDiffPreview, input.request).pipe(
patchReads.withPermit,