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 isThreadSessionRunning,
12} from "@t3tools/client-runtime/state/threads";
13import type { EnvironmentId, OrchestrationThreadShell, ThreadId } from "@t3tools/contracts";
14import * as Option from "effect/Option";
15import { AsyncResult, Atom } from "effect/unstable/reactivity";
16
17import { environmentCatalog } from "../connection/catalog";
18import { connectionAtomRuntime } from "../connection/runtime";
19import { environmentSnapshotAtom } from "./shell";
20
21export const threadEnvironment = createThreadEnvironmentAtoms(
22 connectionAtomRuntime,
23 environmentSnapshotAtom,
24);
25const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime);
26export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(
27 environmentThreads.stateAtom,
28);
29export const environmentThreadShells = createEnvironmentThreadShellAtoms({
30 catalogValueAtom: environmentCatalog.catalogValueAtom,
31 snapshotAtom: threadEnvironment.snapshotAtom,
32});
33
34const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(
35 Atom.withLabel("web-environment-thread:empty"),
36);
37
38export function useEnvironmentThread(
39 environmentId: EnvironmentId | null,
40 threadId: ThreadId | null,
41): EnvironmentThreadState {
42 const result = useAtomValue(
43 environmentId !== null && threadId !== null
44 ? environmentThreads.stateAtom(environmentId, threadId)
45 : EMPTY_THREAD_STATE_ATOM,
46 );
47 return Option.getOrElse(
48 AsyncResult.value(result),
49 () => EMPTY_ENVIRONMENT_THREAD_STATE,
50 ) as EnvironmentThreadState;
51}
52
53type KeptThreads = ReadonlyMap<EnvironmentId, ReadonlySet<ThreadId>>;
54
55// True once a thread's own stream no longer needs to stay open: it is in sync
56// and shows a settled session, or it cannot progress (deleted or failed). A
57// stream that is still loading or reconnecting keeps waiting for the stop.
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" && !Option.exists(data, (thread) => isThreadSessionRunning(thread.session))
64 );
65}
66
67/**
68 * Keeps the thread state atom mounted for each running thread in the listed
69 * environments. Mount the result; its value is only bookkeeping.
70 *
71 * The shell and detail streams are independent, so the shell can report a
72 * stop before the detail loads or catches up. A stopped thread stays mounted
73 * until its own detail is live and shows the stop too. Then the stream closes
74 * and saves the settled state to disk.
75 */
76export function createRunningThreadKeepAliveAtom<E>(input: {
77 readonly environmentIdsAtom: Atom.Atom<ReadonlyArray<EnvironmentId>>;
78 readonly threadsAtom: (
79 environmentId: EnvironmentId,
80 ) => Atom.Atom<ReadonlyArray<Pick<OrchestrationThreadShell, "id" | "session">>>;
81 readonly stateAtom: (
82 environmentId: EnvironmentId,
83 threadId: ThreadId,
84 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentThreadState, E>>;
85}) {
86 // Keeps its identity until a thread starts or stops, so ordinary shell
87 // updates do not rebuild the keep-alive set.
88 const runningThreadIdsAtom = Atom.family((environmentId: EnvironmentId) => {
89 let previous: ReadonlyArray<ThreadId> = [];
90 return Atom.make((get) => {
91 const running = get(input.threadsAtom(environmentId)).flatMap((thread) =>
92 isThreadSessionRunning(thread.session) ? [thread.id] : [],
93 );
94 if (arrayElementsEqual(previous, running)) return previous;
95 previous = running;
96 return running;
97 }).pipe(Atom.withLabel(`web-running-thread-ids:${environmentId}`));
98 });
99
100 return Atom.make((get): KeptThreads => {
101 const previous = Option.getOrUndefined(get.self<KeptThreads>());
102 const kept = new Map<EnvironmentId, ReadonlySet<ThreadId>>();
103 // An environment that leaves the list is not visited, so its mounts drop.
104 for (const environmentId of get(input.environmentIdsAtom)) {
105 const threadIds = new Set(get(runningThreadIdsAtom(environmentId)));
106 for (const threadId of previous?.get(environmentId) ?? []) {
107 if (threadIds.has(threadId)) continue;
108 const stateAtom = input.stateAtom(environmentId, threadId);
109 // `once`, not `get`: a dependency on a stopped thread would hold its
110 // stream open until some other change rebuilds this atom.
111 if (isDetailDone(get.once(stateAtom))) continue;
112 threadIds.add(threadId);
113 // Rebuild when this detail is done, not on each update.
114 get.subscribe(stateAtom, (state) => {
115 if (isDetailDone(state)) get.refreshSelf();
116 });
117 }
118 for (const threadId of threadIds) get.mount(input.stateAtom(environmentId, threadId));
119 kept.set(environmentId, threadIds);
120 }
121 return kept;
122 }).pipe(Atom.withLabel("web-running-thread-keep-alive"));
123}
124
125/** Mounted by `RunningThreadKeepAlive` on desktop, for every enabled environment. */
126export const runningThreadKeepAliveAtom = createRunningThreadKeepAliveAtom({
127 environmentIdsAtom: Atom.map(environmentCatalog.catalogValueAtom, (catalog) => [
128 ...enabledEnvironmentIds(catalog),
129 ]),
130 threadsAtom: environmentThreadShells.environmentThreadsAtom,
131 stateAtom: environmentThreads.stateAtom,
132});