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

threads.ts

946 lines33.9 KB

1import {
2 ORCHESTRATION_V2_WS_METHODS,
3 type EnvironmentId as EnvironmentIdType,
4 type OrchestrationV2ThreadDetailSnapshot,
5 type OrchestrationV2ThreadProjection,
6 type OrchestrationV2ThreadStreamItem,
7 type ThreadId as ThreadIdType,
8} from "@t3tools/contracts";
9import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot";
10import * as Cause from "effect/Cause";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as Scope from "effect/Scope";
14import * as Option from "effect/Option";
15import * as Queue from "effect/Queue";
16import * as Ref from "effect/Ref";
17import * as Result from "effect/Result";
18import * as Semaphore from "effect/Semaphore";
19import * as Stream from "effect/Stream";
20import * as SubscriptionRef from "effect/SubscriptionRef";
21import { HttpClient } from "effect/http";
22import { Atom } from "effect/reactivity";
23​
24import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
25import * as EnvironmentRegistry from "../connection/registry.ts";
26import { connectionProjectionPhase } from "../connection/model.ts";
27import * as EnvironmentSupervisor from "../connection/supervisor.ts";
28import * as ConnectionWakeups from "../connection/wakeups.ts";
29import * as Persistence from "../platform/persistence.ts";
30import { runCachePersistence } from "./cachePersistence.ts";
31import * as ManagedRelay from "../relay/managedRelay.ts";
32import { subscribeDynamic } from "../rpc/client.ts";
33import { parseThreadKey, threadKey } from "./entities.ts";
34import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
35import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts";
36import { followStreamInEnvironment } from "./runtime.ts";
37import * as ThreadHistoryController from "./threadHistoryController.ts";
38import { fetchEnvironmentThreadHistoryPage } from "./threadHistoryHttp.ts";
39import {
40 applyHistoryPageMeta,
41 clearActiveHistoryLoading,
42 EMPTY_THREAD_HISTORY_META,
43 isActiveHistoryRequestCursor,
44 mergeOlderHistoryIntoProjection,
45 type ThreadHistoryMeta,
46} from "./threadHistoryMerge.ts";
47import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
48import {
49 EMPTY_ENVIRONMENT_THREAD_STATE,
50 type EnvironmentThreadState,
51 type EnvironmentThreadStatus,
52} from "./threadState.ts";
53​
54function statusWithoutLiveData(
55 data: Option.Option<OrchestrationV2ThreadProjection>,
56): EnvironmentThreadStatus {
57 return Option.isSome(data) ? "cached" : "empty";
59​
60function formatThreadError(cause: Cause.Cause<unknown>): string {
61 const error = Cause.squash(cause);
62 return error instanceof Error && error.message.trim().length > 0
63 ? error.message
64 : "Could not synchronize the thread.";
66​
67function formatHistoryError(error: unknown): string {
68 if (error instanceof Error && error.message.trim().length > 0) {
69 return error.message;
70 }
71 return "Could not load earlier activity.";
73​
74function historyMetaFromCachedSnapshot(
75 snapshot: OrchestrationV2ThreadDetailSnapshot,
76): ThreadHistoryMeta {
77 const historyCursor = snapshot.historyCursor ?? null;
78 const hasMoreHistory = snapshot.hasMoreHistory ?? false;
79 return {
80 historyCursor,
81 hasMoreHistory,
82 loading: false,
83 error: null,
84 expanded: false,
85 latestLocalTurnOrdinal: snapshot.latestLocalTurnOrdinal ?? null,
86 };
88​
89function snapshotToPersist(
90 snapshotSequence: number,
91 projection: OrchestrationV2ThreadProjection,
92 history: ThreadHistoryMeta,
93 acceptsBoundedSnapshots: boolean,
94): OrchestrationV2ThreadDetailSnapshot {
95 // A complete bounded snapshot still proves paging support. Retain that evidence
96 // so a thread that grows while closed can resume with a bounded fallback.
97 if (acceptsBoundedSnapshots || history.hasMoreHistory || history.historyCursor !== null) {
98 return {
99 snapshotSequence,
100 projection,
101 historyCursor: history.historyCursor,
102 hasMoreHistory: history.hasMoreHistory,
103 latestLocalTurnOrdinal: history.latestLocalTurnOrdinal,
104 };
105 }
106 return { snapshotSequence, projection };
108​
109function shouldPersistThread(
110 thread: OrchestrationV2ThreadProjection,
111 history: ThreadHistoryMeta,
112): boolean {
113 // After the user loads older pages the in-memory timeline can grow large.
114 // Keep those expanded projections out of the monolithic cache.
115 if (history.expanded) {
116 return false;
117 }
118 return !thread.runs.some(
119 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
120 );
122​
123interface ThreadResumeSnapshot {
124 readonly state: EnvironmentThreadState;
125 readonly sequence: number;
126 readonly persisted: boolean;
127 readonly acceptsBoundedSnapshots?: boolean;
129​
130interface ThreadResumeCache {
131 snapshot: ThreadResumeSnapshot | undefined;
132 owner: object | undefined;
134​
135function matchesThreadSnapshot(
136 current: ThreadResumeSnapshot,
137 projection: OrchestrationV2ThreadProjection | null,
138 sequence: number,
139 history: Pick<ThreadHistoryMeta, "historyCursor" | "hasMoreHistory" | "latestLocalTurnOrdinal">,
140): boolean {
141 if (current.sequence !== sequence || Option.getOrNull(current.state.data) !== projection)
142 return false;
143 const currentHistory = current.state.history;
144 return (
145 currentHistory.historyCursor === history.historyCursor &&
146 currentHistory.hasMoreHistory === history.hasMoreHistory &&
147 (!(history.hasMoreHistory || history.historyCursor !== null) ||
148 currentHistory.latestLocalTurnOrdinal === history.latestLocalTurnOrdinal)
149 );
151​
152function cachedThreadState(value: EnvironmentThreadState): EnvironmentThreadState {
153 return {
154 ...value,
155 status:
156 value.status === "deleted" || (value.status === "live" && Option.isSome(value.data))
157 ? value.status
158 : statusWithoutLiveData(value.data),
159 error: Option.none(),
160 history: { ...value.history, loading: false, error: null },
161 };
163​
164export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
165 threadId: ThreadIdType,
166 resumeCache?: ThreadResumeCache,
167) {
168 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
169 const cache = yield* Persistence.EnvironmentCacheStore;
170 const snapshotLoader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
171 const historyController = yield* Effect.serviceOption(
172 ThreadHistoryController.ThreadHistoryController,
173 );
174 const httpClient = yield* Effect.serviceOption(HttpClient.HttpClient);
175 const dpopSigner = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
176 const remoteAuthorization = yield* Effect.serviceOption(
177 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
178 );
179 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
180 const environmentId = supervisor.target.environmentId;
181 const retained = resumeCache?.snapshot;
182 const owner = {};
183 if (resumeCache) resumeCache.owner = owner;
184 const cached =
185 retained === undefined
186 ? yield* cache.loadThread(environmentId, threadId).pipe(
187 Effect.catch((error) =>
188 Effect.logWarning("Could not load cached thread.").pipe(
189 Effect.annotateLogs({
190 environmentId,
191 threadId,
192 error: error.message,
193 }),
194 Effect.as(Option.none<OrchestrationV2ThreadDetailSnapshot>()),
195 ),
196 ),
197 )
198 : Option.none<OrchestrationV2ThreadDetailSnapshot>();
199 const cachedThread = Option.map(cached, (snapshot) => snapshot.projection);
200 const initialState: EnvironmentThreadState = retained
201 ? cachedThreadState(retained.state)
202 : {
203 data: cachedThread,
204 status: statusWithoutLiveData(cachedThread),
205 error: Option.none(),
206 history: Option.match(cached, {
207 onNone: () => EMPTY_THREAD_HISTORY_META,
208 onSome: historyMetaFromCachedSnapshot,
209 }),
210 };
211 const state = yield* SubscriptionRef.make(initialState);
212 const canLoadHistory = Option.isSome(httpClient) && Option.isSome(historyController);
213 const acceptsBoundedSocketSnapshots = yield* Ref.make(canLoadHistory);
214 // Seed the resume cursor from the cached snapshot so a warm cache can catch up
215 // via `afterSequence` instead of re-downloading the full thread body.
216 const initialSequence =
217 retained?.sequence ??
218 Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence });
219 const lastSequence = yield* SubscriptionRef.make(initialSequence);
220 let committed: ThreadResumeSnapshot = {
221 state: initialState,
222 sequence: initialSequence,
223 persisted: retained?.persisted ?? Option.isSome(cached),
224 acceptsBoundedSnapshots: canLoadHistory,
225 };
226 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
227 const awaitingCompletion = yield* Ref.make(false);
228 const applyLock = yield* Semaphore.make(1);
229 // Save only completed data/cursor updates. A canceled scope must not cache
230 // a cursor whose event has not reached the data yet.
231 const remember = Effect.gen(function* () {
232 const current = yield* SubscriptionRef.get(state);
233 const sequence = yield* SubscriptionRef.get(lastSequence);
234 committed = {
235 state: current,
236 sequence,
237 acceptsBoundedSnapshots: yield* Ref.get(acceptsBoundedSocketSnapshots),
238 persisted:
239 committed.persisted &&
240 matchesThreadSnapshot(committed, Option.getOrNull(current.data), sequence, current.history),
241 };
242 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
243 });
244 const persistence = yield* Queue.sliding<OrchestrationV2ThreadDetailSnapshot>(1);
245​
246 const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
247 snapshot: OrchestrationV2ThreadDetailSnapshot,
248 ) {
249 if (resumeCache !== undefined && resumeCache.owner !== owner) return;
250 if (committed.state.status === "deleted") return;
251 if (
252 committed.persisted &&
253 matchesThreadSnapshot(
254 committed,
255 snapshot.projection,
256 snapshot.snapshotSequence,
257 historyMetaFromCachedSnapshot(snapshot),
258 )
259 )
260 return;
261 yield* cache.saveThread(environmentId, snapshot).pipe(
262 Effect.tap(() =>
263 Effect.sync(() => {
264 if (
265 !matchesThreadSnapshot(
266 committed,
267 snapshot.projection,
268 snapshot.snapshotSequence,
269 historyMetaFromCachedSnapshot(snapshot),
270 )
271 )
272 return;
273 committed = { ...committed, persisted: true };
274 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
275 }),
276 ),
277 Effect.catch((error) =>
278 Effect.logWarning("Could not persist the thread cache.").pipe(
279 Effect.annotateLogs({
280 environmentId,
281 threadId,
282 error: error.message,
283 }),
284 ),
285 ),
286 );
287 });
288​
289 yield* Effect.addFinalizer(() =>
290 Effect.suspend(() => {
291 const { state: current, sequence: snapshotSequence } = committed;
292 return Option.match(current.data, {
293 onNone: () => Effect.void,
294 onSome: (projection) =>
295 shouldPersistThread(projection, current.history)
296 ? persist(
297 snapshotToPersist(
298 snapshotSequence,
299 projection,
300 current.history,
301 committed.acceptsBoundedSnapshots === true,
302 ),
303 )
304 : Effect.void,
305 });
306 }),
307 );
308​
309 yield* runCachePersistence(persistence, persist).pipe(Effect.forkScoped);
310​
311 const setConnecting = SubscriptionRef.update(state, (current) =>
312 current.status === "deleted" || Option.isSome(current.error)
313 ? current
314 : {
315 ...current,
316 status: "synchronizing" as const,
317 error: Option.none(),
318 },
319 );
320 const setReady = SubscriptionRef.update(state, (current) =>
321 current.status === "live" || current.status === "deleted" || Option.isSome(current.error)
322 ? current
323 : {
324 ...current,
325 status: "synchronizing" as const,
326 error: Option.none(),
327 },
328 );
329 const setDisconnected = Effect.gen(function* () {
330 yield* Ref.set(awaitingCompletion, false);
331 yield* SubscriptionRef.update(state, (current) => ({
332 ...current,
333 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
334 }));
335 });
336 const setStreamError = (message: string) =>
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(message),
344 })),
345 ),
346 );
347​
348 const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
349 thread: OrchestrationV2ThreadProjection,
350 options?: {
351 readonly resetHistory?: boolean;
352 readonly history?: ThreadHistoryMeta;
353 },
354 ) {
355 const waiting = yield* Ref.get(awaitingCompletion);
356 // Atomic with concurrent history meta updates: never get-then-set the whole
357 // state when only the projection changes. Bounded installs pass history so
358 // projection + cursor persist together in one enqueue.
359 const next = yield* SubscriptionRef.updateAndGet(state, (previous) => {
360 const history =
361 options?.history !== undefined
362 ? options.history
363 : options?.resetHistory === true
364 ? EMPTY_THREAD_HISTORY_META
365 : previous.history;
366 return {
367 ...previous,
368 data: Option.some(thread),
369 status: Option.isSome(previous.error)
370 ? ("cached" as const)
371 : waiting
372 ? ("synchronizing" as const)
373 : ("live" as const),
374 error: previous.error,
375 history,
376 };
377 });
378 // Active projections can update many times per second and retain large tool
379 // payloads. Persist once the run settles so cache encoding stays off the
380 // streaming path. Progressive meta rides along when the window is incomplete.
381 if (shouldPersistThread(thread, next.history)) {
382 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
383 yield* Queue.offer(
384 persistence,
385 snapshotToPersist(
386 snapshotSequence,
387 thread,
388 next.history,
389 yield* Ref.get(acceptsBoundedSocketSnapshots),
390 ),
391 );
392 }
393 });
394​
395 const patchHistoryMeta = (patch: (history: ThreadHistoryMeta) => ThreadHistoryMeta) =>
396 SubscriptionRef.update(state, (current) => ({
397 ...current,
398 history: patch(current.history),
399 }));
400​
401 const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
402 yield* Ref.set(awaitingCompletion, false);
403 yield* SubscriptionRef.set(state, {
404 data: Option.none(),
405 status: "deleted",
406 error: Option.none(),
407 history: EMPTY_THREAD_HISTORY_META,
408 });
409 yield* remember;
410 if (resumeCache !== undefined && resumeCache.owner !== owner) return;
411 yield* cache.removeThread(environmentId, threadId).pipe(
412 Effect.catch((error) =>
413 Effect.logWarning("Could not remove the cached thread.").pipe(
414 Effect.annotateLogs({
415 environmentId,
416 threadId,
417 error: error.message,
418 }),
419 ),
420 ),
421 );
422 });
423​
424 type EventItem = Extract<OrchestrationV2ThreadStreamItem, { kind: "event" }>;
425 type SequencedItem = Extract<
426 OrchestrationV2ThreadStreamItem,
427 { kind: "event" | "unknown-event" }
428 >;
429 const applyEventsLocked = Effect.fn("EnvironmentThreadState.applyEventsLocked")(function* (
430 items: ReadonlyArray<SequencedItem>,
431 ) {
432 const appliedSequence = yield* SubscriptionRef.get(lastSequence);
433 let sequence = appliedSequence;
434 const fresh: EventItem[] = [];
435 for (const item of items) {
436 if (item.sequence <= sequence) continue;
437 sequence = item.sequence;
438 if (item.kind === "event") {
439 fresh.push(item);
440 continue;
441 }
442 yield* Effect.logDebug("Skipped a thread event type this client does not know.").pipe(
443 Effect.annotateLogs({
444 environmentId,
445 threadId,
446 eventType: item.eventType.slice(0, 64),
447 sequence: item.sequence,
448 }),
449 );
450 }
451 if (sequence === appliedSequence) return;
452 yield* SubscriptionRef.set(lastSequence, sequence);
453 if (fresh.length === 0) return;
454​
455 const waiting = yield* Ref.get(awaitingCompletion);
456 // Apply against the latest projection/history in one update so a concurrent
457 // loadEarlier merge (or history-meta patch) cannot be clobbered by a stale
458 // get-then-set rebuild.
459 type EventApplyResult =
460 | { readonly _tag: "noop" }
461 | { readonly _tag: "delete" }
462 | {
463 readonly _tag: "applied";
464 readonly projection: OrchestrationV2ThreadProjection;
465 readonly history: ThreadHistoryMeta;
466 };
467​
468 const applyEvent = (
469 current: EnvironmentThreadState,
470 item: EventItem,
471 ): readonly [EventApplyResult, EnvironmentThreadState] => {
472 if (current.status === "deleted") {
473 return [{ _tag: "noop" }, current];
474 }
475 if (Option.isNone(current.data)) {
476 return [
477 item.event.type === "thread.deleted" ? { _tag: "delete" } : { _tag: "noop" },
478 current,
479 ];
480 }
481 if (item.event.type === "thread.deleted") {
482 return [{ _tag: "delete" }, current];
483 }
484​
485 // Incomplete progressive windows only (hasMore or open cursor). Do not
486 // use expanded: it remains true after the last page as a cache marker.
487 const partial =
488 current.history.hasMoreHistory || current.history.historyCursor !== null
489 ? {
490 partialTimeline: true as const,
491 latestLocalTurnOrdinal: current.history.latestLocalTurnOrdinal,
492 }
493 : undefined;
494 const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event, partial);
495 if (next === null || next === current.data.value) {
496 return [{ _tag: "noop" }, current];
497 }
498​
499 let history = current.history;
500 if (partial !== undefined && item.event.type === "turn-item.updated") {
501 const ordinal = item.event.payload.ordinal;
502 const watermark = history.latestLocalTurnOrdinal;
503 if (watermark === null || ordinal > watermark) {
504 history = { ...history, latestLocalTurnOrdinal: ordinal };
505 }
506 }
507​
508 const updated: EnvironmentThreadState = {
509 ...current,
510 data: Option.some(next),
511 status: waiting ? "synchronizing" : "live",
512 error: Option.none(),
513 history,
514 };
515 return [{ _tag: "applied", projection: next, history: updated.history }, updated];
516 };
517​
518 const result = yield* SubscriptionRef.modify(
519 state,
520 (current): readonly [EventApplyResult, EnvironmentThreadState] => {
521 let result: EventApplyResult = { _tag: "noop" };
522 for (const item of fresh) {
523 const [applied, next] = applyEvent(current, item);
524 current = next;
525 if (applied._tag !== "noop") result = applied;
526 if (applied._tag === "delete") break;
527 }
528 return [result, current];
529 },
530 );
531​
532 if (result._tag === "delete") {
533 yield* setDeleted();
534 return;
535 }
536 if (result._tag === "applied" && shouldPersistThread(result.projection, result.history)) {
537 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
538 yield* Queue.offer(
539 persistence,
540 snapshotToPersist(
541 snapshotSequence,
542 result.projection,
543 result.history,
544 yield* Ref.get(acceptsBoundedSocketSnapshots),
545 ),
546 );
547 }
548 });
549​
550 const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* (
551 item: OrchestrationV2ThreadStreamItem,
552 ) {
553 if (item.kind === "synchronized") {
554 yield* Ref.set(awaitingCompletion, false);
555 yield* SubscriptionRef.update(state, (current) =>
556 Option.isSome(current.data) && current.status !== "deleted" && Option.isNone(current.error)
557 ? { ...current, status: "live" as const, error: Option.none() }
558 : current,
559 );
560 return;
561 }
562​
563 if (item.kind === "snapshot") {
564 yield* SubscriptionRef.set(lastSequence, item.snapshotSequence);
565 const hasProgressiveHistory =
566 item.historyCursor !== undefined ||
567 item.hasMoreHistory !== undefined ||
568 item.latestLocalTurnOrdinal !== undefined;
569 yield* setThread(
570 boundedSnapshotProjection(item),
571 hasProgressiveHistory
572 ? {
573 history: {
574 historyCursor: item.historyCursor ?? null,
575 hasMoreHistory: item.hasMoreHistory ?? false,
576 loading: false,
577 error: null,
578 expanded: false,
579 latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null,
580 },
581 }
582 : { resetHistory: true },
583 );
584 return;
585 }
586​
587 yield* applyEventsLocked([item]);
588 });
589​
590 const applyItems = Effect.fn("EnvironmentThreadState.applyItems")(function* (
591 items: ReadonlyArray<OrchestrationV2ThreadStreamItem>,
592 ) {
593 yield* applyLock.withPermits(1)(
594 Effect.gen(function* () {
595 let events: SequencedItem[] = [];
596 for (const item of items) {
597 if (
598 item.kind === "unknown-event" ||
599 (item.kind === "event" && item.event.type !== "thread.deleted")
600 ) {
601 events.push(item);
602 continue;
603 }
604 yield* applyEventsLocked(events);
605 events = [];
606 yield* applyItemLocked(item);
607 }
608 yield* applyEventsLocked(events);
609 yield* remember;
610 }),
611 );
612 });
613​
614 const loadEarlier = Effect.fn("EnvironmentThreadState.loadEarlier")(function* (
615 throughEntryId?: string,
616 ) {
617 const current = yield* SubscriptionRef.get(state);
618 if (
619 current.status === "deleted" ||
620 Option.isNone(current.data) ||
621 !current.history.hasMoreHistory ||
622 current.history.historyCursor === null
623 ) {
624 return { _tag: "noop" } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;
625 }
626 if (current.history.loading) {
627 return { _tag: "busy" } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;
628 }
629​
630 // Capture the cursor that initiated this request. Completions/failures must
631 // no-op if a socket or new bounded snapshot replaced progressive meta mid-flight.
632 const requestCursor = current.history.historyCursor;
633 yield* patchHistoryMeta((history) =>
634 isActiveHistoryRequestCursor(requestCursor, history)
635 ? { ...history, loading: true, error: null }
636 : history,
637 );
638​
639 const failLoad = (message: string) =>
640 SubscriptionRef.modify(
641 state,
642 (
643 latest,
644 ): readonly [
645 ThreadHistoryController.ThreadHistoryLoadEarlierResult,
646 EnvironmentThreadState,
647 ] =>
648 isActiveHistoryRequestCursor(requestCursor, latest.history)
649 ? [
650 { _tag: "error", message },
651 {
652 ...latest,
653 history: { ...latest.history, loading: false, error: message },
654 },
655 ]
656 : [{ _tag: "noop" }, latest],
657 );
658​
659 const runLoad = Effect.gen(function* () {
660 const preparedOption = yield* SubscriptionRef.get(supervisor.prepared);
661 if (Option.isNone(preparedOption) || Option.isNone(httpClient))
662 return yield* failLoad("Environment is not connected.");
663​
664 const views =
665 throughEntryId === undefined ? [undefined] : ["conversation" as const, undefined];
666 for (const view of views) {
667 const pageResult = yield* fetchEnvironmentThreadHistoryPage({
668 prepared: preparedOption.value,
669 threadId,
670 cursor: requestCursor,
671 throughEntryId,
672 view,
673 signer: dpopSigner,
674 remoteAuthorization,
675 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result);
676 if (Result.isFailure(pageResult))
677 return yield* failLoad(formatHistoryError(pageResult.failure));
678 const page = pageResult.success;
679 const complete = view === undefined;
680 const waiting = yield* Ref.get(awaitingCompletion);
681 const result = yield* applyLock.withPermits(1)(
682 SubscriptionRef.modify(
683 state,
684 (
685 latest,
686 ): readonly [
687 ThreadHistoryController.ThreadHistoryLoadEarlierResult,
688 EnvironmentThreadState,
689 ] => {
690 if (!isActiveHistoryRequestCursor(requestCursor, latest.history))
691 return [{ _tag: "noop" }, latest];
692 if (Option.isNone(latest.data) || latest.status === "deleted")
693 return [{ _tag: "noop" }, { ...latest, history: EMPTY_THREAD_HISTORY_META }];
694 return [
695 { _tag: "loaded" },
696 {
697 ...latest,
698 data: Option.some(mergeOlderHistoryIntoProjection(latest.data.value, page.items)),
699 status: complete && waiting ? "synchronizing" : latest.status,
700 history: complete
701 ? applyHistoryPageMeta(latest.history, page)
702 : { ...latest.history, expanded: true },
703 },
704 ];
705 },
706 ),
707 );
708 if (result._tag !== "loaded") return result;
709 if (complete) yield* remember;
710 }
711 return { _tag: "loaded" } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;
712 });
713​
714 return yield* runLoad.pipe(
715 Effect.onInterrupt(() =>
716 SubscriptionRef.update(state, (latest) => ({
717 ...latest,
718 history: clearActiveHistoryLoading(requestCursor, latest.history),
719 })),
720 ),
721 );
722 });
723​
724 if (Option.isSome(historyController)) {
725 const scope = yield* Scope.Scope;
726 const registration = yield* historyController.value.register(environmentId, threadId, {
727 loadEarlier: (throughEntryId) =>
728 loadEarlier(throughEntryId).pipe(Effect.forkIn(scope), Effect.flatMap(Fiber.join)),
729 });
730 yield* Effect.addFinalizer(() => historyController.value.unregister(registration));
731 }
732​
733 yield* SubscriptionRef.changes(supervisor.state).pipe(
734 Stream.runForEach((connectionState) => {
735 switch (connectionProjectionPhase(connectionState)) {
736 case "synchronizing":
737 return setConnecting;
738 case "disconnected":
739 return setDisconnected;
740 case "ready":
741 return setReady;
742 }
743 }),
744 Effect.forkScoped,
745 );
746​
747 const foregroundResubscriptions = Option.match(wakeups, {
748 onNone: () => Stream.never,
749 onSome: (service) =>
750 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
751 });
752​
753 // Only the first subscription after a warm live resume keeps the retained
754 // status. A replacement session or foreground resubscribe on the same scope
755 // may have missed events, so those show sync progress until confirmed.
756 const resumingLive = yield* Ref.make(initialState.status === "live");
757 const markSynchronizing = Effect.gen(function* () {
758 if (yield* Ref.get(resumingLive)) return;
759 yield* SubscriptionRef.update(state, (current) =>
760 current.status === "deleted"
761 ? current
762 : { ...current, status: "synchronizing" as const, error: Option.none() },
763 );
764 });
765​
766 yield* markSynchronizing;
767 yield* Effect.forkScoped(
768 subscribeDynamic(
769 ORCHESTRATION_V2_WS_METHODS.subscribeThread,
770 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
771 let current = yield* SubscriptionRef.get(state);
772 // A prior definitive miss (or delete event) already cleared this thread.
773 // Park the subscription attempt without opening the socket so we do not
774 // retry forever against a known-missing id.
775 if (current.status === "deleted") {
776 return yield* Effect.never;
777 }
778​
779 const supportsCompletionMarker = yield* session.initialConfig.pipe(
780 Effect.map((config) => config.threadResumeCompletionMarker === true),
781 Effect.orElseSucceed(() => false),
782 );
783 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
784 yield* markSynchronizing;
785 yield* Ref.set(resumingLive, false);
786​
787 if (Option.isNone(current.data)) {
788 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
789 Effect.flatMap(
790 Option.match({
791 onSome: Effect.succeed,
792 onNone: () =>
793 SubscriptionRef.changes(supervisor.prepared).pipe(
794 Stream.filter(Option.isSome),
795 Stream.map((value) => value.value),
796 Stream.runHead,
797 Effect.map(Option.getOrThrow),
798 ),
799 }),
800 ),
801 );
802 const httpResult: ThreadSnapshotLoader.ThreadSnapshotLoadResult =
803 yield* snapshotLoader.load(prepared, threadId);
804 switch (httpResult._tag) {
805 case "present": {
806 if (canLoadHistory && httpResult.history !== undefined) {
807 yield* Ref.set(acceptsBoundedSocketSnapshots, true);
808 }
809 // Atomic projection + progressive meta so a settled bounded window
810 // never persists as a complete full-timeline cache entry. Socket
811 // snapshots still go through applyItem (resetHistory).
812 yield* applyLock.withPermits(1)(
813 Effect.gen(function* () {
814 yield* SubscriptionRef.set(lastSequence, httpResult.snapshot.snapshotSequence);
815 const history: ThreadHistoryMeta =
816 httpResult.history !== undefined
817 ? {
818 historyCursor: httpResult.history.historyCursor,
819 hasMoreHistory: httpResult.history.hasMoreHistory,
820 loading: false,
821 error: null,
822 expanded: false,
823 latestLocalTurnOrdinal: httpResult.history.latestLocalTurnOrdinal ?? null,
824 }
825 : EMPTY_THREAD_HISTORY_META;
826 yield* setThread(httpResult.snapshot.projection, { history });
827 yield* remember;
828 }),
829 );
830 current = yield* SubscriptionRef.get(state);
831 break;
832 }
833 case "missing": {
834 yield* setDeleted();
835 return yield* Effect.never;
836 }
837 case "unavailable": {
838 break;
839 }
840 }
841 }
842​
843 const sequence = yield* SubscriptionRef.get(lastSequence);
844 const canResume = Option.isSome(current.data);
845 const acceptBoundedSnapshot = yield* Ref.get(acceptsBoundedSocketSnapshots);
846 if (!supportsCompletionMarker && canResume) {
847 yield* SubscriptionRef.update(state, (value) => ({
848 ...value,
849 status: value.status === "deleted" ? value.status : ("live" as const),
850 error: Option.none(),
851 }));
852 }
853​
854 return {
855 threadId,
856 ...(canResume ? { afterSequence: sequence } : {}),
857 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
858 ...(acceptBoundedSnapshot
859 ? { acceptBoundedSnapshot: true as const, acceptCompactTurnItems: true as const }
860 : {}),
861 };
862 }),
863 {
864 onDefect: () => setStreamError("Could not synchronize the thread."),
865 onExpectedFailure: (cause) => setStreamError(formatThreadError(cause)),
866 retryExpectedFailureAfter: "250 millis",
867 resubscribe: foregroundResubscriptions,
868 },
869 ).pipe(Stream.runForEachArray(applyItems)),
870 );
871​
872 return state;
873});
874​
875function threadStateChanges(
876 environmentId: EnvironmentIdType,
877 threadId: ThreadIdType,
878 resumeCache?: ThreadResumeCache,
879) {
880 return followStreamInEnvironment(
881 environmentId,
882 Stream.unwrap(
883 makeEnvironmentThreadState(threadId, resumeCache).pipe(Effect.map(SubscriptionRef.changes)),
884 ),
885 );
887​
888export function createEnvironmentThreadStateAtoms<R, E>(
889 runtime: Atom.AtomRuntime<
890 | EnvironmentRegistry.EnvironmentRegistry
891 | Persistence.EnvironmentCacheStore
892 | ThreadSnapshotLoader.ThreadSnapshotLoader
893 | R,
894 E
895 >,
896) {
897 // Cache definitions must outlive collectible live-atom definitions. The
898 // registry retains these nodes without retaining environment or RPC scopes.
899 const resumeFamily = Atom.family((key: string) =>
900 Atom.make((): ThreadResumeCache => ({
901 snapshot: undefined,
902 owner: undefined,
903 })).pipe(
904 Atom.setIdleTTL(THREAD_SNAPSHOT_IDLE_TTL_MS),
905 Atom.withLabel(`environment-thread-resume:${key}`),
906 ),
907 );
908 const family = Atom.family((key: string) => {
909 const { environmentId, threadId } = parseThreadKey(key);
910 const resumeAtom = resumeFamily(key);
911 return runtime
912 .atom(
913 (get) => {
914 get.mount(resumeAtom);
915 const resume = get.once(resumeAtom);
916 const live = threadStateChanges(environmentId, threadId, resume);
917 return resume.snapshot === undefined
918 ? live
919 : Stream.concat(Stream.succeed(cachedThreadState(resume.snapshot.state)), live);
920 },
921 {
922 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
923 },
924 )
925 .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state:${key}`));
926 });
927​
928 return {
929 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
930 family(threadKey({ environmentId, threadId })),
931 };
933​
934export * from "./archivedThreads.ts";
935export * from "./checkpointDiff.ts";
936export * as BoundedThreadSnapshotLoader from "./boundedThreadSnapshotHttp.ts";
937export * as ThreadHistoryController from "./threadHistoryController.ts";
938export type { ThreadHistoryLoadEarlierResult } from "./threadHistoryController.ts";
939export * from "./threadHistoryMerge.ts";
940export * from "./threadSnapshotHttp.ts";
941export * from "./composerPathSearch.ts";
942export * from "./threadCommands.ts";
943export * from "./threadFeedback.ts";
944export * from "./threadDetail.ts";
945export * from "./threadShell.ts";
946export * from "./threadState.ts";