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

boundedThreadSnapshotHttp.test.ts

251 lines7.8 KB

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 ...(compact ? { turnItemsOmitLocalVisible: true } : {}),
119});
120​
121describe("boundedThreadSnapshotLoader", () => {
122 it.effect.each([
123 ["an older server that ignores the opt-in", false],
124 ["a server that sends compact turnItems", true],
125 ] as const)("requests compact turnItems and loads %s", ([, compact]) => {
126 const urls: string[] = [];
127 const fetchFn = ((input: RequestInfo | URL) => {
128 urls.push(String(input));
129 return Promise.resolve(Response.json(boundedBody(compact)));
130 }) satisfies typeof fetch;
131​
132 return Effect.gen(function* () {
133 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
134 const result = yield* loader.load(PREPARED, THREAD_ID);
135 expect(new URL(urls[0]!).searchParams.get("compactTurnItems")).toBe("1");
136 expect(result._tag).toBe("present");
137 if (result._tag !== "present") return;
138 expect(result.snapshot.projection.turnItems.map((item) => String(item.id))).toEqual([
139 "local-1",
140 "local-2",
141 "older-dependency",
142 ]);
143 expect("turnItemsOmitLocalVisible" in result.snapshot).toBe(false);
144 expect(result.history).toEqual({
145 historyCursor: "bounded-cursor",
146 hasMoreHistory: true,
147 latestLocalTurnOrdinal: 2,
148 });
149 }).pipe(
150 Effect.provide(
151 Layer.provide(BoundedThreadSnapshotHttp.layer, RpcHttp.layerRemoteHttpClient(fetchFn)),
152 ),
153 );
154 });
155​
156 it.effect("falls back to full HTTP snapshot when bounded returns a plain route 404", () => {
157 const fetchFn = ((input: RequestInfo | URL) => {
158 const url = String(input);
159 if (url.includes(`/api/orchestration/threads/${THREAD_ID}/bounded`)) {
160 return Promise.resolve(
161 new Response("Not Found", {
162 status: 404,
163 headers: { "content-type": "text/plain" },
164 }),
165 );
166 }
167 expect(url).toContain(`/api/orchestration/threads/${THREAD_ID}`);
168 expect(url.includes("/bounded")).toBe(false);
169 return Promise.resolve(
170 new Response(JSON.stringify(FULL_SNAPSHOT_BODY), {
171 status: 200,
172 headers: { "content-type": "application/json" },
173 }),
174 );
175 }) satisfies typeof fetch;
176​
177 return Effect.gen(function* () {
178 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
179 const result = yield* loader.load(PREPARED, THREAD_ID);
180 expect(result._tag).toBe("present");
181 if (result._tag === "present") {
182 expect(result.snapshot.snapshotSequence).toBe(9);
183 expect(result.snapshot.projection.thread.title).toBe("Full fallback thread");
184 expect(result.history).toBeUndefined();
185 }
186 }).pipe(
187 Effect.provide(
188 Layer.provide(BoundedThreadSnapshotHttp.layer, RpcHttp.layerRemoteHttpClient(fetchFn)),
189 ),
190 );
191 });
192​
193 it.effect("treats structured EnvironmentResourceNotFoundError from bounded as missing", () => {
194 const fetchFn = ((input: RequestInfo | URL) => {
195 const url = String(input);
196 expect(url).toContain(`/api/orchestration/threads/${THREAD_ID}/bounded`);
197 return Promise.resolve(
198 Response.json(
199 {
200 _tag: "EnvironmentResourceNotFoundError",
201 code: "not_found",
202 reason: "thread_not_found",
203 traceId: "trace-bounded-missing",
204 },
205 { status: 404 },
206 ),
207 );
208 }) satisfies typeof fetch;
209​
210 return Effect.gen(function* () {
211 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
212 const result = yield* loader.load(PREPARED, THREAD_ID);
213 expect(result).toEqual({ _tag: "missing" });
214 }).pipe(
215 Effect.provide(
216 Layer.provide(BoundedThreadSnapshotHttp.layer, RpcHttp.layerRemoteHttpClient(fetchFn)),
217 ),
218 );
219 });
220​
221 it.effect(
222 "uses socket fallback directly when the bounded endpoint has a transient failure",
223 () => {
224 let fullCalls = 0;
225 const fetchFn = ((input: RequestInfo | URL) => {
226 const url = String(input);
227 if (url.includes("/bounded")) {
228 return Promise.resolve(new Response("Service Unavailable", { status: 503 }));
229 }
230 fullCalls += 1;
231 return Promise.resolve(
232 new Response(JSON.stringify(FULL_SNAPSHOT_BODY), {
233 status: 200,
234 headers: { "content-type": "application/json" },
235 }),
236 );
237 }) satisfies typeof fetch;
238​
239 return Effect.gen(function* () {
240 const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;
241 const result = yield* loader.load(PREPARED, THREAD_ID);
242 expect(result).toEqual({ _tag: "unavailable" });
243 expect(fullCalls).toBe(0);
244 }).pipe(
245 Effect.provide(
246 Layer.provide(BoundedThreadSnapshotHttp.layer, RpcHttp.layerRemoteHttpClient(fetchFn)),
247 ),
248 );
249 },
250 );
251});