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

boundedThreadSnapshotHttp.test.ts

259 lines8.3 KB

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