1import { useAtomValue } from "@effect/atom-react";
2import {
3 type ArchivedSnapshotEntry,
4 createArchivedThreadSnapshotsAtomFamily,
5 makeArchivedThreadsEnvironmentKey,
6} from "@t3tools/client-runtime/state/threads";
7import type { EnvironmentId } from "@t3tools/contracts";
8import { useCallback, useMemo } from "react";
9
10import { orchestrationEnvironment } from "../state/orchestration";
11import { appAtomRegistry } from "../rpc/atomRegistry";
12
13function archivedSnapshotAtom(environmentId: EnvironmentId) {
14 return orchestrationEnvironment.archivedShellSnapshot({
15 environmentId,
16 input: {},
17 });
18}
19
20const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({
21 getSnapshotAtom: archivedSnapshotAtom,
22 labelPrefix: "web:archived-thread-snapshots",
23});
24
25export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentId): void {
26 appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
27}
28
29export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray<EnvironmentId>): {
30 readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
31 readonly error: string | null;
32 readonly isLoading: boolean;
33 readonly refresh: () => void;
34} {
35 const environmentKey = useMemo(
36 () => makeArchivedThreadsEnvironmentKey(environmentIds),
37 [environmentIds],
38 );
39 const result = useAtomValue(archivedSnapshotsAtom(environmentKey));
40 const refresh = useCallback(() => {
41 for (const environmentId of environmentIds) {
42 appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
43 }
44 }, [environmentIds]);
45
46 return {
47 ...result,
48 refresh,
49 };
50}