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

threads.ts

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