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

threads.ts

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