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

threads.ts

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