Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { enabledEnvironmentIds } from "@t3tools/client-runtime/state/connections";
3import { arrayElementsEqual } from "@t3tools/client-runtime/state/entities";
4import {
5 createEnvironmentThreadDetailAtoms,
6 createEnvironmentThreadShellAtoms,
7 createEnvironmentThreadStateAtoms,
8 EMPTY_ENVIRONMENT_THREAD_STATE,
9 type EnvironmentThreadState,
10 createThreadEnvironmentAtoms,
11} from "@t3tools/client-runtime/state/threads";
12import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
13import * as Option from "effect/Option";
14import { AsyncResult, Atom } from "effect/reactivity";
15
16import { environmentCatalog } from "../connection/catalog";
17import { connectionAtomRuntime } from "../connection/runtime";
18import { environmentSnapshotAtom } from "./shell";
19
20export const threadEnvironment = createThreadEnvironmentAtoms(
21 connectionAtomRuntime,
22 environmentSnapshotAtom,
23);
24const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime);
25export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(
26 environmentThreads.stateAtom,
27);
28export const environmentThreadShells = createEnvironmentThreadShellAtoms({
29 catalogValueAtom: environmentCatalog.catalogValueAtom,
30 snapshotAtom: threadEnvironment.snapshotAtom,
31});
32
33const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(
34 Atom.withLabel("web-environment-thread:empty"),
35);
36
37export function useEnvironmentThread(
38 environmentId: EnvironmentId | null,
39 threadId: ThreadId | null,
40): EnvironmentThreadState {
41 const result = useAtomValue(
42 environmentId !== null && threadId !== null
43 ? environmentThreads.stateAtom(environmentId, threadId)
44 : EMPTY_THREAD_STATE_ATOM,
45 );
46 const state = Option.getOrElse(
47 AsyncResult.value(result),
48 () => EMPTY_ENVIRONMENT_THREAD_STATE,
49 ) as EnvironmentThreadState;
50 return state;
51}
52
53const isRunning = (status: string) =>
54 status === "preparing" || status === "queued" || status === "starting" || status === "running";
55
56type KeptThreads = ReadonlyMap<EnvironmentId, ReadonlySet<ThreadId>>;
57
58function isDetailDone<E>(result: AsyncResult.AsyncResult<EnvironmentThreadState, E>): boolean {
59 if (!AsyncResult.isSuccess(result)) return true;
60 const { status, data, error } = result.value;
61 if (status === "deleted" || Option.isSome(error)) return true;
62 return (
63 status === "live" &&
64 !Option.exists(data, (thread) => thread.runs.some((run) => isRunning(run.status)))
65 );
66}
67
68/**
69 * The shell and detail streams are independent, so the shell can report a stop
70 * before the detail loads or catches up. A stopped thread stays mounted until
71 * its own detail is live and shows the stop too.
72 */
73export function createRunningThreadKeepAliveAtom<E>(input: {
74 readonly environmentIdsAtom: Atom.Atom<ReadonlyArray<EnvironmentId>>;
75 readonly threadsAtom: (
76 environmentId: EnvironmentId,
77 ) => Atom.Atom<ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id" | "status">>>;
78 readonly stateAtom: (
79 environmentId: EnvironmentId,
80 threadId: ThreadId,
81 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentThreadState, E>>;
82}) {
83 const runningThreadIdsAtom = Atom.family((environmentId: EnvironmentId) => {
84 let previous: ReadonlyArray<ThreadId> = [];
85 return Atom.make((get) => {
86 const running = get(input.threadsAtom(environmentId)).flatMap((thread) =>
87 isRunning(thread.status) ? [thread.id] : [],
88 );
89 if (arrayElementsEqual(previous, running)) return previous;
90 previous = running;
91 return running;
92 }).pipe(Atom.withLabel(`web-running-thread-ids:${environmentId}`));
93 });
94
95 return Atom.make((get): KeptThreads => {
96 const previous = Option.getOrUndefined(get.self<KeptThreads>());
97 const kept = new Map<EnvironmentId, ReadonlySet<ThreadId>>();
98 for (const environmentId of get(input.environmentIdsAtom)) {
99 const threadIds = new Set(get(runningThreadIdsAtom(environmentId)));
100 for (const threadId of previous?.get(environmentId) ?? []) {
101 if (threadIds.has(threadId)) continue;
102 const stateAtom = input.stateAtom(environmentId, threadId);
103 // `once`, not `get`: a dependency on a stopped thread would hold its
104 // stream open until some other change rebuilds this atom.
105 if (isDetailDone(get.once(stateAtom))) continue;
106 threadIds.add(threadId);
107 get.subscribe(stateAtom, (state) => {
108 if (isDetailDone(state)) get.refreshSelf();
109 });
110 }
111 for (const threadId of threadIds) get.mount(input.stateAtom(environmentId, threadId));
112 kept.set(environmentId, threadIds);
113 }
114 return kept;
115 }).pipe(Atom.withLabel("web-running-thread-keep-alive"));
116}
117
118export const runningThreadKeepAliveAtom = createRunningThreadKeepAliveAtom({
119 environmentIdsAtom: Atom.map(environmentCatalog.catalogValueAtom, (catalog) => [
120 ...enabledEnvironmentIds(catalog),
121 ]),
122 threadsAtom: environmentThreadShells.environmentThreadsAtom,
123 stateAtom: environmentThreads.stateAtom,
124});