Open History to see the last commit
1import type { OrchestrationThreadDetailSnapshot, ThreadId } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import { HttpClient } from "effect/unstable/http";
8
9import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
10import type { PreparedConnection } from "../connection/model.ts";
11import { environmentEndpointUrl } from "../environment/endpoint.ts";
12import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
13import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
14import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
15
16// Bounded so a pathologically slow endpoint cannot block the (cheaper) socket
17// fallback for long. The cached thread renders while this runs, so the wait only
18// delays the transition to live data on the first open, not the initial paint.
19const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 6_000;
20
21/**
22 * Load a thread's detail snapshot over HTTP instead of embedding it in the
23 * WebSocket subscription's first frame. The response is gzip-compressible by
24 * the transport and keeps the (potentially multi-KB) snapshot off the socket.
25 */
26/**
27 * Optional turn window for a snapshot fetch. Only send a window to servers
28 * that advertise `threadSnapshotPagination`; older servers reject unknown
29 * query parameters.
30 */
31export interface ThreadSnapshotWindow {
32 readonly turnLimit: number;
33 readonly beforeCursor?: string;
34}
35
36export const fetchEnvironmentThreadSnapshot = Effect.fn(
37 "clientRuntime.state.fetchEnvironmentThreadSnapshot",
38)(function* (input: {
39 readonly prepared: PreparedConnection;
40 readonly threadId: ThreadId;
41 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
42 readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
43 readonly timeoutMs?: number;
44 readonly window?: ThreadSnapshotWindow;
45}) {
46 return yield* executeAuthenticatedEnvironmentHttpRequest({
47 ...input,
48 method: "GET",
49 url: (httpBaseUrl) =>
50 environmentEndpointUrl(httpBaseUrl, `/api/orchestration/threads/${input.threadId}`),
51 timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
52 request: ({ client, headers }) =>
53 client.orchestration.threadSnapshot({
54 params: { threadId: input.threadId },
55 payload: {
56 ...(input.window !== undefined ? { turnLimit: input.window.turnLimit } : {}),
57 ...(input.window?.beforeCursor !== undefined
58 ? { beforeCursor: input.window.beforeCursor }
59 : {}),
60 },
61 headers,
62 }),
63 });
64});
65
66export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
67
68/**
69 * Loads a thread's detail snapshot over HTTP, returning `Option.none()` when it
70 * cannot be loaded (so the caller falls back to the socket-embedded snapshot).
71 * Decouples the thread state machine from the underlying HTTP + DPoP details and
72 * keeps them out of test contexts.
73 */
74export class ThreadSnapshotLoader extends Context.Service<
75 ThreadSnapshotLoader,
76 {
77 readonly load: (
78 prepared: PreparedConnection,
79 threadId: ThreadId,
80 window?: ThreadSnapshotWindow,
81 ) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;
82 }
83>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
84
85export const threadSnapshotLoaderLayer: Layer.Layer<
86 ThreadSnapshotLoader,
87 never,
88 HttpClient.HttpClient
89> = Layer.effect(
90 ThreadSnapshotLoader,
91 Effect.gen(function* () {
92 const httpClient = yield* HttpClient.HttpClient;
93 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
94 // connections, so the loader must not hard-require it (bearer/primary
95 // connections work without one).
96 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
97 const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
98 return ThreadSnapshotLoader.of({
99 load: (prepared: PreparedConnection, threadId: ThreadId, window?: ThreadSnapshotWindow) =>
100 fetchEnvironmentThreadSnapshot({
101 prepared,
102 threadId,
103 signer,
104 remoteAuthorization,
105 ...(window !== undefined ? { window } : {}),
106 }).pipe(
107 Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),
108 Effect.provideService(HttpClient.HttpClient, httpClient),
109 // A genuinely missing thread (404) is expected — the socket
110 // subscription is the source of truth for thread existence and will
111 // surface the deletion — so don't treat it as an error worth warning
112 // about; just defer to the socket path.
113 Effect.catchTags({
114 EnvironmentResourceNotFoundError: () =>
115 Effect.logDebug(
116 "Thread snapshot not found over HTTP; deferring to the socket subscription.",
117 ).pipe(
118 Effect.annotateLogs({ threadId }),
119 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
120 ),
121 }),
122 Effect.catchCause((cause) =>
123 Effect.logWarning(
124 "Could not load the thread snapshot over HTTP; using the socket snapshot instead.",
125 ).pipe(
126 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
127 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
128 ),
129 ),
130 ),
131 });
132 }),
133);