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

threadDetail.ts

530 lines21.5 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​
151function isStreamingAssistantMessage(visibleItem: VisibleTurnItem): boolean {
152 return visibleItem.item.type === "assistant_message" && visibleItem.item.streaming;
154​
155/** Whether `next` only streams more text into assistant messages that were already streaming. */
156function sameApartFromStreamedAssistantText(
157 previous: OrchestrationV2ThreadProjection["visibleTurnItems"],
158 next: OrchestrationV2ThreadProjection["visibleTurnItems"],
159): boolean {
160 return sameProjectionArray(
161 previous,
162 next,
163 (before, after) =>
164 before === after ||
165 (isStreamingAssistantMessage(before) &&
166 isStreamingAssistantMessage(after) &&
167 sameVisibleTurnItemStructure(before, after)),
168 );
170​
171/**
172 * Whether `previous` and `next` have the same ThreadStructure: they differ
173 * only by text streamed into existing assistant and reasoning items or by a
174 * visit mark. The same items exist, with the same status, and every other
175 * field is unchanged.
176 */
177export function sameThreadStructure(
178 previous: OrchestrationV2ThreadProjection,
179 next: OrchestrationV2ThreadProjection,
180): boolean {
181 if (previous === next) return true;
182 for (const key of Object.keys(next) as Array<keyof OrchestrationV2ThreadProjection>) {
183 if (
184 key === "thread" ||
185 key === "turnItems" ||
186 key === "visibleTurnItems" ||
187 key === "updatedAt"
188 ) {
189 continue;
190 }
191 if (previous[key] !== next[key]) return false;
192 }
193 if (
194 previous.thread !== next.thread &&
195 !sameApartFromStripped(
196 sameAppThread,
197 previous.thread,
198 toThreadStructureThread(previous.thread),
199 next.thread,
200 )
201 ) {
202 return false;
203 }
204 return (
205 sameProjectionArray(previous.turnItems, next.turnItems, sameTurnItemStructure) &&
206 sameProjectionArray(
207 previous.visibleTurnItems,
208 next.visibleTurnItems,
209 sameVisibleTurnItemStructure,
210 )
211 );
213​
214export function createEnvironmentThreadDetailAtoms<E>(
215 threadStateAtom: (
216 environmentId: ScopedThreadRef["environmentId"],
217 threadId: ScopedThreadRef["threadId"],
218 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentThreadState, E>>,
219) {
220 const threadStateValueAtomFamily = Atom.family((key: string) => {
221 const ref = parseThreadKey(key);
222 return Atom.make((get) =>
223 AsyncResult.getOrElse(
224 get(threadStateAtom(ref.environmentId, ref.threadId)),
225 () => EMPTY_ENVIRONMENT_THREAD_STATE,
226 ),
227 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state-value:${key}`));
228 });
229​
230 const threadAtomFamily = Atom.family((key: string) => {
231 const ref = parseThreadKey(key);
232 let previousProjection: OrchestrationV2ThreadProjection | null = null;
233 let previousValue: EnvironmentThread | null = null;
234 return Atom.make((get) => {
235 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
236 if (projection === previousProjection) return previousValue;
237 previousProjection = projection;
238 previousValue = projection === null ? null : { environmentId: ref.environmentId, projection };
239 return previousValue;
240 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread:${key}`));
241 });
242​
243 // Streamed assistant and reasoning text replaces an item several times a
244 // second. Readers of the thread's structure (runs, requests, which items
245 // exist and their status) keep the previous value through those updates.
246 const quietThreadAtomFamily = Atom.family((key: string) => {
247 let previousProjection: OrchestrationV2ThreadProjection | null = null;
248 let previous: EnvironmentThreadStructure | null = null;
249 return Atom.make((get) => {
250 const next = get(threadAtomFamily(key));
251 if (next === null) {
252 previousProjection = null;
253 previous = null;
254 } else if (
255 previousProjection === null ||
256 !sameThreadStructure(previousProjection, next.projection)
257 ) {
258 previous = {
259 environmentId: next.environmentId,
260 projection: toThreadStructure(next.projection),
261 };
262 }
263 // Comparing the latest projection lets consecutive replacements bypass history scans.
264 previousProjection = next?.projection ?? null;
265 return previous;
266 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-quiet-thread:${key}`));
267 });
268​
269 const visibleTurnItemsAtomFamily = Atom.family((key: string) => {
270 const projectQuestionHistory = createQuestionHistoryProjector();
271 return Atom.make((get): OrchestrationV2ThreadProjection["visibleTurnItems"] => {
272 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
273 return projection === null ? EMPTY_VISIBLE_TURN_ITEMS : projectQuestionHistory(projection);
274 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-visible-turn-items:${key}`));
275 });
276​
277 const quietVisibleTurnItemsAtomFamily = Atom.family((key: string) => {
278 const projectQuestionHistory = createQuestionHistoryProjector<ThreadStructureVisibleTurnItem>();
279 return Atom.make((get) => {
280 const thread = get(quietThreadAtomFamily(key));
281 return thread === null
282 ? EMPTY_THREAD_STRUCTURE_TURN_ITEMS
283 : projectQuestionHistory(thread.projection);
284 }).pipe(
285 Atom.setIdleTTL(0),
286 Atom.withLabel(`environment-quiet-thread-visible-turn-items:${key}`),
287 );
288 });
289​
290 // Holds while only streamed assistant text moves, so the timeline re-renders on structure;
291 // each streaming message reads its text through assistantMessageTextAtom.
292 const timelineVisibleTurnItemsAtomFamily = Atom.family((key: string) => {
293 let previous = EMPTY_VISIBLE_TURN_ITEMS;
294 return Atom.make((get) => {
295 const next = get(visibleTurnItemsAtomFamily(key));
296 if (!sameApartFromStreamedAssistantText(previous, next)) previous = next;
297 return previous;
298 }).pipe(
299 Atom.setIdleTTL(0),
300 Atom.withLabel(`environment-thread-timeline-visible-turn-items:${key}`),
301 );
302 });
303​
304 const assistantMessageTextAtomFamily = Atom.family((key: string) => {
305 const separator = key.lastIndexOf("\u0000");
306 const thread = key.slice(0, separator);
307 const itemId = key.slice(separator + 1);
308 return Atom.make((get) => {
309 const item = get(visibleTurnItemsAtomFamily(thread)).find(
310 (visibleItem) => visibleItem.item.id === itemId,
311 )?.item;
312 return item?.type === "assistant_message" ? item.text : null;
313 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-assistant-message-text:${key}`));
314 });
315​
316 const queueWorkflowAtomFamily = Atom.family((key: string) => {
317 let previous: Pick<
318 OrchestrationV2ThreadProjection,
319 "thread" | "runs" | "messages" | "providerThreads" | "providerSessions" | "providerTurns"
320 > | null = null;
321 let value: ThreadQueueWorkflowState | null = null;
322 return Atom.make((get) => {
323 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
324 if (projection === null) {
325 previous = null;
326 value = null;
327 } else if (
328 previous === null ||
329 projection.thread !== previous.thread ||
330 projection.runs !== previous.runs ||
331 projection.messages !== previous.messages ||
332 projection.providerThreads !== previous.providerThreads ||
333 projection.providerSessions !== previous.providerSessions ||
334 projection.providerTurns !== previous.providerTurns
335 ) {
336 value = deriveThreadQueueWorkflowState(projection);
337 const { thread, runs, messages, providerThreads, providerSessions, providerTurns } =
338 projection;
339 previous = { thread, runs, messages, providerThreads, providerSessions, providerTurns };
340 }
341 return value;
342 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-queue:${key}`));
343 });
344 const runStopAtomFamily = Atom.family((key: string) => {
345 let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems"> | null = null;
346 let stop: RunStopPresentation | null = null;
347 return Atom.make((get) => {
348 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
349 if (projection === null) {
350 previous = null;
351 stop = null;
352 } else if (
353 projection.runs !== previous?.runs ||
354 projection.turnItems !== previous?.turnItems
355 ) {
356 const { runs, turnItems } = projection;
357 previous = { runs, turnItems };
358 const next = presentRunStop(previous);
359 if (
360 next?.state !== stop?.state ||
361 next?.runId !== stop?.runId ||
362 next?.requestedAt !== stop?.requestedAt ||
363 next?.background !== stop?.background
364 )
365 stop = next;
366 }
367 return stop;
368 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-run-stop:${key}`));
369 });
370 const queuedCountAtomFamily = Atom.family((key: string) => {
371 let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "messages"> | null = null;
372 let count = 0;
373 return Atom.make((get) => {
374 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
375 if (projection === null) {
376 previous = null;
377 count = 0;
378 } else if (projection.runs !== previous?.runs || projection.messages !== previous?.messages) {
379 const { runs, messages } = projection;
380 previous = { runs, messages };
381 count = getUserQueuedThreadRuns(previous).length;
382 }
383 return count;
384 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-queue-count:${key}`));
385 });
386​
387 const turnSubagentsAtomFamily = Atom.family((key: string) => {
388 let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "subagents"> | null = null;
389 let value: ThreadTurnSubagents | null = null;
390 return Atom.make((get) => {
391 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
392 if (projection === null) {
393 previous = null;
394 value = null;
395 } else if (
396 projection.runs !== previous?.runs ||
397 projection.subagents !== previous?.subagents
398 ) {
399 const { runs, subagents } = projection;
400 previous = { runs, subagents };
401 value = deriveThreadTurnSubagents(previous);
402 }
403 return value;
404 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-turn-subagents:${key}`));
405 });
406​
407 const checkpointSummariesAtomFamily = Atom.family((key: string) => {
408 let previous: Pick<OrchestrationV2ThreadProjection, "checkpoints" | "messages"> | null = null;
409 let value = EMPTY_CHECKPOINT_SUMMARIES;
410 return Atom.make((get) => {
411 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
412 if (projection === null) {
413 previous = null;
414 value = EMPTY_CHECKPOINT_SUMMARIES;
415 } else if (
416 projection.checkpoints !== previous?.checkpoints ||
417 projection.messages !== previous?.messages
418 ) {
419 const { checkpoints, messages } = projection;
420 previous = { checkpoints, messages };
421 value = deriveThreadCheckpointSummaries(previous);
422 }
423 return value;
424 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-checkpoint-summaries:${key}`));
425 });
426​
427 const lastVisitedAtAtomFamily = Atom.family((key: string) =>
428 Atom.make(
429 (get) =>
430 Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.thread.lastVisitedAt ?? null,
431 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-last-visited:${key}`)),
432 );
433 const updatedAtAtomFamily = Atom.family((key: string) =>
434 Atom.make(
435 (get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.updatedAt ?? null,
436 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-updated-at:${key}`)),
437 );
438 const worktreePathAtomFamily = Atom.family((key: string) =>
439 Atom.make(
440 (get) =>
441 Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.thread.worktreePath ?? null,
442 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-worktree:${key}`)),
443 );
444 const pendingRequestsAtomFamily = Atom.family((key: string) => {
445 let previous: Pick<OrchestrationV2ThreadProjection, "runtimeRequests" | "turnItems"> | null =
446 null;
447 let value: PendingThreadRequests | null = null;
448 return Atom.make((get) => {
449 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
450 if (projection === null) {
451 previous = null;
452 value = null;
453 return value;
454 }
455 const runtimeRequests = projection.runtimeRequests.filter(
456 (request) => request.status === "pending",
457 );
458 const ids = new Set(runtimeRequests.map((request) => request.id));
459 const turnItems =
460 ids.size === 0
461 ? []
462 : projection.turnItems.filter(
463 (item) =>
464 (item.type === "approval_request" || item.type === "user_input_request") &&
465 ids.has(item.requestId),
466 );
467 if (
468 previous === null ||
469 !arrayElementsEqual(previous.runtimeRequests, runtimeRequests) ||
470 !arrayElementsEqual(previous.turnItems, turnItems)
471 ) {
472 previous = { runtimeRequests, turnItems };
473 value = derivePendingThreadRequests(previous);
474 }
475 return value;
476 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-pending-requests:${key}`));
477 });
478​
479 const statusAtomFamily = Atom.family((key: string) =>
480 Atom.make((get) => get(threadStateValueAtomFamily(key)).status).pipe(
481 Atom.setIdleTTL(0),
482 Atom.withLabel(`environment-thread-status:${key}`),
483 ),
484 );
485 const sequenceAtomFamily = Atom.family((key: string) =>
486 Atom.make((get) => get(threadStateValueAtomFamily(key)).sequence).pipe(
487 Atom.setIdleTTL(0),
488 Atom.withLabel(`environment-thread-sequence:${key}`),
489 ),
490 );
491 const errorAtomFamily = Atom.family((key: string) =>
492 Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe(
493 Atom.setIdleTTL(0),
494 Atom.withLabel(`environment-thread-error:${key}`),
495 ),
496 );
497 const historyAtomFamily = Atom.family((key: string) =>
498 Atom.make((get) => get(threadStateValueAtomFamily(key)).history).pipe(
499 Atom.setIdleTTL(0),
500 Atom.withLabel(`environment-thread-history:${key}`),
501 ),
502 );
503​
504 return {
505 worktreePathAtom: (ref: ScopedThreadRef) => worktreePathAtomFamily(threadKey(ref)),
506 updatedAtAtom: (ref: ScopedThreadRef) => updatedAtAtomFamily(threadKey(ref)),
507 lastVisitedAtAtom: (ref: ScopedThreadRef) => lastVisitedAtAtomFamily(threadKey(ref)),
508 pendingRequestsAtom: (ref: ScopedThreadRef) => pendingRequestsAtomFamily(threadKey(ref)),
509 queueWorkflowAtom: (ref: ScopedThreadRef) => queueWorkflowAtomFamily(threadKey(ref)),
510 queuedCountAtom: (ref: ScopedThreadRef) => queuedCountAtomFamily(threadKey(ref)),
511 runStopAtom: (ref: ScopedThreadRef) => runStopAtomFamily(threadKey(ref)),
512 turnSubagentsAtom: (ref: ScopedThreadRef) => turnSubagentsAtomFamily(threadKey(ref)),
513 checkpointSummariesAtom: (ref: ScopedThreadRef) =>
514 checkpointSummariesAtomFamily(threadKey(ref)),
515 stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)),
516 threadAtom: (ref: ScopedThreadRef) => threadAtomFamily(threadKey(ref)),
517 quietThreadAtom: (ref: ScopedThreadRef) => quietThreadAtomFamily(threadKey(ref)),
518 visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)),
519 quietVisibleTurnItemsAtom: (ref: ScopedThreadRef) =>
520 quietVisibleTurnItemsAtomFamily(threadKey(ref)),
521 timelineVisibleTurnItemsAtom: (ref: ScopedThreadRef) =>
522 timelineVisibleTurnItemsAtomFamily(threadKey(ref)),
523 assistantMessageTextAtom: (ref: ScopedThreadRef, itemId: string) =>
524 assistantMessageTextAtomFamily(`${threadKey(ref)}\u0000${itemId}`),
525 statusAtom: (ref: ScopedThreadRef) => statusAtomFamily(threadKey(ref)),
526 sequenceAtom: (ref: ScopedThreadRef) => sequenceAtomFamily(threadKey(ref)),
527 errorAtom: (ref: ScopedThreadRef) => errorAtomFamily(threadKey(ref)),
528 historyAtom: (ref: ScopedThreadRef) => historyAtomFamily(threadKey(ref)),
529 };