Open History to see the last commit
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";
78}
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;
96}
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;
103}
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;
110}
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 );
121}
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 };
136}
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 };
156}
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 );
170}
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;
193}
194
195interface ThreadResumeSnapshot {
196 readonly state: EnvironmentThreadState;
197 readonly sequence: number;
198 readonly persisted: boolean;
199 readonly acceptsBoundedSnapshots?: boolean;
200}
201
202interface ThreadResumeCache {
203 snapshot: ThreadResumeSnapshot | undefined;
204 owner: object | undefined;
205}
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 );
222}
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 };
235}
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;
249}
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 // A 404 can arrive before the thread exists, so a miss asks HTTP again while mounted.
524 let httpMisses = 0;
525 const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
526 yield* Ref.set(awaitingCompletion, false);
527 yield* SubscriptionRef.set(state, {
528 data: Option.none(),
529 status: "deleted",
530 error: Option.none(),
531 history: EMPTY_THREAD_HISTORY_META,
532 sequence: yield* SubscriptionRef.get(lastSequence),
533 });
534 yield* remember;
535 if (resumeCache !== undefined && resumeCache.owner !== owner) return;
536 yield* cache.removeThread(environmentId, threadId).pipe(
537 Effect.catch((error) =>
538 Effect.logWarning("Could not remove the cached thread.").pipe(
539 Effect.annotateLogs({
540 environmentId,
541 threadId,
542 error: error.message,
543 }),
544 ),
545 ),
546 );
547 });
548
549 type EventItem = Extract<OrchestrationV2ThreadStreamItem, { kind: "event" }>;
550 type SequencedItem = Extract<
551 OrchestrationV2ThreadStreamItem,
552 { kind: "event" | "unknown-event" }
553 >;
554 // Per-batch streaming spans add trace volume without a useful timing boundary.
555 const applyEventsLocked = Effect.fnUntraced(function* (
556 items: ReadonlyArray<SequencedItem>,
557 // Replayed catch-up events may predate a backward host clock correction.
558 live: boolean,
559 ) {
560 const appliedSequence = yield* SubscriptionRef.get(lastSequence);
561 let sequence = appliedSequence;
562 const fresh: EventItem[] = [];
563 for (const item of items) {
564 if (item.sequence <= sequence) continue;
565 sequence = item.sequence;
566 if (item.kind === "event") {
567 fresh.push(item);
568 continue;
569 }
570 yield* Effect.logDebug("Skipped a thread event type this client does not know.").pipe(
571 Effect.annotateLogs({
572 environmentId,
573 threadId,
574 eventType: item.eventType.slice(0, 64),
575 sequence: item.sequence,
576 }),
577 );
578 }
579 if (sequence === appliedSequence) return;
580 yield* SubscriptionRef.set(lastSequence, sequence);
581 if (fresh.length === 0) return;
582
583 if (live) {
584 const receivedAtMs = yield* Clock.currentTimeMillis;
585 for (const item of fresh) {
586 observeServerTime(
587 environmentId,
588 DateTime.toEpochMillis(item.event.occurredAt),
589 receivedAtMs,
590 );
591 }
592 }
593
594 const waiting = yield* Ref.get(awaitingCompletion);
595 // Apply against the latest projection/history in one update so a concurrent
596 // loadEarlier merge (or history-meta patch) cannot be clobbered by a stale
597 // get-then-set rebuild.
598 type EventApplyResult =
599 | { readonly _tag: "noop" }
600 | { readonly _tag: "delete" }
601 | {
602 readonly _tag: "applied";
603 readonly projection: OrchestrationV2ThreadProjection;
604 readonly history: ThreadHistoryMeta;
605 };
606
607 const applyEvent = (
608 current: EnvironmentThreadState,
609 item: EventItem,
610 ): readonly [EventApplyResult, EnvironmentThreadState] => {
611 if (current.status === "deleted") {
612 return [{ _tag: "noop" }, current];
613 }
614 if (Option.isNone(current.data)) {
615 return [
616 item.event.type === "thread.deleted" ? { _tag: "delete" } : { _tag: "noop" },
617 current,
618 ];
619 }
620 if (item.event.type === "thread.deleted") {
621 return [{ _tag: "delete" }, current];
622 }
623
624 // Incomplete progressive windows only (hasMore or open cursor). Do not
625 // use expanded: it remains true after the last page as a cache marker.
626 const partial =
627 current.history.hasMoreHistory || current.history.historyCursor !== null
628 ? {
629 partialTimeline: true as const,
630 latestLocalTurnOrdinal: current.history.latestLocalTurnOrdinal,
631 }
632 : undefined;
633 const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event, partial);
634 if (next === null || next === current.data.value) {
635 return [{ _tag: "noop" }, current];
636 }
637
638 let history = current.history;
639 if (partial !== undefined && item.event.type === "turn-item.updated") {
640 const ordinal = item.event.payload.ordinal;
641 const watermark = history.latestLocalTurnOrdinal;
642 if (watermark === null || ordinal > watermark) {
643 history = { ...history, latestLocalTurnOrdinal: ordinal };
644 }
645 }
646
647 const updated: EnvironmentThreadState = {
648 ...current,
649 data: Option.some(next),
650 status: waiting ? "synchronizing" : "live",
651 error: Option.none(),
652 history,
653 };
654 return [{ _tag: "applied", projection: next, history: updated.history }, updated];
655 };
656
657 const result = yield* SubscriptionRef.modify(
658 state,
659 (current): readonly [EventApplyResult, EnvironmentThreadState] => {
660 let result: EventApplyResult = { _tag: "noop" };
661 for (const item of fresh) {
662 const [applied, next] = applyEvent(current, item);
663 current = next;
664 if (applied._tag !== "noop") result = applied;
665 if (applied._tag === "delete") break;
666 }
667 // A batch that changed nothing keeps its state object, so readers do not re-render.
668 return [result, result._tag === "noop" ? current : { ...current, sequence }];
669 },
670 );
671
672 if (result._tag === "delete") {
673 httpMisses = 0;
674 yield* setDeleted();
675 return;
676 }
677 if (result._tag === "applied" && shouldPersistThread(result.projection, result.history)) {
678 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
679 yield* queuePersist(
680 snapshotToPersist(
681 snapshotSequence,
682 result.projection,
683 result.history,
684 yield* Ref.get(acceptsBoundedSocketSnapshots),
685 ),
686 );
687 }
688 });
689
690 const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* (
691 item: OrchestrationV2ThreadStreamItem,
692 ) {
693 if (item.kind === "synchronized") {
694 yield* Ref.set(awaitingCompletion, false);
695 yield* SubscriptionRef.updateSome(state, (current) =>
696 Option.isSome(current.data) &&
697 current.status !== "deleted" &&
698 current.status !== "live" &&
699 Option.isNone(current.error)
700 ? Option.some({ ...current, status: "live" as const })
701 : Option.none(),
702 );
703 return;
704 }
705
706 if (item.kind === "snapshot") {
707 yield* Ref.set(forceSnapshot, false);
708 yield* SubscriptionRef.set(lastSequence, item.snapshotSequence);
709 const hasProgressiveHistory =
710 item.historyCursor !== undefined ||
711 item.hasMoreHistory !== undefined ||
712 item.latestLocalTurnOrdinal !== undefined;
713 yield* setThread(
714 boundedSnapshotProjection(item),
715 hasProgressiveHistory
716 ? {
717 history: {
718 historyCursor: item.historyCursor ?? null,
719 hasMoreHistory: item.hasMoreHistory ?? false,
720 loading: false,
721 error: null,
722 expanded: false,
723 latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null,
724 },
725 }
726 : { resetHistory: true },
727 );
728 return;
729 }
730
731 yield* applyEventsLocked([item], false);
732 });
733
734 // Items held until the completion marker apply together, so a replay-only resume renders once.
735 // A new attempt drops the previous attempt's held and late items (unapplied, so its cursor
736 // replays them). Both run under applyLock: each batch lands wholly before or after an attempt.
737 let attempt: unknown;
738 let catchUp: OrchestrationV2ThreadStreamItem[] = [];
739 const startAttempt = applyLock.withPermits(1)(
740 Effect.sync(() => {
741 attempt = undefined;
742 catchUp = [];
743 }),
744 );
745 // Keep this per-batch streaming path untraced for the same reason as applyEventsLocked.
746 const receiveItems = Effect.fnUntraced(function* (
747 received: ReadonlyArray<readonly [input: unknown, item: OrchestrationV2ThreadStreamItem]>,
748 ) {
749 yield* applyLock.withPermits(1)(
750 Effect.gen(function* () {
751 let completes = false;
752 for (const [input, item] of received) {
753 if (input !== attempt) continue;
754 catchUp.push(item);
755 if (item.kind === "synchronized") completes = true;
756 }
757 if (catchUp.length === 0) return;
758 if (!completes && (yield* Ref.get(awaitingCompletion))) {
759 // A warm resume keeps its "live" status until it learns it is behind.
760 yield* SubscriptionRef.updateSome(state, (current) =>
761 current.status === "live"
762 ? Option.some({ ...current, status: "synchronizing" as const })
763 : Option.none(),
764 );
765 return;
766 }
767 const items = catchUp;
768 catchUp = [];
769 let live = !(yield* Ref.get(awaitingCompletion));
770 let events: SequencedItem[] = [];
771 for (const item of items) {
772 if (
773 item.kind === "unknown-event" ||
774 (item.kind === "event" && item.event.type !== "thread.deleted")
775 ) {
776 events.push(item);
777 continue;
778 }
779 // Clearing the flag first lets the events before the marker publish
780 // "live", so a catch-up ending in the marker is one state change.
781 if (item.kind === "synchronized") yield* Ref.set(awaitingCompletion, false);
782 yield* applyEventsLocked(events, live);
783 events = [];
784 yield* applyItemLocked(item);
785 if (item.kind === "synchronized") live = true;
786 }
787 yield* applyEventsLocked(events, live);
788 yield* remember;
789 }),
790 );
791 });
792
793 const loadEarlier = Effect.fn("EnvironmentThreadState.loadEarlier")(function* (
794 throughEntryId?: string,
795 workAnchorId?: string,
796 ): Effect.fn.Return<ThreadHistoryController.ThreadHistoryLoadEarlierResult> {
797 const workCursor = (latest: EnvironmentThreadState) =>
798 Option.getOrNull(latest.data)?.visibleTurnItems.find(
799 (row) => row.sourceItemId === workAnchorId,
800 )?.item.deferredWork?.cursor ?? null;
801 const current = yield* SubscriptionRef.get(state);
802 const initialCursor =
803 workAnchorId === undefined ? current.history.historyCursor : workCursor(current);
804 if (
805 current.status === "deleted" ||
806 Option.isNone(current.data) ||
807 initialCursor === null ||
808 (workAnchorId === undefined && !current.history.hasMoreHistory)
809 )
810 return { _tag: "noop" };
811 if (workAnchorId === undefined && current.history.loading) return { _tag: "busy" };
812 let requestCursor = initialCursor;
813 const isCurrent = (latest: EnvironmentThreadState) =>
814 workAnchorId === undefined
815 ? isActiveHistoryRequestCursor(requestCursor, latest.history)
816 : workCursor(latest) === requestCursor;
817 const staleResult = (
818 latest: EnvironmentThreadState,
819 ): ThreadHistoryController.ThreadHistoryLoadEarlierResult =>
820 workAnchorId !== undefined && workCursor(latest) !== null
821 ? { _tag: "error", message: WORK_HISTORY_CHANGED_ERROR }
822 : { _tag: "noop" };
823 if (workAnchorId === undefined)
824 yield* patchHistoryMeta((history) =>
825 isActiveHistoryRequestCursor(requestCursor, history)
826 ? { ...history, loading: true, error: null }
827 : history,
828 );
829 const failLoad = (message: string) =>
830 SubscriptionRef.modify(
831 state,
832 (
833 latest,
834 ): readonly [
835 ThreadHistoryController.ThreadHistoryLoadEarlierResult,
836 EnvironmentThreadState,
837 ] =>
838 isCurrent(latest)
839 ? [
840 { _tag: "error", message },
841 {
842 ...latest,
843 history:
844 workAnchorId === undefined
845 ? { ...latest.history, loading: false, error: message }
846 : latest.history,
847 },
848 ]
849 : [staleResult(latest), latest],
850 );
851
852 const runLoad = Effect.gen(function* () {
853 while (true) {
854 const preparedOption = yield* SubscriptionRef.get(supervisor.prepared);
855 if (Option.isNone(preparedOption) || Option.isNone(httpClient))
856 return yield* failLoad("Environment is not connected.");
857 const views =
858 workAnchorId !== undefined
859 ? ["work" as const]
860 : throughEntryId === undefined
861 ? [undefined]
862 : ["conversation" as const, undefined];
863 let nextCursor: string | null = null;
864 for (const view of views) {
865 const pageResult = yield* fetchEnvironmentThreadHistoryPage({
866 prepared: preparedOption.value,
867 threadId,
868 cursor: requestCursor,
869 throughEntryId: workAnchorId ?? throughEntryId,
870 view,
871 signer: dpopSigner,
872 remoteAuthorization,
873 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result);
874 if (Result.isFailure(pageResult))
875 return yield* failLoad(formatHistoryError(pageResult.failure));
876 const page = pageResult.success;
877 const complete = view !== "conversation";
878 const keepPaging =
879 complete &&
880 (workAnchorId !== undefined
881 ? page.nextCursor !== null
882 : throughEntryId === undefined &&
883 page.hasMoreHistory &&
884 !page.items.some(({ item }) => startsTurn(item)));
885 if (keepPaging && (page.nextCursor === null || page.nextCursor === requestCursor))
886 return yield* failLoad(
887 workAnchorId === undefined
888 ? "History did not advance."
889 : "Work history did not advance.",
890 );
891 const waiting = yield* Ref.get(awaitingCompletion);
892 const result = yield* applyLock.withPermits(1)(
893 SubscriptionRef.modify(
894 state,
895 (
896 latest,
897 ): readonly [
898 ThreadHistoryController.ThreadHistoryLoadEarlierResult,
899 EnvironmentThreadState,
900 ] => {
901 if (!isCurrent(latest)) return [staleResult(latest), latest];
902 if (Option.isNone(latest.data) || latest.status === "deleted")
903 return [{ _tag: "noop" }, { ...latest, history: EMPTY_THREAD_HISTORY_META }];
904 return [
905 { _tag: "loaded" },
906 {
907 ...latest,
908 data: Option.some(
909 mergeOlderSubagentsIntoProjection(
910 mergeOlderHistoryIntoProjection(
911 latest.data.value,
912 page.items,
913 workAnchorId === undefined
914 ? undefined
915 : { anchorId: workAnchorId, nextCursor: page.nextCursor },
916 ),
917 page.subagents,
918 ),
919 ),
920 status:
921 workAnchorId === undefined && complete && waiting
922 ? "synchronizing"
923 : latest.status,
924 history:
925 workAnchorId === undefined && complete
926 ? { ...applyHistoryPageMeta(latest.history, page), loading: keepPaging }
927 : { ...latest.history, expanded: true },
928 },
929 ];
930 },
931 ),
932 );
933 if (result._tag !== "loaded") return result;
934 if (complete) yield* applyLock.withPermits(1)(remember);
935 nextCursor = keepPaging ? page.nextCursor : null;
936 }
937 if (nextCursor === null) return { _tag: "loaded" } as const;
938 requestCursor = nextCursor;
939 }
940 });
941 return yield* runLoad.pipe(
942 Effect.onInterrupt(() =>
943 SubscriptionRef.update(state, (latest) => ({
944 ...latest,
945 history: clearActiveHistoryLoading(requestCursor, latest.history),
946 })),
947 ),
948 );
949 });
950
951 // A cached item can stay running after the server finished it, and no event will ever
952 // name it again: it can sit outside every bounded window, and a repeated Stop records
953 // nothing new. Stop asks the server about each pending item instead of
954 // inferring status from what a snapshot omits, and settles only those items.
955 const reconcilePendingWork = Effect.fn("EnvironmentThreadState.reconcilePendingWork")(
956 function* () {
957 const current = yield* SubscriptionRef.get(state);
958 if (current.status === "deleted" || Option.isNone(current.data)) return;
959 const pending = pendingBackgroundTurnItems(current.data.value);
960 if (pending.length === 0) return;
961 const queried = new Set<string>(pending.map((item) => item.id));
962 const fetched = yield* Effect.forEach(
963 pending,
964 (item) =>
965 request(ORCHESTRATION_V2_WS_METHODS.getTurnItem, { threadId, itemId: item.id }).pipe(
966 Effect.timeout("10 seconds"),
967 Effect.map((result) => result.item),
968 Effect.orElseSucceed(() => null),
969 ),
970 { concurrency: 4 },
971 );
972 const settled = new Map(
973 fetched.flatMap((item) =>
974 item === null || isOrchestrationV2WorkActive(item.status) ? [] : [[item.id, item]],
975 ),
976 );
977 yield* applyLock.withPermits(1)(
978 Effect.gen(function* () {
979 const latest = yield* SubscriptionRef.get(state);
980 if (latest.status === "deleted" || Option.isNone(latest.data)) return;
981 const thread = settleTurnItems(threadId, latest.data.value, settled);
982 if (thread !== latest.data.value) {
983 yield* setThread(thread);
984 yield* remember;
985 }
986 // An expanded timeline is never saved, so reload would bring the stale row back.
987 // Repair the snapshot last handed to the cache instead, keeping its window and cursor.
988 // A resumed state skipped the cache load, so read the saved snapshot then.
989 if (shouldPersistThread(thread, latest.history)) return;
990 // A terminal event that landed during the lookup is newer than any reply, and the
991 // expanded live state never saves it, whatever the lookup returned.
992 const latestItems = new Map(settled);
993 for (const item of thread.turnItems) {
994 if (queried.has(item.id) && !isOrchestrationV2WorkActive(item.status)) {
995 latestItems.set(item.id, item);
996 }
997 }
998 if (latestItems.size === 0) return;
999 const saved =
1000 queuedSnapshot ??
1001 Option.getOrUndefined(
1002 yield* cache
1003 .loadThread(environmentId, threadId)
1004 .pipe(Effect.orElseSucceed(() => Option.none())),
1005 );
1006 if (saved === undefined) return;
1007 const projection = settleTurnItems(threadId, saved.projection, latestItems);
1008 if (projection !== saved.projection) yield* queuePersist({ ...saved, projection });
1009 }),
1010 );
1011 },
1012 );
1013
1014 if (Option.isSome(historyController)) {
1015 const scope = yield* Scope.Scope;
1016 const registration = yield* historyController.value.register(environmentId, threadId, {
1017 loadEarlier: (throughEntryId, workAnchorId) =>
1018 loadEarlier(throughEntryId, workAnchorId).pipe(
1019 Effect.forkIn(scope),
1020 Effect.flatMap(Fiber.join),
1021 ),
1022 reconcilePendingWork: () =>
1023 reconcilePendingWork().pipe(
1024 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1025 Effect.forkIn(scope),
1026 Effect.flatMap(Fiber.join),
1027 ),
1028 });
1029 yield* Effect.addFinalizer(() => historyController.value.unregister(registration));
1030 }
1031
1032 yield* SubscriptionRef.changes(supervisor.state).pipe(
1033 Stream.runForEach((connectionState) => {
1034 switch (connectionProjectionPhase(connectionState)) {
1035 case "synchronizing":
1036 return setConnecting;
1037 case "disconnected":
1038 return setDisconnected;
1039 case "ready":
1040 return setReady;
1041 }
1042 }),
1043 Effect.forkScoped,
1044 );
1045
1046 const foregroundResubscriptions = Option.match(wakeups, {
1047 onNone: () => Stream.never,
1048 onSome: (service) =>
1049 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
1050 });
1051
1052 // Only the first subscription after a warm live resume keeps the retained
1053 // status. A replacement session or foreground resubscribe on the same scope
1054 // may have missed events, so those show sync progress until confirmed.
1055 const resumingLive = yield* Ref.make(initialState.status === "live");
1056 // A cold open tries the socket snapshot once. Any later cold attempt, after a
1057 // failure or a dropped session, asks HTTP, which also tells a missing thread
1058 // apart from a failed load.
1059 const socketOpenTried = yield* Ref.make(false);
1060 const socketOnlyOpen = yield* Ref.make(false);
1061 const failedSocketOnlyOpen = Effect.gen(function* () {
1062 return (
1063 (yield* Ref.get(socketOnlyOpen)) && Option.isNone((yield* SubscriptionRef.get(state)).data)
1064 );
1065 });
1066 // A stream defect parks the subscription until something resubscribes it.
1067 const resubscribes = yield* Queue.unbounded<void>();
1068 // A resumed replay that dies (an event this client cannot decode) dies the same
1069 // way from the same cursor, so later attempts reload the full snapshot until one applies.
1070 const resuming = yield* Ref.make(false);
1071 // A subagent can settle on the server without an event a replay would carry, so a cached
1072 // live subagent opens with a snapshot rather than resuming from the saved cursor.
1073 const forceSnapshot = yield* Ref.make(
1074 Option.exists(cachedThread, (thread) =>
1075 thread.subagents.some((subagent) => isOrchestrationV2WorkActive(subagent.status)),
1076 ),
1077 );
1078 const markSynchronizing = Effect.gen(function* () {
1079 if (yield* Ref.get(resumingLive)) return;
1080 yield* SubscriptionRef.update(state, (current) =>
1081 current.status === "deleted"
1082 ? current
1083 : { ...current, status: "synchronizing" as const, error: Option.none() },
1084 );
1085 });
1086
1087 yield* markSynchronizing;
1088 let defectRetries = 0;
1089 const backOffAfterDefect = Effect.suspend(() => {
1090 const retryDelay = subscriptionRetryDelay(THREAD_SUBSCRIPTION_RETRY_DELAY, defectRetries);
1091 defectRetries += 1;
1092 return setStreamError(THREAD_SYNC_ERROR).pipe(Effect.andThen(Effect.sleep(retryDelay)));
1093 });
1094 const followThread = (): Effect.Effect<
1095 void,
1096 never,
1097 EnvironmentSupervisor.EnvironmentSupervisor
1098 > =>
1099 subscribeDynamicWithInput(
1100 ORCHESTRATION_V2_WS_METHODS.subscribeThread,
1101 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
1102 yield* startAttempt;
1103 let current = yield* SubscriptionRef.get(state);
1104 // Imports can restore a deleted thread under its id. Check once per attempt
1105 // for an event-confirmed deletion, distinct from a cold open that got a 404.
1106 const recheckDeletion = current.status === "deleted" && httpMisses === 0;
1107
1108 const config = yield* Effect.option(session.initialConfig);
1109 yield* Ref.set(awaitingCompletion, true);
1110 yield* markSynchronizing;
1111 yield* Ref.set(resumingLive, false);
1112
1113 // A server that pages snapshots sends the same bounded window over the
1114 // socket, so a cold open can skip the HTTP round trip.
1115 const socketOnly =
1116 !recheckDeletion &&
1117 Option.isNone(current.data) &&
1118 canLoadHistory &&
1119 Option.exists(config, (value) => value.threadSnapshotPagination === true) &&
1120 !(yield* Ref.getAndSet(socketOpenTried, true));
1121 yield* Ref.set(socketOnlyOpen, socketOnly);
1122
1123 if (Option.isNone(current.data) && !socketOnly) {
1124 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
1125 Effect.flatMap(
1126 Option.match({
1127 onSome: Effect.succeed,
1128 onNone: () =>
1129 SubscriptionRef.changes(supervisor.prepared).pipe(
1130 Stream.filter(Option.isSome),
1131 Stream.map((value) => value.value),
1132 Stream.runHead,
1133 Effect.map(Option.getOrThrow),
1134 ),
1135 }),
1136 ),
1137 );
1138 const httpResult: ThreadSnapshotLoader.ThreadSnapshotLoadResult =
1139 yield* snapshotLoader.load(prepared, threadId);
1140 switch (httpResult._tag) {
1141 case "present": {
1142 httpMisses = 0;
1143 if (canLoadHistory && httpResult.history !== undefined) {
1144 yield* Ref.set(acceptsBoundedSocketSnapshots, true);
1145 }
1146 // Atomic projection + progressive meta so a settled bounded window
1147 // never persists as a complete full-timeline cache entry. Socket
1148 // snapshots still go through applyItem (resetHistory).
1149 yield* applyLock.withPermits(1)(
1150 Effect.gen(function* () {
1151 yield* SubscriptionRef.set(lastSequence, httpResult.snapshot.snapshotSequence);
1152 const history: ThreadHistoryMeta =
1153 httpResult.history !== undefined
1154 ? {
1155 historyCursor: httpResult.history.historyCursor,
1156 hasMoreHistory: httpResult.history.hasMoreHistory,
1157 loading: false,
1158 error: null,
1159 expanded: false,
1160 latestLocalTurnOrdinal: httpResult.history.latestLocalTurnOrdinal ?? null,
1161 }
1162 : EMPTY_THREAD_HISTORY_META;
1163 yield* setThread(httpResult.snapshot.projection, { history });
1164 yield* remember;
1165 }),
1166 );
1167 current = yield* SubscriptionRef.get(state);
1168 break;
1169 }
1170 case "missing": {
1171 if (recheckDeletion) return yield* Effect.never;
1172 if (current.status !== "deleted") yield* setDeleted();
1173 // A 404 also means "not created yet". Only a delete event may outlive this mount.
1174 if (resumeCache?.owner === owner) resumeCache.snapshot = undefined;
1175 yield* Effect.sleep(
1176 subscriptionRetryDelay(THREAD_SUBSCRIPTION_RETRY_DELAY, httpMisses++),
1177 );
1178 yield* Queue.offer(resubscribes, undefined);
1179 return yield* Effect.never;
1180 }
1181 case "unavailable": {
1182 if (recheckDeletion) return yield* Effect.never;
1183 break;
1184 }
1185 }
1186 }
1187
1188 const sequence = yield* SubscriptionRef.get(lastSequence);
1189 const canResume = Option.isSome(current.data) && !(yield* Ref.get(forceSnapshot));
1190 yield* Ref.set(resuming, canResume);
1191 const acceptBoundedSnapshot = yield* Ref.get(acceptsBoundedSocketSnapshots);
1192
1193 const input = {
1194 threadId,
1195 ...(canResume ? { afterSequence: sequence } : {}),
1196 requestCompletionMarker: true as const,
1197 ...(acceptBoundedSnapshot
1198 ? {
1199 acceptBoundedSnapshot: true as const,
1200 acceptDeferredWork: true as const,
1201 acceptCompactTurnItems: true as const,
1202 acceptCompactIds: true as const,
1203 }
1204 : {}),
1205 acceptDedupedBodies: true as const,
1206 };
1207 attempt = input;
1208 return input;
1209 }),
1210 {
1211 // A socket-only open that fails retries over HTTP, which tells a
1212 // missing thread apart from a failure, before showing an error.
1213 onDefect: Effect.fn("EnvironmentThreadState.onDefect")(function* (cause) {
1214 if (yield* failedSocketOnlyOpen) {
1215 yield* Ref.set(socketOnlyOpen, false);
1216 return yield* Queue.offer(resubscribes, undefined);
1217 }
1218 if (!Cause.hasDies(cause)) {
1219 return yield* setStreamError(THREAD_SYNC_ERROR);
1220 }
1221 yield* Ref.set(forceSnapshot, true);
1222 if (yield* Ref.getAndSet(resuming, false)) {
1223 return yield* Queue.offer(resubscribes, undefined);
1224 }
1225 yield* backOffAfterDefect;
1226 yield* Queue.offer(resubscribes, undefined);
1227 }),
1228 onExpectedFailure: Effect.fn("EnvironmentThreadState.onExpectedFailure")(function* (cause) {
1229 const retryOverHttp = !isAuthorizationFailure(cause) && (yield* failedSocketOnlyOpen);
1230 if (!retryOverHttp) yield* setStreamError(formatThreadError(cause));
1231 }),
1232 retryExpectedFailureAfter: THREAD_SUBSCRIPTION_RETRY_DELAY,
1233 resubscribe: Stream.merge(foregroundResubscriptions, Stream.fromQueue(resubscribes)),
1234 },
1235 ).pipe(
1236 Stream.runForEachArray((items) =>
1237 receiveItems(items).pipe(
1238 Effect.andThen(
1239 Effect.sync(() => {
1240 defectRetries = 0;
1241 }),
1242 ),
1243 ),
1244 ),
1245 // A defect while applying items ends the stream; resubscribe for a fresh snapshot.
1246 Effect.catchCause((cause) =>
1247 Cause.hasInterrupts(cause)
1248 ? Effect.interrupt
1249 : Effect.logWarning("Thread subscription failed; resubscribing.", {
1250 cause: Cause.pretty(cause),
1251 environmentId,
1252 threadId,
1253 }).pipe(
1254 Effect.andThen(Ref.set(forceSnapshot, true)),
1255 Effect.andThen(backOffAfterDefect),
1256 Effect.andThen(Effect.suspend(followThread)),
1257 ),
1258 ),
1259 );
1260 yield* Effect.forkScoped(followThread());
1261
1262 return state;
1263});
1264
1265// Following stops at removal but leaves the last value, so an open screen would keep the thread.
1266const environmentRemovals = (environmentId: EnvironmentIdType) =>
1267 Stream.unwrap(
1268 EnvironmentRegistry.EnvironmentRegistry.pipe(
1269 Effect.map((registry) =>
1270 SubscriptionRef.changes(registry.entries).pipe(
1271 Stream.map((entries) => entries.has(environmentId)),
1272 Stream.changes,
1273 Stream.dropWhile((registered) => !registered),
1274 Stream.filter((registered) => !registered),
1275 ),
1276 ),
1277 ),
1278 );
1279
1280function threadStateChanges(
1281 environmentId: EnvironmentIdType,
1282 threadId: ThreadIdType,
1283 resumeCache?: ThreadResumeCache,
1284) {
1285 return Stream.merge(
1286 followStreamInEnvironment(
1287 environmentId,
1288 Stream.unwrap(
1289 makeEnvironmentThreadState(threadId, resumeCache).pipe(Effect.map(SubscriptionRef.changes)),
1290 ),
1291 ),
1292 environmentRemovals(environmentId).pipe(Stream.as(EMPTY_ENVIRONMENT_THREAD_STATE)),
1293 );
1294}
1295
1296export function createEnvironmentThreadStateAtoms<R, E>(
1297 runtime: Atom.AtomRuntime<
1298 | EnvironmentRegistry.EnvironmentRegistry
1299 | Persistence.EnvironmentCacheStore
1300 | ThreadSnapshotLoader.ThreadSnapshotLoader
1301 | R,
1302 E
1303 >,
1304) {
1305 // Cache definitions must outlive collectible live-atom definitions. The
1306 // registry retains these nodes without retaining environment or RPC scopes.
1307 const resumeFamily = Atom.family((key: string) =>
1308 Atom.make((): ThreadResumeCache => ({
1309 snapshot: undefined,
1310 owner: undefined,
1311 })).pipe(
1312 Atom.setIdleTTL(THREAD_SNAPSHOT_IDLE_TTL_MS),
1313 Atom.withLabel(`environment-thread-resume:${key}`),
1314 ),
1315 );
1316 const family = Atom.family((key: string) => {
1317 const { environmentId, threadId } = parseThreadKey(key);
1318 const resumeAtom = resumeFamily(key);
1319 return runtime
1320 .atom(
1321 (get) => {
1322 get.mount(resumeAtom);
1323 const resume = get.once(resumeAtom);
1324 const live = threadStateChanges(environmentId, threadId, resume);
1325 return resume.snapshot === undefined
1326 ? live
1327 : Stream.concat(Stream.succeed(cachedThreadState(resume.snapshot.state)), live);
1328 },
1329 {
1330 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
1331 },
1332 )
1333 .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state:${key}`));
1334 });
1335
1336 return {
1337 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
1338 family(threadKey({ environmentId, threadId })),
1339 };
1340}
1341
1342export * from "./archivedThreads.ts";
1343export * from "./checkpointDiff.ts";
1344export * as BoundedThreadSnapshotLoader from "./boundedThreadSnapshotHttp.ts";
1345export * as ThreadHistoryController from "./threadHistoryController.ts";
1346export type { ThreadHistoryLoadEarlierResult } from "./threadHistoryController.ts";
1347export * from "./threadHistoryMerge.ts";
1348export * from "./threadSnapshotHttp.ts";
1349export * from "./composerPathSearch.ts";
1350export * from "./threadCommands.ts";
1351export * from "./threadFeedback.ts";
1352export * from "./threadDetail.ts";
1353export * from "./threadFamilies.ts";
1354export * from "./olderSettledThreads.ts";
1355export * from "./threadShell.ts";
1356export * from "./threadState.ts";
1357export * from "./threadTagFilter.ts";