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

threads.ts

1,304 lines49.7 KB

1import { mFallback, msg } from "gt-i18n";
2import type { MFunctionType } from "gt-i18n/types";
3import {
4 isOrchestrationV2WorkActive,
5 ORCHESTRATION_V2_WS_METHODS,
6 type EnvironmentId as EnvironmentIdType,
7 type OrchestrationV2ThreadDetailSnapshot,
8 type OrchestrationV2ThreadProjection,
9 type OrchestrationV2ThreadStreamItem,
10 type OrchestrationV2TurnItem,
11 type ThreadId as ThreadIdType,
12} from "@t3tools/contracts";
13import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot";
14import { pendingBackgroundTurnItems } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
15import * as Cause from "effect/Cause";
16import * as Effect from "effect/Effect";
17import * as Fiber from "effect/Fiber";
18import * as Scope from "effect/Scope";
19import * as Option from "effect/Option";
20import * as Queue from "effect/Queue";
21import * as Ref from "effect/Ref";
22import * as Result from "effect/Result";
23import * as Semaphore from "effect/Semaphore";
24import * as Stream from "effect/Stream";
25import * as SubscriptionRef from "effect/SubscriptionRef";
26import { HttpClient } from "effect/http";
27import { Atom } from "effect/reactivity";
28​
29import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
30import * as EnvironmentRegistry from "../connection/registry.ts";
31import { connectionProjectionPhase } from "../connection/model.ts";
32import * as EnvironmentSupervisor from "../connection/supervisor.ts";
33import * as ConnectionWakeups from "../connection/wakeups.ts";
34import * as Persistence from "../platform/persistence.ts";
35import { runCachePersistence } from "./cachePersistence.ts";
36import * as ManagedRelay from "../relay/managedRelay.ts";
37import {
38 isAuthorizationFailure,
39 request,
40 subscribeDynamicWithInput,
41 subscriptionRetryDelay,
42} from "../rpc/client.ts";
43import { parseThreadKey, threadKey } from "./entities.ts";
44import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
45import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts";
46import { followStreamInEnvironment } from "./runtime.ts";
47import * as ThreadHistoryController from "./threadHistoryController.ts";
48import { fetchEnvironmentThreadHistoryPage } from "./threadHistoryHttp.ts";
49import {
50 applyHistoryPageMeta,
51 clearActiveHistoryLoading,
52 EMPTY_THREAD_HISTORY_META,
53 isActiveHistoryRequestCursor,
54 mergeOlderHistoryIntoProjection,
55 mergeOlderSubagentsIntoProjection,
56 type ThreadHistoryMeta,
57} from "./threadHistoryMerge.ts";
58import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
59import { makeThreadRequestsResolvedAnnouncer } from "./threadRequests.ts";
60import {
61 EMPTY_ENVIRONMENT_THREAD_STATE,
62 type EnvironmentThreadState,
63 type EnvironmentThreadStatus,
64} from "./threadState.ts";
65​
66const THREAD_SUBSCRIPTION_RETRY_DELAY = "250 millis";
67​
68function statusWithoutLiveData(
69 data: Option.Option<OrchestrationV2ThreadProjection>,
70): EnvironmentThreadStatus {
71 return Option.isSome(data) ? "cached" : "empty";
73​
74const THREAD_SYNC_ERROR = msg("Could not synchronize the thread.");
75const HISTORY_LOAD_ERROR = msg("Could not load earlier activity.");
76const WORK_HISTORY_CHANGED_ERROR = msg("Work history changed. Retry loading it.");
77const THREAD_ERRORS: ReadonlySet<string> = new Set([
78 THREAD_SYNC_ERROR,
79 HISTORY_LOAD_ERROR,
80 WORK_HISTORY_CHANGED_ERROR,
81]);
82​
83/**
84 * A thread or history error in the active language. Errors this module wrote translate;
85 * messages from the server or another error stay as they are.
86 * @public
87 */
88export function threadErrorText(error: string, resolve: MFunctionType = mFallback): string {
89 return THREAD_ERRORS.has(error) ? resolve(error) : error;
91​
92function formatThreadError(cause: Cause.Cause<unknown>): string {
93 const error = Cause.squash(cause);
94 return error instanceof Error && error.message.trim().length > 0
95 ? error.message
96 : THREAD_SYNC_ERROR;
98​
99function formatHistoryError(error: unknown): string {
100 if (error instanceof Error && error.message.trim().length > 0) {
101 return error.message;
102 }
103 return HISTORY_LOAD_ERROR;
105​
106// Steers join a running turn; every other user message opens one. The timeline shows every
107// notification as a response boundary, whether it opened its run or arrived mid-run.
108function startsTurn(item: OrchestrationV2TurnItem): boolean {
109 return (
110 item.type === "notification" ||
111 (item.type === "user_message" &&
112 item.inputIntent !== "steer" &&
113 item.inputIntent !== "promoted_queued_to_steer")
114 );
116​
117function historyMetaFromCachedSnapshot(
118 snapshot: OrchestrationV2ThreadDetailSnapshot,
119): ThreadHistoryMeta {
120 const historyCursor = snapshot.historyCursor ?? null;
121 const hasMoreHistory = snapshot.hasMoreHistory ?? false;
122 return {
123 historyCursor,
124 hasMoreHistory,
125 loading: false,
126 error: null,
127 expanded: false,
128 latestLocalTurnOrdinal: snapshot.latestLocalTurnOrdinal ?? null,
129 };
131​
132function snapshotToPersist(
133 snapshotSequence: number,
134 projection: OrchestrationV2ThreadProjection,
135 history: ThreadHistoryMeta,
136 acceptsBoundedSnapshots: boolean,
137): OrchestrationV2ThreadDetailSnapshot {
138 // A complete bounded snapshot still proves paging support. Retain that evidence
139 // so a thread that grows while closed can resume with a bounded fallback.
140 if (acceptsBoundedSnapshots || history.hasMoreHistory || history.historyCursor !== null) {
141 return {
142 snapshotSequence,
143 projection,
144 historyCursor: history.historyCursor,
145 hasMoreHistory: history.hasMoreHistory,
146 latestLocalTurnOrdinal: history.latestLocalTurnOrdinal,
147 };
148 }
149 return { snapshotSequence, projection };
151​
152function shouldPersistThread(
153 thread: OrchestrationV2ThreadProjection,
154 history: ThreadHistoryMeta,
155): boolean {
156 // After the user loads older pages the in-memory timeline can grow large.
157 // Keep those expanded projections out of the monolithic cache.
158 if (history.expanded) {
159 return false;
160 }
161 return !thread.runs.some(
162 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
163 );
165​
166// Only still-active local copies take the server's item: events applied meanwhile win,
167// and inherited rows belong to another thread.
168function settleTurnItems(
169 threadId: ThreadIdType,
170 projection: OrchestrationV2ThreadProjection,
171 settled: ReadonlyMap<string, OrchestrationV2TurnItem>,
172): OrchestrationV2ThreadProjection {
173 let changed = false;
174 const settle = (item: OrchestrationV2TurnItem, id: string) => {
175 const server = settled.get(id);
176 if (server === undefined || !isOrchestrationV2WorkActive(item.status)) return item;
177 changed = true;
178 return server;
179 };
180 const turnItems = projection.turnItems.map((item) => settle(item, item.id));
181 const visibleTurnItems = projection.visibleTurnItems.map((row) => {
182 if (row.sourceThreadId !== threadId) return row;
183 const item = settle(row.item, row.sourceItemId);
184 return item === row.item ? row : { ...row, item };
185 });
186 return changed ? { ...projection, turnItems, visibleTurnItems } : projection;
188​
189interface ThreadResumeSnapshot {
190 readonly state: EnvironmentThreadState;
191 readonly sequence: number;
192 readonly persisted: boolean;
193 readonly acceptsBoundedSnapshots?: boolean;
195​
196interface ThreadResumeCache {
197 snapshot: ThreadResumeSnapshot | undefined;
198 owner: object | undefined;
200​
201function matchesThreadSnapshot(
202 current: ThreadResumeSnapshot,
203 projection: OrchestrationV2ThreadProjection | null,
204 sequence: number,
205 history: Pick<ThreadHistoryMeta, "historyCursor" | "hasMoreHistory" | "latestLocalTurnOrdinal">,
206): boolean {
207 if (current.sequence !== sequence || Option.getOrNull(current.state.data) !== projection)
208 return false;
209 const currentHistory = current.state.history;
210 return (
211 currentHistory.historyCursor === history.historyCursor &&
212 currentHistory.hasMoreHistory === history.hasMoreHistory &&
213 (!(history.hasMoreHistory || history.historyCursor !== null) ||
214 currentHistory.latestLocalTurnOrdinal === history.latestLocalTurnOrdinal)
215 );
217​
218function cachedThreadState(value: EnvironmentThreadState): EnvironmentThreadState {
219 return {
220 ...value,
221 status:
222 value.status === "deleted" || (value.status === "live" && Option.isSome(value.data))
223 ? value.status
224 : statusWithoutLiveData(value.data),
225 error: Option.none(),
226 history: { ...value.history, loading: false, error: null },
227 };
229​
230function hasMissingPendingQuestionCard(projection: OrchestrationV2ThreadProjection): boolean {
231 const pending = new Set(
232 projection.runtimeRequests
233 .filter((request) => request.kind === "user_input" && request.status === "pending")
234 .map((request) => request.id),
235 );
236 if (pending.size === 0) return false;
237 for (const item of projection.turnItems) {
238 if (item.type === "user_input_request") pending.delete(item.requestId);
239 if (pending.size === 0) return false;
240 }
241 return true;
243​
244export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
245 threadId: ThreadIdType,
246 resumeCache?: ThreadResumeCache,
247) {
248 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
249 const cache = yield* Persistence.EnvironmentCacheStore;
250 const snapshotLoader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
251 const historyController = yield* Effect.serviceOption(
252 ThreadHistoryController.ThreadHistoryController,
253 );
254 const httpClient = yield* Effect.serviceOption(HttpClient.HttpClient);
255 const dpopSigner = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
256 const remoteAuthorization = yield* Effect.serviceOption(
257 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
258 );
259 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
260 const environmentId = supervisor.target.environmentId;
261 const candidate = resumeCache?.snapshot;
262 const retained =
263 candidate &&
264 Option.isSome(candidate.state.data) &&
265 hasMissingPendingQuestionCard(candidate.state.data.value)
266 ? undefined
267 : candidate;
268 const owner = {};
269 if (resumeCache) resumeCache.owner = owner;
270 const loaded =
271 retained === undefined
272 ? yield* cache.loadThread(environmentId, threadId).pipe(
273 Effect.catch((error) =>
274 Effect.logWarning("Could not load cached thread.").pipe(
275 Effect.annotateLogs({
276 environmentId,
277 threadId,
278 error: error.message,
279 }),
280 Effect.as(Option.none<OrchestrationV2ThreadDetailSnapshot>()),
281 ),
282 ),
283 )
284 : Option.none<OrchestrationV2ThreadDetailSnapshot>();
285 // Old bounded caches can omit a pending question's card; replay alone cannot restore it.
286 const cached = Option.filter(
287 loaded,
288 (snapshot) => !hasMissingPendingQuestionCard(snapshot.projection),
289 );
290 const cachedThread = Option.map(cached, (snapshot) => snapshot.projection);
291 // Seed the resume cursor from the cached snapshot so a warm cache can catch up
292 // via `afterSequence` instead of re-downloading the full thread body.
293 const initialSequence =
294 retained?.sequence ??
295 Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence });
296 const initialState: EnvironmentThreadState = retained
297 ? cachedThreadState(retained.state)
298 : {
299 data: cachedThread,
300 status: statusWithoutLiveData(cachedThread),
301 error: Option.none(),
302 history: Option.match(cached, {
303 onNone: () => EMPTY_THREAD_HISTORY_META,
304 onSome: historyMetaFromCachedSnapshot,
305 }),
306 sequence: initialSequence,
307 };
308 const state = yield* SubscriptionRef.make(initialState);
309 const canLoadHistory = Option.isSome(httpClient) && Option.isSome(historyController);
310 const acceptsBoundedSocketSnapshots = yield* Ref.make(canLoadHistory);
311 const lastSequence = yield* SubscriptionRef.make(initialSequence);
312 let committed: ThreadResumeSnapshot = {
313 state: initialState,
314 sequence: initialSequence,
315 persisted: retained?.persisted ?? Option.isSome(cached),
316 acceptsBoundedSnapshots: canLoadHistory,
317 };
318 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
319 const awaitingCompletion = yield* Ref.make(false);
320 const applyLock = yield* Semaphore.make(1);
321 // Save only completed data/cursor updates. A canceled scope must not cache
322 // a cursor whose event has not reached the data yet.
323 const announceRequests = makeThreadRequestsResolvedAnnouncer(environmentId, threadId);
324 const remember = Effect.gen(function* () {
325 const current = yield* SubscriptionRef.get(state);
326 const sequence = yield* SubscriptionRef.get(lastSequence);
327 // Only a synchronized projection from the scope that owns the thread is
328 // authoritative: a cached one can predate a request the user already has
329 // drafts for, and a superseded scope can lag its successor.
330 const owns = resumeCache === undefined || resumeCache.owner === owner;
331 if (owns && current.status === "deleted") announceRequests([]);
332 else if (owns && current.status === "live" && Option.isSome(current.data))
333 announceRequests(current.data.value.runtimeRequests);
334 committed = {
335 state: current,
336 sequence,
337 acceptsBoundedSnapshots: yield* Ref.get(acceptsBoundedSocketSnapshots),
338 persisted:
339 committed.persisted &&
340 matchesThreadSnapshot(committed, Option.getOrNull(current.data), sequence, current.history),
341 };
342 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
343 });
344 const persistence = yield* Queue.sliding<OrchestrationV2ThreadDetailSnapshot>(1);
345 let queuedSnapshot = Option.getOrUndefined(cached);
346 let savedSnapshot = queuedSnapshot;
347 const queuePersist = (snapshot: OrchestrationV2ThreadDetailSnapshot) =>
348 Effect.suspend(() => {
349 queuedSnapshot = snapshot;
350 return Queue.offer(persistence, snapshot);
351 });
352​
353 const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
354 snapshot: OrchestrationV2ThreadDetailSnapshot,
355 ) {
356 if (resumeCache !== undefined && resumeCache.owner !== owner) return;
357 if (committed.state.status === "deleted") return;
358 if (
359 committed.persisted &&
360 matchesThreadSnapshot(
361 committed,
362 snapshot.projection,
363 snapshot.snapshotSequence,
364 historyMetaFromCachedSnapshot(snapshot),
365 )
366 )
367 return;
368 yield* cache.saveThread(environmentId, snapshot).pipe(
369 Effect.tap(() =>
370 Effect.sync(() => {
371 savedSnapshot = snapshot;
372 if (
373 !matchesThreadSnapshot(
374 committed,
375 snapshot.projection,
376 snapshot.snapshotSequence,
377 historyMetaFromCachedSnapshot(snapshot),
378 )
379 )
380 return;
381 committed = { ...committed, persisted: true };
382 if (resumeCache?.owner === owner) resumeCache.snapshot = committed;
383 }),
384 ),
385 Effect.catch((error) =>
386 Effect.logWarning("Could not persist the thread cache.").pipe(
387 Effect.annotateLogs({
388 environmentId,
389 threadId,
390 error: error.message,
391 }),
392 ),
393 ),
394 );
395 });
396​
397 yield* Effect.addFinalizer(() =>
398 Effect.suspend(() => {
399 const { state: current, sequence: snapshotSequence } = committed;
400 return Option.match(current.data, {
401 onNone: () => Effect.void,
402 onSome: (projection) =>
403 !current.history.expanded
404 ? persist(
405 snapshotToPersist(
406 snapshotSequence,
407 projection,
408 current.history,
409 committed.acceptsBoundedSnapshots === true,
410 ),
411 )
412 : // The consumer may still be waiting out its delay; an expanded thread queues
413 // only cache repairs, which must survive leaving the thread.
414 queuedSnapshot !== undefined && queuedSnapshot !== savedSnapshot
415 ? persist(queuedSnapshot)
416 : Effect.void,
417 });
418 }),
419 );
420​
421 yield* runCachePersistence(persistence, persist).pipe(Effect.forkScoped);
422​
423 const setConnecting = SubscriptionRef.update(state, (current) =>
424 current.status === "deleted" || Option.isSome(current.error)
425 ? current
426 : {
427 ...current,
428 status: "synchronizing" as const,
429 error: Option.none(),
430 },
431 );
432 const setReady = SubscriptionRef.update(state, (current) =>
433 current.status === "live" || current.status === "deleted" || Option.isSome(current.error)
434 ? current
435 : {
436 ...current,
437 status: "synchronizing" as const,
438 error: Option.none(),
439 },
440 );
441 const setDisconnected = Effect.gen(function* () {
442 yield* Ref.set(awaitingCompletion, false);
443 yield* SubscriptionRef.update(state, (current) => ({
444 ...current,
445 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
446 }));
447 });
448 const setStreamError = (message: string) =>
449 Ref.set(awaitingCompletion, false).pipe(
450 Effect.andThen(
451 SubscriptionRef.update(state, (current) => ({
452 ...current,
453 status:
454 current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
455 error: Option.some(message),
456 })),
457 ),
458 );
459​
460 const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
461 thread: OrchestrationV2ThreadProjection,
462 options?: {
463 readonly resetHistory?: boolean;
464 readonly history?: ThreadHistoryMeta;
465 },
466 ) {
467 const waiting = yield* Ref.get(awaitingCompletion);
468 const sequence = yield* SubscriptionRef.get(lastSequence);
469 // Atomic with concurrent history meta updates: never get-then-set the whole
470 // state when only the projection changes. Bounded installs pass history so
471 // projection + cursor persist together in one enqueue.
472 const next = yield* SubscriptionRef.updateAndGet(state, (previous) => {
473 const history =
474 options?.history !== undefined
475 ? options.history
476 : options?.resetHistory === true
477 ? EMPTY_THREAD_HISTORY_META
478 : previous.history;
479 return {
480 ...previous,
481 data: Option.some(thread),
482 status: Option.isSome(previous.error)
483 ? ("cached" as const)
484 : waiting
485 ? ("synchronizing" as const)
486 : ("live" as const),
487 error: previous.error,
488 history,
489 sequence,
490 };
491 });
492 // Active projections can update many times per second and retain large tool
493 // payloads. Persist once the run settles so cache encoding stays off the
494 // streaming path. Progressive meta rides along when the window is incomplete.
495 if (shouldPersistThread(thread, next.history)) {
496 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
497 yield* queuePersist(
498 snapshotToPersist(
499 snapshotSequence,
500 thread,
501 next.history,
502 yield* Ref.get(acceptsBoundedSocketSnapshots),
503 ),
504 );
505 }
506 });
507​
508 const patchHistoryMeta = (patch: (history: ThreadHistoryMeta) => ThreadHistoryMeta) =>
509 SubscriptionRef.update(state, (current) => ({
510 ...current,
511 history: patch(current.history),
512 }));
513​
514 const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
515 yield* Ref.set(awaitingCompletion, false);
516 yield* SubscriptionRef.set(state, {
517 data: Option.none(),
518 status: "deleted",
519 error: Option.none(),
520 history: EMPTY_THREAD_HISTORY_META,
521 sequence: yield* SubscriptionRef.get(lastSequence),
522 });
523 yield* remember;
524 if (resumeCache !== undefined && resumeCache.owner !== owner) return;
525 yield* cache.removeThread(environmentId, threadId).pipe(
526 Effect.catch((error) =>
527 Effect.logWarning("Could not remove the cached thread.").pipe(
528 Effect.annotateLogs({
529 environmentId,
530 threadId,
531 error: error.message,
532 }),
533 ),
534 ),
535 );
536 });
537​
538 type EventItem = Extract<OrchestrationV2ThreadStreamItem, { kind: "event" }>;
539 type SequencedItem = Extract<
540 OrchestrationV2ThreadStreamItem,
541 { kind: "event" | "unknown-event" }
542 >;
543 // Per-batch streaming spans add trace volume without a useful timing boundary.
544 const applyEventsLocked = Effect.fnUntraced(function* (items: ReadonlyArray<SequencedItem>) {
545 const appliedSequence = yield* SubscriptionRef.get(lastSequence);
546 let sequence = appliedSequence;
547 const fresh: EventItem[] = [];
548 for (const item of items) {
549 if (item.sequence <= sequence) continue;
550 sequence = item.sequence;
551 if (item.kind === "event") {
552 fresh.push(item);
553 continue;
554 }
555 yield* Effect.logDebug("Skipped a thread event type this client does not know.").pipe(
556 Effect.annotateLogs({
557 environmentId,
558 threadId,
559 eventType: item.eventType.slice(0, 64),
560 sequence: item.sequence,
561 }),
562 );
563 }
564 if (sequence === appliedSequence) return;
565 yield* SubscriptionRef.set(lastSequence, sequence);
566 if (fresh.length === 0) return;
567​
568 const waiting = yield* Ref.get(awaitingCompletion);
569 // Apply against the latest projection/history in one update so a concurrent
570 // loadEarlier merge (or history-meta patch) cannot be clobbered by a stale
571 // get-then-set rebuild.
572 type EventApplyResult =
573 | { readonly _tag: "noop" }
574 | { readonly _tag: "delete" }
575 | {
576 readonly _tag: "applied";
577 readonly projection: OrchestrationV2ThreadProjection;
578 readonly history: ThreadHistoryMeta;
579 };
580​
581 const applyEvent = (
582 current: EnvironmentThreadState,
583 item: EventItem,
584 ): readonly [EventApplyResult, EnvironmentThreadState] => {
585 if (current.status === "deleted") {
586 return [{ _tag: "noop" }, current];
587 }
588 if (Option.isNone(current.data)) {
589 return [
590 item.event.type === "thread.deleted" ? { _tag: "delete" } : { _tag: "noop" },
591 current,
592 ];
593 }
594 if (item.event.type === "thread.deleted") {
595 return [{ _tag: "delete" }, current];
596 }
597​
598 // Incomplete progressive windows only (hasMore or open cursor). Do not
599 // use expanded: it remains true after the last page as a cache marker.
600 const partial =
601 current.history.hasMoreHistory || current.history.historyCursor !== null
602 ? {
603 partialTimeline: true as const,
604 latestLocalTurnOrdinal: current.history.latestLocalTurnOrdinal,
605 }
606 : undefined;
607 const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event, partial);
608 if (next === null || next === current.data.value) {
609 return [{ _tag: "noop" }, current];
610 }
611​
612 let history = current.history;
613 if (partial !== undefined && item.event.type === "turn-item.updated") {
614 const ordinal = item.event.payload.ordinal;
615 const watermark = history.latestLocalTurnOrdinal;
616 if (watermark === null || ordinal > watermark) {
617 history = { ...history, latestLocalTurnOrdinal: ordinal };
618 }
619 }
620​
621 const updated: EnvironmentThreadState = {
622 ...current,
623 data: Option.some(next),
624 status: waiting ? "synchronizing" : "live",
625 error: Option.none(),
626 history,
627 };
628 return [{ _tag: "applied", projection: next, history: updated.history }, updated];
629 };
630​
631 const result = yield* SubscriptionRef.modify(
632 state,
633 (current): readonly [EventApplyResult, EnvironmentThreadState] => {
634 let result: EventApplyResult = { _tag: "noop" };
635 for (const item of fresh) {
636 const [applied, next] = applyEvent(current, item);
637 current = next;
638 if (applied._tag !== "noop") result = applied;
639 if (applied._tag === "delete") break;
640 }
641 // A batch that changed nothing keeps its state object, so readers do not re-render.
642 return [result, result._tag === "noop" ? current : { ...current, sequence }];
643 },
644 );
645​
646 if (result._tag === "delete") {
647 yield* setDeleted();
648 return;
649 }
650 if (result._tag === "applied" && shouldPersistThread(result.projection, result.history)) {
651 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
652 yield* queuePersist(
653 snapshotToPersist(
654 snapshotSequence,
655 result.projection,
656 result.history,
657 yield* Ref.get(acceptsBoundedSocketSnapshots),
658 ),
659 );
660 }
661 });
662​
663 const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* (
664 item: OrchestrationV2ThreadStreamItem,
665 ) {
666 if (item.kind === "synchronized") {
667 yield* Ref.set(awaitingCompletion, false);
668 yield* SubscriptionRef.updateSome(state, (current) =>
669 Option.isSome(current.data) &&
670 current.status !== "deleted" &&
671 current.status !== "live" &&
672 Option.isNone(current.error)
673 ? Option.some({ ...current, status: "live" as const })
674 : Option.none(),
675 );
676 return;
677 }
678​
679 if (item.kind === "snapshot") {
680 yield* Ref.set(forceSnapshot, false);
681 yield* SubscriptionRef.set(lastSequence, item.snapshotSequence);
682 const hasProgressiveHistory =
683 item.historyCursor !== undefined ||
684 item.hasMoreHistory !== undefined ||
685 item.latestLocalTurnOrdinal !== undefined;
686 yield* setThread(
687 boundedSnapshotProjection(item),
688 hasProgressiveHistory
689 ? {
690 history: {
691 historyCursor: item.historyCursor ?? null,
692 hasMoreHistory: item.hasMoreHistory ?? false,
693 loading: false,
694 error: null,
695 expanded: false,
696 latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null,
697 },
698 }
699 : { resetHistory: true },
700 );
701 return;
702 }
703​
704 yield* applyEventsLocked([item]);
705 });
706​
707 // Items held until the completion marker apply together, so a replay-only resume renders once.
708 // A new attempt drops the previous attempt's held and late items (unapplied, so its cursor
709 // replays them). Both run under applyLock: each batch lands wholly before or after an attempt.
710 let attempt: unknown;
711 let catchUp: OrchestrationV2ThreadStreamItem[] = [];
712 const startAttempt = applyLock.withPermits(1)(
713 Effect.sync(() => {
714 attempt = undefined;
715 catchUp = [];
716 }),
717 );
718 // Keep this per-batch streaming path untraced for the same reason as applyEventsLocked.
719 const receiveItems = Effect.fnUntraced(function* (
720 received: ReadonlyArray<readonly [input: unknown, item: OrchestrationV2ThreadStreamItem]>,
721 ) {
722 yield* applyLock.withPermits(1)(
723 Effect.gen(function* () {
724 let completes = false;
725 for (const [input, item] of received) {
726 if (input !== attempt) continue;
727 catchUp.push(item);
728 if (item.kind === "synchronized") completes = true;
729 }
730 if (catchUp.length === 0) return;
731 if (!completes && (yield* Ref.get(awaitingCompletion))) {
732 // A warm resume keeps its "live" status until it learns it is behind.
733 yield* SubscriptionRef.updateSome(state, (current) =>
734 current.status === "live"
735 ? Option.some({ ...current, status: "synchronizing" as const })
736 : Option.none(),
737 );
738 return;
739 }
740 const items = catchUp;
741 catchUp = [];
742 let events: SequencedItem[] = [];
743 for (const item of items) {
744 if (
745 item.kind === "unknown-event" ||
746 (item.kind === "event" && item.event.type !== "thread.deleted")
747 ) {
748 events.push(item);
749 continue;
750 }
751 // Clearing the flag first lets the events before the marker publish
752 // "live", so a catch-up ending in the marker is one state change.
753 if (item.kind === "synchronized") yield* Ref.set(awaitingCompletion, false);
754 yield* applyEventsLocked(events);
755 events = [];
756 yield* applyItemLocked(item);
757 }
758 yield* applyEventsLocked(events);
759 yield* remember;
760 }),
761 );
762 });
763​
764 const loadEarlier = Effect.fn("EnvironmentThreadState.loadEarlier")(function* (
765 throughEntryId?: string,
766 workAnchorId?: string,
767 ): Effect.fn.Return<ThreadHistoryController.ThreadHistoryLoadEarlierResult> {
768 const workCursor = (latest: EnvironmentThreadState) =>
769 Option.getOrNull(latest.data)?.visibleTurnItems.find(
770 (row) => row.sourceItemId === workAnchorId,
771 )?.item.deferredWork?.cursor ?? null;
772 const current = yield* SubscriptionRef.get(state);
773 const initialCursor =
774 workAnchorId === undefined ? current.history.historyCursor : workCursor(current);
775 if (
776 current.status === "deleted" ||
777 Option.isNone(current.data) ||
778 initialCursor === null ||
779 (workAnchorId === undefined && !current.history.hasMoreHistory)
780 )
781 return { _tag: "noop" };
782 if (workAnchorId === undefined && current.history.loading) return { _tag: "busy" };
783 let requestCursor = initialCursor;
784 const isCurrent = (latest: EnvironmentThreadState) =>
785 workAnchorId === undefined
786 ? isActiveHistoryRequestCursor(requestCursor, latest.history)
787 : workCursor(latest) === requestCursor;
788 const staleResult = (
789 latest: EnvironmentThreadState,
790 ): ThreadHistoryController.ThreadHistoryLoadEarlierResult =>
791 workAnchorId !== undefined && workCursor(latest) !== null
792 ? { _tag: "error", message: WORK_HISTORY_CHANGED_ERROR }
793 : { _tag: "noop" };
794 if (workAnchorId === undefined)
795 yield* patchHistoryMeta((history) =>
796 isActiveHistoryRequestCursor(requestCursor, history)
797 ? { ...history, loading: true, error: null }
798 : history,
799 );
800 const failLoad = (message: string) =>
801 SubscriptionRef.modify(
802 state,
803 (
804 latest,
805 ): readonly [
806 ThreadHistoryController.ThreadHistoryLoadEarlierResult,
807 EnvironmentThreadState,
808 ] =>
809 isCurrent(latest)
810 ? [
811 { _tag: "error", message },
812 {
813 ...latest,
814 history:
815 workAnchorId === undefined
816 ? { ...latest.history, loading: false, error: message }
817 : latest.history,
818 },
819 ]
820 : [staleResult(latest), latest],
821 );
822​
823 const runLoad = Effect.gen(function* () {
824 while (true) {
825 const preparedOption = yield* SubscriptionRef.get(supervisor.prepared);
826 if (Option.isNone(preparedOption) || Option.isNone(httpClient))
827 return yield* failLoad("Environment is not connected.");
828 const views =
829 workAnchorId !== undefined
830 ? ["work" as const]
831 : throughEntryId === undefined
832 ? [undefined]
833 : ["conversation" as const, undefined];
834 let nextCursor: string | null = null;
835 for (const view of views) {
836 const pageResult = yield* fetchEnvironmentThreadHistoryPage({
837 prepared: preparedOption.value,
838 threadId,
839 cursor: requestCursor,
840 throughEntryId: workAnchorId ?? throughEntryId,
841 view,
842 signer: dpopSigner,
843 remoteAuthorization,
844 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result);
845 if (Result.isFailure(pageResult))
846 return yield* failLoad(formatHistoryError(pageResult.failure));
847 const page = pageResult.success;
848 const complete = view !== "conversation";
849 const keepPaging =
850 complete &&
851 (workAnchorId !== undefined
852 ? page.nextCursor !== null
853 : throughEntryId === undefined &&
854 page.hasMoreHistory &&
855 !page.items.some(({ item }) => startsTurn(item)));
856 if (keepPaging && (page.nextCursor === null || page.nextCursor === requestCursor))
857 return yield* failLoad(
858 workAnchorId === undefined
859 ? "History did not advance."
860 : "Work history did not advance.",
861 );
862 const waiting = yield* Ref.get(awaitingCompletion);
863 const result = yield* applyLock.withPermits(1)(
864 SubscriptionRef.modify(
865 state,
866 (
867 latest,
868 ): readonly [
869 ThreadHistoryController.ThreadHistoryLoadEarlierResult,
870 EnvironmentThreadState,
871 ] => {
872 if (!isCurrent(latest)) return [staleResult(latest), latest];
873 if (Option.isNone(latest.data) || latest.status === "deleted")
874 return [{ _tag: "noop" }, { ...latest, history: EMPTY_THREAD_HISTORY_META }];
875 return [
876 { _tag: "loaded" },
877 {
878 ...latest,
879 data: Option.some(
880 mergeOlderSubagentsIntoProjection(
881 mergeOlderHistoryIntoProjection(
882 latest.data.value,
883 page.items,
884 workAnchorId === undefined
885 ? undefined
886 : { anchorId: workAnchorId, nextCursor: page.nextCursor },
887 ),
888 page.subagents,
889 ),
890 ),
891 status:
892 workAnchorId === undefined && complete && waiting
893 ? "synchronizing"
894 : latest.status,
895 history:
896 workAnchorId === undefined && complete
897 ? { ...applyHistoryPageMeta(latest.history, page), loading: keepPaging }
898 : { ...latest.history, expanded: true },
899 },
900 ];
901 },
902 ),
903 );
904 if (result._tag !== "loaded") return result;
905 if (complete) yield* applyLock.withPermits(1)(remember);
906 nextCursor = keepPaging ? page.nextCursor : null;
907 }
908 if (nextCursor === null) return { _tag: "loaded" } as const;
909 requestCursor = nextCursor;
910 }
911 });
912 return yield* runLoad.pipe(
913 Effect.onInterrupt(() =>
914 SubscriptionRef.update(state, (latest) => ({
915 ...latest,
916 history: clearActiveHistoryLoading(requestCursor, latest.history),
917 })),
918 ),
919 );
920 });
921​
922 // A cached item can stay running after the server finished it, and no event will ever
923 // name it again: it can sit outside every bounded window, and a repeated Stop records
924 // nothing new. Stop asks the server about each pending item instead of
925 // inferring status from what a snapshot omits, and settles only those items.
926 const reconcilePendingWork = Effect.fn("EnvironmentThreadState.reconcilePendingWork")(
927 function* () {
928 const current = yield* SubscriptionRef.get(state);
929 if (current.status === "deleted" || Option.isNone(current.data)) return;
930 const pending = pendingBackgroundTurnItems(current.data.value);
931 if (pending.length === 0) return;
932 const queried = new Set<string>(pending.map((item) => item.id));
933 const fetched = yield* Effect.forEach(
934 pending,
935 (item) =>
936 request(ORCHESTRATION_V2_WS_METHODS.getTurnItem, { threadId, itemId: item.id }).pipe(
937 Effect.timeout("10 seconds"),
938 Effect.map((result) => result.item),
939 Effect.orElseSucceed(() => null),
940 ),
941 { concurrency: 4 },
942 );
943 const settled = new Map(
944 fetched.flatMap((item) =>
945 item === null || isOrchestrationV2WorkActive(item.status) ? [] : [[item.id, item]],
946 ),
947 );
948 yield* applyLock.withPermits(1)(
949 Effect.gen(function* () {
950 const latest = yield* SubscriptionRef.get(state);
951 if (latest.status === "deleted" || Option.isNone(latest.data)) return;
952 const thread = settleTurnItems(threadId, latest.data.value, settled);
953 if (thread !== latest.data.value) {
954 yield* setThread(thread);
955 yield* remember;
956 }
957 // An expanded timeline is never saved, so reload would bring the stale row back.
958 // Repair the snapshot last handed to the cache instead, keeping its window and cursor.
959 // A resumed state skipped the cache load, so read the saved snapshot then.
960 if (shouldPersistThread(thread, latest.history)) return;
961 // A terminal event that landed during the lookup is newer than any reply, and the
962 // expanded live state never saves it, whatever the lookup returned.
963 const latestItems = new Map(settled);
964 for (const item of thread.turnItems) {
965 if (queried.has(item.id) && !isOrchestrationV2WorkActive(item.status)) {
966 latestItems.set(item.id, item);
967 }
968 }
969 if (latestItems.size === 0) return;
970 const saved =
971 queuedSnapshot ??
972 Option.getOrUndefined(
973 yield* cache
974 .loadThread(environmentId, threadId)
975 .pipe(Effect.orElseSucceed(() => Option.none())),
976 );
977 if (saved === undefined) return;
978 const projection = settleTurnItems(threadId, saved.projection, latestItems);
979 if (projection !== saved.projection) yield* queuePersist({ ...saved, projection });
980 }),
981 );
982 },
983 );
984​
985 if (Option.isSome(historyController)) {
986 const scope = yield* Scope.Scope;
987 const registration = yield* historyController.value.register(environmentId, threadId, {
988 loadEarlier: (throughEntryId, workAnchorId) =>
989 loadEarlier(throughEntryId, workAnchorId).pipe(
990 Effect.forkIn(scope),
991 Effect.flatMap(Fiber.join),
992 ),
993 reconcilePendingWork: () =>
994 reconcilePendingWork().pipe(
995 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
996 Effect.forkIn(scope),
997 Effect.flatMap(Fiber.join),
998 ),
999 });
1000 yield* Effect.addFinalizer(() => historyController.value.unregister(registration));
1002​
1003 yield* SubscriptionRef.changes(supervisor.state).pipe(
1004 Stream.runForEach((connectionState) => {
1005 switch (connectionProjectionPhase(connectionState)) {
1006 case "synchronizing":
1007 return setConnecting;
1008 case "disconnected":
1009 return setDisconnected;
1010 case "ready":
1011 return setReady;
1013 }),
1014 Effect.forkScoped,
1015 );
1016​
1017 const foregroundResubscriptions = Option.match(wakeups, {
1018 onNone: () => Stream.never,
1019 onSome: (service) =>
1020 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
1021 });
1022​
1023 // Only the first subscription after a warm live resume keeps the retained
1024 // status. A replacement session or foreground resubscribe on the same scope
1025 // may have missed events, so those show sync progress until confirmed.
1026 const resumingLive = yield* Ref.make(initialState.status === "live");
1027 // A cold open tries the socket snapshot once. Any later cold attempt, after a
1028 // failure or a dropped session, asks HTTP, which also tells a missing thread
1029 // apart from a failed load.
1030 const socketOpenTried = yield* Ref.make(false);
1031 const socketOnlyOpen = yield* Ref.make(false);
1032 const failedSocketOnlyOpen = Effect.gen(function* () {
1033 return (
1034 (yield* Ref.get(socketOnlyOpen)) && Option.isNone((yield* SubscriptionRef.get(state)).data)
1035 );
1036 });
1037 // A stream defect parks the subscription until something resubscribes it.
1038 const resubscribes = yield* Queue.unbounded<void>();
1039 // A resumed replay that dies (an event this client cannot decode) dies the same
1040 // way from the same cursor, so later attempts reload the full snapshot until one applies.
1041 const resuming = yield* Ref.make(false);
1042 const forceSnapshot = yield* Ref.make(false);
1043 const markSynchronizing = Effect.gen(function* () {
1044 if (yield* Ref.get(resumingLive)) return;
1045 yield* SubscriptionRef.update(state, (current) =>
1046 current.status === "deleted"
1047 ? current
1048 : { ...current, status: "synchronizing" as const, error: Option.none() },
1049 );
1050 });
1051​
1052 yield* markSynchronizing;
1053 // A 404 can arrive before the thread exists, so a miss asks HTTP again while mounted.
1054 let httpMisses = 0;
1055 let defectRetries = 0;
1056 const backOffAfterDefect = Effect.suspend(() => {
1057 const retryDelay = subscriptionRetryDelay(THREAD_SUBSCRIPTION_RETRY_DELAY, defectRetries);
1058 defectRetries += 1;
1059 return setStreamError(THREAD_SYNC_ERROR).pipe(Effect.andThen(Effect.sleep(retryDelay)));
1060 });
1061 const followThread = (): Effect.Effect<
1062 void,
1063 never,
1064 EnvironmentSupervisor.EnvironmentSupervisor
1065 > =>
1066 subscribeDynamicWithInput(
1067 ORCHESTRATION_V2_WS_METHODS.subscribeThread,
1068 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
1069 yield* startAttempt;
1070 let current = yield* SubscriptionRef.get(state);
1071 // A delete event already cleared this thread. Park without opening the socket.
1072 if (current.status === "deleted" && httpMisses === 0) {
1073 return yield* Effect.never;
1075​
1076 const config = yield* Effect.option(session.initialConfig);
1077 yield* Ref.set(awaitingCompletion, true);
1078 yield* markSynchronizing;
1079 yield* Ref.set(resumingLive, false);
1080​
1081 // A server that pages snapshots sends the same bounded window over the
1082 // socket, so a cold open can skip the HTTP round trip.
1083 const socketOnly =
1084 Option.isNone(current.data) &&
1085 canLoadHistory &&
1086 Option.exists(config, (value) => value.threadSnapshotPagination === true) &&
1087 !(yield* Ref.getAndSet(socketOpenTried, true));
1088 yield* Ref.set(socketOnlyOpen, socketOnly);
1089​
1090 if (Option.isNone(current.data) && !socketOnly) {
1091 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
1092 Effect.flatMap(
1093 Option.match({
1094 onSome: Effect.succeed,
1095 onNone: () =>
1096 SubscriptionRef.changes(supervisor.prepared).pipe(
1097 Stream.filter(Option.isSome),
1098 Stream.map((value) => value.value),
1099 Stream.runHead,
1100 Effect.map(Option.getOrThrow),
1101 ),
1102 }),
1103 ),
1104 );
1105 const httpResult: ThreadSnapshotLoader.ThreadSnapshotLoadResult =
1106 yield* snapshotLoader.load(prepared, threadId);
1107 switch (httpResult._tag) {
1108 case "present": {
1109 httpMisses = 0;
1110 if (canLoadHistory && httpResult.history !== undefined) {
1111 yield* Ref.set(acceptsBoundedSocketSnapshots, true);
1113 // Atomic projection + progressive meta so a settled bounded window
1114 // never persists as a complete full-timeline cache entry. Socket
1115 // snapshots still go through applyItem (resetHistory).
1116 yield* applyLock.withPermits(1)(
1117 Effect.gen(function* () {
1118 yield* SubscriptionRef.set(lastSequence, httpResult.snapshot.snapshotSequence);
1119 const history: ThreadHistoryMeta =
1120 httpResult.history !== undefined
1121 ? {
1122 historyCursor: httpResult.history.historyCursor,
1123 hasMoreHistory: httpResult.history.hasMoreHistory,
1124 loading: false,
1125 error: null,
1126 expanded: false,
1127 latestLocalTurnOrdinal: httpResult.history.latestLocalTurnOrdinal ?? null,
1129 : EMPTY_THREAD_HISTORY_META;
1130 yield* setThread(httpResult.snapshot.projection, { history });
1131 yield* remember;
1132 }),
1133 );
1134 current = yield* SubscriptionRef.get(state);
1135 break;
1137 case "missing": {
1138 if (current.status !== "deleted") yield* setDeleted();
1139 // A 404 also means "not created yet". Only a delete event may outlive this mount.
1140 if (resumeCache?.owner === owner) resumeCache.snapshot = undefined;
1141 yield* Effect.sleep(
1142 subscriptionRetryDelay(THREAD_SUBSCRIPTION_RETRY_DELAY, httpMisses++),
1143 );
1144 yield* Queue.offer(resubscribes, undefined);
1145 return yield* Effect.never;
1147 case "unavailable": {
1148 break;
1152​
1153 const sequence = yield* SubscriptionRef.get(lastSequence);
1154 const canResume = Option.isSome(current.data) && !(yield* Ref.get(forceSnapshot));
1155 yield* Ref.set(resuming, canResume);
1156 const acceptBoundedSnapshot = yield* Ref.get(acceptsBoundedSocketSnapshots);
1157​
1158 const input = {
1159 threadId,
1160 ...(canResume ? { afterSequence: sequence } : {}),
1161 requestCompletionMarker: true as const,
1162 ...(acceptBoundedSnapshot
1163 ? {
1164 acceptBoundedSnapshot: true as const,
1165 acceptDeferredWork: true as const,
1166 acceptCompactTurnItems: true as const,
1167 acceptCompactIds: true as const,
1169 : {}),
1170 acceptDedupedBodies: true as const,
1171 };
1172 attempt = input;
1173 return input;
1174 }),
1176 // A socket-only open that fails retries over HTTP, which tells a
1177 // missing thread apart from a failure, before showing an error.
1178 onDefect: Effect.fn("EnvironmentThreadState.onDefect")(function* (cause) {
1179 if (yield* failedSocketOnlyOpen) {
1180 yield* Ref.set(socketOnlyOpen, false);
1181 return yield* Queue.offer(resubscribes, undefined);
1183 if (!Cause.hasDies(cause)) {
1184 return yield* setStreamError(THREAD_SYNC_ERROR);
1186 yield* Ref.set(forceSnapshot, true);
1187 if (yield* Ref.getAndSet(resuming, false)) {
1188 return yield* Queue.offer(resubscribes, undefined);
1190 yield* backOffAfterDefect;
1191 yield* Queue.offer(resubscribes, undefined);
1192 }),
1193 onExpectedFailure: Effect.fn("EnvironmentThreadState.onExpectedFailure")(function* (cause) {
1194 const retryOverHttp = !isAuthorizationFailure(cause) && (yield* failedSocketOnlyOpen);
1195 if (!retryOverHttp) yield* setStreamError(formatThreadError(cause));
1196 }),
1197 retryExpectedFailureAfter: THREAD_SUBSCRIPTION_RETRY_DELAY,
1198 resubscribe: Stream.merge(foregroundResubscriptions, Stream.fromQueue(resubscribes)),
1199 },
1200 ).pipe(
1201 Stream.runForEachArray((items) =>
1202 receiveItems(items).pipe(
1203 Effect.andThen(
1204 Effect.sync(() => {
1205 defectRetries = 0;
1206 }),
1207 ),
1208 ),
1209 ),
1210 // A defect while applying items ends the stream; resubscribe for a fresh snapshot.
1211 Effect.catchCause((cause) =>
1212 Cause.hasInterrupts(cause)
1213 ? Effect.interrupt
1214 : Effect.logWarning("Thread subscription failed; resubscribing.", {
1215 cause: Cause.pretty(cause),
1216 environmentId,
1217 threadId,
1218 }).pipe(
1219 Effect.andThen(Ref.set(forceSnapshot, true)),
1220 Effect.andThen(backOffAfterDefect),
1221 Effect.andThen(Effect.suspend(followThread)),
1222 ),
1223 ),
1224 );
1225 yield* Effect.forkScoped(followThread());
1226​
1227 return state;
1228});
1229​
1230function threadStateChanges(
1231 environmentId: EnvironmentIdType,
1232 threadId: ThreadIdType,
1233 resumeCache?: ThreadResumeCache,
1234) {
1235 return followStreamInEnvironment(
1236 environmentId,
1237 Stream.unwrap(
1238 makeEnvironmentThreadState(threadId, resumeCache).pipe(Effect.map(SubscriptionRef.changes)),
1239 ),
1240 );
1242​
1243export function createEnvironmentThreadStateAtoms<R, E>(
1244 runtime: Atom.AtomRuntime<
1245 | EnvironmentRegistry.EnvironmentRegistry
1246 | Persistence.EnvironmentCacheStore
1247 | ThreadSnapshotLoader.ThreadSnapshotLoader
1248 | R,
1250 >,
1251) {
1252 // Cache definitions must outlive collectible live-atom definitions. The
1253 // registry retains these nodes without retaining environment or RPC scopes.
1254 const resumeFamily = Atom.family((key: string) =>
1255 Atom.make((): ThreadResumeCache => ({
1256 snapshot: undefined,
1257 owner: undefined,
1258 })).pipe(
1259 Atom.setIdleTTL(THREAD_SNAPSHOT_IDLE_TTL_MS),
1260 Atom.withLabel(`environment-thread-resume:${key}`),
1261 ),
1262 );
1263 const family = Atom.family((key: string) => {
1264 const { environmentId, threadId } = parseThreadKey(key);
1265 const resumeAtom = resumeFamily(key);
1266 return runtime
1267 .atom(
1268 (get) => {
1269 get.mount(resumeAtom);
1270 const resume = get.once(resumeAtom);
1271 const live = threadStateChanges(environmentId, threadId, resume);
1272 return resume.snapshot === undefined
1273 ? live
1274 : Stream.concat(Stream.succeed(cachedThreadState(resume.snapshot.state)), live);
1275 },
1277 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
1278 },
1280 .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state:${key}`));
1281 });
1282​
1283 return {
1284 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
1285 family(threadKey({ environmentId, threadId })),
1286 };
1288​
1289export * from "./archivedThreads.ts";
1290export * from "./checkpointDiff.ts";
1291export * as BoundedThreadSnapshotLoader from "./boundedThreadSnapshotHttp.ts";
1292export * as ThreadHistoryController from "./threadHistoryController.ts";
1293export type { ThreadHistoryLoadEarlierResult } from "./threadHistoryController.ts";
1294export * from "./threadHistoryMerge.ts";
1295export * from "./threadSnapshotHttp.ts";
1296export * from "./composerPathSearch.ts";
1297export * from "./threadCommands.ts";
1298export * from "./threadFeedback.ts";
1299export * from "./threadDetail.ts";
1300export * from "./threadFamilies.ts";
1301export * from "./olderSettledThreads.ts";
1302export * from "./threadShell.ts";
1303export * from "./threadState.ts";
1304export * from "./threadTagFilter.ts";