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

threads.ts

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