Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threads.ts

143 lines5.8 KB

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