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

threads.ts

862 lines33.0 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;
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 });
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 */
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 }));
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​
161function cachedThreadState(value: EnvironmentThreadState): EnvironmentThreadState {
162 return {
163 ...value,
164 status: value.status === "deleted" ? "deleted" : statusWithoutLiveData(value.data),
165 error: Option.none(),
166 page: Option.map(value.page, (page) => ({ ...page, loadingOlder: false })),
167 };
169​
170export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
171 threadId: ThreadIdType,
172 resumeCache?: ThreadResumeCache,
173) {
174 const supervisor = yield* EnvironmentSupervisor;
175 const cache = yield* EnvironmentCacheStore;
176 const snapshotLoader = yield* ThreadSnapshotLoader;
177 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
178 const environmentId = supervisor.target.environmentId;
179 const retained = resumeCache?.snapshot;
180 const owner = {};
181 if (resumeCache) resumeCache.owner = owner;
182 const cached =
183 retained === undefined
184 ? yield* cache.loadThread(environmentId, threadId).pipe(
185 Effect.catch((error) =>
186 Effect.logWarning("Could not load cached thread.").pipe(
187 Effect.annotateLogs({
188 environmentId,
189 threadId,
190 error: error.message,
191 }),
192 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
193 ),
194 ),
195 )
196 : Option.none<OrchestrationThreadDetailSnapshot>();
197 const cachedThread = Option.map(cached, (snapshot) => snapshot.thread);
198 const initialState: EnvironmentThreadState = retained
199 ? cachedThreadState(retained.state)
200 : {
201 data: cachedThread,
202 status: statusWithoutLiveData(cachedThread),
203 error: Option.none(),
204 // A cached windowed snapshot restores its page cursor so "load earlier"
205 // works while rendering from cache; a cached full snapshot has no page.
206 page: Option.flatMap(cached, (snapshot) => pageStateFromSnapshot(snapshot.page)),
207 };
208 const state = yield* SubscriptionRef.make(initialState);
209 // Seed the resume cursor from the cached snapshot so a warm cache can catch up
210 // via `afterSequence` instead of re-downloading the full thread body.
211 const initialSequence =
212 retained?.sequence ??
213 Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence });
214 const lastSequence = yield* SubscriptionRef.make(initialSequence);
215 let committed: ThreadResumeSnapshot = {
216 state: initialState,
217 sequence: initialSequence,
218 persisted: retained?.persisted ?? Option.isSome(cached),
219 };
220 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
221 const awaitingCompletion = yield* Ref.make(false);
222 // Bumped whenever loaded history may have been rewritten out from under an
223 // in-flight older-page fetch (snapshot replacement, revert, deletion). A
224 // page response captured under an older epoch is discarded, not merged.
225 const historyEpoch = yield* Ref.make(0);
226 // Serializes stream-item application against older-page staleness checks +
227 // merges. Without it, a revert or snapshot processed between loadOlderTurns'
228 // epoch check and its merge could still slip resurrected history in.
229 const applyLock = yield* Semaphore.make(1);
230 // Save only completed data/cursor updates. A canceled scope must not cache
231 // a cursor whose event has not reached the data yet.
232 const remember = Effect.gen(function* () {
233 const current = yield* SubscriptionRef.get(state);
234 const sequence = yield* SubscriptionRef.get(lastSequence);
235 committed = {
236 state: current,
237 sequence,
238 persisted:
239 committed.persisted &&
240 matchesThreadSnapshot(
241 committed,
242 Option.getOrNull(current.data),
243 sequence,
244 Option.getOrUndefined(current.page),
245 ),
246 };
247 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
248 });
249 // Whether the connected server accepts windowed reads; set per subscription
250 // from the session config. Gates loadOlderTurns so a reconnect to a
251 // pre-pagination server never sends unsupported window parameters.
252 const paginationSupported = yield* Ref.make(false);
253 // An older page whose thread watermark is ahead of the live state, parked
254 // until the subscription catches up (see mergeOlderPage's caller). At most
255 // one can exist because loadOlderTurns no-ops while loadingOlder is true.
256 const pendingOlderPage = yield* Ref.make<{
257 readonly snapshot: OrchestrationThreadDetailSnapshot;
258 readonly epoch: number;
259 } | null>(null);
260 const persistence = yield* Queue.sliding<OrchestrationThreadDetailSnapshot>(1);
261​
262 const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
263 snapshot: OrchestrationThreadDetailSnapshot,
264 ) {
265 if (resumeCache !== undefined && resumeCache.owner !== owner) return;
266 if (
267 committed.persisted &&
268 matchesThreadSnapshot(committed, snapshot.thread, snapshot.snapshotSequence, snapshot.page)
269 )
270 return;
271 yield* cache.saveThread(environmentId, snapshot).pipe(
272 Effect.tap(() =>
273 Effect.sync(() => {
274 if (
275 !matchesThreadSnapshot(
276 committed,
277 snapshot.thread,
278 snapshot.snapshotSequence,
279 snapshot.page,
280 )
281 )
282 return;
283 committed = { ...committed, persisted: true };
284 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
285 }),
286 ),
287 Effect.catch((error) =>
288 Effect.logWarning("Could not persist the thread cache.").pipe(
289 Effect.annotateLogs({
290 environmentId,
291 threadId,
292 error: error.message,
293 }),
294 ),
295 ),
296 );
297 });
298​
299 yield* Stream.fromQueue(persistence).pipe(
300 Stream.debounce("500 millis"),
301 Stream.runForEach(persist),
302 Effect.forkScoped,
303 );
304​
305 const setSynchronizing = SubscriptionRef.update(state, (current) =>
306 current.status === "deleted"
307 ? current
308 : {
309 ...current,
310 status: "synchronizing" as const,
311 error: Option.none(),
312 },
313 );
314 const setReady = SubscriptionRef.update(state, (current) =>
315 current.status === "live" || current.status === "deleted"
316 ? current
317 : {
318 ...current,
319 status: "synchronizing" as const,
320 error: Option.none(),
321 },
322 );
323 const setDisconnected = Effect.gen(function* () {
324 yield* Ref.set(awaitingCompletion, false);
325 // The capability belongs to the session that advertised it. During a
326 // reconnect, a new prepared connection can exist before the new session's
327 // config arrives; leaving the old value would let loadOlderTurns send
328 // window parameters to a server that may not accept them (review
329 // finding). makeSubscribeInput re-sets it from the next session's config.
330 yield* Ref.set(paginationSupported, false);
331 yield* SubscriptionRef.update(state, (current) => ({
332 ...current,
333 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
334 }));
335 });
336 const setStreamError = (cause: Cause.Cause<unknown>) =>
337 Ref.set(awaitingCompletion, false).pipe(
338 Effect.andThen(
339 SubscriptionRef.update(state, (current) => ({
340 ...current,
341 status:
342 current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
343 error: Option.some(formatThreadError(cause)),
344 })),
345 ),
346 );
347​
348 const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
349 thread: OrchestrationThread,
350 // "keep" preserves the current page state (live events touch only loaded
351 // recent turns); a snapshot or merged page passes its own page state.
352 page: Option.Option<EnvironmentThreadPageState> | "keep",
353 ) {
354 const waiting = yield* Ref.get(awaitingCompletion);
355 yield* SubscriptionRef.update(state, (current) => ({
356 data: Option.some(thread),
357 status: waiting ? ("synchronizing" as const) : ("live" as const),
358 error: Option.none(),
359 page: page === "keep" ? current.page : page,
360 }));
361 // Active threads can update many times per second and retain large tool
362 // payloads. The server remains the source of truth while a turn is active;
363 // persist once it settles so cache encoding stays off the streaming path.
364 if (shouldPersistThread(thread)) {
365 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
366 const currentPage = yield* SubscriptionRef.get(state).pipe(Effect.map((value) => value.page));
367 yield* Queue.offer(persistence, {
368 snapshotSequence,
369 thread,
370 // Persist the window boundary with the window's content so a cache
371 // restore can keep paging from where the loaded history ends.
372 ...Option.match(currentPage, {
373 onNone: () => ({}),
374 onSome: (value) =>
375 ({
376 page: {
377 beforeCursor: value.beforeCursor,
378 hasMore: value.hasMore,
379 snapshotSequence,
380 },
381 }) as const,
382 }),
383 });
384 }
385 });
386​
387 const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
388 yield* Ref.set(awaitingCompletion, false);
389 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
390 yield* SubscriptionRef.set(state, {
391 data: Option.none(),
392 status: "deleted",
393 error: Option.none(),
394 page: Option.none(),
395 });
396 yield* remember;
397 if (resumeCache !== undefined && resumeCache.owner !== owner) return;
398 yield* cache.removeThread(environmentId, threadId).pipe(
399 Effect.catch((error) =>
400 Effect.logWarning("Could not remove the cached thread.").pipe(
401 Effect.annotateLogs({
402 environmentId,
403 threadId,
404 error: error.message,
405 }),
406 ),
407 ),
408 );
409 });
410​
411 // Body of applyItem, running under applyLock.
412 const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* (
413 item: OrchestrationThreadStreamItem,
414 ) {
415 if (item.kind === "synchronized") {
416 yield* Ref.set(awaitingCompletion, false);
417 yield* SubscriptionRef.update(state, (current) =>
418 Option.isSome(current.data) && current.status !== "deleted"
419 ? { ...current, status: "live" as const, error: Option.none() }
420 : current,
421 );
422 return;
423 }
424​
425 if (item.kind === "snapshot") {
426 // A fresh snapshot replaces all loaded history, including older
427 // pages: a turn reverted while disconnected would otherwise survive
428 // in the preserved history with no event left to remove it. The
429 // epoch bump discards any older-page fetch racing this snapshot.
430 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
431 yield* SubscriptionRef.set(lastSequence, item.snapshot.snapshotSequence);
432 yield* setThread(item.snapshot.thread, pageStateFromSnapshot(item.snapshot.page));
433 return;
434 }
435​
436 const sequence = yield* SubscriptionRef.get(lastSequence);
437 if (item.event.sequence <= sequence) {
438 return;
439 }
440 yield* SubscriptionRef.set(lastSequence, item.event.sequence);
441​
442 const current = yield* SubscriptionRef.get(state);
443 if (Option.isNone(current.data)) {
444 if (item.event.type === "thread.deleted") {
445 yield* setDeleted();
446 }
447 return;
448 }
449 if (item.event.type === "thread.reverted") {
450 // A revert rewrites loaded history (whole turns disappear), so an
451 // older-page fetch in flight may straddle the removed range; the epoch
452 // bump discards it. The stored page cursor stays valid: cursors are an
453 // (anchor, turnId) keyset derived from event content, which survives
454 // the revert projector's row rewrite, so no refresh is needed — the
455 // revert reducer's turn filtering fully handles loaded history.
456 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
457 }
458 const result = applyThreadDetailEvent(current.data.value, item.event);
459 if (result.kind === "updated") {
460 yield* setThread(result.thread, "keep");
461 } else if (result.kind === "deleted") {
462 yield* setDeleted();
463 }
464 // The event may have advanced the live state past a parked page's
465 // watermark; merge it as soon as that happens.
466 yield* tryMergePendingOlderPage();
467 });
468​
469 // Merges a parked older page once the live state has caught up to the
470 // page's thread watermark, or discards it if history was rewritten
471 // (epoch advanced) while it waited. Must run under applyLock.
472 const tryMergePendingOlderPage = Effect.fn("EnvironmentThreadState.tryMergePendingOlderPage")(
473 function* () {
474 const pending = yield* Ref.get(pendingOlderPage);
475 if (pending === null) {
476 return;
477 }
478 const epochNow = yield* Ref.get(historyEpoch);
479 if (epochNow !== pending.epoch) {
480 yield* Ref.set(pendingOlderPage, null);
481 yield* SubscriptionRef.update(state, (value) => ({
482 ...value,
483 page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: false })),
484 }));
485 return;
486 }
487 const watermark = pending.snapshot.page?.threadSequence;
488 const loadedSequence = yield* SubscriptionRef.get(lastSequence);
489 if (watermark !== undefined && watermark > loadedSequence) {
490 return;
491 }
492 yield* Ref.set(pendingOlderPage, null);
493 yield* mergeOlderPage(pending.snapshot);
494 },
495 );
496​
497 const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* (
498 item: OrchestrationThreadStreamItem,
499 ) {
500 yield* applyLock.withPermits(1)(applyItemLocked(item).pipe(Effect.andThen(remember)));
501 });
502​
503 // Merges an older disjoint page below the currently loaded window. All four
504 // windowed collections prepend; identity dedupe guards the (server-bug or
505 // cursor-misuse) case of overlapping pages so a row never renders twice.
506 const mergeOlderPage = Effect.fn("EnvironmentThreadState.mergeOlderPage")(function* (
507 snapshot: OrchestrationThreadDetailSnapshot,
508 ) {
509 // The merge is built inside the update callback so it composes with
510 // whatever thread value is current at commit time. The applyLock already
511 // serializes this against event application; the atomic build is defense
512 // in depth against future callers outside the lock.
513 let merged: OrchestrationThread | null = null;
514 yield* SubscriptionRef.update(state, (value) => {
515 if (Option.isNone(value.data)) {
516 return value;
517 }
518 const loaded = value.data.value;
519 const older = snapshot.thread;
520 const mergeById = <T extends { readonly id: string }>(
521 olderRows: ReadonlyArray<T>,
522 loadedRows: ReadonlyArray<T>,
523 ): ReadonlyArray<T> => {
524 const seen = new Set(loadedRows.map((row) => row.id));
525 return [...olderRows.filter((row) => !seen.has(row.id)), ...loadedRows];
526 };
527 const seenCheckpoints = new Set(loaded.checkpoints.map((row) => row.turnId));
528 merged = {
529 // Thread metadata stays the loaded (newer) snapshot's; only the
530 // windowed collections gain rows from the older page.
531 ...loaded,
532 messages: mergeById(older.messages, loaded.messages),
533 activities: mergeById(older.activities, loaded.activities),
534 proposedPlans: mergeById(older.proposedPlans, loaded.proposedPlans),
535 checkpoints: [
536 ...older.checkpoints.filter((row) => !seenCheckpoints.has(row.turnId)),
537 ...loaded.checkpoints,
538 ],
539 };
540 return {
541 ...value,
542 data: Option.some(merged),
543 page: pageStateFromSnapshot(snapshot.page),
544 };
545 });
546 // Persist the widened window under the *loaded* watermark: the merged
547 // content is only known consistent with the state it merged into, not
548 // with the page's own (possibly newer) sequence.
549 if (merged !== null && shouldPersistThread(merged)) {
550 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
551 yield* Queue.offer(persistence, {
552 snapshotSequence,
553 thread: merged,
554 ...(snapshot.page === undefined ? {} : { page: { ...snapshot.page, snapshotSequence } }),
555 });
556 }
557 yield* remember;
558 });
559​
560 const loadOlderTurns = Effect.fn("EnvironmentThreadState.loadOlderTurns")(function* () {
561 // Gated on the connected server's capability: a reconnect to a
562 // pre-pagination server must never receive window parameters.
563 if (!(yield* Ref.get(paginationSupported))) {
564 return;
565 }
566 const current = yield* SubscriptionRef.get(state);
567 const page = Option.getOrNull(current.page);
568 if (page === null || page.loadingOlder || !page.hasMore || page.beforeCursor === null) {
569 return;
570 }
571 const prepared = Option.getOrNull(yield* SubscriptionRef.get(supervisor.prepared));
572 if (prepared === null) {
573 return;
574 }
575 const epochAtStart = yield* Ref.get(historyEpoch);
576 yield* SubscriptionRef.update(state, (value) => ({
577 ...value,
578 page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: true })),
579 }));
580 const window: ThreadSnapshotWindow = {
581 turnLimit: OLDER_THREAD_PAGE_USER_TURN_LIMIT,
582 beforeCursor: page.beforeCursor,
583 };
584 const response = yield* snapshotLoader.load(prepared, threadId, window);
585 // Staleness check and merge run under the same lock as stream-item
586 // application, so a revert/snapshot cannot land between them (TOCTOU
587 // review finding) — anything that rewrites history bumps the epoch
588 // before this permit is acquired.
589 yield* applyLock.withPermits(1)(
590 Effect.gen(function* () {
591 const epochNow = yield* Ref.get(historyEpoch);
592 const loadedSequence = yield* SubscriptionRef.get(lastSequence);
593 // A page carrying a sequence older than the loaded state was read
594 // from a projection behind what we render; merging it could
595 // resurrect turns a newer snapshot or revert already removed.
596 const stale =
597 epochNow !== epochAtStart ||
598 Option.match(response, {
599 onNone: () => false,
600 onSome: (snapshot) => snapshot.snapshotSequence < loadedSequence,
601 });
602 if (Option.isNone(response) || stale) {
603 yield* SubscriptionRef.update(state, (value) => ({
604 ...value,
605 page: Option.map(value.page, (existing) => ({ ...existing, loadingOlder: false })),
606 }));
607 return;
608 }
609 // A page read AHEAD of the live state may include content (e.g.
610 // streaming deltas of an out-of-window turn) the subscription has
611 // not delivered yet; merging now and then replaying those events
612 // would duplicate them. Park the page until the live state reaches
613 // the page's thread-scoped watermark; loadingOlder stays true so
614 // the UI shows progress and no second fetch starts. Pages from
615 // pre-watermark servers (threadSequence absent) merge immediately,
616 // preserving the old behavior.
617 const watermark = response.value.page?.threadSequence;
618 if (watermark !== undefined && watermark > loadedSequence) {
619 yield* Ref.set(pendingOlderPage, {
620 snapshot: response.value,
621 epoch: epochNow,
622 });
623 return;
624 }
625 yield* mergeOlderPage(response.value);
626 }),
627 );
628 });
629​
630 yield* SubscriptionRef.changes(supervisor.state).pipe(
631 Stream.runForEach((connectionState) => {
632 switch (connectionProjectionPhase(connectionState)) {
633 case "synchronizing":
634 return setSynchronizing;
635 case "disconnected":
636 return setDisconnected;
637 case "ready":
638 return setReady;
639 }
640 }),
641 Effect.forkScoped,
642 );
643​
644 const foregroundResubscriptions = Option.match(wakeups, {
645 onNone: () => Stream.never,
646 onSome: (service) =>
647 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
648 });
649​
650 yield* setSynchronizing;
651 yield* Effect.forkScoped(
652 subscribeDynamic(
653 ORCHESTRATION_WS_METHODS.subscribeThread,
654 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
655 const config = yield* session.initialConfig.pipe(
656 Effect.orElseSucceed(
657 () =>
658 ({}) as {
659 threadResumeCompletionMarker?: boolean;
660 threadSnapshotPagination?: boolean;
661 },
662 ),
663 );
664 const supportsCompletionMarker = config.threadResumeCompletionMarker === true;
665 // Windowed loads are gated on the server capability: pre-pagination
666 // servers reject unknown query params, and a windowed WS fallback to
667 // such a server would silently hide history.
668 const supportsPagination = config.threadSnapshotPagination === true;
669 yield* Ref.set(paginationSupported, supportsPagination);
670 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
671 yield* setSynchronizing;
672​
673 let current = yield* SubscriptionRef.get(state);
674 // A windowed cache resuming against a server without pagination is a
675 // trap: afterSequence resume keeps only the window, and the missing
676 // older turns can never be loaded (the server has no cursor reads).
677 // Drop the window marker and treat the data as needing a full reload.
678 if (!supportsPagination) {
679 yield* applyLock.withPermits(1)(
680 Effect.gen(function* () {
681 if (Option.isNone((yield* SubscriptionRef.get(state)).page)) return;
682 yield* Ref.update(historyEpoch, (epoch) => epoch + 1);
683 yield* SubscriptionRef.update(state, (value) => ({
684 ...value,
685 data: Option.none(),
686 status: value.status === "deleted" ? value.status : ("empty" as const),
687 page: Option.none(),
688 }));
689 yield* SubscriptionRef.set(lastSequence, 0);
690 yield* remember;
691 }),
692 );
693 current = yield* SubscriptionRef.get(state);
694 }
695 if (Option.isNone(current.data) && current.status !== "deleted") {
696 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
697 Effect.flatMap(
698 Option.match({
699 onSome: Effect.succeed,
700 onNone: () =>
701 SubscriptionRef.changes(supervisor.prepared).pipe(
702 Stream.filter(Option.isSome),
703 Stream.map((value) => value.value),
704 Stream.runHead,
705 Effect.map(Option.getOrThrow),
706 ),
707 }),
708 ),
709 );
710 const httpSnapshot = yield* snapshotLoader.load(
711 prepared,
712 threadId,
713 supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : undefined,
714 );
715 if (Option.isSome(httpSnapshot)) {
716 yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
717 current = yield* SubscriptionRef.get(state);
718 }
719 }
720​
721 const sequence = yield* SubscriptionRef.get(lastSequence);
722 const canResume = Option.isSome(current.data);
723 if (!supportsCompletionMarker && canResume) {
724 yield* SubscriptionRef.update(state, (value) => ({
725 ...value,
726 status: value.status === "deleted" ? value.status : ("live" as const),
727 error: Option.none(),
728 }));
729 }
730​
731 return {
732 threadId,
733 ...(canResume ? { afterSequence: sequence } : {}),
734 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
735 // The WS fallback snapshot (sent when afterSequence is missing or
736 // the gap is too large) should be windowed the same as the HTTP
737 // path; without this a resume failure re-downloads the full thread.
738 ...(supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : {}),
739 };
740 }),
741 {
742 onExpectedFailure: setStreamError,
743 retryExpectedFailureAfter: "250 millis",
744 resubscribe: foregroundResubscriptions,
745 },
746 ).pipe(Stream.runForEach(applyItem)),
747 );
748​
749 // Expose loadOlderTurns to UI actions through the request registry.
750 // Requests funnel through a sliding queue drained serially, so mashing
751 // "load earlier" coalesces (loadOlderTurns itself no-ops while a fetch is
752 // in flight).
753 const olderTurnRequestRegistry = yield* ThreadOlderTurnRequests;
754 const olderTurnRequests = yield* Queue.sliding<void>(1);
755 yield* Stream.fromQueue(olderTurnRequests).pipe(
756 Stream.runForEach(() => loadOlderTurns()),
757 Effect.forkScoped,
758 );
759 const deregister = olderTurnRequestRegistry.register(
760 threadKey({ environmentId, threadId }),
761 () => {
762 Queue.offerUnsafe(olderTurnRequests, undefined);
763 },
764 );
765 yield* Effect.addFinalizer(() => Effect.sync(deregister));
766​
767 yield* Effect.addFinalizer(() =>
768 Effect.suspend(() => {
769 const { state: current, sequence: snapshotSequence } = committed;
770 return Option.match(current.data, {
771 onNone: () => Effect.void,
772 onSome: (thread) =>
773 shouldPersistThread(thread)
774 ? persist({
775 snapshotSequence,
776 thread,
777 ...Option.match(current.page, {
778 onNone: () => ({}),
779 onSome: (page) =>
780 ({
781 page: {
782 beforeCursor: page.beforeCursor,
783 hasMore: page.hasMore,
784 snapshotSequence,
785 },
786 }) as const,
787 }),
788 })
789 : Effect.void,
790 });
791 }),
792 );
793​
794 return state;
795});
796​
797export function threadStateChanges(
798 environmentId: EnvironmentIdType,
799 threadId: ThreadIdType,
800 resumeCache?: ThreadResumeCache,
801) {
802 return followStreamInEnvironment(
803 environmentId,
804 Stream.unwrap(
805 makeEnvironmentThreadState(threadId, resumeCache).pipe(Effect.map(SubscriptionRef.changes)),
806 ),
807 );
809​
810export function createEnvironmentThreadStateAtoms<R, E>(
811 runtime: Atom.AtomRuntime<
812 EnvironmentRegistry | EnvironmentCacheStore | ThreadSnapshotLoader | R,
813 E
814 >,
815) {
816 // Cache definitions must outlive collectible live-atom definitions. The
817 // registry retains these nodes without retaining environment or RPC scopes.
818 const resumeFamily = Atom.family((key: string) =>
819 Atom.make((): ThreadResumeCache => ({
820 snapshot: undefined,
821 owner: undefined,
822 })).pipe(
823 Atom.setIdleTTL(THREAD_SNAPSHOT_IDLE_TTL_MS),
824 Atom.withLabel(`environment-thread-resume:${key}`),
825 ),
826 );
827 const family = Atom.family((key: string) => {
828 const { environmentId, threadId } = parseThreadKey(key);
829 const resumeAtom = resumeFamily(key);
830 return runtime
831 .atom(
832 (get) => {
833 get.mount(resumeAtom);
834 const resume = get.once(resumeAtom);
835 const live = threadStateChanges(environmentId, threadId, resume);
836 return resume.snapshot === undefined
837 ? live
838 : Stream.concat(Stream.succeed(cachedThreadState(resume.snapshot.state)), live);
839 },
840 {
841 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
842 },
843 )
844 .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state:${key}`));
845 });
846​
847 return {
848 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
849 family(threadKey({ environmentId, threadId })),
850 };
852​
853export * from "./archivedThreads.ts";
854export * from "./checkpointDiff.ts";
855export * from "./threadSnapshotHttp.ts";
856export * from "./composerPathSearch.ts";
857export * from "./threadCommands.ts";
858export * from "./threadFeedback.ts";
859export * from "./threadDetail.ts";
860export * from "./threadReducer.ts";
861export * from "./threadShell.ts";
862export * from "./threadState.ts";