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

threads.ts

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