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