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