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

threadDetail.ts

226 lines9.8 KB

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