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