Open History to see the last commit
1import {
2 ORCHESTRATION_WS_METHODS,
3 type EnvironmentId as EnvironmentIdType,
4 type OrchestrationThread,
5 type OrchestrationThreadDetailPage,
6 type OrchestrationThreadDetailSnapshot,
7 type OrchestrationThreadStreamItem,
8 type ThreadId as ThreadIdType,
9} from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import * as Context from "effect/Context";
12import * as Effect from "effect/Effect";
13import * as Option from "effect/Option";
14import * as Queue from "effect/Queue";
15import * as Ref from "effect/Ref";
16import * as Semaphore from "effect/Semaphore";
17import * as Stream from "effect/Stream";
18import * as SubscriptionRef from "effect/SubscriptionRef";
19import { Atom } from "effect/unstable/reactivity";
20
21import { EnvironmentRegistry } from "../connection/registry.ts";
22import { connectionProjectionPhase } from "../connection/model.ts";
23import { EnvironmentSupervisor } from "../connection/supervisor.ts";
24import * as ConnectionWakeups from "../connection/wakeups.ts";
25import { EnvironmentCacheStore } from "../platform/persistence.ts";
26import { subscribeDynamic } from "../rpc/client.ts";
27import { ThreadSnapshotLoader, type ThreadSnapshotWindow } from "./threadSnapshotHttp.ts";
28import { parseThreadKey, threadKey } from "./entities.ts";
29import { applyThreadDetailEvent } from "./threadReducer.ts";
30import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts";
31import { followStreamInEnvironment } from "./runtime.ts";
32import {
33 EMPTY_ENVIRONMENT_THREAD_STATE,
34 type EnvironmentThreadPageState,
35 type EnvironmentThreadState,
36 type EnvironmentThreadStatus,
37} from "./threadState.ts";
38
39function statusWithoutLiveData(data: Option.Option<OrchestrationThread>): EnvironmentThreadStatus {
40 return Option.isSome(data) ? "cached" : "empty";
41}
42
43/**
44 * Turn window sizes for paginated thread loads: the initial page covers the
45 * last 10 user-anchored turns (subagent/fan-out turns ride along), each
46 * "load earlier" tap fetches 20 more. Sized so first paint on the heaviest
47 * observed threads stays around 100K gzipped while median threads load fully.
48 */
49export const INITIAL_THREAD_USER_TURN_LIMIT = 10;
50const OLDER_THREAD_PAGE_USER_TURN_LIMIT = 20;
51
52function pageStateFromSnapshot(
53 page: OrchestrationThreadDetailPage | undefined,
54): Option.Option<EnvironmentThreadPageState> {
55 return page === undefined
56 ? Option.none()
57 : Option.some({
58 beforeCursor: page.beforeCursor,
59 hasMore: page.hasMore,
60 loadingOlder: false,
61 });
62}
63
64interface ThreadOlderTurnRequestRegistry {
65 /**
66 * Registers the live state machine for a thread. Returns the deregistration
67 * cleanup; registration lives exactly as long as the machine's scope, and a
68 * successor machine for the same thread simply replaces the entry.
69 */
70 readonly register: (key: string, handler: () => void) => () => void;
71 readonly request: (key: string) => boolean;
72}
73
74function makeThreadOlderTurnRequestRegistry(): ThreadOlderTurnRequestRegistry {
75 const handlers = new Map<string, () => void>();
76 return {
77 register: (key, handler) => {
78 handlers.set(key, handler);
79 return () => {
80 if (handlers.get(key) === handler) {
81 handlers.delete(key);
82 }
83 };
84 },
85 request: (key) => {
86 const handler = handlers.get(key);
87 if (handler === undefined) {
88 return false;
89 }
90 handler();
91 return true;
92 },
93 };
94}
95
96const defaultOlderTurnRequestRegistry = makeThreadOlderTurnRequestRegistry();
97
98/**
99 * Channel from UI actions to the live per-thread state machines. The machines
100 * resolve it from the Effect environment (overridable in tests); the default
101 * instance is shared with the sync `requestOlderThreadTurns` entry point so
102 * the apps get working wiring without providing anything.
103 */
104class ThreadOlderTurnRequests extends Context.Reference<ThreadOlderTurnRequestRegistry>(
105 "@t3tools/client-runtime/state/threads/ThreadOlderTurnRequests",
106 { defaultValue: () => defaultOlderTurnRequestRegistry },
107) {}
108
109/**
110 * Asks the live state machine for `threadId` to fetch the next older page.
111 * Returns false when no machine is live or no fetch was started (no cursor,
112 * already loading); callers render from `EnvironmentThreadState.page` and can
113 * treat false as "nothing to do".
114 */
115export function requestOlderThreadTurns(
116 environmentId: EnvironmentIdType,
117 threadId: ThreadIdType,
118): boolean {
119 return defaultOlderTurnRequestRegistry.request(threadKey({ environmentId, threadId }));
120}
121
122function formatThreadError(cause: Cause.Cause<unknown>): string {
123 const error = Cause.squash(cause);
124 return error instanceof Error && error.message.trim().length > 0
125 ? error.message
126 : "Could not synchronize the thread.";
127}
128
129/**
130 * A starting or running session is mid-turn. Its detail can change many times
131 * per second, so the disk cache waits for it to settle.
132 */
133export function isThreadSessionRunning(session: OrchestrationThread["session"]): boolean {
134 return session?.status === "starting" || session?.status === "running";
135}
136
137function shouldPersistThread(thread: OrchestrationThread): boolean {
138 return !isThreadSessionRunning(thread.session);
139}
140
141interface ThreadResumeSnapshot {
142 readonly state: EnvironmentThreadState;
143 readonly sequence: number;
144 readonly persisted: boolean;
145}
146
147interface ThreadResumeCache {
148 snapshot: ThreadResumeSnapshot | undefined;
149 owner: object | undefined;
150}
151
152function matchesThreadSnapshot(
153 current: ThreadResumeSnapshot,
154 thread: OrchestrationThread | null,
155 sequence: number,
156 page: Pick<EnvironmentThreadPageState, "beforeCursor" | "hasMore"> | undefined,
157): boolean {
158 if (current.sequence !== sequence || Option.getOrNull(current.state.data) !== thread)
159 return false;
160 const currentPage = Option.getOrUndefined(current.state.page);
161 return currentPage === undefined
162 ? page === undefined
163 : page !== undefined &&
164 currentPage.beforeCursor === page.beforeCursor &&
165 currentPage.hasMore === page.hasMore;
166}
167
168// A retained "live" state stays live: the cursor resume that follows only
169// replays what the thread missed, and on servers that send the completion
170// marker the first replayed event moves the status to "synchronizing" on its
171// own. Downgrading here would flash a sync label on every return to a
172// recently viewed thread.
173function cachedThreadState(value: EnvironmentThreadState): EnvironmentThreadState {
174 return {
175 ...value,
176 status:
177 value.status === "deleted" || (value.status === "live" && Option.isSome(value.data))
178 ? value.status
179 : statusWithoutLiveData(value.data),
180 error: Option.none(),
181 page: Option.map(value.page, (page) => ({ ...page, loadingOlder: false })),
182 };
183}
184
185export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
186 threadId: ThreadIdType,
187 resumeCache?: ThreadResumeCache,
188) {
189 const supervisor = yield* EnvironmentSupervisor;
190 const cache = yield* EnvironmentCacheStore;
191 const snapshotLoader = yield* ThreadSnapshotLoader;
192 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
193 const environmentId = supervisor.target.environmentId;
194 const retained = resumeCache?.snapshot;
195 const owner = {};
196 if (resumeCache) resumeCache.owner = owner;
197 const cached =
198 retained === undefined
199 ? yield* cache.loadThread(environmentId, threadId).pipe(
200 Effect.catch((error) =>
201 Effect.logWarning("Could not load cached thread.").pipe(
202 Effect.annotateLogs({
203 environmentId,
204 threadId,
205 error: error.message,
206 }),
207 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
208 ),
209 ),
210 )
211 : Option.none<OrchestrationThreadDetailSnapshot>();
212 const cachedThread = Option.map(cached, (snapshot) => snapshot.thread);
213 const initialState: EnvironmentThreadState = retained
214 ? cachedThreadState(retained.state)
215 : {
216 data: cachedThread,
217 status: statusWithoutLiveData(cachedThread),
218 error: Option.none(),
219 // A cached windowed snapshot restores its page cursor so "load earlier"
220 // works while rendering from cache; a cached full snapshot has no page.
221 page: Option.flatMap(cached, (snapshot) => pageStateFromSnapshot(snapshot.page)),
222 };
223 const state = yield* SubscriptionRef.make(initialState);
224 // Seed the resume cursor from the cached snapshot so a warm cache can catch up
225 // via `afterSequence` instead of re-downloading the full thread body.
226 const initialSequence =
227 retained?.sequence ??
228 Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence });
229 const lastSequence = yield* SubscriptionRef.make(initialSequence);
230 let committed: ThreadResumeSnapshot = {
231 state: initialState,
232 sequence: initialSequence,
233 persisted: retained?.persisted ?? Option.isSome(cached),
234 };
235 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
236 const awaitingCompletion = yield* Ref.make(false);
237 // Bumped whenever loaded history may have been rewritten out from under an
238 // in-flight older-page fetch (snapshot replacement, revert, deletion). A
239 // page response captured under an older epoch is discarded, not merged.
240 const historyEpoch = yield* Ref.make(0);
241 // Serializes stream-item application against older-page staleness checks +
242 // merges. Without it, a revert or snapshot processed between loadOlderTurns'
243 // epoch check and its merge could still slip resurrected history in.
244 const applyLock = yield* Semaphore.make(1);
245 // Save only completed data/cursor updates. A canceled scope must not cache
246 // a cursor whose event has not reached the data yet.
247 const remember = Effect.gen(function* () {
248 const current = yield* SubscriptionRef.get(state);
249 const sequence = yield* SubscriptionRef.get(lastSequence);
250 committed = {
251 state: current,
252 sequence,
253 persisted:
254 committed.persisted &&
255 matchesThreadSnapshot(
256 committed,
257 Option.getOrNull(current.data),
258 sequence,
259 Option.getOrUndefined(current.page),
260 ),
261 };
262 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
263 });
264 // Whether the connected server accepts windowed reads; set per subscription
265 // from the session config. Gates loadOlderTurns so a reconnect to a
266 // pre-pagination server never sends unsupported window parameters.
267 const paginationSupported = yield* Ref.make(false);
268 const reasoningMessagesSupported = yield* Ref.make(false);
269 // An older page whose thread watermark is ahead of the live state, parked
270 // until the subscription catches up (see mergeOlderPage's caller). At most
271 // one can exist because loadOlderTurns no-ops while loadingOlder is true.
272 const pendingOlderPage = yield* Ref.make<{
273 readonly snapshot: OrchestrationThreadDetailSnapshot;
274 readonly epoch: number;
275 } | null>(null);
276 const persistence = yield* Queue.sliding<OrchestrationThreadDetailSnapshot>(1);
277
278 const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
279 snapshot: OrchestrationThreadDetailSnapshot,
280 ) {
281 if (resumeCache !== undefined && resumeCache.owner !== owner) return;
282 if (
283 committed.persisted &&
284 matchesThreadSnapshot(committed, snapshot.thread, snapshot.snapshotSequence, snapshot.page)
285 )
286 return;
287 yield* cache.saveThread(environmentId, snapshot).pipe(
288 Effect.tap(() =>
289 Effect.sync(() => {
290 if (
291 !matchesThreadSnapshot(
292 committed,
293 snapshot.thread,
294 snapshot.snapshotSequence,
295 snapshot.page,
296 )
297 )
298 return;
299 committed = { ...committed, persisted: true };
300 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
301 }),
302 ),
303 Effect.catch((error) =>
304 Effect.logWarning("Could not persist the thread cache.").pipe(
305 Effect.annotateLogs({
306 environmentId,
307 threadId,
308 error: error.message,
309 }),
310 ),
311 ),
312 );
313 });
314
315 yield* Stream.fromQueue(persistence).pipe(
316 Stream.debounce("500 millis"),
317 Stream.runForEach(persist),
318 Effect.forkScoped,
319 );
320
321 const setConnecting = SubscriptionRef.update(state, (current) =>
322 current.status === "deleted" || Option.isSome(current.error)
323 ? current
324 : {
325 ...current,
326 status: "synchronizing" as const,
327 error: Option.none(),
328 },
329 );
330 const setReady = SubscriptionRef.update(state, (current) =>
331 current.status === "live" || current.status === "deleted" || Option.isSome(current.error)
332 ? current
333 : {
334 ...current,
335 status: "synchronizing" as const,
336 error: Option.none(),
337 },
338 );
339 const setDisconnected = Effect.gen(function* () {
340 yield* Ref.set(awaitingCompletion, false);
341 // The capability belongs to the session that advertised it. During a
342 // reconnect, a new prepared connection can exist before the new session's
343 // config arrives; leaving the old value would let loadOlderTurns send
344 // window parameters to a server that may not accept them (review
345 // finding). makeSubscribeInput re-sets it from the next session's config.
346 yield* Ref.set(paginationSupported, false);
347 yield* Ref.set(reasoningMessagesSupported, false);
348 yield* SubscriptionRef.update(state, (current) => ({
349 ...current,
350 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
351 }));
352 });
353 const setStreamError = (message: string) =>
354 Ref.set(awaitingCompletion, false).pipe(
355 Effect.andThen(
356 SubscriptionRef.update(state, (current) => ({
357 ...current,
358 status:
359 current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
360 error: Option.some(message),
361 })),
362 ),
363 );
364
365 const offerThreadPersistence = Effect.fn("EnvironmentThreadState.offerThreadPersistence")(
366 function* (thread: OrchestrationThread, snapshotSequence: number) {
367 const currentPage = yield* SubscriptionRef.get(state).pipe(Effect.map((value) => value.page));
368 yield* Queue.offer(persistence, {
369 snapshotSequence,
370 thread,
371 // Persist the window boundary with the window's content so a cache
372 // restore can keep paging from where the loaded history ends.
373 ...Option.match(currentPage, {
374 onNone: () => ({}),
375 onSome: (value) =>
376 ({
377 page: {
378 beforeCursor: value.beforeCursor,
379 hasMore: value.hasMore,
380 snapshotSequence,
381 },
382 }) as const,
383 }),
384 });
385 },
386 );
387
388 const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
389 thread: OrchestrationThread,
390 // "keep" preserves the current page state (live events touch only loaded
391 // recent turns); a snapshot or merged page passes its own page state.
392 page: Option.Option<EnvironmentThreadPageState> | "keep",
393 ) {
394 const waiting = yield* Ref.get(awaitingCompletion);
395 yield* SubscriptionRef.update(state, (current) => ({
396 data: Option.some(thread),
397 // Buffered values from the failed attempt can still arrive after its error.
398 status: Option.isSome(current.error)
399 ? ("cached" as const)
400 : waiting
401 ? ("synchronizing" as const)
402 : ("live" as const),
403 error: current.error,
404 page: page === "keep" ? current.page : page,
405 }));
406 // Active threads can update many times per second and retain large tool
407 // payloads. The server remains the source of truth while a turn is active;
408 // persist once it settles so cache encoding stays off the streaming path.
409 if (shouldPersistThread(thread)) {
410 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
411 yield* offerThreadPersistence(thread, snapshotSequence);
412 }
413 });
414
415 const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
416 yield* Ref.set(awaitingCompletion, false);
417 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
418 yield* SubscriptionRef.set(state, {
419 data: Option.none(),
420 status: "deleted",
421 error: Option.none(),
422 page: Option.none(),
423 });
424 yield* remember;
425 if (resumeCache !== undefined && resumeCache.owner !== owner) return;
426 yield* cache.removeThread(environmentId, threadId).pipe(
427 Effect.catch((error) =>
428 Effect.logWarning("Could not remove the cached thread.").pipe(
429 Effect.annotateLogs({
430 environmentId,
431 threadId,
432 error: error.message,
433 }),
434 ),
435 ),
436 );
437 });
438
439 // Body of applyItem, running under applyLock.
440 const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* (
441 item: OrchestrationThreadStreamItem,
442 ) {
443 if (item.kind === "synchronized") {
444 yield* Ref.set(awaitingCompletion, false);
445 yield* SubscriptionRef.update(state, (current) =>
446 Option.isSome(current.data) && current.status !== "deleted" && Option.isNone(current.error)
447 ? { ...current, status: "live" as const, error: Option.none() }
448 : current,
449 );
450 return;
451 }
452
453 if (item.kind === "snapshot") {
454 // A fresh snapshot replaces all loaded history, including older
455 // pages: a turn reverted while disconnected would otherwise survive
456 // in the preserved history with no event left to remove it. The
457 // epoch bump discards any older-page fetch racing this snapshot.
458 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
459 // A parked response must not clear loadingOlder on a request started
460 // from the replacement snapshot's cursor.
461 yield* Ref.set(pendingOlderPage, null);
462 yield* SubscriptionRef.set(lastSequence, item.snapshot.snapshotSequence);
463 yield* setThread(item.snapshot.thread, pageStateFromSnapshot(item.snapshot.page));
464 return;
465 }
466
467 const sequence = yield* SubscriptionRef.get(lastSequence);
468 if (item.event.sequence <= sequence) {
469 return;
470 }
471 yield* SubscriptionRef.set(lastSequence, item.event.sequence);
472
473 const current = yield* SubscriptionRef.get(state);
474 if (Option.isNone(current.data)) {
475 if (item.event.type === "thread.deleted") {
476 yield* setDeleted();
477 }
478 return;
479 }
480 if (item.event.type === "thread.reverted") {
481 // A revert rewrites loaded history (whole turns disappear), so an
482 // older-page fetch in flight may straddle the removed range; the epoch
483 // bump discards it. The stored page cursor stays valid: cursors are an
484 // (anchor, turnId) keyset derived from event content, which survives
485 // the revert projector's row rewrite, so no refresh is needed — the
486 // revert reducer's turn filtering fully handles loaded history.
487 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
488 }
489 const result = applyThreadDetailEvent(current.data.value, item.event);
490 if (result.kind === "updated") {
491 yield* setThread(result.thread, "keep");
492 } else if (result.kind === "deleted") {
493 yield* setDeleted();
494 }
495 // The event may have advanced the live state past a parked page's
496 // watermark; merge it as soon as that happens.
497 yield* tryMergePendingOlderPage();
498 });
499
500 // Merges a parked older page once the live state has caught up to the
501 // page's thread watermark, or discards it if history was rewritten
502 // (epoch advanced) while it waited. Must run under applyLock.
503 const tryMergePendingOlderPage = Effect.fn("EnvironmentThreadState.tryMergePendingOlderPage")(
504 function* () {
505 const pending = yield* Ref.get(pendingOlderPage);
506 if (pending === null) {
507 return;
508 }
509 const epochNow = yield* Ref.get(historyEpoch);
510 if (epochNow !== pending.epoch) {
511 yield* Ref.set(pendingOlderPage, null);
512 yield* SubscriptionRef.update(state, (value) => ({
513 ...value,
514 page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: false })),
515 }));
516 return;
517 }
518 const watermark = pending.snapshot.page?.threadSequence;
519 const loadedSequence = yield* SubscriptionRef.get(lastSequence);
520 if (watermark !== undefined && watermark > loadedSequence) {
521 return;
522 }
523 yield* Ref.set(pendingOlderPage, null);
524 yield* mergeOlderPage(pending.snapshot);
525 },
526 );
527
528 const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* (
529 item: OrchestrationThreadStreamItem,
530 ) {
531 yield* applyLock.withPermits(1)(applyItemLocked(item).pipe(Effect.andThen(remember)));
532 });
533
534 const applyItems = Effect.fn("EnvironmentThreadState.applyItems")(function* (
535 items: ReadonlyArray<OrchestrationThreadStreamItem>,
536 ) {
537 yield* applyLock.withPermits(1)(
538 Effect.gen(function* () {
539 const current = yield* SubscriptionRef.get(state);
540 if (
541 Option.isNone(current.data) ||
542 (yield* Ref.get(pendingOlderPage)) !== null ||
543 items.some(
544 (item) =>
545 item.kind === "snapshot" ||
546 (item.kind === "event" &&
547 (item.event.type === "thread.reverted" || item.event.type === "thread.deleted")),
548 )
549 ) {
550 for (const item of items) {
551 yield* applyItemLocked(item);
552 yield* remember;
553 }
554 return;
555 }
556
557 let thread = current.data.value;
558 let sequence = yield* SubscriptionRef.get(lastSequence);
559 let synchronized = false;
560 // Retain the last settled state even if the next turn starts before
561 // this batch publishes. Its cursor must describe that settled content.
562 let persistable: { thread: OrchestrationThread; sequence: number } | undefined;
563 for (const item of items) {
564 if (item.kind === "synchronized") {
565 synchronized = true;
566 } else if (item.kind === "event" && item.event.sequence > sequence) {
567 sequence = item.event.sequence;
568 const result = applyThreadDetailEvent(thread, item.event);
569 if (result.kind === "updated") {
570 thread = result.thread;
571 if (shouldPersistThread(thread)) persistable = { thread, sequence };
572 }
573 }
574 }
575 yield* SubscriptionRef.set(lastSequence, sequence);
576 if (thread !== current.data.value) yield* setThread(thread, "keep");
577 if (persistable !== undefined && !shouldPersistThread(thread)) {
578 yield* offerThreadPersistence(persistable.thread, persistable.sequence);
579 }
580 if (synchronized) yield* applyItemLocked({ kind: "synchronized" });
581 yield* remember;
582 }),
583 );
584 });
585
586 // Merges an older disjoint page below the currently loaded window. All four
587 // windowed collections prepend; identity dedupe guards the (server-bug or
588 // cursor-misuse) case of overlapping pages so a row never renders twice.
589 const mergeOlderPage = Effect.fn("EnvironmentThreadState.mergeOlderPage")(function* (
590 snapshot: OrchestrationThreadDetailSnapshot,
591 ) {
592 // The merge is built inside the update callback so it composes with
593 // whatever thread value is current at commit time. The applyLock already
594 // serializes this against event application; the atomic build is defense
595 // in depth against future callers outside the lock.
596 let merged: OrchestrationThread | null = null;
597 yield* SubscriptionRef.update(state, (value) => {
598 if (Option.isNone(value.data)) {
599 return value;
600 }
601 const loaded = value.data.value;
602 const older = snapshot.thread;
603 const mergeById = <T extends { readonly id: string }>(
604 olderRows: ReadonlyArray<T>,
605 loadedRows: ReadonlyArray<T>,
606 ): ReadonlyArray<T> => {
607 const seen = new Set(loadedRows.map((row) => row.id));
608 return [...olderRows.filter((row) => !seen.has(row.id)), ...loadedRows];
609 };
610 const seenCheckpoints = new Set(loaded.checkpoints.map((row) => row.turnId));
611 merged = {
612 // Thread metadata stays the loaded (newer) snapshot's; only the
613 // windowed collections gain rows from the older page.
614 ...loaded,
615 messages: mergeById(older.messages, loaded.messages),
616 activities: mergeById(older.activities, loaded.activities),
617 proposedPlans: mergeById(older.proposedPlans, loaded.proposedPlans),
618 checkpoints: [
619 ...older.checkpoints.filter((row) => !seenCheckpoints.has(row.turnId)),
620 ...loaded.checkpoints,
621 ],
622 };
623 return {
624 ...value,
625 data: Option.some(merged),
626 page: pageStateFromSnapshot(snapshot.page),
627 };
628 });
629 // Persist the widened window under the *loaded* watermark: the merged
630 // content is only known consistent with the state it merged into, not
631 // with the page's own (possibly newer) sequence.
632 if (merged !== null && shouldPersistThread(merged)) {
633 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
634 yield* Queue.offer(persistence, {
635 snapshotSequence,
636 thread: merged,
637 ...(snapshot.page === undefined ? {} : { page: { ...snapshot.page, snapshotSequence } }),
638 });
639 }
640 yield* remember;
641 });
642
643 const loadOlderTurns = Effect.fn("EnvironmentThreadState.loadOlderTurns")(function* () {
644 // Gated on the connected server's capability: a reconnect to a
645 // pre-pagination server must never receive window parameters.
646 if (!(yield* Ref.get(paginationSupported))) {
647 return;
648 }
649 const current = yield* SubscriptionRef.get(state);
650 const page = Option.getOrNull(current.page);
651 if (page === null || page.loadingOlder || !page.hasMore || page.beforeCursor === null) {
652 return;
653 }
654 const prepared = Option.getOrNull(yield* SubscriptionRef.get(supervisor.prepared));
655 if (prepared === null) {
656 return;
657 }
658 const epochAtStart = yield* Ref.get(historyEpoch);
659 yield* SubscriptionRef.update(state, (value) => ({
660 ...value,
661 page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: true })),
662 }));
663 const window: ThreadSnapshotWindow = {
664 turnLimit: OLDER_THREAD_PAGE_USER_TURN_LIMIT,
665 beforeCursor: page.beforeCursor,
666 };
667 const response = yield* snapshotLoader.load(
668 prepared,
669 threadId,
670 window,
671 yield* Ref.get(reasoningMessagesSupported),
672 );
673 // Staleness check and merge run under the same lock as stream-item
674 // application, so a revert/snapshot cannot land between them (TOCTOU
675 // review finding) — anything that rewrites history bumps the epoch
676 // before this permit is acquired.
677 yield* applyLock.withPermits(1)(
678 Effect.gen(function* () {
679 const epochNow = yield* Ref.get(historyEpoch);
680 const loadedSequence = yield* SubscriptionRef.get(lastSequence);
681 // A page carrying a sequence older than the loaded state was read
682 // from a projection behind what we render; merging it could
683 // resurrect turns a newer snapshot or revert already removed.
684 const stale =
685 epochNow !== epochAtStart ||
686 Option.match(response, {
687 onNone: () => false,
688 onSome: (snapshot) => snapshot.snapshotSequence < loadedSequence,
689 });
690 if (Option.isNone(response) || stale) {
691 yield* SubscriptionRef.update(state, (value) => ({
692 ...value,
693 page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: false })),
694 }));
695 return;
696 }
697 // A page read AHEAD of the live state may include content (e.g.
698 // streaming deltas of an out-of-window turn) the subscription has
699 // not delivered yet; merging now and then replaying those events
700 // would duplicate them. Park the page until the live state reaches
701 // the page's thread-scoped watermark; loadingOlder stays true so
702 // the UI shows progress and no second fetch starts. Pages from
703 // pre-watermark servers (threadSequence absent) merge immediately,
704 // preserving the old behavior.
705 const watermark = response.value.page?.threadSequence;
706 if (watermark !== undefined && watermark > loadedSequence) {
707 yield* Ref.set(pendingOlderPage, {
708 snapshot: response.value,
709 epoch: epochNow,
710 });
711 return;
712 }
713 yield* mergeOlderPage(response.value);
714 }),
715 );
716 });
717
718 yield* SubscriptionRef.changes(supervisor.state).pipe(
719 Stream.runForEach((connectionState) => {
720 switch (connectionProjectionPhase(connectionState)) {
721 case "synchronizing":
722 return setConnecting;
723 case "disconnected":
724 return setDisconnected;
725 case "ready":
726 return setReady;
727 }
728 }),
729 Effect.forkScoped,
730 );
731
732 const foregroundResubscriptions = Option.match(wakeups, {
733 onNone: () => Stream.never,
734 onSome: (service) =>
735 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
736 });
737
738 // Only the first subscription after a warm live resume keeps the retained
739 // status. A replacement session or foreground resubscribe on the same scope
740 // may have missed events, so those show sync progress until confirmed.
741 const resumingLive = yield* Ref.make(initialState.status === "live");
742 const markSynchronizing = Effect.gen(function* () {
743 if (yield* Ref.get(resumingLive)) return;
744 // Connection notifications do not establish that a terminated load restarted.
745 // Clear its diagnostic only when this subscription actually tries again.
746 yield* SubscriptionRef.update(state, (current) =>
747 current.status === "deleted"
748 ? current
749 : { ...current, status: "synchronizing" as const, error: Option.none() },
750 );
751 });
752
753 yield* markSynchronizing;
754 yield* Effect.forkScoped(
755 subscribeDynamic(
756 ORCHESTRATION_WS_METHODS.subscribeThread,
757 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
758 const config = yield* session.initialConfig.pipe(
759 Effect.orElseSucceed(
760 () =>
761 ({}) as {
762 threadResumeCompletionMarker?: boolean;
763 threadSnapshotPagination?: boolean;
764 reasoningMessages?: boolean;
765 },
766 ),
767 );
768 const supportsCompletionMarker = config.threadResumeCompletionMarker === true;
769 // Windowed loads are gated on the server capability: pre-pagination
770 // servers reject unknown query params, and a windowed WS fallback to
771 // such a server would silently hide history.
772 const supportsPagination = config.threadSnapshotPagination === true;
773 const supportsReasoningMessages = config.reasoningMessages === true;
774 yield* Ref.set(reasoningMessagesSupported, supportsReasoningMessages);
775 yield* Ref.set(paginationSupported, supportsPagination);
776 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
777 yield* markSynchronizing;
778 yield* Ref.set(resumingLive, false);
779
780 let current = yield* SubscriptionRef.get(state);
781 // A windowed cache resuming against a server without pagination is a
782 // trap: afterSequence resume keeps only the window, and the missing
783 // older turns can never be loaded (the server has no cursor reads).
784 // Drop the window marker and treat the data as needing a full reload.
785 if (!supportsPagination) {
786 yield* applyLock.withPermits(1)(
787 Effect.gen(function* () {
788 if (Option.isNone((yield* SubscriptionRef.get(state)).page)) return;
789 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
790 yield* SubscriptionRef.update(state, (value) => ({
791 ...value,
792 data: Option.none(),
793 status: value.status === "deleted" ? value.status : ("empty" as const),
794 page: Option.none(),
795 }));
796 yield* SubscriptionRef.set(lastSequence, 0);
797 yield* remember;
798 }),
799 );
800 current = yield* SubscriptionRef.get(state);
801 }
802 if (Option.isNone(current.data) && current.status !== "deleted") {
803 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
804 Effect.flatMap(
805 Option.match({
806 onSome: Effect.succeed,
807 onNone: () =>
808 SubscriptionRef.changes(supervisor.prepared).pipe(
809 Stream.filter(Option.isSome),
810 Stream.map((value) => value.value),
811 Stream.runHead,
812 Effect.map(Option.getOrThrow),
813 ),
814 }),
815 ),
816 );
817 const httpSnapshot = yield* snapshotLoader.load(
818 prepared,
819 threadId,
820 supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : undefined,
821 supportsReasoningMessages,
822 );
823 if (Option.isSome(httpSnapshot)) {
824 yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
825 current = yield* SubscriptionRef.get(state);
826 }
827 }
828
829 const sequence = yield* SubscriptionRef.get(lastSequence);
830 const canResume = Option.isSome(current.data);
831 if (!supportsCompletionMarker && canResume) {
832 yield* SubscriptionRef.update(state, (value) => ({
833 ...value,
834 status: value.status === "deleted" ? value.status : ("live" as const),
835 error: Option.none(),
836 }));
837 }
838
839 return {
840 threadId,
841 ...(canResume ? { afterSequence: sequence } : {}),
842 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
843 ...(supportsReasoningMessages ? { reasoningMessages: true as const } : {}),
844 // The WS fallback snapshot (sent when afterSequence is missing or
845 // the gap is too large) should be windowed the same as the HTTP
846 // path; without this a resume failure re-downloads the full thread.
847 ...(supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : {}),
848 };
849 }),
850 {
851 onDefect: () => setStreamError("Could not synchronize the thread."),
852 onExpectedFailure: (cause) => setStreamError(formatThreadError(cause)),
853 retryExpectedFailureAfter: "250 millis",
854 resubscribe: foregroundResubscriptions,
855 },
856 ).pipe(
857 Stream.runForEachArray((items) =>
858 items.length === 1 ? applyItem(items[0]!) : applyItems(items),
859 ),
860 ),
861 );
862
863 // Expose loadOlderTurns to UI actions through the request registry.
864 // Requests funnel through a sliding queue drained serially, so mashing
865 // "load earlier" coalesces (loadOlderTurns itself no-ops while a fetch is
866 // in flight).
867 const olderTurnRequestRegistry = yield* ThreadOlderTurnRequests;
868 const olderTurnRequests = yield* Queue.sliding<void>(1);
869 yield* Stream.fromQueue(olderTurnRequests).pipe(
870 Stream.runForEach(() => loadOlderTurns()),
871 Effect.forkScoped,
872 );
873 const deregister = olderTurnRequestRegistry.register(
874 threadKey({ environmentId, threadId }),
875 () => {
876 Queue.offerUnsafe(olderTurnRequests, undefined);
877 },
878 );
879 yield* Effect.addFinalizer(() => Effect.sync(deregister));
880
881 yield* Effect.addFinalizer(() =>
882 Effect.suspend(() => {
883 const { state: current, sequence: snapshotSequence } = committed;
884 return Option.match(current.data, {
885 onNone: () => Effect.void,
886 onSome: (thread) =>
887 shouldPersistThread(thread)
888 ? persist({
889 snapshotSequence,
890 thread,
891 ...Option.match(current.page, {
892 onNone: () => ({}),
893 onSome: (page) =>
894 ({
895 page: {
896 beforeCursor: page.beforeCursor,
897 hasMore: page.hasMore,
898 snapshotSequence,
899 },
900 }) as const,
901 }),
902 })
903 : Effect.void,
904 });
905 }),
906 );
907
908 return state;
909});
910
911function threadStateChanges(
912 environmentId: EnvironmentIdType,
913 threadId: ThreadIdType,
914 resumeCache?: ThreadResumeCache,
915) {
916 return followStreamInEnvironment(
917 environmentId,
918 Stream.unwrap(
919 makeEnvironmentThreadState(threadId, resumeCache).pipe(Effect.map(SubscriptionRef.changes)),
920 ),
921 );
922}
923
924export function createEnvironmentThreadStateAtoms<R, E>(
925 runtime: Atom.AtomRuntime<
926 EnvironmentRegistry | EnvironmentCacheStore | ThreadSnapshotLoader | R,
927 E
928 >,
929) {
930 // Cache definitions must outlive collectible live-atom definitions. The
931 // registry retains these nodes without retaining environment or RPC scopes.
932 const resumeFamily = Atom.family((key: string) =>
933 Atom.make((): ThreadResumeCache => ({
934 snapshot: undefined,
935 owner: undefined,
936 })).pipe(
937 Atom.setIdleTTL(THREAD_SNAPSHOT_IDLE_TTL_MS),
938 Atom.withLabel(`environment-thread-resume:${key}`),
939 ),
940 );
941 const family = Atom.family((key: string) => {
942 const { environmentId, threadId } = parseThreadKey(key);
943 const resumeAtom = resumeFamily(key);
944 return runtime
945 .atom(
946 (get) => {
947 get.mount(resumeAtom);
948 const resume = get.once(resumeAtom);
949 const live = threadStateChanges(environmentId, threadId, resume);
950 return resume.snapshot === undefined
951 ? live
952 : Stream.concat(Stream.succeed(cachedThreadState(resume.snapshot.state)), live);
953 },
954 {
955 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
956 },
957 )
958 .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state:${key}`));
959 });
960
961 return {
962 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
963 family(threadKey({ environmentId, threadId })),
964 };
965}
966
967export * from "./archivedThreads.ts";
968export * from "./checkpointDiff.ts";
969export * from "./threadSnapshotHttp.ts";
970export * from "./composerPathSearch.ts";
971export * from "./threadCommands.ts";
972export * from "./threadFeedback.ts";
973export * from "./threadDetail.ts";
974export * from "./threadReducer.ts";
975export * from "./threadShell.ts";
976export * from "./threadState.ts";