1import { useAtomValue } from "@effect/atom-react";
2import {
3 createEnvironmentThreadDetailAtoms,
4 createEnvironmentThreadShellAtoms,
5 createEnvironmentThreadStateAtoms,
6 EMPTY_ENVIRONMENT_THREAD_STATE,
7 type EnvironmentThreadState,
8 createThreadEnvironmentAtoms,
9} from "@t3tools/client-runtime/state/threads";
10import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
11import * as Option from "effect/Option";
12import { AsyncResult, Atom } from "effect/reactivity";
13
14import { environmentCatalog } from "../connection/catalog";
15import { connectionAtomRuntime } from "../connection/runtime";
16import { environmentSnapshotAtom } from "./shell";
17
18export const threadEnvironment = createThreadEnvironmentAtoms(
19 connectionAtomRuntime,
20 environmentSnapshotAtom,
21);
22export const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime);
23export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(
24 environmentThreads.stateAtom,
25);
26export const environmentThreadShells = createEnvironmentThreadShellAtoms({
27 catalogValueAtom: environmentCatalog.catalogValueAtom,
28 snapshotAtom: threadEnvironment.snapshotAtom,
29});
30
31const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(
32 Atom.withLabel("mobile-environment-thread:empty"),
33);
34
35export function useEnvironmentThread(
36 environmentId: EnvironmentId | null,
37 threadId: ThreadId | null,
38): EnvironmentThreadState {
39 const result = useAtomValue(
40 environmentId !== null && threadId !== null
41 ? environmentThreads.stateAtom(environmentId, threadId)
42 : EMPTY_THREAD_STATE_ATOM,
43 );
44 const state = Option.getOrElse(
45 AsyncResult.value(result),
46 () => EMPTY_ENVIRONMENT_THREAD_STATE,
47 ) as EnvironmentThreadState;
48 return state;
49}