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

threads.ts

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