Open History to see the last commit
1import {
2 OrchestrationV2AppThread,
3 OrchestrationV2TurnItem,
4 type OrchestrationV2ThreadProjection,
5 type ScopedThreadRef,
6} from "@t3tools/contracts";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9import { AsyncResult, Atom } from "effect/reactivity";
10
11import {
12 deriveThreadQueueWorkflowState,
13 getUserQueuedThreadRuns,
14 type ThreadQueueWorkflowState,
15} from "./threadWorkflows.ts";
16import { deriveThreadTurnSubagents, type ThreadTurnSubagents } from "./threadSubagents.ts";
17import {
18 deriveThreadCheckpointSummaries,
19 type ThreadCheckpointSummary,
20} from "./threadCheckpoints.ts";
21import type {
22 EnvironmentThread,
23 EnvironmentThreadStructure,
24 ThreadStructure,
25 ThreadStructureThread,
26 ThreadStructureTurnItem,
27 ThreadStructureVisibleTurnItem,
28} from "./models.ts";
29import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threadState.ts";
30import {
31 createQuestionHistoryProjector,
32 derivePendingThreadRequests,
33 type PendingThreadRequests,
34} from "./threadRequests.ts";
35import { arrayElementsEqual, parseThreadKey, threadKey } from "./entities.ts";
36
37const EMPTY_VISIBLE_TURN_ITEMS: OrchestrationV2ThreadProjection["visibleTurnItems"] = Object.freeze(
38 [],
39);
40const EMPTY_THREAD_STRUCTURE_TURN_ITEMS: ReadonlyArray<ThreadStructureVisibleTurnItem> =
41 Object.freeze([]);
42const EMPTY_CHECKPOINT_SUMMARIES: ReadonlyArray<ThreadCheckpointSummary> = Object.freeze([]);
43
44type TurnItem = OrchestrationV2ThreadProjection["turnItems"][number];
45type VisibleTurnItem = OrchestrationV2ThreadProjection["visibleTurnItems"][number];
46type AppThread = OrchestrationV2ThreadProjection["thread"];
47
48// Items are stripped once each: unchanged items keep their identity across
49// structure changes, which the incremental timeline relies on.
50const structureTurnItems = new WeakMap<TurnItem, ThreadStructureTurnItem>();
51const structureVisibleTurnItems = new WeakMap<VisibleTurnItem, ThreadStructureVisibleTurnItem>();
52
53function toThreadStructureTurnItem(item: TurnItem): ThreadStructureTurnItem {
54 if (item.type !== "assistant_message" && item.type !== "reasoning") return item;
55 let structure = structureTurnItems.get(item);
56 if (structure === undefined) {
57 const { text: _text, updatedAt: _updatedAt, ...rest } = item;
58 structure = rest;
59 structureTurnItems.set(item, structure);
60 }
61 return structure;
62}
63
64function toThreadStructureVisibleTurnItem(
65 visibleItem: VisibleTurnItem,
66): ThreadStructureVisibleTurnItem {
67 const item = toThreadStructureTurnItem(visibleItem.item);
68 if (item === visibleItem.item) return visibleItem;
69 let structure = structureVisibleTurnItems.get(visibleItem);
70 if (structure === undefined) {
71 structure = { ...visibleItem, item };
72 structureVisibleTurnItems.set(visibleItem, structure);
73 }
74 return structure;
75}
76
77/** Whether the structure kept every field of this row: true for all but streamed items. */
78export function isCompleteTurnItemRow(row: ThreadStructureVisibleTurnItem): row is VisibleTurnItem {
79 return row.item.type !== "assistant_message" && row.item.type !== "reasoning";
80}
81
82// The open thread is marked visited several times while a reply streams. Visit
83// state is read from the shell, or from lastVisitedAtAtom while the thread is
84// not in the shell index yet, so a mark is not structure.
85function toThreadStructureThread(thread: AppThread): ThreadStructureThread {
86 const { updatedAt: _updatedAt, lastVisitedAt: _lastVisitedAt, ...structure } = thread;
87 return structure;
88}
89
90function toThreadStructure(projection: OrchestrationV2ThreadProjection): ThreadStructure {
91 const { updatedAt: _updatedAt, ...structure } = projection;
92 return {
93 ...structure,
94 thread: toThreadStructureThread(projection.thread),
95 turnItems: projection.turnItems.map(toThreadStructureTurnItem),
96 visibleTurnItems: projection.visibleTurnItems.map(toThreadStructureVisibleTurnItem),
97 };
98}
99
100const sameTurnItem = Schema.toEquivalence(OrchestrationV2TurnItem);
101const sameAppThread = Schema.toEquivalence(OrchestrationV2AppThread);
102
103// Overlays previous's structure on next, so the fields the strip functions
104// remove are exactly the ones ignored here.
105function sameApartFromStripped<T extends object>(
106 same: (left: T, right: T) => boolean,
107 previous: T,
108 previousStructure: object,
109 next: T,
110): boolean {
111 return (
112 Object.keys(previous).length === Object.keys(next).length &&
113 same(Object.assign({}, next, previousStructure), next)
114 );
115}
116
117function sameTurnItemStructure(previous: TurnItem, next: TurnItem): boolean {
118 if (previous === next) return true;
119 const structure = toThreadStructureTurnItem(previous);
120 if (previous.id !== next.id || previous.type !== next.type || structure === previous) {
121 return false;
122 }
123 return sameApartFromStripped(sameTurnItem, previous, structure, next);
124}
125
126/**
127 * Whether `previous` and `next` have the same ThreadStructure: they differ
128 * only by text streamed into existing assistant and reasoning items or by a
129 * visit mark. The same items exist, with the same status, and every other
130 * field is unchanged.
131 */
132export function sameThreadStructure(
133 previous: OrchestrationV2ThreadProjection,
134 next: OrchestrationV2ThreadProjection,
135): boolean {
136 if (previous === next) return true;
137 for (const key of Object.keys(next) as Array<keyof OrchestrationV2ThreadProjection>) {
138 if (
139 key === "thread" ||
140 key === "turnItems" ||
141 key === "visibleTurnItems" ||
142 key === "updatedAt"
143 ) {
144 continue;
145 }
146 if (previous[key] !== next[key]) return false;
147 }
148 if (
149 previous.thread !== next.thread &&
150 !sameApartFromStripped(
151 sameAppThread,
152 previous.thread,
153 toThreadStructureThread(previous.thread),
154 next.thread,
155 )
156 ) {
157 return false;
158 }
159 if (
160 previous.turnItems.length !== next.turnItems.length ||
161 previous.visibleTurnItems.length !== next.visibleTurnItems.length
162 ) {
163 return false;
164 }
165 for (let index = 0; index < next.turnItems.length; index += 1) {
166 if (!sameTurnItemStructure(previous.turnItems[index]!, next.turnItems[index]!)) {
167 return false;
168 }
169 }
170 for (let index = 0; index < next.visibleTurnItems.length; index += 1) {
171 const before = previous.visibleTurnItems[index]!;
172 const after = next.visibleTurnItems[index]!;
173 if (before === after) continue;
174 if (
175 before.position !== after.position ||
176 before.visibility !== after.visibility ||
177 before.sourceThreadId !== after.sourceThreadId ||
178 before.sourceItemId !== after.sourceItemId ||
179 !sameTurnItemStructure(before.item, after.item)
180 ) {
181 return false;
182 }
183 }
184 return true;
185}
186
187export function createEnvironmentThreadDetailAtoms<E>(
188 threadStateAtom: (
189 environmentId: ScopedThreadRef["environmentId"],
190 threadId: ScopedThreadRef["threadId"],
191 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentThreadState, E>>,
192) {
193 const threadStateValueAtomFamily = Atom.family((key: string) => {
194 const ref = parseThreadKey(key);
195 return Atom.make((get) =>
196 Option.getOrElse(
197 AsyncResult.value(get(threadStateAtom(ref.environmentId, ref.threadId))),
198 () => EMPTY_ENVIRONMENT_THREAD_STATE,
199 ),
200 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state-value:${key}`));
201 });
202
203 const threadAtomFamily = Atom.family((key: string) => {
204 const ref = parseThreadKey(key);
205 let previousProjection: OrchestrationV2ThreadProjection | null = null;
206 let previousValue: EnvironmentThread | null = null;
207 return Atom.make((get) => {
208 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
209 if (projection === previousProjection) return previousValue;
210 previousProjection = projection;
211 previousValue = projection === null ? null : { environmentId: ref.environmentId, projection };
212 return previousValue;
213 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread:${key}`));
214 });
215
216 // Streamed assistant and reasoning text replaces an item several times a
217 // second. Readers of the thread's structure (runs, requests, which items
218 // exist and their status) keep the previous value through those updates.
219 const quietThreadAtomFamily = Atom.family((key: string) => {
220 let previousProjection: OrchestrationV2ThreadProjection | null = null;
221 let previous: EnvironmentThreadStructure | null = null;
222 return Atom.make((get) => {
223 const next = get(threadAtomFamily(key));
224 if (next === null) {
225 previousProjection = null;
226 previous = null;
227 } else if (
228 previousProjection === null ||
229 !sameThreadStructure(previousProjection, next.projection)
230 ) {
231 previous = {
232 environmentId: next.environmentId,
233 projection: toThreadStructure(next.projection),
234 };
235 }
236 // Compared against the latest projection, a delta only compares the item it replaced.
237 previousProjection = next?.projection ?? null;
238 return previous;
239 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-quiet-thread:${key}`));
240 });
241
242 const visibleTurnItemsAtomFamily = Atom.family((key: string) => {
243 const projectQuestionHistory = createQuestionHistoryProjector();
244 return Atom.make((get): OrchestrationV2ThreadProjection["visibleTurnItems"] => {
245 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
246 return projection === null ? EMPTY_VISIBLE_TURN_ITEMS : projectQuestionHistory(projection);
247 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-visible-turn-items:${key}`));
248 });
249
250 const quietVisibleTurnItemsAtomFamily = Atom.family((key: string) => {
251 const projectQuestionHistory = createQuestionHistoryProjector<ThreadStructureVisibleTurnItem>();
252 return Atom.make((get) => {
253 const thread = get(quietThreadAtomFamily(key));
254 return thread === null
255 ? EMPTY_THREAD_STRUCTURE_TURN_ITEMS
256 : projectQuestionHistory(thread.projection);
257 }).pipe(
258 Atom.setIdleTTL(0),
259 Atom.withLabel(`environment-quiet-thread-visible-turn-items:${key}`),
260 );
261 });
262
263 const queueWorkflowAtomFamily = Atom.family((key: string) => {
264 let previous: Pick<
265 OrchestrationV2ThreadProjection,
266 "thread" | "runs" | "messages" | "providerThreads" | "providerSessions" | "providerTurns"
267 > | null = null;
268 let value: ThreadQueueWorkflowState | null = null;
269 return Atom.make((get) => {
270 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
271 if (projection === null) {
272 previous = null;
273 value = null;
274 } else if (
275 previous === null ||
276 projection.thread !== previous.thread ||
277 projection.runs !== previous.runs ||
278 projection.messages !== previous.messages ||
279 projection.providerThreads !== previous.providerThreads ||
280 projection.providerSessions !== previous.providerSessions ||
281 projection.providerTurns !== previous.providerTurns
282 ) {
283 value = deriveThreadQueueWorkflowState(projection);
284 const { thread, runs, messages, providerThreads, providerSessions, providerTurns } =
285 projection;
286 previous = { thread, runs, messages, providerThreads, providerSessions, providerTurns };
287 }
288 return value;
289 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-queue:${key}`));
290 });
291 const queuedCountAtomFamily = Atom.family((key: string) => {
292 let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "messages"> | null = null;
293 let count = 0;
294 return Atom.make((get) => {
295 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
296 if (projection === null) {
297 previous = null;
298 count = 0;
299 } else if (projection.runs !== previous?.runs || projection.messages !== previous?.messages) {
300 const { runs, messages } = projection;
301 previous = { runs, messages };
302 count = getUserQueuedThreadRuns(previous).length;
303 }
304 return count;
305 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-queue-count:${key}`));
306 });
307
308 const turnSubagentsAtomFamily = Atom.family((key: string) => {
309 let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "subagents"> | null = null;
310 let value: ThreadTurnSubagents | null = null;
311 return Atom.make((get) => {
312 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
313 if (projection === null) {
314 previous = null;
315 value = null;
316 } else if (
317 projection.runs !== previous?.runs ||
318 projection.subagents !== previous?.subagents
319 ) {
320 const { runs, subagents } = projection;
321 previous = { runs, subagents };
322 value = deriveThreadTurnSubagents(previous);
323 }
324 return value;
325 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-turn-subagents:${key}`));
326 });
327
328 const checkpointSummariesAtomFamily = Atom.family((key: string) => {
329 let previous: Pick<OrchestrationV2ThreadProjection, "checkpoints" | "messages"> | null = null;
330 let value = EMPTY_CHECKPOINT_SUMMARIES;
331 return Atom.make((get) => {
332 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
333 if (projection === null) {
334 previous = null;
335 value = EMPTY_CHECKPOINT_SUMMARIES;
336 } else if (
337 projection.checkpoints !== previous?.checkpoints ||
338 projection.messages !== previous?.messages
339 ) {
340 const { checkpoints, messages } = projection;
341 previous = { checkpoints, messages };
342 value = deriveThreadCheckpointSummaries(previous);
343 }
344 return value;
345 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-checkpoint-summaries:${key}`));
346 });
347
348 const lastVisitedAtAtomFamily = Atom.family((key: string) =>
349 Atom.make(
350 (get) =>
351 Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.thread.lastVisitedAt ?? null,
352 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-last-visited:${key}`)),
353 );
354 const updatedAtAtomFamily = Atom.family((key: string) =>
355 Atom.make(
356 (get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.updatedAt ?? null,
357 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-updated-at:${key}`)),
358 );
359 const worktreePathAtomFamily = Atom.family((key: string) =>
360 Atom.make(
361 (get) =>
362 Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.thread.worktreePath ?? null,
363 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-worktree:${key}`)),
364 );
365 const pendingRequestsAtomFamily = Atom.family((key: string) => {
366 let previous: Pick<OrchestrationV2ThreadProjection, "runtimeRequests" | "turnItems"> | null =
367 null;
368 let value: PendingThreadRequests | null = null;
369 return Atom.make((get) => {
370 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
371 if (projection === null) {
372 previous = null;
373 value = null;
374 return value;
375 }
376 const runtimeRequests = projection.runtimeRequests.filter(
377 (request) => request.status === "pending",
378 );
379 const ids = new Set(runtimeRequests.map((request) => request.id));
380 const turnItems =
381 ids.size === 0
382 ? []
383 : projection.turnItems.filter(
384 (item) =>
385 (item.type === "approval_request" || item.type === "user_input_request") &&
386 ids.has(item.requestId),
387 );
388 if (
389 previous === null ||
390 !arrayElementsEqual(previous.runtimeRequests, runtimeRequests) ||
391 !arrayElementsEqual(previous.turnItems, turnItems)
392 ) {
393 previous = { runtimeRequests, turnItems };
394 value = derivePendingThreadRequests(previous);
395 }
396 return value;
397 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-pending-requests:${key}`));
398 });
399
400 const statusAtomFamily = Atom.family((key: string) =>
401 Atom.make((get) => get(threadStateValueAtomFamily(key)).status).pipe(
402 Atom.setIdleTTL(0),
403 Atom.withLabel(`environment-thread-status:${key}`),
404 ),
405 );
406 const errorAtomFamily = Atom.family((key: string) =>
407 Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe(
408 Atom.setIdleTTL(0),
409 Atom.withLabel(`environment-thread-error:${key}`),
410 ),
411 );
412 const historyAtomFamily = Atom.family((key: string) =>
413 Atom.make((get) => get(threadStateValueAtomFamily(key)).history).pipe(
414 Atom.setIdleTTL(0),
415 Atom.withLabel(`environment-thread-history:${key}`),
416 ),
417 );
418
419 return {
420 worktreePathAtom: (ref: ScopedThreadRef) => worktreePathAtomFamily(threadKey(ref)),
421 updatedAtAtom: (ref: ScopedThreadRef) => updatedAtAtomFamily(threadKey(ref)),
422 lastVisitedAtAtom: (ref: ScopedThreadRef) => lastVisitedAtAtomFamily(threadKey(ref)),
423 pendingRequestsAtom: (ref: ScopedThreadRef) => pendingRequestsAtomFamily(threadKey(ref)),
424 queueWorkflowAtom: (ref: ScopedThreadRef) => queueWorkflowAtomFamily(threadKey(ref)),
425 queuedCountAtom: (ref: ScopedThreadRef) => queuedCountAtomFamily(threadKey(ref)),
426 turnSubagentsAtom: (ref: ScopedThreadRef) => turnSubagentsAtomFamily(threadKey(ref)),
427 checkpointSummariesAtom: (ref: ScopedThreadRef) =>
428 checkpointSummariesAtomFamily(threadKey(ref)),
429 stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)),
430 threadAtom: (ref: ScopedThreadRef) => threadAtomFamily(threadKey(ref)),
431 quietThreadAtom: (ref: ScopedThreadRef) => quietThreadAtomFamily(threadKey(ref)),
432 visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)),
433 quietVisibleTurnItemsAtom: (ref: ScopedThreadRef) =>
434 quietVisibleTurnItemsAtomFamily(threadKey(ref)),
435 statusAtom: (ref: ScopedThreadRef) => statusAtomFamily(threadKey(ref)),
436 errorAtom: (ref: ScopedThreadRef) => errorAtomFamily(threadKey(ref)),
437 historyAtom: (ref: ScopedThreadRef) => historyAtomFamily(threadKey(ref)),
438 };
439}