Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
3import { Atom } from "effect/reactivity";
4import { useMemo } from "react";
5import { msg, useMessages } from "gt-react-native";
6
7import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints";
8import type { EnvironmentId, ReviewDiffPreviewSource, ThreadId } from "@t3tools/contracts";
9
10import { useCheckpointDiff } from "../../state/queries";
11import { useEnvironmentQuery } from "../../state/query";
12import { useEnvironmentPresentation } from "../../state/presentation";
13import { lastReviewGitSectionsAtom, reviewEnvironment } from "../../state/review";
14import { lastReviewTurnDiffsAtom, reviewTurnDiffText } from "../../state/reviewTurnDiffs";
15import { environmentSession } from "../../state/session";
16import { useSelectedThreadProjection } from "../../state/use-thread-detail";
17import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
18import { useThreadSelection } from "../../state/use-thread-selection";
19import {
20 buildReviewSectionItems,
21 getReadyReviewCheckpoints,
22 getReviewSectionIdForCheckpoint,
23 resolveReviewSelectedSectionId,
24 reviewTurnDiffsBySectionId,
25 type ReviewGitSectionKind,
26 type ReviewSectionItem,
27} from "./reviewModel";
28import { setReviewSelectedSectionId, type ReviewCacheForThread } from "./reviewState";
29
30const NO_GIT_SECTIONS_ATOM = Atom.make<ReadonlyArray<ReviewDiffPreviewSource>>([]).pipe(
31 Atom.keepAlive,
32 Atom.withLabel("mobile:review:git-sections:null"),
33);
34const NO_TURN_DIFFS_ATOM = Atom.make<Readonly<Record<number, string>>>({}).pipe(
35 Atom.keepAlive,
36 Atom.withLabel("mobile:review:turn-diffs:null"),
37);
38
39export function useReviewSections(input: {
40 readonly enabled?: boolean;
41 readonly environmentId?: EnvironmentId;
42 readonly threadId?: ThreadId;
43 readonly reviewCache: ReviewCacheForThread;
44}) {
45 const { environmentId, reviewCache, threadId } = input;
46 const messages = useMessages();
47 const enabled = input.enabled ?? true;
48 const fileAccessSession = useEnvironmentQuery(
49 environmentId === undefined ? null : environmentSession.sessionStateAtom(environmentId),
50 );
51 const fileEnvironment = useEnvironmentPresentation(environmentId ?? null);
52 const fileAccess = resolveFilesystemReadAccess(
53 {
54 isCatalogReady: fileEnvironment.isReady,
55 connection: fileEnvironment.presentation?.connection ?? null,
56 session: fileAccessSession.data,
57 sessionError: fileAccessSession.error,
58 },
59 messages,
60 );
61 const { canReadFiles } = fileAccess;
62 const selectedThread = useSelectedThreadProjection();
63 const { selectedThreadCwd } = useSelectedThreadWorktree();
64 const { selectedThreadProject } = useThreadSelection();
65 const diffPreviewQuery = (sourceKind: ReviewGitSectionKind) =>
66 canReadFiles && enabled && environmentId !== undefined && selectedThreadCwd !== null
67 ? reviewEnvironment.diffPreview({
68 environmentId,
69 input: { cwd: selectedThreadCwd, sourceKind },
70 })
71 : null;
72 const workingTreePreview = useEnvironmentQuery(diffPreviewQuery("working-tree"));
73 const branchPreview = useEnvironmentQuery(diffPreviewQuery("branch-range"));
74 const lastGitSections = useAtomValue(
75 environmentId !== undefined && selectedThreadCwd !== null
76 ? lastReviewGitSectionsAtom(environmentId, selectedThreadCwd)
77 : NO_GIT_SECTIONS_ATOM,
78 );
79
80 const gitSections = (
81 [
82 ["working-tree", workingTreePreview],
83 ["branch-range", branchPreview],
84 ] as const
85 ).flatMap(([kind, preview]) =>
86 (preview.data?.incomplete
87 ? lastGitSections
88 : (preview.data?.sources ?? lastGitSections)
89 ).filter((source) => source.kind === kind),
90 );
91
92 const lastTurnDiffs = useAtomValue(
93 environmentId !== undefined && threadId !== undefined
94 ? lastReviewTurnDiffsAtom(environmentId, threadId)
95 : NO_TURN_DIFFS_ATOM,
96 );
97
98 const readyCheckpoints = getReadyReviewCheckpoints(
99 selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
100 );
101 const checkpointBySectionId = new Map(
102 readyCheckpoints.map((checkpoint) => [getReviewSectionIdForCheckpoint(checkpoint), checkpoint]),
103 );
104 // Turns show their last answered diff; the active turn's live query below overrides it.
105 // Section ids and the selection do not depend on the live query, so they are resolved first.
106 const cachedSections = buildReviewSectionItems({
107 checkpoints: readyCheckpoints,
108 gitSections: canReadFiles || fileAccess.isPending ? gitSections : [],
109 turnDiffById: reviewTurnDiffsBySectionId(readyCheckpoints, lastTurnDiffs),
110 gitSectionStates: {
111 "working-tree": gitSectionState(fileAccess.isPending, workingTreePreview),
112 "branch-range": gitSectionState(fileAccess.isPending, branchPreview),
113 },
114 ...(selectedThreadProject ? { rootName: selectedThreadProject.title } : {}),
115 resolve: messages,
116 });
117 const selectedSectionId = resolveReviewSelectedSectionId(
118 cachedSections,
119 reviewCache.selectedSectionId,
120 );
121
122 const selectedCheckpoint =
123 selectedSectionId === null ? undefined : checkpointBySectionId.get(selectedSectionId);
124 const activeCheckpoint = selectedCheckpoint ?? readyCheckpoints[0] ?? null;
125 const activeSectionId = activeCheckpoint
126 ? getReviewSectionIdForCheckpoint(activeCheckpoint)
127 : null;
128 const activeTurnDiff = useCheckpointDiff({
129 environmentId: enabled ? (environmentId ?? null) : null,
130 threadId: enabled ? (threadId ?? null) : null,
131 fromTurnCount:
132 enabled && activeCheckpoint ? Math.max(0, activeCheckpoint.checkpointTurnCount - 1) : null,
133 toTurnCount: enabled ? (activeCheckpoint?.checkpointTurnCount ?? null) : null,
134 ignoreWhitespace: false,
135 });
136 const activeTurnDiffData = activeTurnDiff.data;
137 const activeTurnDiffText = useMemo(
138 () => (activeTurnDiffData == null ? null : reviewTurnDiffText(activeTurnDiffData)),
139 [activeTurnDiffData],
140 );
141
142 const reviewSections = cachedSections.map((section): ReviewSectionItem => {
143 if (section.kind === "turn") {
144 return section.id === activeSectionId
145 ? {
146 ...section,
147 diff: activeTurnDiffText ?? section.diff,
148 isLoading: activeTurnDiff.isPending,
149 }
150 : section;
151 }
152 // Keep the selected section while its grant loads, without displaying cached host files.
153 return fileAccess.isPending ? { ...section, diff: null, isLoading: true } : section;
154 });
155 const selectedSection =
156 reviewSections.find((section) => section.id === selectedSectionId) ?? null;
157
158 const selectedGitPreview =
159 selectedSection?.kind === "working-tree"
160 ? workingTreePreview
161 : selectedSection?.kind === "branch-range"
162 ? branchPreview
163 : null;
164
165 const refreshSelectedSection = async () => {
166 if (!enabled) {
167 return;
168 }
169 if (selectedSection?.kind === "turn") {
170 activeTurnDiff.refresh();
171 return;
172 }
173 if (selectedGitPreview) {
174 selectedGitPreview.refresh();
175 } else {
176 workingTreePreview.refresh();
177 branchPreview.refresh();
178 }
179 };
180
181 const selectSection = (sectionId: string) => {
182 if (reviewCache.threadKey) {
183 setReviewSelectedSectionId(reviewCache.threadKey, sectionId);
184 }
185 };
186
187 return {
188 error:
189 (selectedSection?.kind === "turn"
190 ? activeTurnDiff.error
191 : (selectedGitPreview?.error ?? null)) ??
192 (selectedSection === null && !fileAccess.isPending && !canReadFiles
193 ? (fileAccess.error ?? messages(msg("This connection cannot read local diffs.")))
194 : null),
195 isSelectedSectionPending:
196 selectedSection?.kind === "turn"
197 ? activeTurnDiff.isPending
198 : (selectedGitPreview?.isPending ?? false),
199 reviewSections,
200 selectedSection,
201 refreshSelectedSection,
202 selectSection,
203 };
204}
205
206function gitSectionState(
207 isFileAccessPending: boolean,
208 preview: { readonly isPending: boolean; readonly error: string | null },
209) {
210 if (isFileAccessPending || preview.isPending) return "loading";
211 return preview.error === null ? null : "failed";
212}