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

threads.ts

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