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

threads.ts

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