Open History to see the last commit
1import { ThreadId } from "@t3tools/contracts";
2import { describe, expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5
6import { PrimaryConnectionTarget, type PreparedConnection } from "../connection/model.ts";
7import * as RpcHttp from "../rpc/http.ts";
8import * as BoundedThreadSnapshotHttp from "./boundedThreadSnapshotHttp.ts";
9import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
10
11const TARGET = new PrimaryConnectionTarget({
12 environmentId: "environment-bounded" as never,
13 label: "Bounded",
14 httpBaseUrl: "https://environment.example.test",
15 wsBaseUrl: "wss://environment.example.test",
16});
17
18const PREPARED: PreparedConnection = {
19 environmentId: TARGET.environmentId,
20 label: TARGET.label,
21 httpBaseUrl: TARGET.httpBaseUrl,
22 socketUrl: TARGET.wsBaseUrl,
23 httpAuthorization: null,
24 target: TARGET,
25};
26
27const THREAD_ID = ThreadId.make("thread-bounded");
28const NOW = "2026-06-20T00:00:00.000Z";
29
30const FULL_SNAPSHOT_BODY = {
31 snapshotSequence: 9,
32 projection: {
33 thread: {
34 createdBy: "user",
35 creationSource: "web",
36 id: String(THREAD_ID),
37 projectId: "project-1",
38 title: "Full fallback thread",
39 providerInstanceId: "codex",
40 modelSelection: { instanceId: "codex", model: "gpt-5" },
41 runtimeMode: "full-access",
42 interactionMode: "default",
43 branch: null,
44 worktreePath: null,
45 activeProviderThreadId: null,
46 lineage: {
47 parentThreadId: null,
48 relationshipToParent: null,
49 rootThreadId: String(THREAD_ID),
50 },
51 forkedFrom: null,
52 createdAt: NOW,
53 updatedAt: NOW,
54 archivedAt: null,
55 deletedAt: null,
56 settledOverride: null,
57 settledAt: null,
58 },
59 runs: [],
60 attempts: [],
61 nodes: [],
62 subagents: [],
63 providerSessions: [],
64 providerThreads: [],
65 providerTurns: [],
66 runtimeRequests: [],
67 messages: [],
68 plans: [],
69 turnItems: [],
70 checkpointScopes: [],
71 checkpoints: [],
72 contextHandoffs: [],
73 contextTransfers: [],
74 visibleTurnItems: [],
75 updatedAt: NOW,
76 },
77};
78
79const AT = "2026-06-20T00:00:00.000Z";
80const command = (id: string, ordinal: number) => ({
81 id,
82 type: "command_execution",
83 threadId: String(THREAD_ID),
84 runId: null,
85 nodeId: null,
86 providerThreadId: null,
87 providerTurnId: null,
88 nativeItemRef: null,
89 parentItemId: null,
90 ordinal,
91 status: "completed",
92 title: null,
93 input: id,
94 exitCode: 0,
95 startedAt: AT,
96 completedAt: AT,
97 updatedAt: AT,
98});
99const LOCAL_ITEMS = [command("local-1", 1), command("local-2", 2)];
100const DEPENDENCY = command("older-dependency", 0);
101const VISIBLE = LOCAL_ITEMS.map((item, position) => ({
102 position,
103 visibility: "local",
104 sourceThreadId: String(THREAD_ID),
105 sourceItemId: item.id,
106 item,
107}));
108const boundedBody = (compact: boolean) => ({
109 snapshotSequence: 12,
110 projection: {
111 ...FULL_SNAPSHOT_BODY.projection,
112 turnItems: compact ? [DEPENDENCY] : [...LOCAL_ITEMS, DEPENDENCY],
113 visibleTurnItems: VISIBLE,
114 },
115 historyCursor: "bounded-cursor",
116 hasMoreHistory: true,
117 latestLocalTurnOrdinal: 2,
118 payloadBudgetExceeded: false,
119 ...(compact ? { turnItemsOmitLocalVisible: true } : {}),
120});
121
122describe("boundedThreadSnapshotLoader", () => {
123 it.effect.each([
124 ["an older server that ignores the opt-in", false],
125 ["a server that sends compact turnItems", true],
126 ] as const)("requests compact turnItems and loads %s", ([, compact]) => {
127 const urls: string[] = [];
128 const fetchFn = ((input: RequestInfo | URL) => {
129 urls.push(String(input));
130 return Promise.resolve(Response.json(boundedBody(compact)));
131 }) satisfies typeof fetch;
132
133 return Effect.gen(function* () {
134 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
135 const result = yield* loader.load(PREPARED, THREAD_ID);
136 expect(new URL(urls[0]!).searchParams.get("compactTurnItems")).toBe("1");
137 expect(result._tag).toBe("present");
138 if (result._tag !== "present") return;
139 expect(result.snapshot.projection.turnItems.map((item) => String(item.id))).toEqual([
140 "local-1",
141 "local-2",
142 "older-dependency",
143 ]);
144 expect("turnItemsOmitLocalVisible" in result.snapshot).toBe(false);
145 expect(result.history).toEqual({
146 historyCursor: "bounded-cursor",
147 hasMoreHistory: true,
148 latestLocalTurnOrdinal: 2,
149 });
150 }).pipe(
151 Effect.provide(
152 Layer.provide(BoundedThreadSnapshotHttp.layer, RpcHttp.layerRemoteHttpClient(fetchFn)),
153 ),
154 );
155 });
156
157 it.effect("falls back to full HTTP snapshot when bounded returns a plain route 404", () => {
158 const fetchFn = ((input: RequestInfo | URL) => {
159 const url = String(input);
160 if (url.includes(`/api/orchestration/threads/${THREAD_ID}/bounded`)) {
161 return Promise.resolve(
162 new Response("Not Found", {
163 status: 404,
164 headers: { "content-type": "text/plain" },
165 }),
166 );
167 }
168 expect(url).toContain(`/api/orchestration/threads/${THREAD_ID}`);
169 expect(url.includes("/bounded")).toBe(false);
170 return Promise.resolve(
171 new Response(JSON.stringify(FULL_SNAPSHOT_BODY), {
172 status: 200,
173 headers: { "content-type": "application/json" },
174 }),
175 );
176 }) satisfies typeof fetch;
177
178 return Effect.gen(function* () {
179 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
180 const result = yield* loader.load(PREPARED, THREAD_ID);
181 expect(result._tag).toBe("present");
182 if (result._tag === "present") {
183 expect(result.snapshot.snapshotSequence).toBe(9);
184 expect(result.snapshot.projection.thread.title).toBe("Full fallback thread");
185 expect(result.history).toBeUndefined();
186 }
187 }).pipe(
188 Effect.provide(
189 Layer.provide(BoundedThreadSnapshotHttp.layer, RpcHttp.layerRemoteHttpClient(fetchFn)),
190 ),
191 );
192 });
193
194 it.effect("treats structured EnvironmentResourceNotFoundError from bounded as missing", () => {
195 const fetchFn = ((input: RequestInfo | URL) => {
196 const url = String(input);
197 expect(url).toContain(`/api/orchestration/threads/${THREAD_ID}/bounded`);
198 return Promise.resolve(
199 Response.json(
200 {
201 _tag: "EnvironmentResourceNotFoundError",
202 code: "not_found",
203 reason: "thread_not_found",
204 traceId: "trace-bounded-missing",
205 },
206 { status: 404 },
207 ),
208 );
209 }) satisfies typeof fetch;
210
211 return Effect.gen(function* () {
212 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
213 const result = yield* loader.load(PREPARED, THREAD_ID);
214 expect(result).toEqual({ _tag: "missing" });
215 }).pipe(
216 Effect.provide(
217 Layer.provide(BoundedThreadSnapshotHttp.layer, RpcHttp.layerRemoteHttpClient(fetchFn)),
218 ),
219 );
220 });
221
222 it.effect("treats structured missing from full fallback as missing", () => {
223 let fullCalls = 0;
224 const fetchFn = ((input: RequestInfo | URL) => {
225 const url = String(input);
226 if (url.includes("/bounded")) {
227 return Promise.resolve(
228 new Response("Not Found", {
229 status: 404,
230 headers: { "content-type": "text/plain" },
231 }),
232 );
233 }
234 fullCalls += 1;
235 return Promise.resolve(
236 Response.json(
237 {
238 _tag: "EnvironmentResourceNotFoundError",
239 code: "not_found",
240 reason: "thread_not_found",
241 traceId: "trace-full-missing",
242 },
243 { status: 404 },
244 ),
245 );
246 }) satisfies typeof fetch;
247
248 return Effect.gen(function* () {
249 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
250 const result = yield* loader.load(PREPARED, THREAD_ID);
251 expect(result).toEqual({ _tag: "missing" });
252 expect(fullCalls).toBe(1);
253 }).pipe(
254 Effect.provide(
255 Layer.provide(BoundedThreadSnapshotHttp.layer, RpcHttp.layerRemoteHttpClient(fetchFn)),
256 ),
257 );
258 });
259
260 it.effect(
261 "uses socket fallback directly when the bounded endpoint has a transient failure",
262 () => {
263 let fullCalls = 0;
264 const fetchFn = ((input: RequestInfo | URL) => {
265 const url = String(input);
266 if (url.includes("/bounded")) {
267 return Promise.resolve(new Response("Service Unavailable", { status: 503 }));
268 }
269 fullCalls += 1;
270 return Promise.resolve(
271 new Response(JSON.stringify(FULL_SNAPSHOT_BODY), {
272 status: 200,
273 headers: { "content-type": "application/json" },
274 }),
275 );
276 }) satisfies typeof fetch;
277
278 return Effect.gen(function* () {
279 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
280 const result = yield* loader.load(PREPARED, THREAD_ID);
281 expect(result).toEqual({ _tag: "unavailable" });
282 expect(fullCalls).toBe(0);
283 }).pipe(
284 Effect.provide(
285 Layer.provide(BoundedThreadSnapshotHttp.layer, RpcHttp.layerRemoteHttpClient(fetchFn)),
286 ),
287 );
288 },
289 );
290});