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";
4
5import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints";
6import type { EnvironmentId, ReviewDiffPreviewSource, ThreadId } from "@t3tools/contracts";
7
8import { useCheckpointDiff } from "../../state/queries";
9import { useEnvironmentQuery } from "../../state/query";
10import { useEnvironmentPresentation } from "../../state/presentation";
11import { lastReviewGitSectionsAtom, reviewEnvironment } from "../../state/review";
12import { lastReviewTurnDiffsAtom } from "../../state/reviewTurnDiffs";
13import { environmentSession } from "../../state/session";
14import { useSelectedThreadProjection } from "../../state/use-thread-detail";
15import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
16import {
17 buildReviewSectionItems,
18 getReadyReviewCheckpoints,
19 getReviewSectionIdForCheckpoint,
20 resolveReviewSelectedSectionId,
21 reviewTurnDiffsBySectionId,
22 type ReviewSectionItem,
23} from "./reviewModel";
24import { setReviewSelectedSectionId, type ReviewCacheForThread } from "./reviewState";
25
26const NO_GIT_SECTIONS_ATOM = Atom.make<ReadonlyArray<ReviewDiffPreviewSource>>([]).pipe(
27 Atom.keepAlive,
28 Atom.withLabel("mobile:review:git-sections:null"),
29);
30const NO_TURN_DIFFS_ATOM = Atom.make<Readonly<Record<number, string>>>({}).pipe(
31 Atom.keepAlive,
32 Atom.withLabel("mobile:review:turn-diffs:null"),
33);
34
35export function useReviewSections(input: {
36 readonly enabled?: boolean;
37 readonly environmentId?: EnvironmentId;
38 readonly threadId?: ThreadId;
39 readonly reviewCache: ReviewCacheForThread;
40}) {
41 const { environmentId, reviewCache, threadId } = input;
42 const enabled = input.enabled ?? true;
43 const fileAccessSession = useEnvironmentQuery(
44 environmentId === undefined ? null : environmentSession.sessionStateAtom(environmentId),
45 );
46 const fileEnvironment = useEnvironmentPresentation(environmentId ?? null);
47 const fileAccess = resolveFilesystemReadAccess({
48 isCatalogReady: fileEnvironment.isReady,
49 connection: fileEnvironment.presentation?.connection ?? null,
50 session: fileAccessSession.data,
51 sessionError: fileAccessSession.error,
52 });
53 const { canReadFiles } = fileAccess;
54 const selectedThread = useSelectedThreadProjection();
55 const { selectedThreadCwd } = useSelectedThreadWorktree();
56 const diffPreview = useEnvironmentQuery(
57 canReadFiles && enabled && environmentId !== undefined && selectedThreadCwd !== null
58 ? reviewEnvironment.diffPreview({
59 environmentId,
60 input: { cwd: selectedThreadCwd },
61 })
62 : null,
63 );
64 const lastGitSections = useAtomValue(
65 environmentId !== undefined && selectedThreadCwd !== null
66 ? lastReviewGitSectionsAtom(environmentId, selectedThreadCwd)
67 : NO_GIT_SECTIONS_ATOM,
68 );
69
70 const lastTurnDiffs = useAtomValue(
71 environmentId !== undefined && threadId !== undefined
72 ? lastReviewTurnDiffsAtom(environmentId, threadId)
73 : NO_TURN_DIFFS_ATOM,
74 );
75
76 const readyCheckpoints = getReadyReviewCheckpoints(
77 selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
78 );
79 const checkpointBySectionId = new Map(
80 readyCheckpoints.map((checkpoint) => [getReviewSectionIdForCheckpoint(checkpoint), checkpoint]),
81 );
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,
94 );
95
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;
102 const activeTurnDiff = useCheckpointDiff({
103 environmentId: enabled ? (environmentId ?? null) : null,
104 threadId: enabled ? (threadId ?? null) : null,
105 fromTurnCount:
106 enabled && activeCheckpoint ? Math.max(0, activeCheckpoint.checkpointTurnCount - 1) : null,
107 toTurnCount: enabled ? (activeCheckpoint?.checkpointTurnCount ?? null) : null,
108 ignoreWhitespace: false,
109 });
110
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 }
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
127 const refreshSelectedSection = async () => {
128 if (!enabled) {
129 return;
130 }
131 if (selectedSection?.kind === "turn") {
132 activeTurnDiff.refresh();
133 return;
134 }
135 diffPreview.refresh();
136 };
137
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 ??
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,
153 reviewSections,
154 selectedSection,
155 refreshSelectedSection,
156 selectSection,
157 };
158}