Open History to see the last commit
1import {
2 ORCHESTRATION_V2_WS_METHODS,
3 type EnvironmentId as EnvironmentIdType,
4 type OrchestrationV2ThreadDetailSnapshot,
5 type OrchestrationV2ThreadProjection,
6 type OrchestrationV2ThreadStreamItem,
7 type ThreadId as ThreadIdType,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as Ref from "effect/Ref";
14import * as Result from "effect/Result";
15import * as Stream from "effect/Stream";
16import * as SubscriptionRef from "effect/SubscriptionRef";
17import { HttpClient } from "effect/unstable/http";
18import { Atom } from "effect/unstable/reactivity";
19
20import { EnvironmentRegistry } from "../connection/registry.ts";
21import { connectionProjectionPhase } from "../connection/model.ts";
22import { EnvironmentSupervisor } from "../connection/supervisor.ts";
23import * as ConnectionWakeups from "../connection/wakeups.ts";
24import { EnvironmentCacheStore } from "../platform/persistence.ts";
25import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
26import { subscribeDynamic } from "../rpc/client.ts";
27import { parseThreadKey, threadKey } from "./entities.ts";
28import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
29import { followStreamInEnvironment } from "./runtime.ts";
30import {
31 ThreadHistoryController,
32 type ThreadHistoryLoadEarlierResult,
33} from "./threadHistoryController.ts";
34import { fetchEnvironmentThreadHistoryPage } from "./threadHistoryHttp.ts";
35import {
36 applyHistoryPageMeta,
37 clearActiveHistoryLoading,
38 EMPTY_THREAD_HISTORY_META,
39 isActiveHistoryRequestCursor,
40 mergeOlderHistoryIntoProjection,
41 type ThreadHistoryMeta,
42} from "./threadHistoryMerge.ts";
43import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
44import { ThreadSnapshotLoader, type ThreadSnapshotLoadResult } from "./threadSnapshotHttp.ts";
45import {
46 EMPTY_ENVIRONMENT_THREAD_STATE,
47 type EnvironmentThreadState,
48 type EnvironmentThreadStatus,
49} from "./threadState.ts";
50
51function statusWithoutLiveData(
52 data: Option.Option<OrchestrationV2ThreadProjection>,
53): EnvironmentThreadStatus {
54 return Option.isSome(data) ? "cached" : "empty";
55}
56
57function formatThreadError(cause: Cause.Cause<unknown>): string {
58 const error = Cause.squash(cause);
59 return error instanceof Error && error.message.trim().length > 0
60 ? error.message
61 : "Could not synchronize the thread.";
62}
63
64function formatHistoryError(error: unknown): string {
65 if (error instanceof Error && error.message.trim().length > 0) {
66 return error.message;
67 }
68 return "Could not load earlier activity.";
69}
70
71function historyMetaFromCachedSnapshot(
72 snapshot: OrchestrationV2ThreadDetailSnapshot,
73): ThreadHistoryMeta {
74 const historyCursor = snapshot.historyCursor ?? null;
75 const hasMoreHistory = snapshot.hasMoreHistory ?? false;
76 return {
77 historyCursor,
78 hasMoreHistory,
79 loading: false,
80 error: null,
81 // Cache never stores expanded progressive history (load-earlier growth).
82 expanded: false,
83 latestLocalTurnOrdinal: snapshot.latestLocalTurnOrdinal ?? null,
84 };
85}
86
87function snapshotToPersist(
88 snapshotSequence: number,
89 projection: OrchestrationV2ThreadProjection,
90 history: ThreadHistoryMeta,
91): OrchestrationV2ThreadDetailSnapshot {
92 // Persist progressive meta with the bounded window so warm resume restores the
93 // history cursor instead of looking like a complete full-projection cache hit.
94 if (history.hasMoreHistory || history.historyCursor !== null) {
95 return {
96 snapshotSequence,
97 projection,
98 historyCursor: history.historyCursor,
99 hasMoreHistory: history.hasMoreHistory,
100 latestLocalTurnOrdinal: history.latestLocalTurnOrdinal,
101 };
102 }
103 return { snapshotSequence, projection };
104}
105
106function shouldPersistThread(
107 thread: OrchestrationV2ThreadProjection,
108 history: ThreadHistoryMeta,
109): boolean {
110 // After the user loads older pages the in-memory timeline can grow large.
111 // Keep those expanded projections out of the monolithic cache.
112 if (history.expanded) {
113 return false;
114 }
115 return !thread.runs.some(
116 (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
117 );
118}
119
120export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
121 threadId: ThreadIdType,
122) {
123 const supervisor = yield* EnvironmentSupervisor;
124 const cache = yield* EnvironmentCacheStore;
125 const snapshotLoader = yield* ThreadSnapshotLoader;
126 const historyController = yield* Effect.serviceOption(ThreadHistoryController);
127 const httpClient = yield* Effect.serviceOption(HttpClient.HttpClient);
128 const dpopSigner = yield* Effect.serviceOption(ManagedRelayDpopSigner);
129 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
130 const environmentId = supervisor.target.environmentId;
131 const cached = yield* cache.loadThread(environmentId, threadId).pipe(
132 Effect.catch((error) =>
133 Effect.logWarning("Could not load cached thread.").pipe(
134 Effect.annotateLogs({
135 environmentId,
136 threadId,
137 error: error.message,
138 }),
139 Effect.as(Option.none<OrchestrationV2ThreadDetailSnapshot>()),
140 ),
141 ),
142 );
143 const cachedThread = Option.map(cached, (snapshot) => snapshot.projection);
144 const cachedHistory = Option.match(cached, {
145 onNone: () => EMPTY_THREAD_HISTORY_META,
146 onSome: historyMetaFromCachedSnapshot,
147 });
148 const state = yield* SubscriptionRef.make<EnvironmentThreadState>({
149 data: cachedThread,
150 status: statusWithoutLiveData(cachedThread),
151 error: Option.none(),
152 history: cachedHistory,
153 });
154 // Seed the resume cursor from the cached snapshot so a warm cache can catch up
155 // via `afterSequence` instead of re-downloading the full thread body.
156 const lastSequence = yield* SubscriptionRef.make(
157 Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence }),
158 );
159 const awaitingCompletion = yield* Ref.make(false);
160 const persistence = yield* Queue.sliding<OrchestrationV2ThreadDetailSnapshot>(1);
161
162 const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
163 snapshot: OrchestrationV2ThreadDetailSnapshot,
164 ) {
165 yield* cache.saveThread(environmentId, snapshot).pipe(
166 Effect.catch((error) =>
167 Effect.logWarning("Could not persist the thread cache.").pipe(
168 Effect.annotateLogs({
169 environmentId,
170 threadId,
171 error: error.message,
172 }),
173 ),
174 ),
175 );
176 });
177
178 yield* Stream.fromQueue(persistence).pipe(
179 Stream.debounce("500 millis"),
180 Stream.runForEach(persist),
181 Effect.forkScoped,
182 );
183
184 const setSynchronizing = SubscriptionRef.update(state, (current) =>
185 current.status === "deleted"
186 ? current
187 : {
188 ...current,
189 status: "synchronizing" as const,
190 error: Option.none(),
191 },
192 );
193 const setReady = SubscriptionRef.update(state, (current) =>
194 current.status === "live" || current.status === "deleted"
195 ? current
196 : {
197 ...current,
198 status: "synchronizing" as const,
199 error: Option.none(),
200 },
201 );
202 const setDisconnected = Effect.gen(function* () {
203 yield* Ref.set(awaitingCompletion, false);
204 yield* SubscriptionRef.update(state, (current) => ({
205 ...current,
206 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
207 }));
208 });
209 const setStreamError = (cause: Cause.Cause<unknown>) =>
210 Ref.set(awaitingCompletion, false).pipe(
211 Effect.andThen(
212 SubscriptionRef.update(state, (current) => ({
213 ...current,
214 status:
215 current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
216 error: Option.some(formatThreadError(cause)),
217 })),
218 ),
219 );
220
221 const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
222 thread: OrchestrationV2ThreadProjection,
223 options?: {
224 /** Socket/full snapshots: drop progressive meta with the new timeline. */
225 readonly resetHistory?: boolean;
226 /**
227 * Explicit progressive meta installed atomically with the projection
228 * (bounded HTTP). Wins over resetHistory when both are supplied.
229 */
230 readonly history?: ThreadHistoryMeta;
231 },
232 ) {
233 const waiting = yield* Ref.get(awaitingCompletion);
234 // Atomic with concurrent history meta updates: never get-then-set the whole
235 // state when only the projection changes. Bounded installs pass history so
236 // projection + cursor persist together in one enqueue.
237 const next = yield* SubscriptionRef.updateAndGet(state, (previous) => {
238 const history =
239 options?.history !== undefined
240 ? options.history
241 : options?.resetHistory === true
242 ? EMPTY_THREAD_HISTORY_META
243 : previous.history;
244 return {
245 ...previous,
246 data: Option.some(thread),
247 status: waiting ? ("synchronizing" as const) : ("live" as const),
248 error: Option.none(),
249 history,
250 };
251 });
252 // Active projections can update many times per second and retain large tool
253 // payloads. Persist once the run settles so cache encoding stays off the
254 // streaming path. Progressive meta rides along when the window is incomplete.
255 if (shouldPersistThread(thread, next.history)) {
256 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
257 yield* Queue.offer(persistence, snapshotToPersist(snapshotSequence, thread, next.history));
258 }
259 });
260
261 const patchHistoryMeta = (patch: (history: ThreadHistoryMeta) => ThreadHistoryMeta) =>
262 SubscriptionRef.update(state, (current) => ({
263 ...current,
264 history: patch(current.history),
265 }));
266
267 const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
268 yield* Ref.set(awaitingCompletion, false);
269 yield* SubscriptionRef.set(state, {
270 data: Option.none(),
271 status: "deleted",
272 error: Option.none(),
273 history: EMPTY_THREAD_HISTORY_META,
274 });
275 yield* cache.removeThread(environmentId, threadId).pipe(
276 Effect.catch((error) =>
277 Effect.logWarning("Could not remove the cached thread.").pipe(
278 Effect.annotateLogs({
279 environmentId,
280 threadId,
281 error: error.message,
282 }),
283 ),
284 ),
285 );
286 });
287
288 const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* (
289 item: OrchestrationV2ThreadStreamItem,
290 ) {
291 if (item.kind === "synchronized") {
292 yield* Ref.set(awaitingCompletion, false);
293 yield* SubscriptionRef.update(state, (current) =>
294 Option.isSome(current.data) && current.status !== "deleted"
295 ? { ...current, status: "live" as const, error: Option.none() }
296 : current,
297 );
298 return;
299 }
300
301 if (item.kind === "snapshot") {
302 yield* SubscriptionRef.set(lastSequence, item.snapshotSequence);
303 // True socket/full snapshots replace the full timeline; progressive cursor
304 // state from a prior bounded window must not stick around. Bounded HTTP
305 // installs call setThread with explicit history and never route here.
306 yield* setThread(item.projection, { resetHistory: true });
307 return;
308 }
309
310 const sequence = yield* SubscriptionRef.get(lastSequence);
311 if (item.sequence <= sequence) {
312 return;
313 }
314 yield* SubscriptionRef.set(lastSequence, item.sequence);
315
316 const waiting = yield* Ref.get(awaitingCompletion);
317 // Apply against the latest projection/history in one update so a concurrent
318 // loadEarlier merge (or history-meta patch) cannot be clobbered by a stale
319 // get-then-set rebuild.
320 type EventApplyResult =
321 | { readonly _tag: "noop" }
322 | { readonly _tag: "delete" }
323 | {
324 readonly _tag: "applied";
325 readonly projection: OrchestrationV2ThreadProjection;
326 readonly history: ThreadHistoryMeta;
327 };
328
329 const result = yield* SubscriptionRef.modify(
330 state,
331 (current): readonly [EventApplyResult, EnvironmentThreadState] => {
332 if (current.status === "deleted") {
333 return [{ _tag: "noop" }, current];
334 }
335 if (Option.isNone(current.data)) {
336 return [
337 item.event.type === "thread.deleted" ? { _tag: "delete" } : { _tag: "noop" },
338 current,
339 ];
340 }
341 if (item.event.type === "thread.deleted") {
342 return [{ _tag: "delete" }, current];
343 }
344
345 // Incomplete progressive windows only (hasMore or open cursor). Do not
346 // use expanded: it remains true after the last page as a cache marker.
347 // Full/web and fully-loaded timelines keep default append-on-miss.
348 const partial =
349 current.history.hasMoreHistory || current.history.historyCursor !== null
350 ? {
351 partialTimeline: true as const,
352 latestLocalTurnOrdinal: current.history.latestLocalTurnOrdinal,
353 }
354 : undefined;
355 const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event, partial);
356 // True no-op when the reducer deliberately returns the current projection
357 // reference (e.g. dropped old partial-timeline turn-item). Do not clear
358 // stream error/status or enqueue persistence.
359 if (next === null || next === current.data.value) {
360 return [{ _tag: "noop" }, current];
361 }
362
363 let history = current.history;
364 if (partial !== undefined && item.event.type === "turn-item.updated") {
365 const ordinal = item.event.payload.ordinal;
366 const watermark = history.latestLocalTurnOrdinal;
367 if (watermark === null || ordinal > watermark) {
368 history = { ...history, latestLocalTurnOrdinal: ordinal };
369 }
370 }
371
372 const updated: EnvironmentThreadState = {
373 ...current,
374 data: Option.some(next),
375 status: waiting ? "synchronizing" : "live",
376 error: Option.none(),
377 history,
378 };
379 return [{ _tag: "applied", projection: next, history: updated.history }, updated];
380 },
381 );
382
383 if (result._tag === "delete") {
384 yield* setDeleted();
385 return;
386 }
387 if (result._tag === "applied" && shouldPersistThread(result.projection, result.history)) {
388 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
389 yield* Queue.offer(
390 persistence,
391 snapshotToPersist(snapshotSequence, result.projection, result.history),
392 );
393 }
394 });
395
396 const loadEarlier = Effect.fn("EnvironmentThreadState.loadEarlier")(function* () {
397 const current = yield* SubscriptionRef.get(state);
398 if (
399 current.status === "deleted" ||
400 Option.isNone(current.data) ||
401 !current.history.hasMoreHistory ||
402 current.history.historyCursor === null
403 ) {
404 return { _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult;
405 }
406 if (current.history.loading) {
407 return { _tag: "busy" } satisfies ThreadHistoryLoadEarlierResult;
408 }
409
410 // Capture the cursor that initiated this request. Completions/failures must
411 // no-op if a socket or new bounded snapshot replaced progressive meta mid-flight.
412 const requestCursor = current.history.historyCursor;
413 yield* patchHistoryMeta((history) =>
414 isActiveHistoryRequestCursor(requestCursor, history)
415 ? { ...history, loading: true, error: null }
416 : history,
417 );
418
419 const runLoad = Effect.gen(function* () {
420 const preparedOption = yield* SubscriptionRef.get(supervisor.prepared);
421 if (Option.isNone(preparedOption) || Option.isNone(httpClient)) {
422 const message = "Environment is not connected.";
423 const stillCurrent = yield* SubscriptionRef.modify(
424 state,
425 (latest): readonly [boolean, EnvironmentThreadState] => {
426 if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) {
427 return [false, latest];
428 }
429 return [
430 true,
431 {
432 ...latest,
433 history: { ...latest.history, loading: false, error: message },
434 },
435 ];
436 },
437 );
438 if (!stillCurrent) {
439 return { _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult;
440 }
441 return {
442 _tag: "error",
443 message,
444 } satisfies ThreadHistoryLoadEarlierResult;
445 }
446
447 const pageResult = yield* fetchEnvironmentThreadHistoryPage({
448 prepared: preparedOption.value,
449 threadId,
450 cursor: requestCursor,
451 signer: dpopSigner,
452 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result);
453
454 if (Result.isFailure(pageResult)) {
455 const message = formatHistoryError(pageResult.failure);
456 // Only mark error when this request's cursor is still active. Leave
457 // stream/status/error alone so concurrent live updates stay intact.
458 const stillCurrent = yield* SubscriptionRef.modify(
459 state,
460 (latest): readonly [boolean, EnvironmentThreadState] => {
461 if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) {
462 return [false, latest];
463 }
464 return [
465 true,
466 {
467 ...latest,
468 history: { ...latest.history, loading: false, error: message },
469 },
470 ];
471 },
472 );
473 if (!stillCurrent) {
474 return { _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult;
475 }
476 return { _tag: "error", message } satisfies ThreadHistoryLoadEarlierResult;
477 }
478
479 const page = pageResult.success;
480 const waiting = yield* Ref.get(awaitingCompletion);
481 // Single atomic merge against whatever is current after the await so a
482 // concurrent applyItem cannot be clobbered by a stale get/set pair.
483 return yield* SubscriptionRef.modify(
484 state,
485 (latest): readonly [ThreadHistoryLoadEarlierResult, EnvironmentThreadState] => {
486 // Stale page: socket/full snapshot or newer bounded install changed the
487 // progressive cursor while this request was in flight. Never mutate the
488 // replacement meta (including deleted/empty installs).
489 if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) {
490 return [{ _tag: "noop" }, latest];
491 }
492 if (Option.isNone(latest.data) || latest.status === "deleted") {
493 return [
494 { _tag: "noop" },
495 {
496 ...latest,
497 history: EMPTY_THREAD_HISTORY_META,
498 },
499 ];
500 }
501
502 const merged = mergeOlderHistoryIntoProjection(latest.data.value, page.items);
503 const history = applyHistoryPageMeta(latest.history, page);
504 return [
505 { _tag: "loaded" },
506 {
507 ...latest,
508 data: Option.some(merged),
509 status: waiting
510 ? ("synchronizing" as const)
511 : latest.status === "live"
512 ? ("live" as const)
513 : latest.status,
514 history,
515 },
516 ];
517 },
518 );
519 });
520
521 // On Effect interruption only: clear loading when this request cursor is
522 // still active. Never mutate stream status/error from the interrupt path.
523 return yield* runLoad.pipe(
524 Effect.onInterrupt(() =>
525 SubscriptionRef.update(state, (latest) => ({
526 ...latest,
527 history: clearActiveHistoryLoading(requestCursor, latest.history),
528 })),
529 ),
530 );
531 });
532
533 if (Option.isSome(historyController)) {
534 const registration = yield* historyController.value.register(environmentId, threadId, {
535 loadEarlier: () => loadEarlier(),
536 });
537 yield* Effect.addFinalizer(() => historyController.value.unregister(registration));
538 }
539
540 yield* SubscriptionRef.changes(supervisor.state).pipe(
541 Stream.runForEach((connectionState) => {
542 switch (connectionProjectionPhase(connectionState)) {
543 case "synchronizing":
544 return setSynchronizing;
545 case "disconnected":
546 return setDisconnected;
547 case "ready":
548 return setReady;
549 }
550 }),
551 Effect.forkScoped,
552 );
553
554 const foregroundResubscriptions = Option.match(wakeups, {
555 onNone: () => Stream.never,
556 onSome: (service) =>
557 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
558 });
559
560 yield* setSynchronizing;
561 yield* Effect.forkScoped(
562 subscribeDynamic(
563 ORCHESTRATION_V2_WS_METHODS.subscribeThread,
564 Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) {
565 let current = yield* SubscriptionRef.get(state);
566 // A prior definitive miss (or delete event) already cleared this thread.
567 // Park the subscription attempt without opening the socket so we do not
568 // retry forever against a known-missing id.
569 if (current.status === "deleted") {
570 return yield* Effect.never;
571 }
572
573 const supportsCompletionMarker = yield* session.initialConfig.pipe(
574 Effect.map((config) => config.threadResumeCompletionMarker === true),
575 Effect.orElseSucceed(() => false),
576 );
577 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
578 yield* setSynchronizing;
579
580 if (Option.isNone(current.data)) {
581 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
582 Effect.flatMap(
583 Option.match({
584 onSome: Effect.succeed,
585 onNone: () =>
586 SubscriptionRef.changes(supervisor.prepared).pipe(
587 Stream.filter(Option.isSome),
588 Stream.map((value) => value.value),
589 Stream.runHead,
590 Effect.map(Option.getOrThrow),
591 ),
592 }),
593 ),
594 );
595 const httpResult: ThreadSnapshotLoadResult = yield* snapshotLoader.load(
596 prepared,
597 threadId,
598 );
599 switch (httpResult._tag) {
600 case "present": {
601 // Atomic projection + progressive meta so a settled bounded window
602 // never persists as a complete full-timeline cache entry. Socket
603 // snapshots still go through applyItem (resetHistory).
604 yield* SubscriptionRef.set(lastSequence, httpResult.snapshot.snapshotSequence);
605 const history: ThreadHistoryMeta =
606 httpResult.history !== undefined
607 ? {
608 historyCursor: httpResult.history.historyCursor,
609 hasMoreHistory: httpResult.history.hasMoreHistory,
610 loading: false,
611 error: null,
612 expanded: false,
613 latestLocalTurnOrdinal: httpResult.history.latestLocalTurnOrdinal ?? null,
614 }
615 : EMPTY_THREAD_HISTORY_META;
616 yield* setThread(httpResult.snapshot.projection, { history });
617 current = yield* SubscriptionRef.get(state);
618 break;
619 }
620 case "missing": {
621 // Definitive HTTP 404: clear any stale cache and do not open or
622 // retry a socket subscription for this attempt.
623 yield* setDeleted();
624 return yield* Effect.never;
625 }
626 case "unavailable": {
627 // Transient HTTP failure: fall through to the socket path.
628 break;
629 }
630 }
631 }
632
633 const sequence = yield* SubscriptionRef.get(lastSequence);
634 const canResume = Option.isSome(current.data);
635 if (!supportsCompletionMarker && canResume) {
636 yield* SubscriptionRef.update(state, (value) => ({
637 ...value,
638 status: value.status === "deleted" ? value.status : ("live" as const),
639 error: Option.none(),
640 }));
641 }
642
643 return {
644 threadId,
645 ...(canResume ? { afterSequence: sequence } : {}),
646 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
647 };
648 }),
649 {
650 onExpectedFailure: setStreamError,
651 retryExpectedFailureAfter: "250 millis",
652 resubscribe: foregroundResubscriptions,
653 },
654 ).pipe(Stream.runForEach(applyItem)),
655 );
656
657 yield* Effect.addFinalizer(() =>
658 Effect.all([SubscriptionRef.get(state), SubscriptionRef.get(lastSequence)]).pipe(
659 Effect.flatMap(([current, snapshotSequence]) =>
660 Option.match(current.data, {
661 onNone: () => Effect.void,
662 onSome: (projection) =>
663 shouldPersistThread(projection, current.history)
664 ? persist(snapshotToPersist(snapshotSequence, projection, current.history))
665 : Effect.void,
666 }),
667 ),
668 ),
669 );
670
671 return state;
672});
673
674export function threadStateChanges(environmentId: EnvironmentIdType, threadId: ThreadIdType) {
675 return followStreamInEnvironment(
676 environmentId,
677 Stream.unwrap(makeEnvironmentThreadState(threadId).pipe(Effect.map(SubscriptionRef.changes))),
678 );
679}
680
681export function createEnvironmentThreadStateAtoms<R, E>(
682 runtime: Atom.AtomRuntime<
683 EnvironmentRegistry | EnvironmentCacheStore | ThreadSnapshotLoader | R,
684 E
685 >,
686) {
687 const family = Atom.family((key: string) => {
688 const { environmentId, threadId } = parseThreadKey(key);
689 return runtime
690 .atom(threadStateChanges(environmentId, threadId), {
691 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
692 })
693 .pipe(
694 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
695 Atom.withLabel(`environment-thread-state:${key}`),
696 );
697 });
698
699 return {
700 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
701 family(threadKey({ environmentId, threadId })),
702 };
703}
704
705export * from "./archivedThreads.ts";
706export * from "./checkpointDiff.ts";
707export * from "./boundedThreadSnapshotHttp.ts";
708export * from "./threadHistoryController.ts";
709export * from "./threadHistoryMerge.ts";
710export * from "./threadSnapshotHttp.ts";
711export * from "./composerPathSearch.ts";
712export * from "./threadCommands.ts";
713export * from "./threadFeedback.ts";
714export * from "./threadDetail.ts";
715export * from "./threadShell.ts";
716export * from "./threadState.ts";