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 // Merges an older disjoint page below the currently loaded window. All four
517 // windowed collections prepend; identity dedupe guards the (server-bug or
518 // cursor-misuse) case of overlapping pages so a row never renders twice.
519 const mergeOlderPage = Effect.fn("EnvironmentThreadState.mergeOlderPage")(function* (
520 snapshot: OrchestrationThreadDetailSnapshot,
521 ) {
522 // The merge is built inside the update callback so it composes with
523 // whatever thread value is current at commit time. The applyLock already
524 // serializes this against event application; the atomic build is defense
525 // in depth against future callers outside the lock.
526 let merged: OrchestrationThread | null = null;
527 yield* SubscriptionRef.update(state, (value) => {
528 if (Option.isNone(value.data)) {
529 return value;
530 }
531 const loaded = value.data.value;
532 const older = snapshot.thread;
533 const mergeById = <T extends { readonly id: string }>(
534 olderRows: ReadonlyArray<T>,
535 loadedRows: ReadonlyArray<T>,
536 ): ReadonlyArray<T> => {
537 const seen = new Set(loadedRows.map((row) => row.id));
538 return [...olderRows.filter((row) => !seen.has(row.id)), ...loadedRows];
539 };
540 const seenCheckpoints = new Set(loaded.checkpoints.map((row) => row.turnId));
541 merged = {
542 // Thread metadata stays the loaded (newer) snapshot's; only the
543 // windowed collections gain rows from the older page.
544 ...loaded,
545 messages: mergeById(older.messages, loaded.messages),
546 activities: mergeById(older.activities, loaded.activities),
547 proposedPlans: mergeById(older.proposedPlans, loaded.proposedPlans),
548 checkpoints: [
549 ...older.checkpoints.filter((row) => !seenCheckpoints.has(row.turnId)),
550 ...loaded.checkpoints,
551 ],
552 };
553 return {
554 ...value,
555 data: Option.some(merged),
556 page: pageStateFromSnapshot(snapshot.page),
557 };
558 });
559 // Persist the widened window under the *loaded* watermark: the merged
560 // content is only known consistent with the state it merged into, not
561 // with the page's own (possibly newer) sequence.
562 if (merged !== null && shouldPersistThread(merged)) {
563 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
564 yield* Queue.offer(persistence, {
565 snapshotSequence,
566 thread: merged,
567 ...(snapshot.page === undefined ? {} : { page: { ...snapshot.page, snapshotSequence } }),
568 });
569 }
570 yield* remember;
571 });
572
573 const loadOlderTurns = Effect.fn("EnvironmentThreadState.loadOlderTurns")(function* () {
574 // Gated on the connected server's capability: a reconnect to a
575 // pre-pagination server must never receive window parameters.
576 if (!(yield* Ref.get(paginationSupported))) {
577 return;
578 }
579 const current = yield* SubscriptionRef.get(state);
580 const page = Option.getOrNull(current.page);
581 if (page === null || page.loadingOlder || !page.hasMore || page.beforeCursor === null) {
582 return;
583 }
584 const prepared = Option.getOrNull(yield* SubscriptionRef.get(supervisor.prepared));
585 if (prepared === null) {
586 return;
587 }
588 const epochAtStart = yield* Ref.get(historyEpoch);
589 yield* SubscriptionRef.update(state, (value) => ({
590 ...value,
591 page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: true })),
592 }));
593 const window: ThreadSnapshotWindow = {
594 turnLimit: OLDER_THREAD_PAGE_USER_TURN_LIMIT,
595 beforeCursor: page.beforeCursor,
596 };
597 const response = yield* snapshotLoader.load(prepared, threadId, window);
598 // Staleness check and merge run under the same lock as stream-item
599 // application, so a revert/snapshot cannot land between them (TOCTOU
600 // review finding) — anything that rewrites history bumps the epoch
601 // before this permit is acquired.
602 yield* applyLock.withPermits(1)(
603 Effect.gen(function* () {
604 const epochNow = yield* Ref.get(historyEpoch);
605 const loadedSequence = yield* SubscriptionRef.get(lastSequence);
606 // A page carrying a sequence older than the loaded state was read
607 // from a projection behind what we render; merging it could
608 // resurrect turns a newer snapshot or revert already removed.
609 const stale =
610 epochNow !== epochAtStart ||
611 Option.match(response, {
612 onNone: () => false,
613 onSome: (snapshot) => snapshot.snapshotSequence < loadedSequence,
614 });
615 if (Option.isNone(response) || stale) {
616 yield* SubscriptionRef.update(state, (value) => ({
617 ...value,
618 page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: false })),
619 }));
620 return;
621 }
622 // A page read AHEAD of the live state may include content (e.g.
623 // streaming deltas of an out-of-window turn) the subscription has
624 // not delivered yet; merging now and then replaying those events
625 // would duplicate them. Park the page until the live state reaches
626 // the page's thread-scoped watermark; loadingOlder stays true so
627 // the UI shows progress and no second fetch starts. Pages from
628 // pre-watermark servers (threadSequence absent) merge immediately,
629 // preserving the old behavior.
630 const watermark = response.value.page?.threadSequence;
631 if (watermark !== undefined && watermark > loadedSequence) {
632 yield* Ref.set(pendingOlderPage, {
633 snapshot: response.value,
634 epoch: epochNow,
635 });
636 return;
637 }
638 yield* mergeOlderPage(response.value);
639 }),
640 );
641 });
642
643 yield* SubscriptionRef.changes(supervisor.state).pipe(
644 Stream.runForEach((connectionState) => {
645 switch (connectionProjectionPhase(connectionState)) {
646 case "synchronizing":
647 return setConnecting;
648 case "disconnected":
649 return setDisconnected;
650 case "ready":
651 return setReady;
652 }
653 }),
654 Effect.forkScoped,
655 );
656
657 const foregroundResubscriptions = Option.match(wakeups, {
658 onNone: () => Stream.never,
659 onSome: (service) =>
660 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
661 });
662
663 // Only the first subscription after a warm live resume keeps the retained
664 // status. A replacement session or foreground resubscribe on the same scope
665 // may have missed events, so those show sync progress until confirmed.
666 const resumingLive = yield* Ref.make(initialState.status === "live");
667 const markSynchronizing = Effect.gen(function* () {
668 if (yield* Ref.get(resumingLive)) return;
669 // Connection notifications do not establish that a terminated load restarted.
670 // Clear its diagnostic only when this subscription actually tries again.
671 yield* SubscriptionRef.update(state, (current) =>
672 current.status === "deleted"
673 ? current
674 : { ...current, status: "synchronizing" as const, error: Option.none() },
675 );
676 });
677
678 yield* markSynchronizing;
679 yield* Effect.forkScoped(
680 subscribeDynamic(
681 ORCHESTRATION_WS_METHODS.subscribeThread,
682 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
683 const config = yield* session.initialConfig.pipe(
684 Effect.orElseSucceed(
685 () =>
686 ({}) as {
687 threadResumeCompletionMarker?: boolean;
688 threadSnapshotPagination?: boolean;
689 },
690 ),
691 );
692 const supportsCompletionMarker = config.threadResumeCompletionMarker === true;
693 // Windowed loads are gated on the server capability: pre-pagination
694 // servers reject unknown query params, and a windowed WS fallback to
695 // such a server would silently hide history.
696 const supportsPagination = config.threadSnapshotPagination === true;
697 yield* Ref.set(paginationSupported, supportsPagination);
698 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
699 yield* markSynchronizing;
700 yield* Ref.set(resumingLive, false);
701
702 let current = yield* SubscriptionRef.get(state);
703 // A windowed cache resuming against a server without pagination is a
704 // trap: afterSequence resume keeps only the window, and the missing
705 // older turns can never be loaded (the server has no cursor reads).
706 // Drop the window marker and treat the data as needing a full reload.
707 if (!supportsPagination) {
708 yield* applyLock.withPermits(1)(
709 Effect.gen(function* () {
710 if (Option.isNone((yield* SubscriptionRef.get(state)).page)) return;
711 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
712 yield* SubscriptionRef.update(state, (value) => ({
713 ...value,
714 data: Option.none(),
715 status: value.status === "deleted" ? value.status : ("empty" as const),
716 page: Option.none(),
717 }));
718 yield* SubscriptionRef.set(lastSequence, 0);
719 yield* remember;
720 }),
721 );
722 current = yield* SubscriptionRef.get(state);
723 }
724 if (Option.isNone(current.data) && current.status !== "deleted") {
725 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
726 Effect.flatMap(
727 Option.match({
728 onSome: Effect.succeed,
729 onNone: () =>
730 SubscriptionRef.changes(supervisor.prepared).pipe(
731 Stream.filter(Option.isSome),
732 Stream.map((value) => value.value),
733 Stream.runHead,
734 Effect.map(Option.getOrThrow),
735 ),
736 }),
737 ),
738 );
739 const httpSnapshot = yield* snapshotLoader.load(
740 prepared,
741 threadId,
742 supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : undefined,
743 );
744 if (Option.isSome(httpSnapshot)) {
745 yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
746 current = yield* SubscriptionRef.get(state);
747 }
748 }
749
750 const sequence = yield* SubscriptionRef.get(lastSequence);
751 const canResume = Option.isSome(current.data);
752 if (!supportsCompletionMarker && canResume) {
753 yield* SubscriptionRef.update(state, (value) => ({
754 ...value,
755 status: value.status === "deleted" ? value.status : ("live" as const),
756 error: Option.none(),
757 }));
758 }
759
760 return {
761 threadId,
762 ...(canResume ? { afterSequence: sequence } : {}),
763 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
764 // The WS fallback snapshot (sent when afterSequence is missing or
765 // the gap is too large) should be windowed the same as the HTTP
766 // path; without this a resume failure re-downloads the full thread.
767 ...(supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : {}),
768 };
769 }),
770 {
771 onDefect: () => setStreamError("Could not synchronize the thread."),
772 onExpectedFailure: (cause) => setStreamError(formatThreadError(cause)),
773 retryExpectedFailureAfter: "250 millis",
774 resubscribe: foregroundResubscriptions,
775 },
776 ).pipe(Stream.runForEach(applyItem)),
777 );
778
779 // Expose loadOlderTurns to UI actions through the request registry.
780 // Requests funnel through a sliding queue drained serially, so mashing
781 // "load earlier" coalesces (loadOlderTurns itself no-ops while a fetch is
782 // in flight).
783 const olderTurnRequestRegistry = yield* ThreadOlderTurnRequests;
784 const olderTurnRequests = yield* Queue.sliding<void>(1);
785 yield* Stream.fromQueue(olderTurnRequests).pipe(
786 Stream.runForEach(() => loadOlderTurns()),
787 Effect.forkScoped,
788 );
789 const deregister = olderTurnRequestRegistry.register(
790 threadKey({ environmentId, threadId }),
791 () => {
792 Queue.offerUnsafe(olderTurnRequests, undefined);
793 },
794 );
795 yield* Effect.addFinalizer(() => Effect.sync(deregister));
796
797 yield* Effect.addFinalizer(() =>
798 Effect.suspend(() => {
799 const { state: current, sequence: snapshotSequence } = committed;
800 return Option.match(current.data, {
801 onNone: () => Effect.void,
802 onSome: (thread) =>
803 shouldPersistThread(thread)
804 ? persist({
805 snapshotSequence,
806 thread,
807 ...Option.match(current.page, {
808 onNone: () => ({}),
809 onSome: (page) =>
810 ({
811 page: {
812 beforeCursor: page.beforeCursor,
813 hasMore: page.hasMore,
814 snapshotSequence,
815 },
816 }) as const,
817 }),
818 })
819 : Effect.void,
820 });
821 }),
822 );
823
824 return state;
825});
826
827function threadStateChanges(
828 environmentId: EnvironmentIdType,
829 threadId: ThreadIdType,
830 resumeCache?: ThreadResumeCache,
831) {
832 return followStreamInEnvironment(
833 environmentId,
834 Stream.unwrap(
835 makeEnvironmentThreadState(threadId, resumeCache).pipe(Effect.map(SubscriptionRef.changes)),
836 ),
837 );
838}
839
840export function createEnvironmentThreadStateAtoms<R, E>(
841 runtime: Atom.AtomRuntime<
842 EnvironmentRegistry | EnvironmentCacheStore | ThreadSnapshotLoader | R,
843 E
844 >,
845) {
846 // Cache definitions must outlive collectible live-atom definitions. The
847 // registry retains these nodes without retaining environment or RPC scopes.
848 const resumeFamily = Atom.family((key: string) =>
849 Atom.make((): ThreadResumeCache => ({
850 snapshot: undefined,
851 owner: undefined,
852 })).pipe(
853 Atom.setIdleTTL(THREAD_SNAPSHOT_IDLE_TTL_MS),
854 Atom.withLabel(`environment-thread-resume:${key}`),
855 ),
856 );
857 const family = Atom.family((key: string) => {
858 const { environmentId, threadId } = parseThreadKey(key);
859 const resumeAtom = resumeFamily(key);
860 return runtime
861 .atom(
862 (get) => {
863 get.mount(resumeAtom);
864 const resume = get.once(resumeAtom);
865 const live = threadStateChanges(environmentId, threadId, resume);
866 return resume.snapshot === undefined
867 ? live
868 : Stream.concat(Stream.succeed(cachedThreadState(resume.snapshot.state)), live);
869 },
870 {
871 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
872 },
873 )
874 .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state:${key}`));
875 });
876
877 return {
878 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
879 family(threadKey({ environmentId, threadId })),
880 };
881}
882
883export * from "./archivedThreads.ts";
884export * from "./checkpointDiff.ts";
885export * from "./threadSnapshotHttp.ts";
886export * from "./composerPathSearch.ts";
887export * from "./threadCommands.ts";
888export * from "./threadFeedback.ts";
889export * from "./threadDetail.ts";
890export * from "./threadReducer.ts";
891export * from "./threadShell.ts";
892export * from "./threadState.ts";