Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threads.ts

957 lines37.1 KB

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