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