Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { OrchestrationV2ThreadProjection, ScopedThreadRef } from "@t3tools/contracts";
3import { resolveWorkspaceFilePath } from "@t3tools/shared/path";
4import { Atom } from "effect/reactivity";
5import { createContext, useEffect, useRef, type ReactNode } from "react";
6
7import { projectEnvironment } from "../state/projects";
8import { useAtomCommand } from "../state/use-atom-command";
9
10export const FileMetadataThreadContext = createContext<ScopedThreadRef | null>(null);
11const EMPTY_RETENTION = Atom.make(undefined);
12
13/** Keeps fetched metadata across virtualized message-row unmounts. */
14export function FileMetadataThreadProvider(props: {
15 threadRef: ScopedThreadRef | null;
16 cwd: string | undefined;
17 checkpoints: OrchestrationV2ThreadProjection["checkpoints"] | undefined;
18 children?: ReactNode;
19}) {
20 const { threadRef, cwd, checkpoints, children } = props;
21 useAtomValue(threadRef ? projectEnvironment.fileMetadataThread(threadRef) : EMPTY_RETENTION);
22 const invalidate = useAtomCommand(projectEnvironment.invalidateFileMetadata, {
23 reportFailure: false,
24 });
25 const previous = useRef<{
26 environmentId: ScopedThreadRef["environmentId"];
27 threadId: ScopedThreadRef["threadId"];
28 cwd: string;
29 checkpoints: OrchestrationV2ThreadProjection["checkpoints"];
30 } | null>(null);
31
32 useEffect(() => {
33 if (!threadRef || !cwd || !checkpoints) {
34 previous.current = null;
35 return;
36 }
37 const before = previous.current;
38 previous.current = { ...threadRef, cwd, checkpoints };
39 if (
40 !before ||
41 before.environmentId !== threadRef.environmentId ||
42 before.threadId !== threadRef.threadId ||
43 before.cwd !== cwd
44 )
45 return;
46 const oldById = new Map(before.checkpoints.map((checkpoint) => [checkpoint.id, checkpoint]));
47 const paths = new Set<string>();
48 for (const checkpoint of checkpoints) {
49 const old = oldById.get(checkpoint.id);
50 oldById.delete(checkpoint.id);
51 if (old?.files === checkpoint.files && old?.status === checkpoint.status) continue;
52 for (const file of checkpoint.files) paths.add(resolveWorkspaceFilePath(file.path, cwd));
53 for (const file of old?.files ?? []) paths.add(resolveWorkspaceFilePath(file.path, cwd));
54 }
55 for (const checkpoint of oldById.values())
56 for (const file of checkpoint.files) paths.add(resolveWorkspaceFilePath(file.path, cwd));
57 if (paths.size > 0)
58 void invalidate({ environmentId: threadRef.environmentId, input: { paths: [...paths] } });
59 }, [threadRef, cwd, checkpoints, invalidate]);
60
61 return <FileMetadataThreadContext value={threadRef}>{children}</FileMetadataThreadContext>;
62}