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