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

threadDetail.ts

195 lines8.4 KB

1import type { OrchestrationV2ThreadProjection, ScopedThreadRef } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import { AsyncResult, Atom } from "effect/unstable/reactivity";
4​
5import {
6 deriveThreadQueueWorkflowState,
7 getUserQueuedThreadRuns,
8 type ThreadQueueWorkflowState,
9} from "./threadWorkflows.ts";
10import { deriveThreadTurnSubagents, type ThreadTurnSubagents } from "./threadSubagents.ts";
11import type { EnvironmentThread } from "./models.ts";
12import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threadState.ts";
13import { derivePendingThreadRequests, type PendingThreadRequests } from "./threadRequests.ts";
14import { arrayElementsEqual, parseThreadKey, threadKey } from "./entities.ts";
15​
16const EMPTY_VISIBLE_TURN_ITEMS: OrchestrationV2ThreadProjection["visibleTurnItems"] = Object.freeze(
17 [],
18);
19​
20export function createEnvironmentThreadDetailAtoms<E>(
21 threadStateAtom: (
22 environmentId: ScopedThreadRef["environmentId"],
23 threadId: ScopedThreadRef["threadId"],
24 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentThreadState, E>>,
25) {
26 const threadStateValueAtomFamily = Atom.family((key: string) => {
27 const ref = parseThreadKey(key);
28 return Atom.make((get) =>
29 Option.getOrElse(
30 AsyncResult.value(get(threadStateAtom(ref.environmentId, ref.threadId))),
31 () => EMPTY_ENVIRONMENT_THREAD_STATE,
32 ),
33 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state-value:${key}`));
34 });
35​
36 const threadAtomFamily = Atom.family((key: string) => {
37 const ref = parseThreadKey(key);
38 let previousProjection: OrchestrationV2ThreadProjection | null = null;
39 let previousValue: EnvironmentThread | null = null;
40 return Atom.make((get) => {
41 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
42 if (projection === previousProjection) return previousValue;
43 previousProjection = projection;
44 previousValue = projection === null ? null : { environmentId: ref.environmentId, projection };
45 return previousValue;
46 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread:${key}`));
47 });
48​
49 const visibleTurnItemsAtomFamily = Atom.family((key: string) =>
50 Atom.make(
51 (get): OrchestrationV2ThreadProjection["visibleTurnItems"] =>
52 Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.visibleTurnItems ??
53 EMPTY_VISIBLE_TURN_ITEMS,
54 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-visible-turn-items:${key}`)),
55 );
56​
57 const queueWorkflowAtomFamily = Atom.family((key: string) => {
58 let previous: Pick<
59 OrchestrationV2ThreadProjection,
60 "thread" | "runs" | "messages" | "providerThreads" | "providerSessions" | "providerTurns"
61 > | null = null;
62 let value: ThreadQueueWorkflowState | null = null;
63 return Atom.make((get) => {
64 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
65 if (projection === null) {
66 previous = null;
67 value = null;
68 } else if (
69 previous === null ||
70 projection.thread !== previous.thread ||
71 projection.runs !== previous.runs ||
72 projection.messages !== previous.messages ||
73 projection.providerThreads !== previous.providerThreads ||
74 projection.providerSessions !== previous.providerSessions ||
75 projection.providerTurns !== previous.providerTurns
76 ) {
77 value = deriveThreadQueueWorkflowState(projection);
78 const { thread, runs, messages, providerThreads, providerSessions, providerTurns } =
79 projection;
80 previous = { thread, runs, messages, providerThreads, providerSessions, providerTurns };
81 }
82 return value;
83 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-queue:${key}`));
84 });
85 const queuedCountAtomFamily = Atom.family((key: string) => {
86 let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "messages"> | null = null;
87 let count = 0;
88 return Atom.make((get) => {
89 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
90 if (projection === null) {
91 previous = null;
92 count = 0;
93 } else if (projection.runs !== previous?.runs || projection.messages !== previous?.messages) {
94 const { runs, messages } = projection;
95 previous = { runs, messages };
96 count = getUserQueuedThreadRuns(previous).length;
97 }
98 return count;
99 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-queue-count:${key}`));
100 });
101​
102 const turnSubagentsAtomFamily = Atom.family((key: string) => {
103 let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "subagents"> | null = null;
104 let value: ThreadTurnSubagents | null = null;
105 return Atom.make((get) => {
106 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
107 if (projection === null) {
108 previous = null;
109 value = null;
110 } else if (
111 projection.runs !== previous?.runs ||
112 projection.subagents !== previous?.subagents
113 ) {
114 const { runs, subagents } = projection;
115 previous = { runs, subagents };
116 value = deriveThreadTurnSubagents(previous);
117 }
118 return value;
119 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-turn-subagents:${key}`));
120 });
121​
122 const worktreePathAtomFamily = Atom.family((key: string) =>
123 Atom.make(
124 (get) =>
125 Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.thread.worktreePath ?? null,
126 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-worktree:${key}`)),
127 );
128 const pendingRequestsAtomFamily = Atom.family((key: string) => {
129 let previous: Pick<OrchestrationV2ThreadProjection, "runtimeRequests" | "turnItems"> | null =
130 null;
131 let value: PendingThreadRequests | null = null;
132 return Atom.make((get) => {
133 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
134 if (projection === null) {
135 previous = null;
136 value = null;
137 return value;
138 }
139 const runtimeRequests = projection.runtimeRequests.filter(
140 (request) => request.status === "pending",
141 );
142 const ids = new Set(runtimeRequests.map((request) => request.id));
143 const turnItems =
144 ids.size === 0
145 ? []
146 : projection.turnItems.filter(
147 (item) =>
148 (item.type === "approval_request" || item.type === "user_input_request") &&
149 ids.has(item.requestId),
150 );
151 if (
152 previous === null ||
153 !arrayElementsEqual(previous.runtimeRequests, runtimeRequests) ||
154 !arrayElementsEqual(previous.turnItems, turnItems)
155 ) {
156 previous = { runtimeRequests, turnItems };
157 value = derivePendingThreadRequests(previous);
158 }
159 return value;
160 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-pending-requests:${key}`));
161 });
162​
163 const statusAtomFamily = Atom.family((key: string) =>
164 Atom.make((get) => get(threadStateValueAtomFamily(key)).status).pipe(
165 Atom.setIdleTTL(0),
166 Atom.withLabel(`environment-thread-status:${key}`),
167 ),
168 );
169 const errorAtomFamily = Atom.family((key: string) =>
170 Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe(
171 Atom.setIdleTTL(0),
172 Atom.withLabel(`environment-thread-error:${key}`),
173 ),
174 );
175 const historyAtomFamily = Atom.family((key: string) =>
176 Atom.make((get) => get(threadStateValueAtomFamily(key)).history).pipe(
177 Atom.setIdleTTL(0),
178 Atom.withLabel(`environment-thread-history:${key}`),
179 ),
180 );
181​
182 return {
183 worktreePathAtom: (ref: ScopedThreadRef) => worktreePathAtomFamily(threadKey(ref)),
184 pendingRequestsAtom: (ref: ScopedThreadRef) => pendingRequestsAtomFamily(threadKey(ref)),
185 queueWorkflowAtom: (ref: ScopedThreadRef) => queueWorkflowAtomFamily(threadKey(ref)),
186 queuedCountAtom: (ref: ScopedThreadRef) => queuedCountAtomFamily(threadKey(ref)),
187 turnSubagentsAtom: (ref: ScopedThreadRef) => turnSubagentsAtomFamily(threadKey(ref)),
188 stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)),
189 threadAtom: (ref: ScopedThreadRef) => threadAtomFamily(threadKey(ref)),
190 visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)),
191 statusAtom: (ref: ScopedThreadRef) => statusAtomFamily(threadKey(ref)),
192 errorAtom: (ref: ScopedThreadRef) => errorAtomFamily(threadKey(ref)),
193 historyAtom: (ref: ScopedThreadRef) => historyAtomFamily(threadKey(ref)),
194 };