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

threadDetail.ts

480 lines19.4 KB

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