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