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

threads.ts

1,380 lines52.8 KB

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