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

threads.ts

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