Open History to see the last commit
1import {
2 ORCHESTRATION_WS_METHODS,
3 type EnvironmentId as EnvironmentIdType,
4 type OrchestrationThread,
5 type OrchestrationThreadDetailPage,
6 type OrchestrationThreadDetailSnapshot,
7 type OrchestrationThreadStreamItem,
8 type ThreadId as ThreadIdType,
9} from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import * as Context from "effect/Context";
12import * as Effect from "effect/Effect";
13import * as Option from "effect/Option";
14import * as Queue from "effect/Queue";
15import * as Ref from "effect/Ref";
16import * as Semaphore from "effect/Semaphore";
17import * as Stream from "effect/Stream";
18import * as SubscriptionRef from "effect/SubscriptionRef";
19import { Atom } from "effect/unstable/reactivity";
20
21import { EnvironmentRegistry } from "../connection/registry.ts";
22import { connectionProjectionPhase } from "../connection/model.ts";
23import { EnvironmentSupervisor } from "../connection/supervisor.ts";
24import * as ConnectionWakeups from "../connection/wakeups.ts";
25import { EnvironmentCacheStore } from "../platform/persistence.ts";
26import { subscribeDynamic } from "../rpc/client.ts";
27import { ThreadSnapshotLoader, type ThreadSnapshotWindow } from "./threadSnapshotHttp.ts";
28import { parseThreadKey, threadKey } from "./entities.ts";
29import { applyThreadDetailEvent } from "./threadReducer.ts";
30import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
31import { followStreamInEnvironment } from "./runtime.ts";
32import {
33 EMPTY_ENVIRONMENT_THREAD_STATE,
34 type EnvironmentThreadPageState,
35 type EnvironmentThreadState,
36 type EnvironmentThreadStatus,
37} from "./threadState.ts";
38
39function statusWithoutLiveData(data: Option.Option<OrchestrationThread>): EnvironmentThreadStatus {
40 return Option.isSome(data) ? "cached" : "empty";
41}
42
43/**
44 * Turn window sizes for paginated thread loads: the initial page covers the
45 * last 10 user-anchored turns (subagent/fan-out turns ride along), each
46 * "load earlier" tap fetches 20 more. Sized so first paint on the heaviest
47 * observed threads stays around 100K gzipped while median threads load fully.
48 */
49export const INITIAL_THREAD_USER_TURN_LIMIT = 10;
50export const OLDER_THREAD_PAGE_USER_TURN_LIMIT = 20;
51
52function pageStateFromSnapshot(
53 page: OrchestrationThreadDetailPage | undefined,
54): Option.Option<EnvironmentThreadPageState> {
55 return page === undefined
56 ? Option.none()
57 : Option.some({
58 beforeCursor: page.beforeCursor,
59 hasMore: page.hasMore,
60 loadingOlder: false,
61 });
62}
63
64interface ThreadOlderTurnRequestRegistry {
65 /**
66 * Registers the live state machine for a thread. Returns the deregistration
67 * cleanup; registration lives exactly as long as the machine's scope, and a
68 * successor machine for the same thread simply replaces the entry.
69 */
70 readonly register: (key: string, handler: () => void) => () => void;
71 readonly request: (key: string) => boolean;
72}
73
74function makeThreadOlderTurnRequestRegistry(): ThreadOlderTurnRequestRegistry {
75 const handlers = new Map<string, () => void>();
76 return {
77 register: (key, handler) => {
78 handlers.set(key, handler);
79 return () => {
80 if (handlers.get(key) === handler) {
81 handlers.delete(key);
82 }
83 };
84 },
85 request: (key) => {
86 const handler = handlers.get(key);
87 if (handler === undefined) {
88 return false;
89 }
90 handler();
91 return true;
92 },
93 };
94}
95
96const defaultOlderTurnRequestRegistry = makeThreadOlderTurnRequestRegistry();
97
98/**
99 * Channel from UI actions to the live per-thread state machines. The machines
100 * resolve it from the Effect environment (overridable in tests); the default
101 * instance is shared with the sync `requestOlderThreadTurns` entry point so
102 * the apps get working wiring without providing anything.
103 */
104export class ThreadOlderTurnRequests extends Context.Reference<ThreadOlderTurnRequestRegistry>(
105 "@t3tools/client-runtime/state/threads/ThreadOlderTurnRequests",
106 { defaultValue: () => defaultOlderTurnRequestRegistry },
107) {}
108
109/**
110 * Asks the live state machine for `threadId` to fetch the next older page.
111 * Returns false when no machine is live or no fetch was started (no cursor,
112 * already loading); callers render from `EnvironmentThreadState.page` and can
113 * treat false as "nothing to do".
114 */
115export function requestOlderThreadTurns(
116 environmentId: EnvironmentIdType,
117 threadId: ThreadIdType,
118): boolean {
119 return defaultOlderTurnRequestRegistry.request(threadKey({ environmentId, threadId }));
120}
121
122function formatThreadError(cause: Cause.Cause<unknown>): string {
123 const error = Cause.squash(cause);
124 return error instanceof Error && error.message.trim().length > 0
125 ? error.message
126 : "Could not synchronize the thread.";
127}
128
129function shouldPersistThread(thread: OrchestrationThread): boolean {
130 const status = thread.session?.status;
131 return status !== "starting" && status !== "running";
132}
133
134export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
135 threadId: ThreadIdType,
136) {
137 const supervisor = yield* EnvironmentSupervisor;
138 const cache = yield* EnvironmentCacheStore;
139 const snapshotLoader = yield* ThreadSnapshotLoader;
140 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
141 const environmentId = supervisor.target.environmentId;
142 const cached = yield* cache.loadThread(environmentId, threadId).pipe(
143 Effect.catch((error) =>
144 Effect.logWarning("Could not load cached thread.").pipe(
145 Effect.annotateLogs({
146 environmentId,
147 threadId,
148 error: error.message,
149 }),
150 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
151 ),
152 ),
153 );
154 const cachedThread = Option.map(cached, (snapshot) => snapshot.thread);
155 const state = yield* SubscriptionRef.make<EnvironmentThreadState>({
156 data: cachedThread,
157 status: statusWithoutLiveData(cachedThread),
158 error: Option.none(),
159 // A cached windowed snapshot restores its page cursor so "load earlier"
160 // works while rendering from cache; a cached full snapshot has no page.
161 page: Option.flatMap(cached, (snapshot) => pageStateFromSnapshot(snapshot.page)),
162 });
163 // Seed the resume cursor from the cached snapshot so a warm cache can catch up
164 // via `afterSequence` instead of re-downloading the full thread body.
165 const lastSequence = yield* SubscriptionRef.make(
166 Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence }),
167 );
168 const awaitingCompletion = yield* Ref.make(false);
169 // Bumped whenever loaded history may have been rewritten out from under an
170 // in-flight older-page fetch (snapshot replacement, revert, deletion). A
171 // page response captured under an older epoch is discarded, not merged.
172 const historyEpoch = yield* Ref.make(0);
173 // Serializes stream-item application against older-page staleness checks +
174 // merges. Without it, a revert or snapshot processed between loadOlderTurns'
175 // epoch check and its merge could still slip resurrected history in.
176 const applyLock = yield* Semaphore.make(1);
177 // Whether the connected server accepts windowed reads; set per subscription
178 // from the session config. Gates loadOlderTurns so a reconnect to a
179 // pre-pagination server never sends unsupported window parameters.
180 const paginationSupported = yield* Ref.make(false);
181 // An older page whose thread watermark is ahead of the live state, parked
182 // until the subscription catches up (see mergeOlderPage's caller). At most
183 // one can exist because loadOlderTurns no-ops while loadingOlder is true.
184 const pendingOlderPage = yield* Ref.make<{
185 readonly snapshot: OrchestrationThreadDetailSnapshot;
186 readonly epoch: number;
187 } | null>(null);
188 const persistence = yield* Queue.sliding<OrchestrationThreadDetailSnapshot>(1);
189
190 const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
191 snapshot: OrchestrationThreadDetailSnapshot,
192 ) {
193 yield* cache.saveThread(environmentId, snapshot).pipe(
194 Effect.catch((error) =>
195 Effect.logWarning("Could not persist the thread cache.").pipe(
196 Effect.annotateLogs({
197 environmentId,
198 threadId,
199 error: error.message,
200 }),
201 ),
202 ),
203 );
204 });
205
206 yield* Stream.fromQueue(persistence).pipe(
207 Stream.debounce("500 millis"),
208 Stream.runForEach(persist),
209 Effect.forkScoped,
210 );
211
212 const setSynchronizing = SubscriptionRef.update(state, (current) =>
213 current.status === "deleted"
214 ? current
215 : {
216 ...current,
217 status: "synchronizing" as const,
218 error: Option.none(),
219 },
220 );
221 const setReady = SubscriptionRef.update(state, (current) =>
222 current.status === "live" || current.status === "deleted"
223 ? current
224 : {
225 ...current,
226 status: "synchronizing" as const,
227 error: Option.none(),
228 },
229 );
230 const setDisconnected = Effect.gen(function* () {
231 yield* Ref.set(awaitingCompletion, false);
232 // The capability belongs to the session that advertised it. During a
233 // reconnect, a new prepared connection can exist before the new session's
234 // config arrives; leaving the old value would let loadOlderTurns send
235 // window parameters to a server that may not accept them (review
236 // finding). makeSubscribeInput re-sets it from the next session's config.
237 yield* Ref.set(paginationSupported, false);
238 yield* SubscriptionRef.update(state, (current) => ({
239 ...current,
240 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
241 }));
242 });
243 const setStreamError = (cause: Cause.Cause<unknown>) =>
244 Ref.set(awaitingCompletion, false).pipe(
245 Effect.andThen(
246 SubscriptionRef.update(state, (current) => ({
247 ...current,
248 status:
249 current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
250 error: Option.some(formatThreadError(cause)),
251 })),
252 ),
253 );
254
255 const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
256 thread: OrchestrationThread,
257 // "keep" preserves the current page state (live events touch only loaded
258 // recent turns); a snapshot or merged page passes its own page state.
259 page: Option.Option<EnvironmentThreadPageState> | "keep",
260 ) {
261 const waiting = yield* Ref.get(awaitingCompletion);
262 yield* SubscriptionRef.update(state, (current) => ({
263 data: Option.some(thread),
264 status: waiting ? ("synchronizing" as const) : ("live" as const),
265 error: Option.none(),
266 page: page === "keep" ? current.page : page,
267 }));
268 // Active threads can update many times per second and retain large tool
269 // payloads. The server remains the source of truth while a turn is active;
270 // persist once it settles so cache encoding stays off the streaming path.
271 if (shouldPersistThread(thread)) {
272 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
273 const currentPage = yield* SubscriptionRef.get(state).pipe(Effect.map((value) => value.page));
274 yield* Queue.offer(persistence, {
275 snapshotSequence,
276 thread,
277 // Persist the window boundary with the window's content so a cache
278 // restore can keep paging from where the loaded history ends.
279 ...Option.match(currentPage, {
280 onNone: () => ({}),
281 onSome: (value) =>
282 ({
283 page: {
284 beforeCursor: value.beforeCursor,
285 hasMore: value.hasMore,
286 snapshotSequence,
287 },
288 }) as const,
289 }),
290 });
291 }
292 });
293
294 const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
295 yield* Ref.set(awaitingCompletion, false);
296 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
297 yield* SubscriptionRef.set(state, {
298 data: Option.none(),
299 status: "deleted",
300 error: Option.none(),
301 page: Option.none(),
302 });
303 yield* cache.removeThread(environmentId, threadId).pipe(
304 Effect.catch((error) =>
305 Effect.logWarning("Could not remove the cached thread.").pipe(
306 Effect.annotateLogs({
307 environmentId,
308 threadId,
309 error: error.message,
310 }),
311 ),
312 ),
313 );
314 });
315
316 // Body of applyItem, running under applyLock.
317 const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* (
318 item: OrchestrationThreadStreamItem,
319 ) {
320 if (item.kind === "synchronized") {
321 yield* Ref.set(awaitingCompletion, false);
322 yield* SubscriptionRef.update(state, (current) =>
323 Option.isSome(current.data) && current.status !== "deleted"
324 ? { ...current, status: "live" as const, error: Option.none() }
325 : current,
326 );
327 return;
328 }
329
330 if (item.kind === "snapshot") {
331 // A fresh snapshot replaces all loaded history, including older
332 // pages: a turn reverted while disconnected would otherwise survive
333 // in the preserved history with no event left to remove it. The
334 // epoch bump discards any older-page fetch racing this snapshot.
335 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
336 yield* SubscriptionRef.set(lastSequence, item.snapshot.snapshotSequence);
337 yield* setThread(item.snapshot.thread, pageStateFromSnapshot(item.snapshot.page));
338 return;
339 }
340
341 const sequence = yield* SubscriptionRef.get(lastSequence);
342 if (item.event.sequence <= sequence) {
343 return;
344 }
345 yield* SubscriptionRef.set(lastSequence, item.event.sequence);
346
347 const current = yield* SubscriptionRef.get(state);
348 if (Option.isNone(current.data)) {
349 if (item.event.type === "thread.deleted") {
350 yield* setDeleted();
351 }
352 return;
353 }
354 if (item.event.type === "thread.reverted") {
355 // A revert rewrites loaded history (whole turns disappear), so an
356 // older-page fetch in flight may straddle the removed range; the epoch
357 // bump discards it. The stored page cursor stays valid: cursors are an
358 // (anchor, turnId) keyset derived from event content, which survives
359 // the revert projector's row rewrite, so no refresh is needed — the
360 // revert reducer's turn filtering fully handles loaded history.
361 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
362 }
363 const result = applyThreadDetailEvent(current.data.value, item.event);
364 if (result.kind === "updated") {
365 yield* setThread(result.thread, "keep");
366 } else if (result.kind === "deleted") {
367 yield* setDeleted();
368 }
369 // The event may have advanced the live state past a parked page's
370 // watermark; merge it as soon as that happens.
371 yield* tryMergePendingOlderPage();
372 });
373
374 // Merges a parked older page once the live state has caught up to the
375 // page's thread watermark, or discards it if history was rewritten
376 // (epoch advanced) while it waited. Must run under applyLock.
377 const tryMergePendingOlderPage = Effect.fn("EnvironmentThreadState.tryMergePendingOlderPage")(
378 function* () {
379 const pending = yield* Ref.get(pendingOlderPage);
380 if (pending === null) {
381 return;
382 }
383 const epochNow = yield* Ref.get(historyEpoch);
384 if (epochNow !== pending.epoch) {
385 yield* Ref.set(pendingOlderPage, null);
386 yield* SubscriptionRef.update(state, (value) => ({
387 ...value,
388 page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: false })),
389 }));
390 return;
391 }
392 const watermark = pending.snapshot.page?.threadSequence;
393 const loadedSequence = yield* SubscriptionRef.get(lastSequence);
394 if (watermark !== undefined && watermark > loadedSequence) {
395 return;
396 }
397 yield* Ref.set(pendingOlderPage, null);
398 yield* mergeOlderPage(pending.snapshot);
399 },
400 );
401
402 const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* (
403 item: OrchestrationThreadStreamItem,
404 ) {
405 yield* applyLock.withPermits(1)(applyItemLocked(item));
406 });
407
408 // Merges an older disjoint page below the currently loaded window. All four
409 // windowed collections prepend; identity dedupe guards the (server-bug or
410 // cursor-misuse) case of overlapping pages so a row never renders twice.
411 const mergeOlderPage = Effect.fn("EnvironmentThreadState.mergeOlderPage")(function* (
412 snapshot: OrchestrationThreadDetailSnapshot,
413 ) {
414 // The merge is built inside the update callback so it composes with
415 // whatever thread value is current at commit time. The applyLock already
416 // serializes this against event application; the atomic build is defense
417 // in depth against future callers outside the lock.
418 let merged: OrchestrationThread | null = null;
419 yield* SubscriptionRef.update(state, (value) => {
420 if (Option.isNone(value.data)) {
421 return value;
422 }
423 const loaded = value.data.value;
424 const older = snapshot.thread;
425 const mergeById = <T extends { readonly id: string }>(
426 olderRows: ReadonlyArray<T>,
427 loadedRows: ReadonlyArray<T>,
428 ): ReadonlyArray<T> => {
429 const seen = new Set(loadedRows.map((row) => row.id));
430 return [...olderRows.filter((row) => !seen.has(row.id)), ...loadedRows];
431 };
432 const seenCheckpoints = new Set(loaded.checkpoints.map((row) => row.turnId));
433 merged = {
434 // Thread metadata stays the loaded (newer) snapshot's; only the
435 // windowed collections gain rows from the older page.
436 ...loaded,
437 messages: mergeById(older.messages, loaded.messages),
438 activities: mergeById(older.activities, loaded.activities),
439 proposedPlans: mergeById(older.proposedPlans, loaded.proposedPlans),
440 checkpoints: [
441 ...older.checkpoints.filter((row) => !seenCheckpoints.has(row.turnId)),
442 ...loaded.checkpoints,
443 ],
444 };
445 return {
446 ...value,
447 data: Option.some(merged),
448 page: pageStateFromSnapshot(snapshot.page),
449 };
450 });
451 // Persist the widened window under the *loaded* watermark: the merged
452 // content is only known consistent with the state it merged into, not
453 // with the page's own (possibly newer) sequence.
454 if (merged !== null && shouldPersistThread(merged)) {
455 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
456 yield* Queue.offer(persistence, {
457 snapshotSequence,
458 thread: merged,
459 ...(snapshot.page === undefined ? {} : { page: { ...snapshot.page, snapshotSequence } }),
460 });
461 }
462 });
463
464 const loadOlderTurns = Effect.fn("EnvironmentThreadState.loadOlderTurns")(function* () {
465 // Gated on the connected server's capability: a reconnect to a
466 // pre-pagination server must never receive window parameters.
467 if (!(yield* Ref.get(paginationSupported))) {
468 return;
469 }
470 const current = yield* SubscriptionRef.get(state);
471 const page = Option.getOrNull(current.page);
472 if (page === null || page.loadingOlder || !page.hasMore || page.beforeCursor === null) {
473 return;
474 }
475 const prepared = Option.getOrNull(yield* SubscriptionRef.get(supervisor.prepared));
476 if (prepared === null) {
477 return;
478 }
479 const epochAtStart = yield* Ref.get(historyEpoch);
480 yield* SubscriptionRef.update(state, (value) => ({
481 ...value,
482 page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: true })),
483 }));
484 const window: ThreadSnapshotWindow = {
485 turnLimit: OLDER_THREAD_PAGE_USER_TURN_LIMIT,
486 beforeCursor: page.beforeCursor,
487 };
488 const response = yield* snapshotLoader.load(prepared, threadId, window);
489 // Staleness check and merge run under the same lock as stream-item
490 // application, so a revert/snapshot cannot land between them (TOCTOU
491 // review finding) — anything that rewrites history bumps the epoch
492 // before this permit is acquired.
493 yield* applyLock.withPermits(1)(
494 Effect.gen(function* () {
495 const epochNow = yield* Ref.get(historyEpoch);
496 const loadedSequence = yield* SubscriptionRef.get(lastSequence);
497 // A page carrying a sequence older than the loaded state was read
498 // from a projection behind what we render; merging it could
499 // resurrect turns a newer snapshot or revert already removed.
500 const stale =
501 epochNow !== epochAtStart ||
502 Option.match(response, {
503 onNone: () => false,
504 onSome: (snapshot) => snapshot.snapshotSequence < loadedSequence,
505 });
506 if (Option.isNone(response) || stale) {
507 yield* SubscriptionRef.update(state, (value) => ({
508 ...value,
509 page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: false })),
510 }));
511 return;
512 }
513 // A page read AHEAD of the live state may include content (e.g.
514 // streaming deltas of an out-of-window turn) the subscription has
515 // not delivered yet; merging now and then replaying those events
516 // would duplicate them. Park the page until the live state reaches
517 // the page's thread-scoped watermark; loadingOlder stays true so
518 // the UI shows progress and no second fetch starts. Pages from
519 // pre-watermark servers (threadSequence absent) merge immediately,
520 // preserving the old behavior.
521 const watermark = response.value.page?.threadSequence;
522 if (watermark !== undefined && watermark > loadedSequence) {
523 yield* Ref.set(pendingOlderPage, {
524 snapshot: response.value,
525 epoch: epochNow,
526 });
527 return;
528 }
529 yield* mergeOlderPage(response.value);
530 }),
531 );
532 });
533
534 yield* SubscriptionRef.changes(supervisor.state).pipe(
535 Stream.runForEach((connectionState) => {
536 switch (connectionProjectionPhase(connectionState)) {
537 case "synchronizing":
538 return setSynchronizing;
539 case "disconnected":
540 return setDisconnected;
541 case "ready":
542 return setReady;
543 }
544 }),
545 Effect.forkScoped,
546 );
547
548 const foregroundResubscriptions = Option.match(wakeups, {
549 onNone: () => Stream.never,
550 onSome: (service) =>
551 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
552 });
553
554 yield* setSynchronizing;
555 yield* Effect.forkScoped(
556 subscribeDynamic(
557 ORCHESTRATION_WS_METHODS.subscribeThread,
558 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
559 const config = yield* session.initialConfig.pipe(
560 Effect.orElseSucceed(
561 () =>
562 ({}) as {
563 threadResumeCompletionMarker?: boolean;
564 threadSnapshotPagination?: boolean;
565 },
566 ),
567 );
568 const supportsCompletionMarker = config.threadResumeCompletionMarker === true;
569 // Windowed loads are gated on the server capability: pre-pagination
570 // servers reject unknown query params, and a windowed WS fallback to
571 // such a server would silently hide history.
572 const supportsPagination = config.threadSnapshotPagination === true;
573 yield* Ref.set(paginationSupported, supportsPagination);
574 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
575 yield* setSynchronizing;
576
577 let current = yield* SubscriptionRef.get(state);
578 // A windowed cache resuming against a server without pagination is a
579 // trap: afterSequence resume keeps only the window, and the missing
580 // older turns can never be loaded (the server has no cursor reads).
581 // Drop the window marker and treat the data as needing a full reload.
582 if (!supportsPagination && Option.isSome(current.page)) {
583 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
584 yield* SubscriptionRef.update(state, (value) => ({
585 ...value,
586 data: Option.none(),
587 status: value.status === "deleted" ? value.status : ("empty" as const),
588 page: Option.none(),
589 }));
590 yield* SubscriptionRef.set(lastSequence, 0);
591 current = yield* SubscriptionRef.get(state);
592 }
593 if (Option.isNone(current.data) && current.status !== "deleted") {
594 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
595 Effect.flatMap(
596 Option.match({
597 onSome: Effect.succeed,
598 onNone: () =>
599 SubscriptionRef.changes(supervisor.prepared).pipe(
600 Stream.filter(Option.isSome),
601 Stream.map((value) => value.value),
602 Stream.runHead,
603 Effect.map(Option.getOrThrow),
604 ),
605 }),
606 ),
607 );
608 const httpSnapshot = yield* snapshotLoader.load(
609 prepared,
610 threadId,
611 supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : undefined,
612 );
613 if (Option.isSome(httpSnapshot)) {
614 yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
615 current = yield* SubscriptionRef.get(state);
616 }
617 }
618
619 const sequence = yield* SubscriptionRef.get(lastSequence);
620 const canResume = Option.isSome(current.data);
621 if (!supportsCompletionMarker && canResume) {
622 yield* SubscriptionRef.update(state, (value) => ({
623 ...value,
624 status: value.status === "deleted" ? value.status : ("live" as const),
625 error: Option.none(),
626 }));
627 }
628
629 return {
630 threadId,
631 ...(canResume ? { afterSequence: sequence } : {}),
632 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
633 // The WS fallback snapshot (sent when afterSequence is missing or
634 // the gap is too large) should be windowed the same as the HTTP
635 // path; without this a resume failure re-downloads the full thread.
636 ...(supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : {}),
637 };
638 }),
639 {
640 onExpectedFailure: setStreamError,
641 retryExpectedFailureAfter: "250 millis",
642 resubscribe: foregroundResubscriptions,
643 },
644 ).pipe(Stream.runForEach(applyItem)),
645 );
646
647 // Expose loadOlderTurns to UI actions through the request registry.
648 // Requests funnel through a sliding queue drained serially, so mashing
649 // "load earlier" coalesces (loadOlderTurns itself no-ops while a fetch is
650 // in flight).
651 const olderTurnRequestRegistry = yield* ThreadOlderTurnRequests;
652 const olderTurnRequests = yield* Queue.sliding<void>(1);
653 yield* Stream.fromQueue(olderTurnRequests).pipe(
654 Stream.runForEach(() => loadOlderTurns()),
655 Effect.forkScoped,
656 );
657 const deregister = olderTurnRequestRegistry.register(
658 threadKey({ environmentId, threadId }),
659 () => {
660 Queue.offerUnsafe(olderTurnRequests, undefined);
661 },
662 );
663 yield* Effect.addFinalizer(() => Effect.sync(deregister));
664
665 yield* Effect.addFinalizer(() =>
666 Effect.all([SubscriptionRef.get(state), SubscriptionRef.get(lastSequence)]).pipe(
667 Effect.flatMap(([current, snapshotSequence]) =>
668 Option.match(current.data, {
669 onNone: () => Effect.void,
670 onSome: (thread) =>
671 shouldPersistThread(thread)
672 ? persist({
673 snapshotSequence,
674 thread,
675 ...Option.match(current.page, {
676 onNone: () => ({}),
677 onSome: (page) =>
678 ({
679 page: {
680 beforeCursor: page.beforeCursor,
681 hasMore: page.hasMore,
682 snapshotSequence,
683 },
684 }) as const,
685 }),
686 })
687 : Effect.void,
688 }),
689 ),
690 ),
691 );
692
693 return state;
694});
695
696export function threadStateChanges(environmentId: EnvironmentIdType, threadId: ThreadIdType) {
697 return followStreamInEnvironment(
698 environmentId,
699 Stream.unwrap(makeEnvironmentThreadState(threadId).pipe(Effect.map(SubscriptionRef.changes))),
700 );
701}
702
703export function createEnvironmentThreadStateAtoms<R, E>(
704 runtime: Atom.AtomRuntime<
705 EnvironmentRegistry | EnvironmentCacheStore | ThreadSnapshotLoader | R,
706 E
707 >,
708) {
709 const family = Atom.family((key: string) => {
710 const { environmentId, threadId } = parseThreadKey(key);
711 return runtime
712 .atom(threadStateChanges(environmentId, threadId), {
713 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
714 })
715 .pipe(
716 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
717 Atom.withLabel(`environment-thread-state:${key}`),
718 );
719 });
720
721 return {
722 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
723 family(threadKey({ environmentId, threadId })),
724 };
725}
726
727export * from "./archivedThreads.ts";
728export * from "./checkpointDiff.ts";
729export * from "./threadSnapshotHttp.ts";
730export * from "./composerPathSearch.ts";
731export * from "./threadCommands.ts";
732export * from "./threadDetail.ts";
733export * from "./threadReducer.ts";
734export * from "./threadShell.ts";
735export * from "./threadState.ts";