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

threads.ts

1,349 lines51.4 KB

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