Open History to see the last commit
1import {
2 OrchestrationV2AppThread,
3 OrchestrationV2ConversationMessage,
4 OrchestrationV2TurnItem,
5 type OrchestrationV2ThreadProjection,
6 type ScopedThreadRef,
7} from "@t3tools/contracts";
8import * as Option from "effect/Option";
9import * as Schema from "effect/Schema";
10import { AsyncResult, Atom } from "effect/reactivity";
11
12import {
13 deriveThreadQueueWorkflowState,
14 getUserQueuedThreadRuns,
15 resolveActiveThreadRun,
16 runStopRequested,
17 type ThreadQueueWorkflowState,
18} from "./threadWorkflows.ts";
19import { deriveThreadTurnSubagents, type ThreadTurnSubagents } from "./threadSubagents.ts";
20import {
21 deriveUsageLimitNoticeRows,
22 presentRunStop,
23 withoutUsageLimitNoticeRows,
24 type RunStopPresentation,
25 type UsageLimitNoticeRows,
26} from "./threadExecution.ts";
27import {
28 deriveThreadCheckpointSummaries,
29 type ThreadCheckpointSummary,
30} from "./threadCheckpoints.ts";
31import type {
32 EnvironmentThread,
33 EnvironmentThreadStructure,
34 ThreadStructure,
35 ThreadStructureThread,
36 ThreadStructureTurnItem,
37 ThreadStructureVisibleTurnItem,
38} from "./models.ts";
39import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threadState.ts";
40import {
41 createQuestionHistoryProjector,
42 derivePendingThreadRequests,
43 type PendingThreadRequests,
44} from "./threadRequests.ts";
45import { arrayElementsEqual, parseThreadKey, threadKey } from "./entities.ts";
46import { getProjectionArrayReplacementIndex } from "./orchestrationV2Projection.ts";
47
48const EMPTY_VISIBLE_TURN_ITEMS: OrchestrationV2ThreadProjection["visibleTurnItems"] = Object.freeze(
49 [],
50);
51const EMPTY_THREAD_STRUCTURE_TURN_ITEMS: ReadonlyArray<ThreadStructureVisibleTurnItem> =
52 Object.freeze([]);
53const EMPTY_CHECKPOINT_SUMMARIES: ReadonlyArray<ThreadCheckpointSummary> = Object.freeze([]);
54
55/**
56 * Changes when the agent may have changed the workspace, so file views and host images refresh.
57 * File tools are explicit; commands, MCP or dynamic tools and subagents are included because
58 * they can mutate the workspace without reporting the paths they touched.
59 */
60export function deriveWorkspaceMutationId(
61 visibleTurnItems: ReadonlyArray<ThreadStructureVisibleTurnItem>,
62 latestCheckpointCompletedAt: string | null,
63) {
64 let itemId: string | null = null;
65 for (let index = visibleTurnItems.length - 1; index >= 0; index -= 1) {
66 const item = visibleTurnItems[index]?.item;
67 if (!item) continue;
68 if (
69 item.type !== "command_execution" &&
70 item.type !== "file_change" &&
71 item.type !== "dynamic_tool" &&
72 item.type !== "subagent"
73 ) {
74 continue;
75 }
76 if (item.status === "pending" || item.status === "running" || item.status === "waiting") {
77 continue;
78 }
79 itemId = item.id;
80 break;
81 }
82 return itemId === null && latestCheckpointCompletedAt === null
83 ? null
84 : JSON.stringify([itemId, latestCheckpointCompletedAt]);
85}
86
87type TurnItem = OrchestrationV2ThreadProjection["turnItems"][number];
88type VisibleTurnItem = OrchestrationV2ThreadProjection["visibleTurnItems"][number];
89type AppThread = OrchestrationV2ThreadProjection["thread"];
90
91// Items are stripped once each: unchanged items keep their identity across
92// structure changes, which the incremental timeline relies on.
93const structureTurnItems = new WeakMap<TurnItem, ThreadStructureTurnItem>();
94const structureVisibleTurnItems = new WeakMap<VisibleTurnItem, ThreadStructureVisibleTurnItem>();
95
96// Queued text, attachments and attribution all come from the message, so its identity covers them.
97function queueWorkflowStatesEqual(
98 left: ThreadQueueWorkflowState,
99 right: ThreadQueueWorkflowState,
100): boolean {
101 return (
102 left.activeRun === right.activeRun &&
103 left.isHeld === right.isHeld &&
104 left.canSendNow === right.canSendNow &&
105 left.canPromoteToSteer === right.canPromoteToSteer &&
106 left.promoteSkipsCompaction === right.promoteSkipsCompaction &&
107 left.queuedRuns.length === right.queuedRuns.length &&
108 left.queuedRuns.every(
109 (queued, index) =>
110 queued.run === right.queuedRuns[index]!.run &&
111 queued.stopBlocksPromotion === right.queuedRuns[index]!.stopBlocksPromotion &&
112 queued.message === right.queuedRuns[index]!.message,
113 )
114 );
115}
116
117function toThreadStructureTurnItem(item: TurnItem): ThreadStructureTurnItem {
118 if (item.type !== "assistant_message" && item.type !== "reasoning") return item;
119 let structure = structureTurnItems.get(item);
120 if (structure === undefined) {
121 const { text: _text, updatedAt: _updatedAt, ...rest } = item;
122 structure = rest;
123 structureTurnItems.set(item, structure);
124 }
125 return structure;
126}
127
128function toThreadStructureVisibleTurnItem(
129 visibleItem: VisibleTurnItem,
130): ThreadStructureVisibleTurnItem {
131 const item = toThreadStructureTurnItem(visibleItem.item);
132 if (item === visibleItem.item) return visibleItem;
133 let structure = structureVisibleTurnItems.get(visibleItem);
134 if (structure === undefined) {
135 structure = { ...visibleItem, item };
136 structureVisibleTurnItems.set(visibleItem, structure);
137 }
138 return structure;
139}
140
141/** Whether the structure kept every field of this row: true for all but streamed items. */
142export function isCompleteTurnItemRow(row: ThreadStructureVisibleTurnItem): row is VisibleTurnItem {
143 return row.item.type !== "assistant_message" && row.item.type !== "reasoning";
144}
145
146// The open thread is marked visited several times while a reply streams. Visit
147// state is read from the shell, or from lastVisitedAtAtom while the thread is
148// not in the shell index yet, so a mark is not structure.
149function toThreadStructureThread(thread: AppThread): ThreadStructureThread {
150 const { updatedAt: _updatedAt, lastVisitedAt: _lastVisitedAt, ...structure } = thread;
151 return structure;
152}
153
154function toThreadStructure(projection: OrchestrationV2ThreadProjection): ThreadStructure {
155 const { updatedAt: _updatedAt, ...structure } = projection;
156 return {
157 ...structure,
158 thread: toThreadStructureThread(projection.thread),
159 turnItems: projection.turnItems.map(toThreadStructureTurnItem),
160 visibleTurnItems: projection.visibleTurnItems.map(toThreadStructureVisibleTurnItem),
161 };
162}
163
164const sameTurnItem = Schema.toEquivalence(OrchestrationV2TurnItem);
165const sameAppThread = Schema.toEquivalence(OrchestrationV2AppThread);
166const sameMessage = Schema.toEquivalence(OrchestrationV2ConversationMessage);
167
168// Overlays previous's structure on next, so the fields the strip functions
169// remove are exactly the ones ignored here.
170function sameApartFromStripped<T extends object>(
171 same: (left: T, right: T) => boolean,
172 previous: T,
173 previousStructure: object,
174 next: T,
175): boolean {
176 return (
177 Object.keys(previous).length === Object.keys(next).length &&
178 same(Object.assign({}, next, previousStructure), next)
179 );
180}
181
182function sameTurnItemStructure(previous: TurnItem, next: TurnItem): boolean {
183 if (previous === next) return true;
184 const structure = toThreadStructureTurnItem(previous);
185 if (previous.id !== next.id || previous.type !== next.type || structure === previous) {
186 return false;
187 }
188 return sameApartFromStripped(sameTurnItem, previous, structure, next);
189}
190
191// A streaming reply's text also lands on its message; readers of that text read the live thread.
192function sameMessageStructure(
193 previous: OrchestrationV2ConversationMessage,
194 next: OrchestrationV2ConversationMessage,
195): boolean {
196 if (previous === next) return true;
197 if (!previous.streaming || !next.streaming || previous.id !== next.id) return false;
198 const { text: _text, updatedAt: _updatedAt, ...structure } = previous;
199 return sameApartFromStripped(sameMessage, previous, structure, next);
200}
201
202function sameProjectionArray<T>(
203 previous: ReadonlyArray<T>,
204 next: ReadonlyArray<T>,
205 same: (previous: T, next: T) => boolean,
206): boolean {
207 if (previous === next) return true;
208 if (previous.length !== next.length) return false;
209 const replacedIndex = getProjectionArrayReplacementIndex(previous, next);
210 if (replacedIndex !== undefined) return same(previous[replacedIndex]!, next[replacedIndex]!);
211 return previous.every((item, index) => same(item, next[index]!));
212}
213
214function sameVisibleTurnItemStructure(before: VisibleTurnItem, after: VisibleTurnItem): boolean {
215 return (
216 before === after ||
217 (before.position === after.position &&
218 before.visibility === after.visibility &&
219 before.sourceThreadId === after.sourceThreadId &&
220 before.sourceItemId === after.sourceItemId &&
221 sameTurnItemStructure(before.item, after.item))
222 );
223}
224
225/** Whether `next` only streams more text into assistant messages that were already streaming. */
226function sameApartFromStreamedAssistantText(
227 previous: OrchestrationV2ThreadProjection["visibleTurnItems"],
228 next: OrchestrationV2ThreadProjection["visibleTurnItems"],
229): boolean {
230 return sameProjectionArray(
231 previous,
232 next,
233 (before, after) =>
234 before === after ||
235 (before.item.type === "assistant_message" &&
236 before.item.streaming &&
237 after.item.type === "assistant_message" &&
238 after.item.streaming &&
239 // An empty message can be absent from the feed until its first visible text.
240 (before.item.text.trim().length === 0) === (after.item.text.trim().length === 0) &&
241 sameVisibleTurnItemStructure(before, after)),
242 );
243}
244
245/**
246 * Whether `previous` and `next` have the same ThreadStructure: they differ
247 * only by text streamed into existing assistant and reasoning items or by a
248 * visit mark. The same items exist, with the same status, and every other
249 * field is unchanged.
250 */
251export function sameThreadStructure(
252 previous: OrchestrationV2ThreadProjection,
253 next: OrchestrationV2ThreadProjection,
254): boolean {
255 if (previous === next) return true;
256 for (const key of Object.keys(next) as Array<keyof OrchestrationV2ThreadProjection>) {
257 if (
258 key === "thread" ||
259 key === "messages" ||
260 key === "turnItems" ||
261 key === "visibleTurnItems" ||
262 key === "updatedAt"
263 ) {
264 continue;
265 }
266 if (previous[key] !== next[key]) return false;
267 }
268 if (
269 previous.thread !== next.thread &&
270 !sameApartFromStripped(
271 sameAppThread,
272 previous.thread,
273 toThreadStructureThread(previous.thread),
274 next.thread,
275 )
276 ) {
277 return false;
278 }
279 return (
280 sameProjectionArray(previous.messages, next.messages, sameMessageStructure) &&
281 sameProjectionArray(previous.turnItems, next.turnItems, sameTurnItemStructure) &&
282 sameProjectionArray(
283 previous.visibleTurnItems,
284 next.visibleTurnItems,
285 sameVisibleTurnItemStructure,
286 )
287 );
288}
289
290export function createEnvironmentThreadDetailAtoms<E>(
291 threadStateAtom: (
292 environmentId: ScopedThreadRef["environmentId"],
293 threadId: ScopedThreadRef["threadId"],
294 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentThreadState, E>>,
295) {
296 const threadStateValueAtomFamily = Atom.family((key: string) => {
297 const ref = parseThreadKey(key);
298 return Atom.make((get) =>
299 AsyncResult.getOrElse(
300 get(threadStateAtom(ref.environmentId, ref.threadId)),
301 () => EMPTY_ENVIRONMENT_THREAD_STATE,
302 ),
303 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state-value:${key}`));
304 });
305
306 const threadAtomFamily = Atom.family((key: string) => {
307 const ref = parseThreadKey(key);
308 let previousProjection: OrchestrationV2ThreadProjection | null = null;
309 let previousValue: EnvironmentThread | null = null;
310 return Atom.make((get) => {
311 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
312 if (projection === previousProjection) return previousValue;
313 previousProjection = projection;
314 previousValue = projection === null ? null : { environmentId: ref.environmentId, projection };
315 return previousValue;
316 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread:${key}`));
317 });
318
319 // Streamed assistant and reasoning text replaces an item several times a
320 // second. Readers of the thread's structure (runs, requests, which items
321 // exist and their status) keep the previous value through those updates.
322 const quietThreadAtomFamily = Atom.family((key: string) => {
323 let previousProjection: OrchestrationV2ThreadProjection | null = null;
324 let previous: EnvironmentThreadStructure | null = null;
325 return Atom.make((get) => {
326 const next = get(threadAtomFamily(key));
327 if (next === null) {
328 previousProjection = null;
329 previous = null;
330 } else if (
331 previousProjection === null ||
332 !sameThreadStructure(previousProjection, next.projection)
333 ) {
334 previous = {
335 environmentId: next.environmentId,
336 projection: toThreadStructure(next.projection),
337 };
338 }
339 // Comparing the latest projection lets consecutive replacements bypass history scans.
340 previousProjection = next?.projection ?? null;
341 return previous;
342 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-quiet-thread:${key}`));
343 });
344
345 // Read from the structure so streamed text does not rescan runs and turn items.
346 const usageLimitNoticeRowsAtomFamily = Atom.family((key: string) => {
347 let previous: EnvironmentThreadStructure | null = null;
348 let value: UsageLimitNoticeRows | null = null;
349 return Atom.make((get) => {
350 const thread = get(quietThreadAtomFamily(key));
351 if (thread !== previous) {
352 previous = thread;
353 value = thread === null ? null : deriveUsageLimitNoticeRows(thread.projection);
354 }
355 return value;
356 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-usage-limit-notice:${key}`));
357 });
358
359 // Presentation only: the projection keeps every row for other readers.
360 const visibleTurnItemsAtomFamily = Atom.family((key: string) => {
361 const projectQuestionHistory = createQuestionHistoryProjector();
362 let previousRows: OrchestrationV2ThreadProjection["visibleTurnItems"] | null = null;
363 let previousNotice: UsageLimitNoticeRows | null = null;
364 let previous = EMPTY_VISIBLE_TURN_ITEMS;
365 return Atom.make((get): OrchestrationV2ThreadProjection["visibleTurnItems"] => {
366 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
367 if (projection === null) return EMPTY_VISIBLE_TURN_ITEMS;
368 const rows = projectQuestionHistory(projection);
369 const notice = get(usageLimitNoticeRowsAtomFamily(key));
370 if (rows !== previousRows || notice !== previousNotice) {
371 previousRows = rows;
372 previousNotice = notice;
373 previous = withoutUsageLimitNoticeRows(rows, notice);
374 }
375 return previous;
376 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-visible-turn-items:${key}`));
377 });
378
379 const quietVisibleTurnItemsAtomFamily = Atom.family((key: string) => {
380 const projectQuestionHistory = createQuestionHistoryProjector<ThreadStructureVisibleTurnItem>();
381 return Atom.make((get) => {
382 const thread = get(quietThreadAtomFamily(key));
383 return thread === null
384 ? EMPTY_THREAD_STRUCTURE_TURN_ITEMS
385 : projectQuestionHistory(thread.projection);
386 }).pipe(
387 Atom.setIdleTTL(0),
388 Atom.withLabel(`environment-quiet-thread-visible-turn-items:${key}`),
389 );
390 });
391
392 // Holds while only streamed assistant text moves, so the timeline re-renders on structure;
393 // each streaming message reads its text through assistantMessageTextAtom.
394 const timelineVisibleTurnItemsAtomFamily = Atom.family((key: string) => {
395 let previous = EMPTY_VISIBLE_TURN_ITEMS;
396 return Atom.make((get) => {
397 const next = get(visibleTurnItemsAtomFamily(key));
398 if (!sameApartFromStreamedAssistantText(previous, next)) previous = next;
399 return previous;
400 }).pipe(
401 Atom.setIdleTTL(0),
402 Atom.withLabel(`environment-thread-timeline-visible-turn-items:${key}`),
403 );
404 });
405
406 const assistantMessageTextAtomFamily = Atom.family((key: string) => {
407 const separator = key.lastIndexOf("\u0000");
408 const thread = key.slice(0, separator);
409 const itemId = key.slice(separator + 1);
410 return Atom.make((get) => {
411 const item = get(visibleTurnItemsAtomFamily(thread)).find(
412 (visibleItem) => visibleItem.item.id === itemId,
413 )?.item;
414 return item?.type === "assistant_message" ? item.text : null;
415 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-assistant-message-text:${key}`));
416 });
417
418 const queueWorkflowAtomFamily = Atom.family((key: string) => {
419 let previous: Pick<
420 OrchestrationV2ThreadProjection,
421 "thread" | "runs" | "messages" | "providerThreads" | "providerSessions" | "providerTurns"
422 > | null = null;
423 let previousStopRequested = false;
424 let previousStructure: EnvironmentThreadStructure | null = null;
425 let stopRequested = false;
426 let value: ThreadQueueWorkflowState | null = null;
427 return Atom.make((get) => {
428 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
429 // The structure holds through streamed text, so Stop is checked without a scan per chunk.
430 const structure = get(quietThreadAtomFamily(key));
431 if (structure !== previousStructure) {
432 previousStructure = structure;
433 stopRequested =
434 structure !== null &&
435 runStopRequested(structure.projection, resolveActiveThreadRun(structure.projection)?.id);
436 }
437 if (projection === null) {
438 previous = null;
439 value = null;
440 } else if (
441 previous === null ||
442 stopRequested !== previousStopRequested ||
443 projection.thread !== previous.thread ||
444 projection.runs !== previous.runs ||
445 projection.messages !== previous.messages ||
446 projection.providerThreads !== previous.providerThreads ||
447 projection.providerSessions !== previous.providerSessions ||
448 projection.providerTurns !== previous.providerTurns
449 ) {
450 const next = deriveThreadQueueWorkflowState(projection);
451 if (value === null || !queueWorkflowStatesEqual(value, next)) value = next;
452 const { thread, runs, messages, providerThreads, providerSessions, providerTurns } =
453 projection;
454 previous = { thread, runs, messages, providerThreads, providerSessions, providerTurns };
455 previousStopRequested = stopRequested;
456 }
457 return value;
458 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-queue:${key}`));
459 });
460 const runStopAtomFamily = Atom.family((key: string) => {
461 let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems"> | null = null;
462 let stop: RunStopPresentation | null = null;
463 return Atom.make((get) => {
464 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
465 if (projection === null) {
466 previous = null;
467 stop = null;
468 } else if (
469 projection.runs !== previous?.runs ||
470 projection.turnItems !== previous?.turnItems
471 ) {
472 const { runs, turnItems } = projection;
473 previous = { runs, turnItems };
474 const next = presentRunStop(previous);
475 if (
476 next?.state !== stop?.state ||
477 next?.runId !== stop?.runId ||
478 next?.requestedAt !== stop?.requestedAt ||
479 next?.background !== stop?.background
480 )
481 stop = next;
482 }
483 return stop;
484 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-run-stop:${key}`));
485 });
486 const queuedCountAtomFamily = Atom.family((key: string) => {
487 let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "messages"> | null = null;
488 let count = 0;
489 return Atom.make((get) => {
490 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
491 if (projection === null) {
492 previous = null;
493 count = 0;
494 } else if (projection.runs !== previous?.runs || projection.messages !== previous?.messages) {
495 const { runs, messages } = projection;
496 previous = { runs, messages };
497 count = getUserQueuedThreadRuns(previous).length;
498 }
499 return count;
500 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-queue-count:${key}`));
501 });
502
503 const turnSubagentsAtomFamily = Atom.family((key: string) => {
504 let previous: Pick<OrchestrationV2ThreadProjection, "runs" | "subagents"> | null = null;
505 let value: ThreadTurnSubagents | null = null;
506 return Atom.make((get) => {
507 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
508 if (projection === null) {
509 previous = null;
510 value = null;
511 } else if (
512 projection.runs !== previous?.runs ||
513 projection.subagents !== previous?.subagents
514 ) {
515 const { runs, subagents } = projection;
516 previous = { runs, subagents };
517 value = deriveThreadTurnSubagents(previous);
518 }
519 return value;
520 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-turn-subagents:${key}`));
521 });
522
523 const checkpointSummariesAtomFamily = Atom.family((key: string) => {
524 let previous: Pick<
525 OrchestrationV2ThreadProjection,
526 "checkpoints" | "checkpointScopes" | "messages"
527 > | null = null;
528 let value = EMPTY_CHECKPOINT_SUMMARIES;
529 return Atom.make((get) => {
530 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
531 if (projection === null) {
532 previous = null;
533 value = EMPTY_CHECKPOINT_SUMMARIES;
534 } else if (
535 projection.checkpoints !== previous?.checkpoints ||
536 projection.checkpointScopes !== previous?.checkpointScopes ||
537 projection.messages !== previous?.messages
538 ) {
539 const { checkpoints, checkpointScopes, messages } = projection;
540 const next = deriveThreadCheckpointSummaries({ checkpoints, checkpointScopes, messages });
541 // The same checkpoints give the same summaries; messages only pick each assistant message.
542 if (
543 checkpoints !== previous?.checkpoints ||
544 checkpointScopes !== previous?.checkpointScopes ||
545 next.some(
546 (summary, index) => summary.assistantMessageId !== value[index]?.assistantMessageId,
547 )
548 )
549 value = next;
550 previous = { checkpoints, checkpointScopes, messages };
551 }
552 return value;
553 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-checkpoint-summaries:${key}`));
554 });
555
556 const lastVisitedAtAtomFamily = Atom.family((key: string) =>
557 Atom.make(
558 (get) =>
559 Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.thread.lastVisitedAt ?? null,
560 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-last-visited:${key}`)),
561 );
562 const updatedAtAtomFamily = Atom.family((key: string) =>
563 Atom.make(
564 (get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.updatedAt ?? null,
565 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-updated-at:${key}`)),
566 );
567 const worktreePathAtomFamily = Atom.family((key: string) =>
568 Atom.make(
569 (get) =>
570 Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.thread.worktreePath ?? null,
571 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-worktree:${key}`)),
572 );
573 const pendingRequestsAtomFamily = Atom.family((key: string) => {
574 let previous: Pick<OrchestrationV2ThreadProjection, "runtimeRequests" | "turnItems"> | null =
575 null;
576 let value: PendingThreadRequests | null = null;
577 return Atom.make((get) => {
578 const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
579 if (projection === null) {
580 previous = null;
581 value = null;
582 return value;
583 }
584 const runtimeRequests = projection.runtimeRequests.filter(
585 (request) => request.status === "pending",
586 );
587 const ids = new Set(runtimeRequests.map((request) => request.id));
588 const turnItems =
589 ids.size === 0
590 ? []
591 : projection.turnItems.filter(
592 (item) =>
593 (item.type === "approval_request" || item.type === "user_input_request") &&
594 ids.has(item.requestId),
595 );
596 if (
597 previous === null ||
598 !arrayElementsEqual(previous.runtimeRequests, runtimeRequests) ||
599 !arrayElementsEqual(previous.turnItems, turnItems)
600 ) {
601 previous = { runtimeRequests, turnItems };
602 value = derivePendingThreadRequests(previous);
603 }
604 return value;
605 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-pending-requests:${key}`));
606 });
607
608 const statusAtomFamily = Atom.family((key: string) =>
609 Atom.make((get) => get(threadStateValueAtomFamily(key)).status).pipe(
610 Atom.setIdleTTL(0),
611 Atom.withLabel(`environment-thread-status:${key}`),
612 ),
613 );
614 const sequenceAtomFamily = Atom.family((key: string) =>
615 Atom.make((get) => get(threadStateValueAtomFamily(key)).sequence).pipe(
616 Atom.setIdleTTL(0),
617 Atom.withLabel(`environment-thread-sequence:${key}`),
618 ),
619 );
620 const errorAtomFamily = Atom.family((key: string) =>
621 Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe(
622 Atom.setIdleTTL(0),
623 Atom.withLabel(`environment-thread-error:${key}`),
624 ),
625 );
626 const historyAtomFamily = Atom.family((key: string) =>
627 Atom.make((get) => get(threadStateValueAtomFamily(key)).history).pipe(
628 Atom.setIdleTTL(0),
629 Atom.withLabel(`environment-thread-history:${key}`),
630 ),
631 );
632
633 const workspaceMutationIdAtomFamily = Atom.family((key: string) =>
634 Atom.make((get) =>
635 deriveWorkspaceMutationId(
636 get(quietVisibleTurnItemsAtomFamily(key)),
637 get(checkpointSummariesAtomFamily(key)).at(-1)?.completedAt ?? null,
638 ),
639 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-workspace-mutation-id:${key}`)),
640 );
641
642 return {
643 worktreePathAtom: (ref: ScopedThreadRef) => worktreePathAtomFamily(threadKey(ref)),
644 workspaceMutationIdAtom: (ref: ScopedThreadRef) =>
645 workspaceMutationIdAtomFamily(threadKey(ref)),
646 updatedAtAtom: (ref: ScopedThreadRef) => updatedAtAtomFamily(threadKey(ref)),
647 lastVisitedAtAtom: (ref: ScopedThreadRef) => lastVisitedAtAtomFamily(threadKey(ref)),
648 pendingRequestsAtom: (ref: ScopedThreadRef) => pendingRequestsAtomFamily(threadKey(ref)),
649 queueWorkflowAtom: (ref: ScopedThreadRef) => queueWorkflowAtomFamily(threadKey(ref)),
650 queuedCountAtom: (ref: ScopedThreadRef) => queuedCountAtomFamily(threadKey(ref)),
651 runStopAtom: (ref: ScopedThreadRef) => runStopAtomFamily(threadKey(ref)),
652 turnSubagentsAtom: (ref: ScopedThreadRef) => turnSubagentsAtomFamily(threadKey(ref)),
653 checkpointSummariesAtom: (ref: ScopedThreadRef) =>
654 checkpointSummariesAtomFamily(threadKey(ref)),
655 stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)),
656 threadAtom: (ref: ScopedThreadRef) => threadAtomFamily(threadKey(ref)),
657 quietThreadAtom: (ref: ScopedThreadRef) => quietThreadAtomFamily(threadKey(ref)),
658 visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)),
659 quietVisibleTurnItemsAtom: (ref: ScopedThreadRef) =>
660 quietVisibleTurnItemsAtomFamily(threadKey(ref)),
661 timelineVisibleTurnItemsAtom: (ref: ScopedThreadRef) =>
662 timelineVisibleTurnItemsAtomFamily(threadKey(ref)),
663 assistantMessageTextAtom: (ref: ScopedThreadRef, itemId: string) =>
664 assistantMessageTextAtomFamily(`${threadKey(ref)}\u0000${itemId}`),
665 statusAtom: (ref: ScopedThreadRef) => statusAtomFamily(threadKey(ref)),
666 sequenceAtom: (ref: ScopedThreadRef) => sequenceAtomFamily(threadKey(ref)),
667 errorAtom: (ref: ScopedThreadRef) => errorAtomFamily(threadKey(ref)),
668 historyAtom: (ref: ScopedThreadRef) => historyAtomFamily(threadKey(ref)),
669 };
670}