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, 03:37 UTC
| 1 | import { mFallback, msg } from "gt-i18n"; |
| 2 | import type { MFunctionType } from "gt-i18n/types"; |
| 3 | import { |
| 4 | isOrchestrationV2WorkActive, |
| 5 | ORCHESTRATION_V2_WS_METHODS, |
| 6 | type EnvironmentId as EnvironmentIdType, |
| 7 | type OrchestrationV2ThreadDetailSnapshot, |
| 8 | type OrchestrationV2ThreadProjection, |
| 9 | type OrchestrationV2ThreadStreamItem, |
| 10 | type OrchestrationV2TurnItem, |
| 11 | type ThreadId as ThreadIdType, |
| 12 | } from "@t3tools/contracts"; |
| 13 | import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; |
| 14 | import { pendingBackgroundTurnItems } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; |
| 15 | import * as Cause from "effect/Cause"; |
| 16 | import * as Effect from "effect/Effect"; |
| 17 | import * as Fiber from "effect/Fiber"; |
| 18 | import * as Scope from "effect/Scope"; |
| 19 | import * as Option from "effect/Option"; |
| 20 | import * as Queue from "effect/Queue"; |
| 21 | import * as Ref from "effect/Ref"; |
| 22 | import * as Result from "effect/Result"; |
| 23 | import * as Semaphore from "effect/Semaphore"; |
| 24 | import * as Stream from "effect/Stream"; |
| 25 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 26 | import { HttpClient } from "effect/http"; |
| 27 | import { Atom } from "effect/reactivity"; |
| 28 | |
| 29 | import * as RemoteEnvironmentAuthorization from "../authorization/service.ts"; |
| 30 | import * as EnvironmentRegistry from "../connection/registry.ts"; |
| 31 | import { connectionProjectionPhase } from "../connection/model.ts"; |
| 32 | import * as EnvironmentSupervisor from "../connection/supervisor.ts"; |
| 33 | import * as ConnectionWakeups from "../connection/wakeups.ts"; |
| 34 | import * as Persistence from "../platform/persistence.ts"; |
| 35 | import { runCachePersistence } from "./cachePersistence.ts"; |
| 36 | import * as ManagedRelay from "../relay/managedRelay.ts"; |
| 37 | import { |
| 38 | isAuthorizationFailure, |
| 39 | request, |
| 40 | subscribeDynamic, |
| 41 | subscriptionRetryDelay, |
| 42 | } from "../rpc/client.ts"; |
| 43 | import { parseThreadKey, threadKey } from "./entities.ts"; |
| 44 | import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; |
| 45 | import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts"; |
| 46 | import { followStreamInEnvironment } from "./runtime.ts"; |
| 47 | import * as ThreadHistoryController from "./threadHistoryController.ts"; |
| 48 | import { fetchEnvironmentThreadHistoryPage } from "./threadHistoryHttp.ts"; |
| 49 | import { |
| 50 | applyHistoryPageMeta, |
| 51 | clearActiveHistoryLoading, |
| 52 | EMPTY_THREAD_HISTORY_META, |
| 53 | isActiveHistoryRequestCursor, |
| 54 | mergeOlderHistoryIntoProjection, |
| 55 | mergeOlderSubagentsIntoProjection, |
| 56 | type ThreadHistoryMeta, |
| 57 | } from "./threadHistoryMerge.ts"; |
| 58 | import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts"; |
| 59 | import { makeThreadRequestsResolvedAnnouncer } from "./threadRequests.ts"; |
| 60 | import { |
| 61 | EMPTY_ENVIRONMENT_THREAD_STATE, |
| 62 | type EnvironmentThreadState, |
| 63 | type EnvironmentThreadStatus, |
| 64 | } from "./threadState.ts"; |
| 65 | |
| 66 | const THREAD_SUBSCRIPTION_RETRY_DELAY = "250 millis"; |
| 67 | |
| 68 | function statusWithoutLiveData( |
| 69 | data: Option.Option<OrchestrationV2ThreadProjection>, |
| 70 | ): EnvironmentThreadStatus { |
| 71 | return Option.isSome(data) ? "cached" : "empty"; |
| 72 | } |
| 73 | |
| 74 | const THREAD_SYNC_ERROR = msg("Could not synchronize the thread."); |
| 75 | const HISTORY_LOAD_ERROR = msg("Could not load earlier activity."); |
| 76 | const WORK_HISTORY_CHANGED_ERROR = msg("Work history changed. Retry loading it."); |
| 77 | const THREAD_ERRORS: ReadonlySet<string> = new Set([ |
| 78 | THREAD_SYNC_ERROR, |
| 79 | HISTORY_LOAD_ERROR, |
| 80 | WORK_HISTORY_CHANGED_ERROR, |
| 81 | ]); |
| 82 | |
| 83 | /** |
| 84 | * A thread or history error in the active language. Errors this module wrote translate; |
| 85 | * messages from the server or another error stay as they are. |
| 86 | * @public |
| 87 | */ |
| 88 | export function threadErrorText(error: string, resolve: MFunctionType = mFallback): string { |
| 89 | return THREAD_ERRORS.has(error) ? resolve(error) : error; |
| 90 | } |
| 91 | |
| 92 | function formatThreadError(cause: Cause.Cause<unknown>): string { |
| 93 | const error = Cause.squash(cause); |
| 94 | return error instanceof Error && error.message.trim().length > 0 |
| 95 | ? error.message |
| 96 | : THREAD_SYNC_ERROR; |
| 97 | } |
| 98 | |
| 99 | function formatHistoryError(error: unknown): string { |
| 100 | if (error instanceof Error && error.message.trim().length > 0) { |
| 101 | return error.message; |
| 102 | } |
| 103 | return HISTORY_LOAD_ERROR; |
| 104 | } |
| 105 | |
| 106 | // Steers join a running turn; every other user message opens one. The timeline shows every |
| 107 | // notification as a response boundary, whether it opened its run or arrived mid-run. |
| 108 | function startsTurn(item: OrchestrationV2TurnItem): boolean { |
| 109 | return ( |
| 110 | item.type === "notification" || |
| 111 | (item.type === "user_message" && |
| 112 | item.inputIntent !== "steer" && |
| 113 | item.inputIntent !== "promoted_queued_to_steer") |
| 114 | ); |
| 115 | } |
| 116 | |
| 117 | function historyMetaFromCachedSnapshot( |
| 118 | snapshot: OrchestrationV2ThreadDetailSnapshot, |
| 119 | ): ThreadHistoryMeta { |
| 120 | const historyCursor = snapshot.historyCursor ?? null; |
| 121 | const hasMoreHistory = snapshot.hasMoreHistory ?? false; |
| 122 | return { |
| 123 | historyCursor, |
| 124 | hasMoreHistory, |
| 125 | loading: false, |
| 126 | error: null, |
| 127 | expanded: false, |
| 128 | latestLocalTurnOrdinal: snapshot.latestLocalTurnOrdinal ?? null, |
| 129 | }; |
| 130 | } |
| 131 | |
| 132 | function snapshotToPersist( |
| 133 | snapshotSequence: number, |
| 134 | projection: OrchestrationV2ThreadProjection, |
| 135 | history: ThreadHistoryMeta, |
| 136 | acceptsBoundedSnapshots: boolean, |
| 137 | ): OrchestrationV2ThreadDetailSnapshot { |
| 138 | // A complete bounded snapshot still proves paging support. Retain that evidence |
| 139 | // so a thread that grows while closed can resume with a bounded fallback. |
| 140 | if (acceptsBoundedSnapshots || history.hasMoreHistory || history.historyCursor !== null) { |
| 141 | return { |
| 142 | snapshotSequence, |
| 143 | projection, |
| 144 | historyCursor: history.historyCursor, |
| 145 | hasMoreHistory: history.hasMoreHistory, |
| 146 | latestLocalTurnOrdinal: history.latestLocalTurnOrdinal, |
| 147 | }; |
| 148 | } |
| 149 | return { snapshotSequence, projection }; |
| 150 | } |
| 151 | |
| 152 | function shouldPersistThread( |
| 153 | thread: OrchestrationV2ThreadProjection, |
| 154 | history: ThreadHistoryMeta, |
| 155 | ): boolean { |
| 156 | // After the user loads older pages the in-memory timeline can grow large. |
| 157 | // Keep those expanded projections out of the monolithic cache. |
| 158 | if (history.expanded) { |
| 159 | return false; |
| 160 | } |
| 161 | return !thread.runs.some( |
| 162 | (run) => run.status === "preparing" || run.status === "starting" || run.status === "running", |
| 163 | ); |
| 164 | } |
| 165 | |
| 166 | // Only still-active local copies take the server's item: events applied meanwhile win, |
| 167 | // and inherited rows belong to another thread. |
| 168 | function settleTurnItems( |
| 169 | threadId: ThreadIdType, |
| 170 | projection: OrchestrationV2ThreadProjection, |
| 171 | settled: ReadonlyMap<string, OrchestrationV2TurnItem>, |
| 172 | ): OrchestrationV2ThreadProjection { |
| 173 | let changed = false; |
| 174 | const settle = (item: OrchestrationV2TurnItem, id: string) => { |
| 175 | const server = settled.get(id); |
| 176 | if (server === undefined || !isOrchestrationV2WorkActive(item.status)) return item; |
| 177 | changed = true; |
| 178 | return server; |
| 179 | }; |
| 180 | const turnItems = projection.turnItems.map((item) => settle(item, item.id)); |
| 181 | const visibleTurnItems = projection.visibleTurnItems.map((row) => { |
| 182 | if (row.sourceThreadId !== threadId) return row; |
| 183 | const item = settle(row.item, row.sourceItemId); |
| 184 | return item === row.item ? row : { ...row, item }; |
| 185 | }); |
| 186 | return changed ? { ...projection, turnItems, visibleTurnItems } : projection; |
| 187 | } |
| 188 | |
| 189 | interface ThreadResumeSnapshot { |
| 190 | readonly state: EnvironmentThreadState; |
| 191 | readonly sequence: number; |
| 192 | readonly persisted: boolean; |
| 193 | readonly acceptsBoundedSnapshots?: boolean; |
| 194 | } |
| 195 | |
| 196 | interface ThreadResumeCache { |
| 197 | snapshot: ThreadResumeSnapshot | undefined; |
| 198 | owner: object | undefined; |
| 199 | } |
| 200 | |
| 201 | function matchesThreadSnapshot( |
| 202 | current: ThreadResumeSnapshot, |
| 203 | projection: OrchestrationV2ThreadProjection | null, |
| 204 | sequence: number, |
| 205 | history: Pick<ThreadHistoryMeta, "historyCursor" | "hasMoreHistory" | "latestLocalTurnOrdinal">, |
| 206 | ): boolean { |
| 207 | if (current.sequence !== sequence || Option.getOrNull(current.state.data) !== projection) |
| 208 | return false; |
| 209 | const currentHistory = current.state.history; |
| 210 | return ( |
| 211 | currentHistory.historyCursor === history.historyCursor && |
| 212 | currentHistory.hasMoreHistory === history.hasMoreHistory && |
| 213 | (!(history.hasMoreHistory || history.historyCursor !== null) || |
| 214 | currentHistory.latestLocalTurnOrdinal === history.latestLocalTurnOrdinal) |
| 215 | ); |
| 216 | } |
| 217 | |
| 218 | function cachedThreadState(value: EnvironmentThreadState): EnvironmentThreadState { |
| 219 | return { |
| 220 | ...value, |
| 221 | status: |
| 222 | value.status === "deleted" || (value.status === "live" && Option.isSome(value.data)) |
| 223 | ? value.status |
| 224 | : statusWithoutLiveData(value.data), |
| 225 | error: Option.none(), |
| 226 | history: { ...value.history, loading: false, error: null }, |
| 227 | }; |
| 228 | } |
| 229 | |
| 230 | function hasMissingPendingQuestionCard(projection: OrchestrationV2ThreadProjection): boolean { |
| 231 | const pending = new Set( |
| 232 | projection.runtimeRequests |
| 233 | .filter((request) => request.kind === "user_input" && request.status === "pending") |
| 234 | .map((request) => request.id), |
| 235 | ); |
| 236 | if (pending.size === 0) return false; |
| 237 | for (const item of projection.turnItems) { |
| 238 | if (item.type === "user_input_request") pending.delete(item.requestId); |
| 239 | if (pending.size === 0) return false; |
| 240 | } |
| 241 | return true; |
| 242 | } |
| 243 | |
| 244 | export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* ( |
| 245 | threadId: ThreadIdType, |
| 246 | resumeCache?: ThreadResumeCache, |
| 247 | ) { |
| 248 | const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; |
| 249 | const cache = yield* Persistence.EnvironmentCacheStore; |
| 250 | const snapshotLoader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader; |
| 251 | const historyController = yield* Effect.serviceOption( |
| 252 | ThreadHistoryController.ThreadHistoryController, |
| 253 | ); |
| 254 | const httpClient = yield* Effect.serviceOption(HttpClient.HttpClient); |
| 255 | const dpopSigner = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner); |
| 256 | const remoteAuthorization = yield* Effect.serviceOption( |
| 257 | RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, |
| 258 | ); |
| 259 | const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups); |
| 260 | const environmentId = supervisor.target.environmentId; |
| 261 | const candidate = resumeCache?.snapshot; |
| 262 | const retained = |
| 263 | candidate && |
| 264 | Option.isSome(candidate.state.data) && |
| 265 | hasMissingPendingQuestionCard(candidate.state.data.value) |
| 266 | ? undefined |
| 267 | : candidate; |
| 268 | const owner = {}; |
| 269 | if (resumeCache) resumeCache.owner = owner; |
| 270 | const loaded = |
| 271 | retained === undefined |
| 272 | ? yield* cache.loadThread(environmentId, threadId).pipe( |
| 273 | Effect.catch((error) => |
| 274 | Effect.logWarning("Could not load cached thread.").pipe( |
| 275 | Effect.annotateLogs({ |
| 276 | environmentId, |
| 277 | threadId, |
| 278 | error: error.message, |
| 279 | }), |
| 280 | Effect.as(Option.none<OrchestrationV2ThreadDetailSnapshot>()), |
| 281 | ), |
| 282 | ), |
| 283 | ) |
| 284 | : Option.none<OrchestrationV2ThreadDetailSnapshot>(); |
| 285 | // Old bounded caches can omit a pending question's card; replay alone cannot restore it. |
| 286 | const cached = Option.filter( |
| 287 | loaded, |
| 288 | (snapshot) => !hasMissingPendingQuestionCard(snapshot.projection), |
| 289 | ); |
| 290 | const cachedThread = Option.map(cached, (snapshot) => snapshot.projection); |
| 291 | // Seed the resume cursor from the cached snapshot so a warm cache can catch up |
| 292 | // via `afterSequence` instead of re-downloading the full thread body. |
| 293 | const initialSequence = |
| 294 | retained?.sequence ?? |
| 295 | Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence }); |
| 296 | const initialState: EnvironmentThreadState = retained |
| 297 | ? cachedThreadState(retained.state) |
| 298 | : { |
| 299 | data: cachedThread, |
| 300 | status: statusWithoutLiveData(cachedThread), |
| 301 | error: Option.none(), |
| 302 | history: Option.match(cached, { |
| 303 | onNone: () => EMPTY_THREAD_HISTORY_META, |
| 304 | onSome: historyMetaFromCachedSnapshot, |
| 305 | }), |
| 306 | sequence: initialSequence, |
| 307 | }; |
| 308 | const state = yield* SubscriptionRef.make(initialState); |
| 309 | const canLoadHistory = Option.isSome(httpClient) && Option.isSome(historyController); |
| 310 | const acceptsBoundedSocketSnapshots = yield* Ref.make(canLoadHistory); |
| 311 | const lastSequence = yield* SubscriptionRef.make(initialSequence); |
| 312 | let committed: ThreadResumeSnapshot = { |
| 313 | state: initialState, |
| 314 | sequence: initialSequence, |
| 315 | persisted: retained?.persisted ?? Option.isSome(cached), |
| 316 | acceptsBoundedSnapshots: canLoadHistory, |
| 317 | }; |
| 318 | if (resumeCache?.owner === owner) resumeCache.snapshot = committed; |
| 319 | const awaitingCompletion = yield* Ref.make(false); |
| 320 | const applyLock = yield* Semaphore.make(1); |
| 321 | // Save only completed data/cursor updates. A canceled scope must not cache |
| 322 | // a cursor whose event has not reached the data yet. |
| 323 | const announceRequests = makeThreadRequestsResolvedAnnouncer(environmentId, threadId); |
| 324 | const remember = Effect.gen(function* () { |
| 325 | const current = yield* SubscriptionRef.get(state); |
| 326 | const sequence = yield* SubscriptionRef.get(lastSequence); |
| 327 | // Only a synchronized projection from the scope that owns the thread is |
| 328 | // authoritative: a cached one can predate a request the user already has |
| 329 | // drafts for, and a superseded scope can lag its successor. |
| 330 | const owns = resumeCache === undefined || resumeCache.owner === owner; |
| 331 | if (owns && current.status === "deleted") announceRequests([]); |
| 332 | else if (owns && current.status === "live" && Option.isSome(current.data)) |
| 333 | announceRequests(current.data.value.runtimeRequests); |
| 334 | committed = { |
| 335 | state: current, |
| 336 | sequence, |
| 337 | acceptsBoundedSnapshots: yield* Ref.get(acceptsBoundedSocketSnapshots), |
| 338 | persisted: |
| 339 | committed.persisted && |
| 340 | matchesThreadSnapshot(committed, Option.getOrNull(current.data), sequence, current.history), |
| 341 | }; |
| 342 | if (resumeCache?.owner === owner) resumeCache.snapshot = committed; |
| 343 | }); |
| 344 | const persistence = yield* Queue.sliding<OrchestrationV2ThreadDetailSnapshot>(1); |
| 345 | let queuedSnapshot = Option.getOrUndefined(cached); |
| 346 | let savedSnapshot = queuedSnapshot; |
| 347 | const queuePersist = (snapshot: OrchestrationV2ThreadDetailSnapshot) => |
| 348 | Effect.suspend(() => { |
| 349 | queuedSnapshot = snapshot; |
| 350 | return Queue.offer(persistence, snapshot); |
| 351 | }); |
| 352 | |
| 353 | const persist = Effect.fn("EnvironmentThreadState.persist")(function* ( |
| 354 | snapshot: OrchestrationV2ThreadDetailSnapshot, |
| 355 | ) { |
| 356 | if (resumeCache !== undefined && resumeCache.owner !== owner) return; |
| 357 | if (committed.state.status === "deleted") return; |
| 358 | if ( |
| 359 | committed.persisted && |
| 360 | matchesThreadSnapshot( |
| 361 | committed, |
| 362 | snapshot.projection, |
| 363 | snapshot.snapshotSequence, |
| 364 | historyMetaFromCachedSnapshot(snapshot), |
| 365 | ) |
| 366 | ) |
| 367 | return; |
| 368 | yield* cache.saveThread(environmentId, snapshot).pipe( |
| 369 | Effect.tap(() => |
| 370 | Effect.sync(() => { |
| 371 | savedSnapshot = snapshot; |
| 372 | if ( |
| 373 | !matchesThreadSnapshot( |
| 374 | committed, |
| 375 | snapshot.projection, |
| 376 | snapshot.snapshotSequence, |
| 377 | historyMetaFromCachedSnapshot(snapshot), |
| 378 | ) |
| 379 | ) |
| 380 | return; |
| 381 | committed = { ...committed, persisted: true }; |
| 382 | if (resumeCache?.owner === owner) resumeCache.snapshot = committed; |
| 383 | }), |
| 384 | ), |
| 385 | Effect.catch((error) => |
| 386 | Effect.logWarning("Could not persist the thread cache.").pipe( |
| 387 | Effect.annotateLogs({ |
| 388 | environmentId, |
| 389 | threadId, |
| 390 | error: error.message, |
| 391 | }), |
| 392 | ), |
| 393 | ), |
| 394 | ); |
| 395 | }); |
| 396 | |
| 397 | yield* Effect.addFinalizer(() => |
| 398 | Effect.suspend(() => { |
| 399 | const { state: current, sequence: snapshotSequence } = committed; |
| 400 | return Option.match(current.data, { |
| 401 | onNone: () => Effect.void, |
| 402 | onSome: (projection) => |
| 403 | !current.history.expanded |
| 404 | ? persist( |
| 405 | snapshotToPersist( |
| 406 | snapshotSequence, |
| 407 | projection, |
| 408 | current.history, |
| 409 | committed.acceptsBoundedSnapshots === true, |
| 410 | ), |
| 411 | ) |
| 412 | : // The consumer may still be waiting out its delay; an expanded thread queues |
| 413 | // only cache repairs, which must survive leaving the thread. |
| 414 | queuedSnapshot !== undefined && queuedSnapshot !== savedSnapshot |
| 415 | ? persist(queuedSnapshot) |
| 416 | : Effect.void, |
| 417 | }); |
| 418 | }), |
| 419 | ); |
| 420 | |
| 421 | yield* runCachePersistence(persistence, persist).pipe(Effect.forkScoped); |
| 422 | |
| 423 | const setConnecting = SubscriptionRef.update(state, (current) => |
| 424 | current.status === "deleted" || Option.isSome(current.error) |
| 425 | ? current |
| 426 | : { |
| 427 | ...current, |
| 428 | status: "synchronizing" as const, |
| 429 | error: Option.none(), |
| 430 | }, |
| 431 | ); |
| 432 | const setReady = SubscriptionRef.update(state, (current) => |
| 433 | current.status === "live" || current.status === "deleted" || Option.isSome(current.error) |
| 434 | ? current |
| 435 | : { |
| 436 | ...current, |
| 437 | status: "synchronizing" as const, |
| 438 | error: Option.none(), |
| 439 | }, |
| 440 | ); |
| 441 | const setDisconnected = Effect.gen(function* () { |
| 442 | yield* Ref.set(awaitingCompletion, false); |
| 443 | yield* SubscriptionRef.update(state, (current) => ({ |
| 444 | ...current, |
| 445 | status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data), |
| 446 | })); |
| 447 | }); |
| 448 | const setStreamError = (message: string) => |
| 449 | Ref.set(awaitingCompletion, false).pipe( |
| 450 | Effect.andThen( |
| 451 | SubscriptionRef.update(state, (current) => ({ |
| 452 | ...current, |
| 453 | status: |
| 454 | current.status === "deleted" ? current.status : statusWithoutLiveData(current.data), |
| 455 | error: Option.some(message), |
| 456 | })), |
| 457 | ), |
| 458 | ); |
| 459 | |
| 460 | const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* ( |
| 461 | thread: OrchestrationV2ThreadProjection, |
| 462 | options?: { |
| 463 | readonly resetHistory?: boolean; |
| 464 | readonly history?: ThreadHistoryMeta; |
| 465 | }, |
| 466 | ) { |
| 467 | const waiting = yield* Ref.get(awaitingCompletion); |
| 468 | const sequence = yield* SubscriptionRef.get(lastSequence); |
| 469 | // Atomic with concurrent history meta updates: never get-then-set the whole |
| 470 | // state when only the projection changes. Bounded installs pass history so |
| 471 | // projection + cursor persist together in one enqueue. |
| 472 | const next = yield* SubscriptionRef.updateAndGet(state, (previous) => { |
| 473 | const history = |
| 474 | options?.history !== undefined |
| 475 | ? options.history |
| 476 | : options?.resetHistory === true |
| 477 | ? EMPTY_THREAD_HISTORY_META |
| 478 | : previous.history; |
| 479 | return { |
| 480 | ...previous, |
| 481 | data: Option.some(thread), |
| 482 | status: Option.isSome(previous.error) |
| 483 | ? ("cached" as const) |
| 484 | : waiting |
| 485 | ? ("synchronizing" as const) |
| 486 | : ("live" as const), |
| 487 | error: previous.error, |
| 488 | history, |
| 489 | sequence, |
| 490 | }; |
| 491 | }); |
| 492 | // Active projections can update many times per second and retain large tool |
| 493 | // payloads. Persist once the run settles so cache encoding stays off the |
| 494 | // streaming path. Progressive meta rides along when the window is incomplete. |
| 495 | if (shouldPersistThread(thread, next.history)) { |
| 496 | const snapshotSequence = yield* SubscriptionRef.get(lastSequence); |
| 497 | yield* queuePersist( |
| 498 | snapshotToPersist( |
| 499 | snapshotSequence, |
| 500 | thread, |
| 501 | next.history, |
| 502 | yield* Ref.get(acceptsBoundedSocketSnapshots), |
| 503 | ), |
| 504 | ); |
| 505 | } |
| 506 | }); |
| 507 | |
| 508 | const patchHistoryMeta = (patch: (history: ThreadHistoryMeta) => ThreadHistoryMeta) => |
| 509 | SubscriptionRef.update(state, (current) => ({ |
| 510 | ...current, |
| 511 | history: patch(current.history), |
| 512 | })); |
| 513 | |
| 514 | const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () { |
| 515 | yield* Ref.set(awaitingCompletion, false); |
| 516 | yield* SubscriptionRef.set(state, { |
| 517 | data: Option.none(), |
| 518 | status: "deleted", |
| 519 | error: Option.none(), |
| 520 | history: EMPTY_THREAD_HISTORY_META, |
| 521 | sequence: yield* SubscriptionRef.get(lastSequence), |
| 522 | }); |
| 523 | yield* remember; |
| 524 | if (resumeCache !== undefined && resumeCache.owner !== owner) return; |
| 525 | yield* cache.removeThread(environmentId, threadId).pipe( |
| 526 | Effect.catch((error) => |
| 527 | Effect.logWarning("Could not remove the cached thread.").pipe( |
| 528 | Effect.annotateLogs({ |
| 529 | environmentId, |
| 530 | threadId, |
| 531 | error: error.message, |
| 532 | }), |
| 533 | ), |
| 534 | ), |
| 535 | ); |
| 536 | }); |
| 537 | |
| 538 | type EventItem = Extract<OrchestrationV2ThreadStreamItem, { kind: "event" }>; |
| 539 | type SequencedItem = Extract< |
| 540 | OrchestrationV2ThreadStreamItem, |
| 541 | { kind: "event" | "unknown-event" } |
| 542 | >; |
| 543 | // Per-batch streaming spans add trace volume without a useful timing boundary. |
| 544 | const applyEventsLocked = Effect.fnUntraced(function* (items: ReadonlyArray<SequencedItem>) { |
| 545 | const appliedSequence = yield* SubscriptionRef.get(lastSequence); |
| 546 | let sequence = appliedSequence; |
| 547 | const fresh: EventItem[] = []; |
| 548 | for (const item of items) { |
| 549 | if (item.sequence <= sequence) continue; |
| 550 | sequence = item.sequence; |
| 551 | if (item.kind === "event") { |
| 552 | fresh.push(item); |
| 553 | continue; |
| 554 | } |
| 555 | yield* Effect.logDebug("Skipped a thread event type this client does not know.").pipe( |
| 556 | Effect.annotateLogs({ |
| 557 | environmentId, |
| 558 | threadId, |
| 559 | eventType: item.eventType.slice(0, 64), |
| 560 | sequence: item.sequence, |
| 561 | }), |
| 562 | ); |
| 563 | } |
| 564 | if (sequence === appliedSequence) return; |
| 565 | yield* SubscriptionRef.set(lastSequence, sequence); |
| 566 | if (fresh.length === 0) return; |
| 567 | |
| 568 | const waiting = yield* Ref.get(awaitingCompletion); |
| 569 | // Apply against the latest projection/history in one update so a concurrent |
| 570 | // loadEarlier merge (or history-meta patch) cannot be clobbered by a stale |
| 571 | // get-then-set rebuild. |
| 572 | type EventApplyResult = |
| 573 | | { readonly _tag: "noop" } |
| 574 | | { readonly _tag: "delete" } |
| 575 | | { |
| 576 | readonly _tag: "applied"; |
| 577 | readonly projection: OrchestrationV2ThreadProjection; |
| 578 | readonly history: ThreadHistoryMeta; |
| 579 | }; |
| 580 | |
| 581 | const applyEvent = ( |
| 582 | current: EnvironmentThreadState, |
| 583 | item: EventItem, |
| 584 | ): readonly [EventApplyResult, EnvironmentThreadState] => { |
| 585 | if (current.status === "deleted") { |
| 586 | return [{ _tag: "noop" }, current]; |
| 587 | } |
| 588 | if (Option.isNone(current.data)) { |
| 589 | return [ |
| 590 | item.event.type === "thread.deleted" ? { _tag: "delete" } : { _tag: "noop" }, |
| 591 | current, |
| 592 | ]; |
| 593 | } |
| 594 | if (item.event.type === "thread.deleted") { |
| 595 | return [{ _tag: "delete" }, current]; |
| 596 | } |
| 597 | |
| 598 | // Incomplete progressive windows only (hasMore or open cursor). Do not |
| 599 | // use expanded: it remains true after the last page as a cache marker. |
| 600 | const partial = |
| 601 | current.history.hasMoreHistory || current.history.historyCursor !== null |
| 602 | ? { |
| 603 | partialTimeline: true as const, |
| 604 | latestLocalTurnOrdinal: current.history.latestLocalTurnOrdinal, |
| 605 | } |
| 606 | : undefined; |
| 607 | const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event, partial); |
| 608 | if (next === null || next === current.data.value) { |
| 609 | return [{ _tag: "noop" }, current]; |
| 610 | } |
| 611 | |
| 612 | let history = current.history; |
| 613 | if (partial !== undefined && item.event.type === "turn-item.updated") { |
| 614 | const ordinal = item.event.payload.ordinal; |
| 615 | const watermark = history.latestLocalTurnOrdinal; |
| 616 | if (watermark === null || ordinal > watermark) { |
| 617 | history = { ...history, latestLocalTurnOrdinal: ordinal }; |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | const updated: EnvironmentThreadState = { |
| 622 | ...current, |
| 623 | data: Option.some(next), |
| 624 | status: waiting ? "synchronizing" : "live", |
| 625 | error: Option.none(), |
| 626 | history, |
| 627 | }; |
| 628 | return [{ _tag: "applied", projection: next, history: updated.history }, updated]; |
| 629 | }; |
| 630 | |
| 631 | const result = yield* SubscriptionRef.modify( |
| 632 | state, |
| 633 | (current): readonly [EventApplyResult, EnvironmentThreadState] => { |
| 634 | let result: EventApplyResult = { _tag: "noop" }; |
| 635 | for (const item of fresh) { |
| 636 | const [applied, next] = applyEvent(current, item); |
| 637 | current = next; |
| 638 | if (applied._tag !== "noop") result = applied; |
| 639 | if (applied._tag === "delete") break; |
| 640 | } |
| 641 | // A batch that changed nothing keeps its state object, so readers do not re-render. |
| 642 | return [result, result._tag === "noop" ? current : { ...current, sequence }]; |
| 643 | }, |
| 644 | ); |
| 645 | |
| 646 | if (result._tag === "delete") { |
| 647 | yield* setDeleted(); |
| 648 | return; |
| 649 | } |
| 650 | if (result._tag === "applied" && shouldPersistThread(result.projection, result.history)) { |
| 651 | const snapshotSequence = yield* SubscriptionRef.get(lastSequence); |
| 652 | yield* queuePersist( |
| 653 | snapshotToPersist( |
| 654 | snapshotSequence, |
| 655 | result.projection, |
| 656 | result.history, |
| 657 | yield* Ref.get(acceptsBoundedSocketSnapshots), |
| 658 | ), |
| 659 | ); |
| 660 | } |
| 661 | }); |
| 662 | |
| 663 | const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* ( |
| 664 | item: OrchestrationV2ThreadStreamItem, |
| 665 | ) { |
| 666 | if (item.kind === "synchronized") { |
| 667 | yield* Ref.set(awaitingCompletion, false); |
| 668 | yield* SubscriptionRef.update(state, (current) => |
| 669 | Option.isSome(current.data) && current.status !== "deleted" && Option.isNone(current.error) |
| 670 | ? { ...current, status: "live" as const, error: Option.none() } |
| 671 | : current, |
| 672 | ); |
| 673 | return; |
| 674 | } |
| 675 | |
| 676 | if (item.kind === "snapshot") { |
| 677 | yield* SubscriptionRef.set(lastSequence, item.snapshotSequence); |
| 678 | const hasProgressiveHistory = |
| 679 | item.historyCursor !== undefined || |
| 680 | item.hasMoreHistory !== undefined || |
| 681 | item.latestLocalTurnOrdinal !== undefined; |
| 682 | yield* setThread( |
| 683 | boundedSnapshotProjection(item), |
| 684 | hasProgressiveHistory |
| 685 | ? { |
| 686 | history: { |
| 687 | historyCursor: item.historyCursor ?? null, |
| 688 | hasMoreHistory: item.hasMoreHistory ?? false, |
| 689 | loading: false, |
| 690 | error: null, |
| 691 | expanded: false, |
| 692 | latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null, |
| 693 | }, |
| 694 | } |
| 695 | : { resetHistory: true }, |
| 696 | ); |
| 697 | return; |
| 698 | } |
| 699 | |
| 700 | yield* applyEventsLocked([item]); |
| 701 | }); |
| 702 | |
| 703 | // Keep this per-batch streaming path untraced for the same reason as applyEventsLocked. |
| 704 | const applyItems = Effect.fnUntraced(function* ( |
| 705 | items: ReadonlyArray<OrchestrationV2ThreadStreamItem>, |
| 706 | ) { |
| 707 | yield* applyLock.withPermits(1)( |
| 708 | Effect.gen(function* () { |
| 709 | let events: SequencedItem[] = []; |
| 710 | for (const item of items) { |
| 711 | if ( |
| 712 | item.kind === "unknown-event" || |
| 713 | (item.kind === "event" && item.event.type !== "thread.deleted") |
| 714 | ) { |
| 715 | events.push(item); |
| 716 | continue; |
| 717 | } |
| 718 | yield* applyEventsLocked(events); |
| 719 | events = []; |
| 720 | yield* applyItemLocked(item); |
| 721 | } |
| 722 | yield* applyEventsLocked(events); |
| 723 | yield* remember; |
| 724 | }), |
| 725 | ); |
| 726 | }); |
| 727 | |
| 728 | const loadEarlier = Effect.fn("EnvironmentThreadState.loadEarlier")(function* ( |
| 729 | throughEntryId?: string, |
| 730 | workAnchorId?: string, |
| 731 | ): Effect.fn.Return<ThreadHistoryController.ThreadHistoryLoadEarlierResult> { |
| 732 | const workCursor = (latest: EnvironmentThreadState) => |
| 733 | Option.getOrNull(latest.data)?.visibleTurnItems.find( |
| 734 | (row) => row.sourceItemId === workAnchorId, |
| 735 | )?.item.deferredWork?.cursor ?? null; |
| 736 | const current = yield* SubscriptionRef.get(state); |
| 737 | const initialCursor = |
| 738 | workAnchorId === undefined ? current.history.historyCursor : workCursor(current); |
| 739 | if ( |
| 740 | current.status === "deleted" || |
| 741 | Option.isNone(current.data) || |
| 742 | initialCursor === null || |
| 743 | (workAnchorId === undefined && !current.history.hasMoreHistory) |
| 744 | ) |
| 745 | return { _tag: "noop" }; |
| 746 | if (workAnchorId === undefined && current.history.loading) return { _tag: "busy" }; |
| 747 | let requestCursor = initialCursor; |
| 748 | const isCurrent = (latest: EnvironmentThreadState) => |
| 749 | workAnchorId === undefined |
| 750 | ? isActiveHistoryRequestCursor(requestCursor, latest.history) |
| 751 | : workCursor(latest) === requestCursor; |
| 752 | const staleResult = ( |
| 753 | latest: EnvironmentThreadState, |
| 754 | ): ThreadHistoryController.ThreadHistoryLoadEarlierResult => |
| 755 | workAnchorId !== undefined && workCursor(latest) !== null |
| 756 | ? { _tag: "error", message: WORK_HISTORY_CHANGED_ERROR } |
| 757 | : { _tag: "noop" }; |
| 758 | if (workAnchorId === undefined) |
| 759 | yield* patchHistoryMeta((history) => |
| 760 | isActiveHistoryRequestCursor(requestCursor, history) |
| 761 | ? { ...history, loading: true, error: null } |
| 762 | : history, |
| 763 | ); |
| 764 | const failLoad = (message: string) => |
| 765 | SubscriptionRef.modify( |
| 766 | state, |
| 767 | ( |
| 768 | latest, |
| 769 | ): readonly [ |
| 770 | ThreadHistoryController.ThreadHistoryLoadEarlierResult, |
| 771 | EnvironmentThreadState, |
| 772 | ] => |
| 773 | isCurrent(latest) |
| 774 | ? [ |
| 775 | { _tag: "error", message }, |
| 776 | { |
| 777 | ...latest, |
| 778 | history: |
| 779 | workAnchorId === undefined |
| 780 | ? { ...latest.history, loading: false, error: message } |
| 781 | : latest.history, |
| 782 | }, |
| 783 | ] |
| 784 | : [staleResult(latest), latest], |
| 785 | ); |
| 786 | |
| 787 | const runLoad = Effect.gen(function* () { |
| 788 | while (true) { |
| 789 | const preparedOption = yield* SubscriptionRef.get(supervisor.prepared); |
| 790 | if (Option.isNone(preparedOption) || Option.isNone(httpClient)) |
| 791 | return yield* failLoad("Environment is not connected."); |
| 792 | const views = |
| 793 | workAnchorId !== undefined |
| 794 | ? ["work" as const] |
| 795 | : throughEntryId === undefined |
| 796 | ? [undefined] |
| 797 | : ["conversation" as const, undefined]; |
| 798 | let nextCursor: string | null = null; |
| 799 | for (const view of views) { |
| 800 | const pageResult = yield* fetchEnvironmentThreadHistoryPage({ |
| 801 | prepared: preparedOption.value, |
| 802 | threadId, |
| 803 | cursor: requestCursor, |
| 804 | throughEntryId: workAnchorId ?? throughEntryId, |
| 805 | view, |
| 806 | signer: dpopSigner, |
| 807 | remoteAuthorization, |
| 808 | }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result); |
| 809 | if (Result.isFailure(pageResult)) |
| 810 | return yield* failLoad(formatHistoryError(pageResult.failure)); |
| 811 | const page = pageResult.success; |
| 812 | const complete = view !== "conversation"; |
| 813 | const keepPaging = |
| 814 | complete && |
| 815 | (workAnchorId !== undefined |
| 816 | ? page.nextCursor !== null |
| 817 | : throughEntryId === undefined && |
| 818 | page.hasMoreHistory && |
| 819 | !page.items.some(({ item }) => startsTurn(item))); |
| 820 | if (keepPaging && (page.nextCursor === null || page.nextCursor === requestCursor)) |
| 821 | return yield* failLoad( |
| 822 | workAnchorId === undefined |
| 823 | ? "History did not advance." |
| 824 | : "Work history did not advance.", |
| 825 | ); |
| 826 | const waiting = yield* Ref.get(awaitingCompletion); |
| 827 | const result = yield* applyLock.withPermits(1)( |
| 828 | SubscriptionRef.modify( |
| 829 | state, |
| 830 | ( |
| 831 | latest, |
| 832 | ): readonly [ |
| 833 | ThreadHistoryController.ThreadHistoryLoadEarlierResult, |
| 834 | EnvironmentThreadState, |
| 835 | ] => { |
| 836 | if (!isCurrent(latest)) return [staleResult(latest), latest]; |
| 837 | if (Option.isNone(latest.data) || latest.status === "deleted") |
| 838 | return [{ _tag: "noop" }, { ...latest, history: EMPTY_THREAD_HISTORY_META }]; |
| 839 | return [ |
| 840 | { _tag: "loaded" }, |
| 841 | { |
| 842 | ...latest, |
| 843 | data: Option.some( |
| 844 | mergeOlderSubagentsIntoProjection( |
| 845 | mergeOlderHistoryIntoProjection( |
| 846 | latest.data.value, |
| 847 | page.items, |
| 848 | workAnchorId === undefined |
| 849 | ? undefined |
| 850 | : { anchorId: workAnchorId, nextCursor: page.nextCursor }, |
| 851 | ), |
| 852 | page.subagents, |
| 853 | ), |
| 854 | ), |
| 855 | status: |
| 856 | workAnchorId === undefined && complete && waiting |
| 857 | ? "synchronizing" |
| 858 | : latest.status, |
| 859 | history: |
| 860 | workAnchorId === undefined && complete |
| 861 | ? { ...applyHistoryPageMeta(latest.history, page), loading: keepPaging } |
| 862 | : { ...latest.history, expanded: true }, |
| 863 | }, |
| 864 | ]; |
| 865 | }, |
| 866 | ), |
| 867 | ); |
| 868 | if (result._tag !== "loaded") return result; |
| 869 | if (complete) yield* applyLock.withPermits(1)(remember); |
| 870 | nextCursor = keepPaging ? page.nextCursor : null; |
| 871 | } |
| 872 | if (nextCursor === null) return { _tag: "loaded" } as const; |
| 873 | requestCursor = nextCursor; |
| 874 | } |
| 875 | }); |
| 876 | return yield* runLoad.pipe( |
| 877 | Effect.onInterrupt(() => |
| 878 | SubscriptionRef.update(state, (latest) => ({ |
| 879 | ...latest, |
| 880 | history: clearActiveHistoryLoading(requestCursor, latest.history), |
| 881 | })), |
| 882 | ), |
| 883 | ); |
| 884 | }); |
| 885 | |
| 886 | // A cached item can stay running after the server finished it, and no event will ever |
| 887 | // name it again: it can sit outside every bounded window, and a repeated Stop records |
| 888 | // nothing new. Stop asks the server about each pending item instead of |
| 889 | // inferring status from what a snapshot omits, and settles only those items. |
| 890 | const reconcilePendingWork = Effect.fn("EnvironmentThreadState.reconcilePendingWork")( |
| 891 | function* () { |
| 892 | const current = yield* SubscriptionRef.get(state); |
| 893 | if (current.status === "deleted" || Option.isNone(current.data)) return; |
| 894 | const pending = pendingBackgroundTurnItems(current.data.value); |
| 895 | if (pending.length === 0) return; |
| 896 | const queried = new Set<string>(pending.map((item) => item.id)); |
| 897 | const fetched = yield* Effect.forEach( |
| 898 | pending, |
| 899 | (item) => |
| 900 | request(ORCHESTRATION_V2_WS_METHODS.getTurnItem, { threadId, itemId: item.id }).pipe( |
| 901 | Effect.timeout("10 seconds"), |
| 902 | Effect.map((result) => result.item), |
| 903 | Effect.orElseSucceed(() => null), |
| 904 | ), |
| 905 | { concurrency: 4 }, |
| 906 | ); |
| 907 | const settled = new Map( |
| 908 | fetched.flatMap((item) => |
| 909 | item === null || isOrchestrationV2WorkActive(item.status) ? [] : [[item.id, item]], |
| 910 | ), |
| 911 | ); |
| 912 | yield* applyLock.withPermits(1)( |
| 913 | Effect.gen(function* () { |
| 914 | const latest = yield* SubscriptionRef.get(state); |
| 915 | if (latest.status === "deleted" || Option.isNone(latest.data)) return; |
| 916 | const thread = settleTurnItems(threadId, latest.data.value, settled); |
| 917 | if (thread !== latest.data.value) { |
| 918 | yield* setThread(thread); |
| 919 | yield* remember; |
| 920 | } |
| 921 | // An expanded timeline is never saved, so reload would bring the stale row back. |
| 922 | // Repair the snapshot last handed to the cache instead, keeping its window and cursor. |
| 923 | // A resumed state skipped the cache load, so read the saved snapshot then. |
| 924 | if (shouldPersistThread(thread, latest.history)) return; |
| 925 | // A terminal event that landed during the lookup is newer than any reply, and the |
| 926 | // expanded live state never saves it, whatever the lookup returned. |
| 927 | const latestItems = new Map(settled); |
| 928 | for (const item of thread.turnItems) { |
| 929 | if (queried.has(item.id) && !isOrchestrationV2WorkActive(item.status)) { |
| 930 | latestItems.set(item.id, item); |
| 931 | } |
| 932 | } |
| 933 | if (latestItems.size === 0) return; |
| 934 | const saved = |
| 935 | queuedSnapshot ?? |
| 936 | Option.getOrUndefined( |
| 937 | yield* cache |
| 938 | .loadThread(environmentId, threadId) |
| 939 | .pipe(Effect.orElseSucceed(() => Option.none())), |
| 940 | ); |
| 941 | if (saved === undefined) return; |
| 942 | const projection = settleTurnItems(threadId, saved.projection, latestItems); |
| 943 | if (projection !== saved.projection) yield* queuePersist({ ...saved, projection }); |
| 944 | }), |
| 945 | ); |
| 946 | }, |
| 947 | ); |
| 948 | |
| 949 | if (Option.isSome(historyController)) { |
| 950 | const scope = yield* Scope.Scope; |
| 951 | const registration = yield* historyController.value.register(environmentId, threadId, { |
| 952 | loadEarlier: (throughEntryId, workAnchorId) => |
| 953 | loadEarlier(throughEntryId, workAnchorId).pipe( |
| 954 | Effect.forkIn(scope), |
| 955 | Effect.flatMap(Fiber.join), |
| 956 | ), |
| 957 | reconcilePendingWork: () => |
| 958 | reconcilePendingWork().pipe( |
| 959 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 960 | Effect.forkIn(scope), |
| 961 | Effect.flatMap(Fiber.join), |
| 962 | ), |
| 963 | }); |
| 964 | yield* Effect.addFinalizer(() => historyController.value.unregister(registration)); |
| 965 | } |
| 966 | |
| 967 | yield* SubscriptionRef.changes(supervisor.state).pipe( |
| 968 | Stream.runForEach((connectionState) => { |
| 969 | switch (connectionProjectionPhase(connectionState)) { |
| 970 | case "synchronizing": |
| 971 | return setConnecting; |
| 972 | case "disconnected": |
| 973 | return setDisconnected; |
| 974 | case "ready": |
| 975 | return setReady; |
| 976 | } |
| 977 | }), |
| 978 | Effect.forkScoped, |
| 979 | ); |
| 980 | |
| 981 | const foregroundResubscriptions = Option.match(wakeups, { |
| 982 | onNone: () => Stream.never, |
| 983 | onSome: (service) => |
| 984 | service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)), |
| 985 | }); |
| 986 | |
| 987 | // Only the first subscription after a warm live resume keeps the retained |
| 988 | // status. A replacement session or foreground resubscribe on the same scope |
| 989 | // may have missed events, so those show sync progress until confirmed. |
| 990 | const resumingLive = yield* Ref.make(initialState.status === "live"); |
| 991 | // A cold open tries the socket snapshot once. Any later cold attempt, after a |
| 992 | // failure or a dropped session, asks HTTP, which also tells a missing thread |
| 993 | // apart from a failed load. |
| 994 | const socketOpenTried = yield* Ref.make(false); |
| 995 | const socketOnlyOpen = yield* Ref.make(false); |
| 996 | const failedSocketOnlyOpen = Effect.gen(function* () { |
| 997 | return ( |
| 998 | (yield* Ref.get(socketOnlyOpen)) && Option.isNone((yield* SubscriptionRef.get(state)).data) |
| 999 | ); |
| 1000 | }); |
| 1001 | // A stream defect parks the subscription until something resubscribes it. |
| 1002 | const resubscribes = yield* Queue.unbounded<void>(); |
| 1003 | const markSynchronizing = Effect.gen(function* () { |
| 1004 | if (yield* Ref.get(resumingLive)) return; |
| 1005 | yield* SubscriptionRef.update(state, (current) => |
| 1006 | current.status === "deleted" |
| 1007 | ? current |
| 1008 | : { ...current, status: "synchronizing" as const, error: Option.none() }, |
| 1009 | ); |
| 1010 | }); |
| 1011 | |
| 1012 | yield* markSynchronizing; |
| 1013 | // A 404 can arrive before the thread exists, so a miss asks HTTP again while mounted. |
| 1014 | let httpMisses = 0; |
| 1015 | let defectRetries = 0; |
| 1016 | const backOffAfterDefect = Effect.suspend(() => { |
| 1017 | const retryDelay = subscriptionRetryDelay(THREAD_SUBSCRIPTION_RETRY_DELAY, defectRetries); |
| 1018 | defectRetries += 1; |
| 1019 | return setStreamError(THREAD_SYNC_ERROR).pipe(Effect.andThen(Effect.sleep(retryDelay))); |
| 1020 | }); |
| 1021 | const followThread = (): Effect.Effect< |
| 1022 | void, |
| 1023 | never, |
| 1024 | EnvironmentSupervisor.EnvironmentSupervisor |
| 1025 | > => |
| 1026 | subscribeDynamic( |
| 1027 | ORCHESTRATION_V2_WS_METHODS.subscribeThread, |
| 1028 | Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) { |
| 1029 | let current = yield* SubscriptionRef.get(state); |
| 1030 | // A delete event already cleared this thread. Park without opening the socket. |
| 1031 | if (current.status === "deleted" && httpMisses === 0) { |
| 1032 | return yield* Effect.never; |
| 1033 | } |
| 1034 | |
| 1035 | const config = yield* Effect.option(session.initialConfig); |
| 1036 | yield* Ref.set(awaitingCompletion, true); |
| 1037 | yield* markSynchronizing; |
| 1038 | yield* Ref.set(resumingLive, false); |
| 1039 | |
| 1040 | // A server that pages snapshots sends the same bounded window over the |
| 1041 | // socket, so a cold open can skip the HTTP round trip. |
| 1042 | const socketOnly = |
| 1043 | Option.isNone(current.data) && |
| 1044 | canLoadHistory && |
| 1045 | Option.exists(config, (value) => value.threadSnapshotPagination === true) && |
| 1046 | !(yield* Ref.getAndSet(socketOpenTried, true)); |
| 1047 | yield* Ref.set(socketOnlyOpen, socketOnly); |
| 1048 | |
| 1049 | if (Option.isNone(current.data) && !socketOnly) { |
| 1050 | const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe( |
| 1051 | Effect.flatMap( |
| 1052 | Option.match({ |
| 1053 | onSome: Effect.succeed, |
| 1054 | onNone: () => |
| 1055 | SubscriptionRef.changes(supervisor.prepared).pipe( |
| 1056 | Stream.filter(Option.isSome), |
| 1057 | Stream.map((value) => value.value), |
| 1058 | Stream.runHead, |
| 1059 | Effect.map(Option.getOrThrow), |
| 1060 | ), |
| 1061 | }), |
| 1062 | ), |
| 1063 | ); |
| 1064 | const httpResult: ThreadSnapshotLoader.ThreadSnapshotLoadResult = |
| 1065 | yield* snapshotLoader.load(prepared, threadId); |
| 1066 | switch (httpResult._tag) { |
| 1067 | case "present": { |
| 1068 | httpMisses = 0; |
| 1069 | if (canLoadHistory && httpResult.history !== undefined) { |
| 1070 | yield* Ref.set(acceptsBoundedSocketSnapshots, true); |
| 1071 | } |
| 1072 | // Atomic projection + progressive meta so a settled bounded window |
| 1073 | // never persists as a complete full-timeline cache entry. Socket |
| 1074 | // snapshots still go through applyItem (resetHistory). |
| 1075 | yield* applyLock.withPermits(1)( |
| 1076 | Effect.gen(function* () { |
| 1077 | yield* SubscriptionRef.set(lastSequence, httpResult.snapshot.snapshotSequence); |
| 1078 | const history: ThreadHistoryMeta = |
| 1079 | httpResult.history !== undefined |
| 1080 | ? { |
| 1081 | historyCursor: httpResult.history.historyCursor, |
| 1082 | hasMoreHistory: httpResult.history.hasMoreHistory, |
| 1083 | loading: false, |
| 1084 | error: null, |
| 1085 | expanded: false, |
| 1086 | latestLocalTurnOrdinal: httpResult.history.latestLocalTurnOrdinal ?? null, |
| 1087 | } |
| 1088 | : EMPTY_THREAD_HISTORY_META; |
| 1089 | yield* setThread(httpResult.snapshot.projection, { history }); |
| 1090 | yield* remember; |
| 1091 | }), |
| 1092 | ); |
| 1093 | current = yield* SubscriptionRef.get(state); |
| 1094 | break; |
| 1095 | } |
| 1096 | case "missing": { |
| 1097 | if (current.status !== "deleted") yield* setDeleted(); |
| 1098 | // A 404 also means "not created yet". Only a delete event may outlive this mount. |
| 1099 | if (resumeCache?.owner === owner) resumeCache.snapshot = undefined; |
| 1100 | yield* Effect.sleep( |
| 1101 | subscriptionRetryDelay(THREAD_SUBSCRIPTION_RETRY_DELAY, httpMisses++), |
| 1102 | ); |
| 1103 | yield* Queue.offer(resubscribes, undefined); |
| 1104 | return yield* Effect.never; |
| 1105 | } |
| 1106 | case "unavailable": { |
| 1107 | break; |
| 1108 | } |
| 1109 | } |
| 1110 | } |
| 1111 | |
| 1112 | const sequence = yield* SubscriptionRef.get(lastSequence); |
| 1113 | const canResume = Option.isSome(current.data); |
| 1114 | const acceptBoundedSnapshot = yield* Ref.get(acceptsBoundedSocketSnapshots); |
| 1115 | |
| 1116 | return { |
| 1117 | threadId, |
| 1118 | ...(canResume ? { afterSequence: sequence } : {}), |
| 1119 | requestCompletionMarker: true as const, |
| 1120 | ...(acceptBoundedSnapshot |
| 1121 | ? { |
| 1122 | acceptBoundedSnapshot: true as const, |
| 1123 | acceptDeferredWork: true as const, |
| 1124 | acceptCompactTurnItems: true as const, |
| 1125 | acceptCompactIds: true as const, |
| 1126 | } |
| 1127 | : {}), |
| 1128 | acceptDedupedBodies: true as const, |
| 1129 | }; |
| 1130 | }), |
| 1131 | { |
| 1132 | // A socket-only open that fails retries over HTTP, which tells a |
| 1133 | // missing thread apart from a failure, before showing an error. |
| 1134 | onDefect: Effect.fn("EnvironmentThreadState.onDefect")(function* (cause) { |
| 1135 | if (yield* failedSocketOnlyOpen) { |
| 1136 | yield* Ref.set(socketOnlyOpen, false); |
| 1137 | return yield* Queue.offer(resubscribes, undefined); |
| 1138 | } |
| 1139 | if (!Cause.hasDies(cause)) { |
| 1140 | return yield* setStreamError(THREAD_SYNC_ERROR); |
| 1141 | } |
| 1142 | yield* backOffAfterDefect; |
| 1143 | yield* Queue.offer(resubscribes, undefined); |
| 1144 | }), |
| 1145 | onExpectedFailure: Effect.fn("EnvironmentThreadState.onExpectedFailure")(function* (cause) { |
| 1146 | const retryOverHttp = !isAuthorizationFailure(cause) && (yield* failedSocketOnlyOpen); |
| 1147 | if (!retryOverHttp) yield* setStreamError(formatThreadError(cause)); |
| 1148 | }), |
| 1149 | retryExpectedFailureAfter: THREAD_SUBSCRIPTION_RETRY_DELAY, |
| 1150 | resubscribe: Stream.merge(foregroundResubscriptions, Stream.fromQueue(resubscribes)), |
| 1151 | }, |
| 1152 | ).pipe( |
| 1153 | Stream.runForEachArray((items) => |
| 1154 | applyItems(items).pipe( |
| 1155 | Effect.andThen( |
| 1156 | Effect.sync(() => { |
| 1157 | defectRetries = 0; |
| 1158 | }), |
| 1159 | ), |
| 1160 | ), |
| 1161 | ), |
| 1162 | // A defect while applying items ends the stream; resubscribe for a fresh snapshot. |
| 1163 | Effect.catchCause((cause) => |
| 1164 | Cause.hasInterrupts(cause) |
| 1165 | ? Effect.interrupt |
| 1166 | : Effect.logWarning("Thread subscription failed; resubscribing.", { |
| 1167 | cause: Cause.pretty(cause), |
| 1168 | environmentId, |
| 1169 | threadId, |
| 1170 | }).pipe( |
| 1171 | Effect.andThen(backOffAfterDefect), |
| 1172 | Effect.andThen(Effect.suspend(followThread)), |
| 1173 | ), |
| 1174 | ), |
| 1175 | ); |
| 1176 | yield* Effect.forkScoped(followThread()); |
| 1177 | |
| 1178 | return state; |
| 1179 | }); |
| 1180 | |
| 1181 | function threadStateChanges( |
| 1182 | environmentId: EnvironmentIdType, |
| 1183 | threadId: ThreadIdType, |
| 1184 | resumeCache?: ThreadResumeCache, |
| 1185 | ) { |
| 1186 | return followStreamInEnvironment( |
| 1187 | environmentId, |
| 1188 | Stream.unwrap( |
| 1189 | makeEnvironmentThreadState(threadId, resumeCache).pipe(Effect.map(SubscriptionRef.changes)), |
| 1190 | ), |
| 1191 | ); |
| 1192 | } |
| 1193 | |
| 1194 | export function createEnvironmentThreadStateAtoms<R, E>( |
| 1195 | runtime: Atom.AtomRuntime< |
| 1196 | | EnvironmentRegistry.EnvironmentRegistry |
| 1197 | | Persistence.EnvironmentCacheStore |
| 1198 | | ThreadSnapshotLoader.ThreadSnapshotLoader |
| 1199 | | R, |
| 1200 | E |
| 1201 | >, |
| 1202 | ) { |
| 1203 | // Cache definitions must outlive collectible live-atom definitions. The |
| 1204 | // registry retains these nodes without retaining environment or RPC scopes. |
| 1205 | const resumeFamily = Atom.family((key: string) => |
| 1206 | Atom.make((): ThreadResumeCache => ({ |
| 1207 | snapshot: undefined, |
| 1208 | owner: undefined, |
| 1209 | })).pipe( |
| 1210 | Atom.setIdleTTL(THREAD_SNAPSHOT_IDLE_TTL_MS), |
| 1211 | Atom.withLabel(`environment-thread-resume:${key}`), |
| 1212 | ), |
| 1213 | ); |
| 1214 | const family = Atom.family((key: string) => { |
| 1215 | const { environmentId, threadId } = parseThreadKey(key); |
| 1216 | const resumeAtom = resumeFamily(key); |
| 1217 | return runtime |
| 1218 | .atom( |
| 1219 | (get) => { |
| 1220 | get.mount(resumeAtom); |
| 1221 | const resume = get.once(resumeAtom); |
| 1222 | const live = threadStateChanges(environmentId, threadId, resume); |
| 1223 | return resume.snapshot === undefined |
| 1224 | ? live |
| 1225 | : Stream.concat(Stream.succeed(cachedThreadState(resume.snapshot.state)), live); |
| 1226 | }, |
| 1227 | { |
| 1228 | initialValue: EMPTY_ENVIRONMENT_THREAD_STATE, |
| 1229 | }, |
| 1230 | ) |
| 1231 | .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state:${key}`)); |
| 1232 | }); |
| 1233 | |
| 1234 | return { |
| 1235 | stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) => |
| 1236 | family(threadKey({ environmentId, threadId })), |
| 1237 | }; |
| 1238 | } |
| 1239 | |
| 1240 | export * from "./archivedThreads.ts"; |
| 1241 | export * from "./checkpointDiff.ts"; |
| 1242 | export * as BoundedThreadSnapshotLoader from "./boundedThreadSnapshotHttp.ts"; |
| 1243 | export * as ThreadHistoryController from "./threadHistoryController.ts"; |
| 1244 | export type { ThreadHistoryLoadEarlierResult } from "./threadHistoryController.ts"; |
| 1245 | export * from "./threadHistoryMerge.ts"; |
| 1246 | export * from "./threadSnapshotHttp.ts"; |
| 1247 | export * from "./composerPathSearch.ts"; |
| 1248 | export * from "./threadCommands.ts"; |
| 1249 | export * from "./threadFeedback.ts"; |
| 1250 | export * from "./threadDetail.ts"; |
| 1251 | export * from "./threadFamilies.ts"; |
| 1252 | export * from "./olderSettledThreads.ts"; |
| 1253 | export * from "./threadShell.ts"; |
| 1254 | export * from "./threadState.ts"; |
| 1255 | export * from "./threadTagFilter.ts"; |