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

threads.ts

936 lines34.4 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 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 };
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 );
124​
125interface ThreadResumeSnapshot {
126 readonly state: EnvironmentThreadState;
127 readonly sequence: number;
128 readonly persisted: boolean;
129 readonly acceptsBoundedSnapshots?: boolean;
131​
132interface ThreadResumeCache {
133 snapshot: ThreadResumeSnapshot | undefined;
134 owner: object | undefined;
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 );
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 };
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 const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* (
419 item: OrchestrationV2ThreadStreamItem,
420 ) {
421 if (item.kind === "synchronized") {
422 yield* Ref.set(awaitingCompletion, false);
423 yield* SubscriptionRef.update(state, (current) =>
424 Option.isSome(current.data) && current.status !== "deleted" && Option.isNone(current.error)
425 ? { ...current, status: "live" as const, error: Option.none() }
426 : current,
427 );
428 return;
429 }
430​
431 if (item.kind === "snapshot") {
432 yield* SubscriptionRef.set(lastSequence, item.snapshotSequence);
433 const hasProgressiveHistory =
434 item.historyCursor !== undefined ||
435 item.hasMoreHistory !== undefined ||
436 item.latestLocalTurnOrdinal !== undefined;
437 // Bounded socket fallbacks carry their cursor. Legacy-compatible full
438 // snapshots omit these fields and still replace progressive state.
439 yield* setThread(
440 item.projection,
441 hasProgressiveHistory
442 ? {
443 history: {
444 historyCursor: item.historyCursor ?? null,
445 hasMoreHistory: item.hasMoreHistory ?? false,
446 loading: false,
447 error: null,
448 expanded: false,
449 latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null,
450 },
451 }
452 : { resetHistory: true },
453 );
454 return;
455 }
456​
457 const sequence = yield* SubscriptionRef.get(lastSequence);
458 if (item.sequence <= sequence) {
459 return;
460 }
461 yield* SubscriptionRef.set(lastSequence, item.sequence);
462​
463 const waiting = yield* Ref.get(awaitingCompletion);
464 // Apply against the latest projection/history in one update so a concurrent
465 // loadEarlier merge (or history-meta patch) cannot be clobbered by a stale
466 // get-then-set rebuild.
467 type EventApplyResult =
468 | { readonly _tag: "noop" }
469 | { readonly _tag: "delete" }
470 | {
471 readonly _tag: "applied";
472 readonly projection: OrchestrationV2ThreadProjection;
473 readonly history: ThreadHistoryMeta;
474 };
475​
476 const result = yield* SubscriptionRef.modify(
477 state,
478 (current): readonly [EventApplyResult, EnvironmentThreadState] => {
479 if (current.status === "deleted") {
480 return [{ _tag: "noop" }, current];
481 }
482 if (Option.isNone(current.data)) {
483 return [
484 item.event.type === "thread.deleted" ? { _tag: "delete" } : { _tag: "noop" },
485 current,
486 ];
487 }
488 if (item.event.type === "thread.deleted") {
489 return [{ _tag: "delete" }, current];
490 }
491​
492 // Incomplete progressive windows only (hasMore or open cursor). Do not
493 // use expanded: it remains true after the last page as a cache marker.
494 // Full/web and fully-loaded timelines keep default append-on-miss.
495 const partial =
496 current.history.hasMoreHistory || current.history.historyCursor !== null
497 ? {
498 partialTimeline: true as const,
499 latestLocalTurnOrdinal: current.history.latestLocalTurnOrdinal,
500 }
501 : undefined;
502 const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event, partial);
503 // True no-op when the reducer deliberately returns the current projection
504 // reference (e.g. dropped old partial-timeline turn-item). Do not clear
505 // stream error/status or enqueue persistence.
506 if (next === null || next === current.data.value) {
507 return [{ _tag: "noop" }, current];
508 }
509​
510 let history = current.history;
511 if (partial !== undefined && item.event.type === "turn-item.updated") {
512 const ordinal = item.event.payload.ordinal;
513 const watermark = history.latestLocalTurnOrdinal;
514 if (watermark === null || ordinal > watermark) {
515 history = { ...history, latestLocalTurnOrdinal: ordinal };
516 }
517 }
518​
519 const updated: EnvironmentThreadState = {
520 ...current,
521 data: Option.some(next),
522 status: waiting ? "synchronizing" : "live",
523 error: Option.none(),
524 history,
525 };
526 return [{ _tag: "applied", projection: next, history: updated.history }, updated];
527 },
528 );
529​
530 if (result._tag === "delete") {
531 yield* setDeleted();
532 return;
533 }
534 if (result._tag === "applied" && shouldPersistThread(result.projection, result.history)) {
535 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
536 yield* Queue.offer(
537 persistence,
538 snapshotToPersist(
539 snapshotSequence,
540 result.projection,
541 result.history,
542 yield* Ref.get(acceptsBoundedSocketSnapshots),
543 ),
544 );
545 }
546 });
547​
548 const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* (
549 item: OrchestrationV2ThreadStreamItem,
550 ) {
551 yield* applyLock.withPermits(1)(applyItemLocked(item).pipe(Effect.andThen(remember)));
552 });
553​
554 const loadEarlier = Effect.fn("EnvironmentThreadState.loadEarlier")(function* () {
555 const current = yield* SubscriptionRef.get(state);
556 if (
557 current.status === "deleted" ||
558 Option.isNone(current.data) ||
559 !current.history.hasMoreHistory ||
560 current.history.historyCursor === null
561 ) {
562 return { _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult;
563 }
564 if (current.history.loading) {
565 return { _tag: "busy" } satisfies ThreadHistoryLoadEarlierResult;
566 }
567​
568 // Capture the cursor that initiated this request. Completions/failures must
569 // no-op if a socket or new bounded snapshot replaced progressive meta mid-flight.
570 const requestCursor = current.history.historyCursor;
571 yield* patchHistoryMeta((history) =>
572 isActiveHistoryRequestCursor(requestCursor, history)
573 ? { ...history, loading: true, error: null }
574 : history,
575 );
576​
577 const runLoad = Effect.gen(function* () {
578 const preparedOption = yield* SubscriptionRef.get(supervisor.prepared);
579 if (Option.isNone(preparedOption) || Option.isNone(httpClient)) {
580 const message = "Environment is not connected.";
581 const stillCurrent = yield* SubscriptionRef.modify(
582 state,
583 (latest): readonly [boolean, EnvironmentThreadState] => {
584 if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) {
585 return [false, latest];
586 }
587 return [
588 true,
589 {
590 ...latest,
591 history: { ...latest.history, loading: false, error: message },
592 },
593 ];
594 },
595 );
596 if (!stillCurrent) {
597 return { _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult;
598 }
599 return {
600 _tag: "error",
601 message,
602 } satisfies ThreadHistoryLoadEarlierResult;
603 }
604​
605 const pageResult = yield* fetchEnvironmentThreadHistoryPage({
606 prepared: preparedOption.value,
607 threadId,
608 cursor: requestCursor,
609 signer: dpopSigner,
610 remoteAuthorization,
611 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result);
612​
613 if (Result.isFailure(pageResult)) {
614 const message = formatHistoryError(pageResult.failure);
615 // Only mark error when this request's cursor is still active. Leave
616 // stream/status/error alone so concurrent live updates stay intact.
617 const stillCurrent = yield* SubscriptionRef.modify(
618 state,
619 (latest): readonly [boolean, EnvironmentThreadState] => {
620 if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) {
621 return [false, latest];
622 }
623 return [
624 true,
625 {
626 ...latest,
627 history: { ...latest.history, loading: false, error: message },
628 },
629 ];
630 },
631 );
632 if (!stillCurrent) {
633 return { _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult;
634 }
635 return { _tag: "error", message } satisfies ThreadHistoryLoadEarlierResult;
636 }
637​
638 const page = pageResult.success;
639 const waiting = yield* Ref.get(awaitingCompletion);
640 // Single atomic merge against whatever is current after the await so a
641 // concurrent applyItem cannot be clobbered by a stale get/set pair.
642 return yield* applyLock.withPermits(1)(
643 SubscriptionRef.modify(
644 state,
645 (latest): readonly [ThreadHistoryLoadEarlierResult, EnvironmentThreadState] => {
646 // Stale page: socket/full snapshot or newer bounded install changed the
647 // progressive cursor while this request was in flight. Never mutate the
648 // replacement meta (including deleted/empty installs).
649 if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) {
650 return [{ _tag: "noop" }, latest];
651 }
652 if (Option.isNone(latest.data) || latest.status === "deleted") {
653 return [
654 { _tag: "noop" },
655 {
656 ...latest,
657 history: EMPTY_THREAD_HISTORY_META,
658 },
659 ];
660 }
661​
662 const merged = mergeOlderHistoryIntoProjection(latest.data.value, page.items);
663 const history = applyHistoryPageMeta(latest.history, page);
664 return [
665 { _tag: "loaded" },
666 {
667 ...latest,
668 data: Option.some(merged),
669 status: waiting
670 ? ("synchronizing" as const)
671 : latest.status === "live"
672 ? ("live" as const)
673 : latest.status,
674 history,
675 },
676 ];
677 },
678 ).pipe(Effect.tap(() => remember)),
679 );
680 });
681​
682 // On Effect interruption only: clear loading when this request cursor is
683 // still active. Never mutate stream status/error from the interrupt path.
684 return yield* runLoad.pipe(
685 Effect.onInterrupt(() =>
686 SubscriptionRef.update(state, (latest) => ({
687 ...latest,
688 history: clearActiveHistoryLoading(requestCursor, latest.history),
689 })),
690 ),
691 );
692 });
693​
694 if (Option.isSome(historyController)) {
695 const scope = yield* Scope.Scope;
696 const registration = yield* historyController.value.register(environmentId, threadId, {
697 loadEarlier: () => loadEarlier().pipe(Effect.forkIn(scope), Effect.flatMap(Fiber.join)),
698 });
699 yield* Effect.addFinalizer(() => historyController.value.unregister(registration));
700 }
701​
702 yield* SubscriptionRef.changes(supervisor.state).pipe(
703 Stream.runForEach((connectionState) => {
704 switch (connectionProjectionPhase(connectionState)) {
705 case "synchronizing":
706 return setConnecting;
707 case "disconnected":
708 return setDisconnected;
709 case "ready":
710 return setReady;
711 }
712 }),
713 Effect.forkScoped,
714 );
715​
716 const foregroundResubscriptions = Option.match(wakeups, {
717 onNone: () => Stream.never,
718 onSome: (service) =>
719 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
720 });
721​
722 // Only the first subscription after a warm live resume keeps the retained
723 // status. A replacement session or foreground resubscribe on the same scope
724 // may have missed events, so those show sync progress until confirmed.
725 const resumingLive = yield* Ref.make(initialState.status === "live");
726 const markSynchronizing = Effect.gen(function* () {
727 if (yield* Ref.get(resumingLive)) return;
728 // Connection notifications do not establish that a terminated load restarted.
729 // Clear its diagnostic only when this subscription actually tries again.
730 yield* SubscriptionRef.update(state, (current) =>
731 current.status === "deleted"
732 ? current
733 : { ...current, status: "synchronizing" as const, error: Option.none() },
734 );
735 });
736​
737 yield* markSynchronizing;
738 yield* Effect.forkScoped(
739 subscribeDynamic(
740 ORCHESTRATION_V2_WS_METHODS.subscribeThread,
741 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
742 let current = yield* SubscriptionRef.get(state);
743 // A prior definitive miss (or delete event) already cleared this thread.
744 // Park the subscription attempt without opening the socket so we do not
745 // retry forever against a known-missing id.
746 if (current.status === "deleted") {
747 return yield* Effect.never;
748 }
749​
750 const supportsCompletionMarker = yield* session.initialConfig.pipe(
751 Effect.map((config) => config.threadResumeCompletionMarker === true),
752 Effect.orElseSucceed(() => false),
753 );
754 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
755 yield* markSynchronizing;
756 yield* Ref.set(resumingLive, false);
757​
758 if (Option.isNone(current.data)) {
759 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
760 Effect.flatMap(
761 Option.match({
762 onSome: Effect.succeed,
763 onNone: () =>
764 SubscriptionRef.changes(supervisor.prepared).pipe(
765 Stream.filter(Option.isSome),
766 Stream.map((value) => value.value),
767 Stream.runHead,
768 Effect.map(Option.getOrThrow),
769 ),
770 }),
771 ),
772 );
773 const httpResult: ThreadSnapshotLoadResult = yield* snapshotLoader.load(
774 prepared,
775 threadId,
776 );
777 switch (httpResult._tag) {
778 case "present": {
779 if (canLoadHistory && httpResult.history !== undefined) {
780 yield* Ref.set(acceptsBoundedSocketSnapshots, true);
781 }
782 // Atomic projection + progressive meta so a settled bounded window
783 // never persists as a complete full-timeline cache entry. Socket
784 // snapshots still go through applyItem (resetHistory).
785 yield* applyLock.withPermits(1)(
786 Effect.gen(function* () {
787 yield* SubscriptionRef.set(lastSequence, httpResult.snapshot.snapshotSequence);
788 const history: ThreadHistoryMeta =
789 httpResult.history !== undefined
790 ? {
791 historyCursor: httpResult.history.historyCursor,
792 hasMoreHistory: httpResult.history.hasMoreHistory,
793 loading: false,
794 error: null,
795 expanded: false,
796 latestLocalTurnOrdinal: httpResult.history.latestLocalTurnOrdinal ?? null,
797 }
798 : EMPTY_THREAD_HISTORY_META;
799 yield* setThread(httpResult.snapshot.projection, { history });
800 yield* remember;
801 }),
802 );
803 current = yield* SubscriptionRef.get(state);
804 break;
805 }
806 case "missing": {
807 // Definitive HTTP 404: clear any stale cache and do not open or
808 // retry a socket subscription for this attempt.
809 yield* setDeleted();
810 return yield* Effect.never;
811 }
812 case "unavailable": {
813 // Transient HTTP failure: fall through to the socket path.
814 break;
815 }
816 }
817 }
818​
819 const sequence = yield* SubscriptionRef.get(lastSequence);
820 const canResume = Option.isSome(current.data);
821 const acceptBoundedSnapshot = yield* Ref.get(acceptsBoundedSocketSnapshots);
822 if (!supportsCompletionMarker && canResume) {
823 yield* SubscriptionRef.update(state, (value) => ({
824 ...value,
825 status: value.status === "deleted" ? value.status : ("live" as const),
826 error: Option.none(),
827 }));
828 }
829​
830 return {
831 threadId,
832 ...(canResume ? { afterSequence: sequence } : {}),
833 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
834 ...(acceptBoundedSnapshot ? { acceptBoundedSnapshot: true as const } : {}),
835 };
836 }),
837 {
838 onDefect: () => setStreamError("Could not synchronize the thread."),
839 onExpectedFailure: (cause) => setStreamError(formatThreadError(cause)),
840 retryExpectedFailureAfter: "250 millis",
841 resubscribe: foregroundResubscriptions,
842 },
843 ).pipe(Stream.runForEach(applyItem)),
844 );
845​
846 yield* Effect.addFinalizer(() =>
847 Effect.suspend(() => {
848 const { state: current, sequence: snapshotSequence } = committed;
849 return Option.match(current.data, {
850 onNone: () => Effect.void,
851 onSome: (projection) =>
852 shouldPersistThread(projection, current.history)
853 ? persist(
854 snapshotToPersist(
855 snapshotSequence,
856 projection,
857 current.history,
858 committed.acceptsBoundedSnapshots === true,
859 ),
860 )
861 : Effect.void,
862 });
863 }),
864 );
865​
866 return state;
867});
868​
869function threadStateChanges(
870 environmentId: EnvironmentIdType,
871 threadId: ThreadIdType,
872 resumeCache?: ThreadResumeCache,
873) {
874 return followStreamInEnvironment(
875 environmentId,
876 Stream.unwrap(
877 makeEnvironmentThreadState(threadId, resumeCache).pipe(Effect.map(SubscriptionRef.changes)),
878 ),
879 );
881​
882export function createEnvironmentThreadStateAtoms<R, E>(
883 runtime: Atom.AtomRuntime<
884 EnvironmentRegistry | EnvironmentCacheStore | ThreadSnapshotLoader | R,
885 E
886 >,
887) {
888 // Cache definitions must outlive collectible live-atom definitions. The
889 // registry retains these nodes without retaining environment or RPC scopes.
890 const resumeFamily = Atom.family((key: string) =>
891 Atom.make((): ThreadResumeCache => ({
892 snapshot: undefined,
893 owner: undefined,
894 })).pipe(
895 Atom.setIdleTTL(THREAD_SNAPSHOT_IDLE_TTL_MS),
896 Atom.withLabel(`environment-thread-resume:${key}`),
897 ),
898 );
899 const family = Atom.family((key: string) => {
900 const { environmentId, threadId } = parseThreadKey(key);
901 const resumeAtom = resumeFamily(key);
902 return runtime
903 .atom(
904 (get) => {
905 get.mount(resumeAtom);
906 const resume = get.once(resumeAtom);
907 const live = threadStateChanges(environmentId, threadId, resume);
908 return resume.snapshot === undefined
909 ? live
910 : Stream.concat(Stream.succeed(cachedThreadState(resume.snapshot.state)), live);
911 },
912 {
913 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
914 },
915 )
916 .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state:${key}`));
917 });
918​
919 return {
920 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
921 family(threadKey({ environmentId, threadId })),
922 };
924​
925export * from "./archivedThreads.ts";
926export * from "./checkpointDiff.ts";
927export * from "./boundedThreadSnapshotHttp.ts";
928export * from "./threadHistoryController.ts";
929export * from "./threadHistoryMerge.ts";
930export * from "./threadSnapshotHttp.ts";
931export * from "./composerPathSearch.ts";
932export * from "./threadCommands.ts";
933export * from "./threadFeedback.ts";
934export * from "./threadDetail.ts";
935export * from "./threadShell.ts";
936export * from "./threadState.ts";