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

threads.ts

1,173 lines44.7 KB

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