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 createThreadFamilyAtoms,
12} from "@t3tools/client-runtime/state/threads";
13import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
14import * as Option from "effect/Option";
15import { AsyncResult, Atom } from "effect/reactivity";
16import { useEffect } from "react";
17
18import { environmentCatalog } from "../connection/catalog";
19import { connectionAtomRuntime } from "../connection/runtime";
20import { appAtomRegistry } from "../rpc/atomRegistry";
21import { environmentShell } from "./shell";
22
23const threadFamilies = createThreadFamilyAtoms(connectionAtomRuntime, environmentShell.stateAtom);
24export const threadEnvironment = createThreadEnvironmentAtoms(
25 connectionAtomRuntime,
26 threadFamilies.snapshotAtom,
27);
28const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime);
29export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(
30 environmentThreads.stateAtom,
31);
32export const environmentThreadShells = createEnvironmentThreadShellAtoms({
33 catalogValueAtom: environmentCatalog.catalogValueAtom,
34 snapshotAtom: threadEnvironment.snapshotAtom,
35});
36
37/** Keeps the subagent tree under `rootThreadId` in the thread list while the caller shows it. */
38export function useThreadFamily(
39 environmentId: EnvironmentId | null,
40 rootThreadId: ThreadId | null,
41): void {
42 useEffect(() => {
43 if (environmentId === null || rootThreadId === null) return;
44 return threadFamilies.mount(appAtomRegistry, environmentId, rootThreadId);
45 }, [environmentId, rootThreadId]);
46}
47
48const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(
49 Atom.withLabel("web-environment-thread:empty"),
50);
51
52export function useEnvironmentThread(
53 environmentId: EnvironmentId | null,
54 threadId: ThreadId | null,
55): EnvironmentThreadState {
56 const result = useAtomValue(
57 environmentId !== null && threadId !== null
58 ? environmentThreads.stateAtom(environmentId, threadId)
59 : EMPTY_THREAD_STATE_ATOM,
60 );
61 const state = Option.getOrElse(
62 AsyncResult.value(result),
63 () => EMPTY_ENVIRONMENT_THREAD_STATE,
64 ) as EnvironmentThreadState;
65 return state;
66}
67
68const isRunning = (status: string) =>
69 status === "preparing" || status === "queued" || status === "starting" || status === "running";
70
71type KeptThreads = ReadonlyMap<EnvironmentId, ReadonlySet<ThreadId>>;
72
73function isDetailDone<E>(result: AsyncResult.AsyncResult<EnvironmentThreadState, E>): boolean {
74 if (!AsyncResult.isSuccess(result)) return true;
75 const { status, data, error } = result.value;
76 if (status === "deleted" || Option.isSome(error)) return true;
77 return (
78 status === "live" &&
79 !Option.exists(data, (thread) => thread.runs.some((run) => isRunning(run.status)))
80 );
81}
82
83/** Keeps stopped threads mounted until their independent detail stream is live and also reports stopped. */
84export function createRunningThreadKeepAliveAtom<E>(input: {
85 readonly environmentIdsAtom: Atom.Atom<ReadonlyArray<EnvironmentId>>;
86 readonly threadsAtom: (
87 environmentId: EnvironmentId,
88 ) => Atom.Atom<ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id" | "status">>>;
89 readonly stateAtom: (
90 environmentId: EnvironmentId,
91 threadId: ThreadId,
92 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentThreadState, E>>;
93}) {
94 const runningThreadIdsAtom = Atom.family((environmentId: EnvironmentId) => {
95 let previous: ReadonlyArray<ThreadId> = [];
96 return Atom.make((get) => {
97 const running = get(input.threadsAtom(environmentId)).flatMap((thread) =>
98 isRunning(thread.status) ? [thread.id] : [],
99 );
100 if (arrayElementsEqual(previous, running)) return previous;
101 previous = running;
102 return running;
103 }).pipe(Atom.withLabel(`web-running-thread-ids:${environmentId}`));
104 });
105
106 return Atom.make((get): KeptThreads => {
107 const previous = Option.getOrUndefined(get.self<KeptThreads>());
108 const kept = new Map<EnvironmentId, ReadonlySet<ThreadId>>();
109 for (const environmentId of get(input.environmentIdsAtom)) {
110 const threadIds = new Set(get(runningThreadIdsAtom(environmentId)));
111 for (const threadId of previous?.get(environmentId) ?? []) {
112 if (threadIds.has(threadId)) continue;
113 const stateAtom = input.stateAtom(environmentId, threadId);
114 // A get dependency would hold stopped streams open until another change rebuilds this atom.
115 if (isDetailDone(get.once(stateAtom))) continue;
116 threadIds.add(threadId);
117 get.subscribe(stateAtom, (state) => {
118 if (isDetailDone(state)) get.refreshSelf();
119 });
120 }
121 for (const threadId of threadIds) get.mount(input.stateAtom(environmentId, threadId));
122 kept.set(environmentId, threadIds);
123 }
124 return kept;
125 }).pipe(Atom.withLabel("web-running-thread-keep-alive"));
126}
127
128export const runningThreadKeepAliveAtom = createRunningThreadKeepAliveAtom({
129 environmentIdsAtom: Atom.map(environmentCatalog.catalogValueAtom, (catalog) => [
130 ...enabledEnvironmentIds(catalog),
131 ]),
132 threadsAtom: environmentThreadShells.environmentThreadsAtom,
133 stateAtom: environmentThreads.stateAtom,
134});