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

threads.ts

142 lines5.6 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 useEffect(() => {
51 if (environmentId === null || rootThreadId === null) return;
52 return threadFamilies.mount(appAtomRegistry, environmentId, rootThreadId);
53 }, [environmentId, rootThreadId]);
55​
56const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(
57 Atom.withLabel("web-environment-thread:empty"),
58);
59​
60export function useEnvironmentThread(
61 environmentId: EnvironmentId | null,
62 threadId: ThreadId | null,
63): EnvironmentThreadState {
64 const result = useAtomValue(
65 environmentId !== null && threadId !== null
66 ? environmentThreads.stateAtom(environmentId, threadId)
67 : EMPTY_THREAD_STATE_ATOM,
68 );
69 const state = Option.getOrElse(
70 AsyncResult.value(result),
71 () => EMPTY_ENVIRONMENT_THREAD_STATE,
72 ) as EnvironmentThreadState;
73 return state;
75​
76const isRunning = (status: string) =>
77 status === "preparing" || status === "queued" || status === "starting" || status === "running";
78​
79type KeptThreads = ReadonlyMap<EnvironmentId, ReadonlySet<ThreadId>>;
80​
81function isDetailDone<E>(result: AsyncResult.AsyncResult<EnvironmentThreadState, E>): boolean {
82 if (!AsyncResult.isSuccess(result)) return true;
83 const { status, data, error } = result.value;
84 if (status === "deleted" || Option.isSome(error)) return true;
85 return (
86 status === "live" &&
87 !Option.exists(data, (thread) => thread.runs.some((run) => isRunning(run.status)))
88 );
90​
91/** Keeps stopped threads mounted until their independent detail stream is live and also reports stopped. */
92export function createRunningThreadKeepAliveAtom<E>(input: {
93 readonly environmentIdsAtom: Atom.Atom<ReadonlyArray<EnvironmentId>>;
94 readonly threadsAtom: (
95 environmentId: EnvironmentId,
96 ) => Atom.Atom<ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id" | "status">>>;
97 readonly stateAtom: (
98 environmentId: EnvironmentId,
99 threadId: ThreadId,
100 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentThreadState, E>>;
101}) {
102 const runningThreadIdsAtom = Atom.family((environmentId: EnvironmentId) => {
103 let previous: ReadonlyArray<ThreadId> = [];
104 return Atom.make((get) => {
105 const running = get(input.threadsAtom(environmentId)).flatMap((thread) =>
106 isRunning(thread.status) ? [thread.id] : [],
107 );
108 if (arrayElementsEqual(previous, running)) return previous;
109 previous = running;
110 return running;
111 }).pipe(Atom.withLabel(`web-running-thread-ids:${environmentId}`));
112 });
113​
114 return Atom.make((get): KeptThreads => {
115 const previous = Option.getOrUndefined(get.self<KeptThreads>());
116 const kept = new Map<EnvironmentId, ReadonlySet<ThreadId>>();
117 for (const environmentId of get(input.environmentIdsAtom)) {
118 const threadIds = new Set(get(runningThreadIdsAtom(environmentId)));
119 for (const threadId of previous?.get(environmentId) ?? []) {
120 if (threadIds.has(threadId)) continue;
121 const stateAtom = input.stateAtom(environmentId, threadId);
122 // A get dependency would hold stopped streams open until another change rebuilds this atom.
123 if (isDetailDone(get.once(stateAtom))) continue;
124 threadIds.add(threadId);
125 get.subscribe(stateAtom, (state) => {
126 if (isDetailDone(state)) get.refreshSelf();
127 });
128 }
129 for (const threadId of threadIds) get.mount(input.stateAtom(environmentId, threadId));
130 kept.set(environmentId, threadIds);
131 }
132 return kept;
133 }).pipe(Atom.withLabel("web-running-thread-keep-alive"));
135​
136export const runningThreadKeepAliveAtom = createRunningThreadKeepAliveAtom({
137 environmentIdsAtom: Atom.map(environmentCatalog.catalogValueAtom, (catalog) => [
138 ...enabledEnvironmentIds(catalog),
139 ]),
140 threadsAtom: environmentThreadShells.environmentThreadsAtom,
141 stateAtom: environmentThreads.stateAtom,
142});