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