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

threads.ts

1,043 lines40.5 KB

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