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

threads.ts

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