Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

reviewState.ts

326 lines10.7 KB

1import { useAtomValue } from "@effect/atom-react";
2​
3import type { EnvironmentId, ReviewDiffPreviewSource, ThreadId } from "@t3tools/contracts";
4import { Atom } from "effect/reactivity";
5​
6import { scopedThreadKey } from "../../lib/scopedEntities";
7import { appAtomRegistry } from "../../state/atom-registry";
8import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";
9​
10const EMPTY_GIT_REVIEW_SECTIONS = Object.freeze<ReadonlyArray<ReviewDiffPreviewSource>>([]);
11const EMPTY_REVIEW_TURN_DIFFS = Object.freeze<Readonly<Record<string, string>>>({});
12const EMPTY_REVIEW_LOADING_TURN_IDS = Object.freeze<Readonly<Record<string, boolean>>>({});
13const EMPTY_REVIEW_ASYNC_STATE = Object.freeze<ReviewAsyncState>({
14 loadingTurnIds: EMPTY_REVIEW_LOADING_TURN_IDS,
15 error: null,
16});
17const EMPTY_REVIEW_SECTION_FILE_IDS = Object.freeze<
18 Readonly<Record<string, ReadonlyArray<string> | undefined>>
19>({});
20const EMPTY_REVIEW_GIT_SECTIONS_ATOM = Atom.make(EMPTY_GIT_REVIEW_SECTIONS).pipe(
21 Atom.keepAlive,
22 Atom.withLabel("mobile:review:git-sections:null"),
23);
24const EMPTY_REVIEW_TURN_DIFFS_ATOM = Atom.make(EMPTY_REVIEW_TURN_DIFFS).pipe(
25 Atom.keepAlive,
26 Atom.withLabel("mobile:review:turn-diffs:null"),
27);
28const EMPTY_REVIEW_SELECTED_SECTION_ID_ATOM = Atom.make<string | null>(null).pipe(
29 Atom.keepAlive,
30 Atom.withLabel("mobile:review:selected-section-id:null"),
31);
32const EMPTY_REVIEW_ASYNC_STATE_ATOM = Atom.make(EMPTY_REVIEW_ASYNC_STATE).pipe(
33 Atom.keepAlive,
34 Atom.withLabel("mobile:review:async-state:null"),
35);
36const EMPTY_REVIEW_SECTION_FILE_IDS_ATOM = Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
37 Atom.keepAlive,
38 Atom.withLabel("mobile:review:section-file-ids:null"),
39);
40​
41const 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​
48const 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​
55const reviewSelectedSectionIdByThreadKeyAtom = Atom.family((threadKey: string) =>
56 Atom.make<string | null>(null).pipe(
57 Atom.keepAlive,
58 Atom.withLabel(`mobile:review:selected-section-id:${threadKey}`),
59 ),
60);
61​
62const 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​
69const reviewExpandedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>
70 Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
71 Atom.keepAlive,
72 Atom.withLabel(`mobile:review:expanded-file-ids:${threadKey}`),
73 ),
74);
75​
76const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>
77 Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
78 Atom.keepAlive,
79 Atom.withLabel(`mobile:review:revealed-large-file-ids:${threadKey}`),
80 ),
81);
82​
83const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>
84 Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
85 Atom.keepAlive,
86 Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`),
87 ),
88);
89​
90export const MAX_CACHED_REVIEW_DIFFS = 8;
91// This bounds source string length, not the parsed or native heap size.
92export const MAX_CACHED_REVIEW_SOURCE_CHARACTERS = 4 * 1024 * 1024;
93​
94interface CachedReviewParsedDiff {
95 readonly diff: string | null;
96 readonly parsed: ReviewParsedDiff;
97 readonly sourceCharacterCount: number;
99​
100const reviewParsedDiffCacheAtom = Atom.make(() => ({
101 entries: new Map<string, CachedReviewParsedDiff>(),
102 sourceCharacterCount: 0,
103})).pipe(Atom.keepAlive, Atom.withLabel("mobile:review:parsed-diffs"));
104​
105export interface ReviewCacheForThread {
106 readonly threadKey: string | null;
107 readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
108 readonly turnDiffById: Readonly<Record<string, string>>;
109 readonly selectedSectionId: string | null;
110 readonly asyncState: ReviewAsyncState;
111 readonly expandedFileIdsBySection: Readonly<Record<string, ReadonlyArray<string> | undefined>>;
112 readonly revealedLargeFileIdsBySection: Readonly<
113 Record<string, ReadonlyArray<string> | undefined>
114 >;
115 readonly viewedFileIdsBySection: Readonly<Record<string, ReadonlyArray<string> | undefined>>;
117​
118export interface ReviewAsyncState {
119 readonly loadingTurnIds: Readonly<Record<string, boolean>>;
120 readonly error: string | null;
122​
123function buildThreadKey(input: {
124 readonly environmentId?: EnvironmentId;
125 readonly threadId?: ThreadId;
126}): string | null {
127 return input.environmentId && input.threadId
128 ? scopedThreadKey(input.environmentId, input.threadId)
129 : null;
131​
132function buildSectionCacheKey(threadKey: string, sectionId: string): string {
133 return `${threadKey}:${sectionId}`;
135​
136export function useReviewCacheForThread(input: {
137 readonly environmentId?: EnvironmentId;
138 readonly threadId?: ThreadId;
139}): ReviewCacheForThread {
140 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 );
147 const selectedSectionId = useAtomValue(
148 threadKey
149 ? reviewSelectedSectionIdByThreadKeyAtom(threadKey)
150 : EMPTY_REVIEW_SELECTED_SECTION_ID_ATOM,
151 );
152 const asyncState = useAtomValue(
153 threadKey ? reviewAsyncStateByThreadKeyAtom(threadKey) : EMPTY_REVIEW_ASYNC_STATE_ATOM,
154 );
155 const expandedFileIdsBySection = useAtomValue(
156 threadKey
157 ? reviewExpandedFileIdsByThreadKeyAtom(threadKey)
158 : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,
159 );
160 const revealedLargeFileIdsBySection = useAtomValue(
161 threadKey
162 ? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey)
163 : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,
164 );
165 const viewedFileIdsBySection = useAtomValue(
166 threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,
167 );
168​
169 return {
170 threadKey,
171 gitSections,
172 turnDiffById,
173 selectedSectionId,
174 asyncState,
175 expandedFileIdsBySection,
176 revealedLargeFileIdsBySection,
177 viewedFileIdsBySection,
178 };
180​
181export function setReviewGitSections(
182 threadKey: string,
183 sections: ReadonlyArray<ReviewDiffPreviewSource>,
184): void {
185 appAtomRegistry.set(reviewGitSectionsByThreadKeyAtom(threadKey), sections);
187​
188export 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 });
196​
197export function setReviewSelectedSectionId(threadKey: string, sectionId: string | null): void {
198 appAtomRegistry.set(reviewSelectedSectionIdByThreadKeyAtom(threadKey), sectionId);
200​
201function updateReviewAsyncState(
202 threadKey: string,
203 update: (current: ReviewAsyncState) => ReviewAsyncState,
204): void {
205 const atom = reviewAsyncStateByThreadKeyAtom(threadKey);
206 appAtomRegistry.set(atom, update(appAtomRegistry.get(atom)));
208​
209export 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 });
227​
228export function setReviewAsyncError(threadKey: string, error: string | null): void {
229 updateReviewAsyncState(threadKey, (current) => ({
230 ...current,
231 error,
232 }));
234​
235export function getReviewAsyncStateSnapshot(threadKey: string): ReviewAsyncState {
236 return appAtomRegistry.get(reviewAsyncStateByThreadKeyAtom(threadKey));
238​
239export function updateReviewExpandedFileIds(
240 threadKey: string,
241 sectionId: string,
242 update: (current: ReadonlyArray<string> | undefined) => ReadonlyArray<string> | undefined,
243): void {
244 const atom = reviewExpandedFileIdsByThreadKeyAtom(threadKey);
245 const current = appAtomRegistry.get(atom);
246 const nextValue = update(current[sectionId]);
247 appAtomRegistry.set(atom, {
248 ...current,
249 [sectionId]: nextValue,
250 });
252​
253export function updateReviewViewedFileIds(
254 threadKey: string,
255 sectionId: string,
256 update: (current: ReadonlyArray<string> | undefined) => ReadonlyArray<string> | undefined,
257): void {
258 const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey);
259 const current = appAtomRegistry.get(atom);
260 const nextValue = update(current[sectionId]);
261 appAtomRegistry.set(atom, {
262 ...current,
263 [sectionId]: nextValue,
264 });
266​
267export function getReviewParsedDiffSourceCharacterCount(input: {
268 readonly threadKey: string;
269 readonly sectionId: string;
270 readonly diff: string | null;
271}): number {
272 const sourceCharacterCount = input.diff?.length ?? 0;
273 const cache = appAtomRegistry.get(reviewParsedDiffCacheAtom);
274 const cached = cache.entries.get(buildSectionCacheKey(input.threadKey, input.sectionId));
275 return cached && cached.diff === (input.diff?.trim() ?? null)
276 ? Math.max(sourceCharacterCount, cached.sourceCharacterCount)
277 : sourceCharacterCount;
279​
280export function getCachedReviewParsedDiff(input: {
281 readonly threadKey: string | null;
282 readonly sectionId: string | null;
283 readonly diff: string | null | undefined;
284}): ReviewParsedDiff {
285 if (!input.threadKey || !input.sectionId) {
286 return buildReviewParsedDiff(input.diff, input.sectionId ?? "mobile-review");
287 }
288​
289 const cacheKey = buildSectionCacheKey(input.threadKey, input.sectionId);
290 const normalizedDiff = input.diff?.trim() ?? null;
291 const cache = appAtomRegistry.get(reviewParsedDiffCacheAtom);
292 const cached = cache.entries.get(cacheKey);
293 if (cached && cached.diff === normalizedDiff) {
294 cache.entries.delete(cacheKey);
295 cache.entries.set(cacheKey, cached);
296 return cached.parsed;
297 }
298​
299 const parsed = buildReviewParsedDiff(input.diff, input.sectionId);
300 if (cached) {
301 cache.entries.delete(cacheKey);
302 cache.sourceCharacterCount -= cached.sourceCharacterCount;
303 }
304 const sourceCharacterCount = input.diff?.length ?? 0;
305 if (sourceCharacterCount > MAX_CACHED_REVIEW_SOURCE_CHARACTERS) {
306 return parsed;
307 }
308​
309 for (const [oldestKey, oldest] of cache.entries) {
310 if (
311 cache.entries.size < MAX_CACHED_REVIEW_DIFFS &&
312 cache.sourceCharacterCount + sourceCharacterCount <= MAX_CACHED_REVIEW_SOURCE_CHARACTERS
313 ) {
314 break;
315 }
316 cache.entries.delete(oldestKey);
317 cache.sourceCharacterCount -= oldest.sourceCharacterCount;
318 }
319 cache.entries.set(cacheKey, {
320 diff: normalizedDiff,
321 parsed,
322 sourceCharacterCount,
323 });
324 cache.sourceCharacterCount += sourceCharacterCount;
325 return parsed;