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

http.test.ts

485 lines18.1 KB

1import {
2 AuthSessionId,
3 type AuthEnvironmentScope,
4 EnvironmentAuthenticatedAuth,
5 EnvironmentAuthenticatedPrincipal,
6 EnvironmentHttpApi,
7 EnvironmentId,
8 EventId,
9 ORCHESTRATION_PROTOCOL_HEADER,
10 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
11 OrchestrationV2AppThread,
12 OrchestrationV2Run,
13 OrchestrationV2ThreadDetailSnapshot,
14 OrchestrationV2TurnItem,
15 OrchestrationV2ThreadTranscript,
16 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
17 ThreadId,
18} from "@t3tools/contracts";
19import { expect, it } from "@effect/vitest";
20import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript";
21import * as Effect from "effect/Effect";
22import * as Context from "effect/Context";
23import * as DateTime from "effect/DateTime";
24import * as Layer from "effect/Layer";
25import * as Schema from "effect/Schema";
26import * as SqlClient from "effect/sql/SqlClient";
27import * as Statement from "effect/sql/Statement";
28import * as HttpRouter from "effect/http/HttpRouter";
29import * as HttpPlatform from "effect/http/HttpPlatform";
30import * as Etag from "effect/http/Etag";
31import * as NodeServices from "@effect/platform-node/NodeServices";
32import * as HttpApi from "effect/http-api/HttpApi";
33import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
34import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
35import * as SqlitePersistence from "../persistence/Sqlite.ts";
36import * as ServerSettings from "../serverSettings.ts";
37​
38import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
39import { ProjectEnrichmentService } from "../project/ProjectEnrichmentService.ts";
40import * as OrchestrationHttp from "./http.ts";
41import { OrchestratorProjectionError } from "./Orchestrator.ts";
42import { EventSinkV2 } from "./EventSink.ts";
43import * as ProjectStore from "./ProjectStore.ts";
44import * as CommandReceiptStore from "./CommandReceiptStore.ts";
45import * as ThreadManagementService from "./ThreadManagementService.ts";
46import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
47import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
48​
49class TranscriptTestApi extends HttpApi.make("environment").add(
50 EnvironmentHttpApi.groups.orchestration,
51) {}
52const decodeTranscript = Schema.decodeUnknownEffect(
53 Schema.toCodecJson(OrchestrationV2ThreadTranscript),
54);
55​
56const now = DateTime.makeUnsafe("2026-09-29T00:00:00.000Z");
57const environmentId = EnvironmentId.make("source-بيئة");
58const output = "Full tool output. ".repeat(4_000);
59const thread = Schema.decodeSync(OrchestrationV2AppThread)({
60 id: "source-thread",
61 projectId: "source-project",
62 title: "Source 界\nconversation",
63 providerInstanceId: "codex",
64 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
65 runtimeMode: "full-access",
66 interactionMode: "default",
67 branch: null,
68 worktreePath: null,
69 activeProviderThreadId: null,
70 lineage: { rootThreadId: "source-thread", parentThreadId: null, relationshipToParent: null },
71 forkedFrom: null,
72 createdBy: "user",
73 creationSource: "web",
74 createdAt: now,
75 updatedAt: now,
76 archivedAt: null,
77 settledOverride: null,
78 settledAt: null,
79 lastVisitedAt: null,
80 deletedAt: null,
81});
82const items = Schema.decodeUnknownSync(Schema.Array(OrchestrationV2TurnItem))(
83 Array.from({ length: 200 }, (_, position) => ({
84 id: `item-${position}`,
85 threadId: "source-thread",
86 runId: null,
87 nodeId: null,
88 providerThreadId: null,
89 providerTurnId: null,
90 nativeItemRef: null,
91 parentItemId: null,
92 ordinal: position,
93 type: "command_execution",
94 status: "completed",
95 title: "Read notes",
96 input: "cat notes.md",
97 output: position === 0 ? output : "Done",
98 startedAt: now,
99 completedAt: now,
100 updatedAt: now,
101 })),
102);
103​
104const rolledBackRun = Schema.decodeSync(OrchestrationV2Run)({
105 id: "run:rolled-back",
106 threadId: "source-thread",
107 ordinal: 1,
108 providerInstanceId: "codex",
109 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
110 providerThreadId: null,
111 userMessageId: "message:rolled-back",
112 rootNodeId: null,
113 activeAttemptId: null,
114 status: "rolled_back",
115 requestedAt: now,
116 startedAt: now,
117 completedAt: now,
118 checkpointId: null,
119 contextHandoffId: null,
120});
121​
122// Serves the orchestration HTTP routes over real stores; `allowed` gates the read scope.
123const serveOrchestrationHttp = (
124 allowed: () => boolean,
125 getThreadSnapshot?: ThreadManagementService.ThreadManagementServiceShape["getThreadSnapshot"],
126) =>
127 Effect.gen(function* () {
128 const runtime = ProviderReplayHarness.layerWithRegistry(
129 { name: "thread-transcript" },
130 ProviderAdapterRegistry.layerFromAdapters([]),
131 { runEffectWorker: false },
132 );
133 const services = yield* Layer.build(
134 Layer.mergeAll(
135 runtime,
136 ThreadManagementService.layer.pipe(
137 Layer.provide(
138 Layer.mergeAll(runtime, CommandReceiptStore.layer, ServerSettings.layerTest({})),
139 ),
140 ),
141 OrchestrationEventStore.layer,
142 ProjectStore.layer,
143 ).pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
144 );
145 const eventSink = Context.get(services, EventSinkV2);
146 yield* eventSink.write({
147 events: [
148 {
149 id: EventId.make("create-source"),
150 type: "thread.created",
151 threadId: thread.id,
152 occurredAt: now,
153 payload: thread,
154 },
155 ],
156 });
157 const routes = HttpApiBuilder.layer(TranscriptTestApi).pipe(
158 Layer.provide(OrchestrationHttp.layer),
159 Layer.provide(
160 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
161 getEnvironmentId: Effect.succeed(environmentId),
162 }),
163 ),
164 Layer.provide(
165 Layer.succeed(EnvironmentAuthenticatedAuth, (effect) =>
166 Effect.suspend(() =>
167 effect.pipe(
168 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
169 sessionId: AuthSessionId.make("test-session"),
170 subject: "test",
171 method: "bearer-access-token",
172 scopes: new Set<AuthEnvironmentScope>(allowed() ? ["orchestration:read"] : []),
173 }),
174 ),
175 ),
176 ),
177 ),
178 Layer.provide(
179 Layer.succeedContext(
180 getThreadSnapshot === undefined
181 ? services
182 : Context.add(services, ThreadManagementService.ThreadManagementService, {
183 ...Context.get(services, ThreadManagementService.ThreadManagementService),
184 getThreadSnapshot,
185 }),
186 ),
187 ),
188 Layer.provide(Layer.mock(ProjectEnrichmentService)({})),
189 Layer.provide(HttpPlatform.layer),
190 Layer.provide(Etag.layerWeak),
191 Layer.provide(NodeServices.layer),
192 );
193 const { handler, dispose } = HttpRouter.toWebHandler(routes, { disableLogger: true });
194 yield* Effect.addFinalizer(() => Effect.promise(dispose));
195 return { services, eventSink, handler };
196 });
197​
198it.effect("exports full history with size, scope, and missing-thread checks", () =>
199 Effect.gen(function* () {
200 let allowed = true;
201 const { services, eventSink, handler } = yield* serveOrchestrationHttp(() => allowed);
202 const read = (threadId: ThreadId) =>
203 Effect.promise(() =>
204 handler(
205 new Request(`http://localhost/api/orchestration/threads/${threadId}/transcript`, {
206 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT },
207 }),
208 ),
209 );
210​
211 const readTranscriptError = Context.get(
212 services,
213 ThreadManagementService.ThreadManagementService,
214 )
215 .getThreadTranscript(thread.id)
216 .pipe(
217 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, {
218 getEnvironmentId: Effect.succeed(environmentId),
219 }),
220 Effect.flip,
221 );
222​
223 const emptyResponse = yield* read(thread.id);
224 expect(emptyResponse.status).toBe(200);
225 expect(
226 (yield* decodeTranscript(yield* Effect.promise(() => emptyResponse.json()))).items,
227 ).toEqual([]);
228 yield* eventSink.write({
229 events: items.map((item) => ({
230 id: EventId.make(`create-${item.id}`),
231 type: "turn-item.updated" as const,
232 threadId: thread.id,
233 occurredAt: now,
234 payload: item,
235 })),
236 });
237​
238 const response = yield* read(thread.id);
239 expect(response.status).toBe(200);
240 const transcript = yield* decodeTranscript(yield* Effect.promise(() => response.json()));
241 expect(transcript.items).toHaveLength(200);
242 expect(transcript.items[0]?.item).toMatchObject({ output });
243 expect(transcript.items[0]?.visibility).toBe("local");
244 expect(transcript.items[199]?.position).toBe(199);
245​
246 const emptyOutputRows = transcript.items.map((row, position) =>
247 position === 0 ? { ...row, item: { ...row.item, output: "" } } : row,
248 );
249 const header = threadTranscriptHeader(environmentId, transcript);
250 const baseSize =
251 Buffer.byteLength(header, "utf8") +
252 emptyOutputRows.reduce(
253 (size, row) => size + Buffer.byteLength(`${JSON.stringify(row)}\n`, "utf8"),
254 0,
255 );
256 const boundaryOutput = "界" + "x".repeat(PROVIDER_SEND_TURN_MAX_FILE_BYTES - baseSize - 3);
257 for (const [suffix, expectedStatus] of [
258 ["", 200],
259 ["x", 400],
260 ] as const) {
261 yield* eventSink.write({
262 events: [
263 {
264 id: EventId.make(`boundary-${expectedStatus}`),
265 type: "turn-item.updated",
266 threadId: thread.id,
267 occurredAt: now,
268 payload: {
269 ...items.find((item) => item.type === "command_execution")!,
270 output: boundaryOutput + suffix,
271 },
272 },
273 ],
274 });
275 const response = yield* read(thread.id);
276 expect(response.status).toBe(expectedStatus);
277 if (expectedStatus === 200) continue;
278 expect(yield* readTranscriptError).toBeInstanceOf(
279 ThreadManagementService.ThreadTranscriptTooLargeError,
280 );
281 expect(yield* Effect.promise(() => response.json())).toMatchObject({
282 _tag: "EnvironmentRequestInvalidError",
283 reason: "thread_transcript_too_large",
284 });
285 }
286​
287 const sql = Context.get(services, SqlClient.SqlClient);
288 const commandItemId = items.find((item) => item.type === "command_execution")!.id;
289 const setCommandPayload = (payload: Statement.Fragment) => sql`
290 UPDATE orchestration_v2_projection_turn_items SET payload_json = ${payload}
291 WHERE turn_item_id = ${commandItemId}
292 `;
293 const fill = (bytes: number) => sql`printf('%.*c', ${bytes}, 'x')`;
294 // Stored bytes the export drops do not count, and neither does a row SQLite cannot parse:
295 // only what the export keeps can reject it.
296 yield* setCommandPayload(sql`json_set(
297 payload_json, '$.output', 'x',
298 '$.droppedLegacyField', ${fill(PROVIDER_SEND_TURN_MAX_FILE_BYTES + 1)}
299 )`);
300 expect((yield* read(thread.id)).status).toBe(200);
301 const deepField = sql`'"droppedDeepField":' || printf('%.*c', 1001, '[') || printf('%.*c', 1001, ']') || ','`;
302 yield* setCommandPayload(
303 sql`replace(payload_json, '"droppedLegacyField":', ${deepField} || '"droppedLegacyField":')`,
304 );
305 expect((yield* read(thread.id)).status).toBe(200);
306 // Tool output over the limit rejects the export, here as the content array a dynamic tool
307 // stores. Its only read is the size.
308 yield* sql`
309 UPDATE orchestration_v2_projection_turn_items SET type = 'dynamic_tool'
310 WHERE turn_item_id = ${commandItemId}
311 `;
312 yield* setCommandPayload(sql`json_set(
313 replace(payload_json, ${deepField}, ''), '$.type', 'dynamic_tool', '$.toolName', NULL,
314 '$.output',
315 json_array(json_object('type', 'text', 'text', ${fill(PROVIDER_SEND_TURN_MAX_FILE_BYTES + 1)}))
316 )`);
317 const reads: Array<string> = [];
318 expect(
319 yield* readTranscriptError.pipe(
320 Effect.provideService(Statement.CurrentTransformer, (statement) => {
321 reads.push(statement.compile()[0]);
322 return Effect.succeed(statement);
323 }),
324 ),
325 ).toBeInstanceOf(ThreadManagementService.ThreadTranscriptTooLargeError);
326 expect(reads).toEqual([expect.stringContaining("octet_length(payload_json)")]);
327 expect((yield* read(thread.id)).status).toBe(400);
328 // The export leaves a rolled back run out, so its output cannot reject it.
329 yield* eventSink.write({
330 events: [
331 {
332 id: EventId.make("create-rolled-back-run"),
333 type: "run.created",
334 threadId: thread.id,
335 occurredAt: now,
336 payload: rolledBackRun,
337 },
338 ],
339 });
340 yield* sql`
341 UPDATE orchestration_v2_projection_turn_items SET run_id = ${rolledBackRun.id}
342 WHERE turn_item_id = ${commandItemId}
343 `;
344 yield* setCommandPayload(sql`json_set(payload_json, '$.runId', ${rolledBackRun.id})`);
345 const withoutRolledBackRun = yield* read(thread.id);
346 expect(withoutRolledBackRun.status).toBe(200);
347 expect(
348 (yield* decodeTranscript(yield* Effect.promise(() => withoutRolledBackRun.json()))).items,
349 ).toHaveLength(199);
350​
351 expect((yield* read(ThreadId.make("missing"))).status).toBe(404);
352 allowed = false;
353 expect((yield* read(thread.id)).status).toBe(403);
354 }),
355);
356​
357const decodeThreadSnapshot = Schema.decodeUnknownSync(
358 Schema.toCodecJson(OrchestrationV2ThreadDetailSnapshot),
359);
360​
361it.effect("streams the full snapshot with the endpoint's errors", () =>
362 Effect.gen(function* () {
363 const { services, eventSink, handler } = yield* serveOrchestrationHttp(() => true);
364 yield* eventSink.write({
365 events: items.map((item) => ({
366 id: EventId.make(`create-${item.id}`),
367 type: "turn-item.updated" as const,
368 threadId: thread.id,
369 occurredAt: now,
370 payload: item,
371 })),
372 });
373 const read = (serve: typeof handler, threadId: ThreadId) =>
374 Effect.promise(() =>
375 serve(
376 new Request(`http://localhost/api/orchestration/threads/${threadId}`, {
377 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT },
378 }),
379 ),
380 );
381 const snapshot = yield* Context.get(
382 services,
383 ThreadManagementService.ThreadManagementService,
384 ).getThreadSnapshot(thread.id);
385​
386 const response = yield* read(handler, thread.id);
387 expect(response.status).toBe(200);
388 expect(response.headers.get("content-type")).toBe("application/json");
389 const body = decodeThreadSnapshot(yield* Effect.promise(() => response.json()));
390 expect(body.snapshotSequence).toBe(snapshot.snapshotSequence);
391 expect(body.projection.turnItems).toHaveLength(snapshot.projection.turnItems.length);
392​
393 const missing = yield* read(handler, ThreadId.make("missing"));
394 expect(missing.status).toBe(404);
395 expect(yield* Effect.promise(() => missing.json())).toMatchObject({
396 _tag: "EnvironmentResourceNotFoundError",
397 reason: "thread_not_found",
398 });
399 const failing = yield* serveOrchestrationHttp(
400 () => true,
401 (threadId) =>
402 Effect.fail(new OrchestratorProjectionError({ threadId, cause: new Error("disk I/O") })),
403 );
404 const failed = yield* read(failing.handler, thread.id);
405 expect(failed.status).toBe(500);
406 expect(yield* Effect.promise(() => failed.json())).toMatchObject({
407 _tag: "EnvironmentInternalError",
408 reason: "orchestration_thread_snapshot_failed",
409 });
410 // A projection its schema rejects is an empty 500, as a failed response encoding is.
411 const [first, ...rest] = snapshot.projection.turnItems;
412 const unencodable = yield* serveOrchestrationHttp(
413 () => true,
414 () =>
415 Effect.succeed({
416 ...snapshot,
417 projection: {
418 ...snapshot.projection,
419 turnItems: [
420 { ...first!, status: "unknown" } as unknown as OrchestrationV2TurnItem,
421 ...rest,
422 ],
423 },
424 }),
425 );
426 const rejected = yield* read(unencodable.handler, thread.id);
427 expect(rejected.status).toBe(500);
428 expect(yield* Effect.promise(() => rejected.text())).toBe("");
429 }),
430);
431​
432it.effect("leaves older settled threads out of the HTTP shell only when asked", () =>
433 Effect.gen(function* () {
434 const { eventSink, handler } = yield* serveOrchestrationHttp(() => true);
435 yield* eventSink.write({
436 events: Array.from({ length: 26 }, (_, index) => {
437 const id = ThreadId.make(`settled-${index}`);
438 return {
439 id: EventId.make(`create-${id}`),
440 type: "thread.created" as const,
441 threadId: id,
442 occurredAt: now,
443 payload: {
444 ...thread,
445 id,
446 lineage: { ...thread.lineage, rootThreadId: id },
447 settledOverride: "settled" as const,
448 settledAt: DateTime.makeUnsafe(Date.UTC(2026, 8, 1 + index)),
449 },
450 };
451 }),
452 });
453 const shell = (query: string) =>
454 Effect.promise(async () => {
455 const response = await handler(
456 new Request(`http://localhost/api/orchestration/shell${query}`, {
457 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT },
458 }),
459 );
460 return (await response.json()) as {
461 readonly snapshotSequence: number;
462 readonly projectIdentities?: string;
463 readonly threads: ReadonlyArray<{ readonly id: string }>;
464 readonly olderSettled?: { readonly counts: ReadonlyArray<unknown> };
465 };
466 });
467​
468 const full = yield* shell("");
469 expect(full.threads).toHaveLength(27);
470 expect(full.olderSettled).toBeUndefined();
471 const cut = yield* shell("?omitOlderSettled=1");
472 expect(cut.threads.map((row) => row.id).toSorted()).toEqual(
473 [thread.id, ...Array.from({ length: 25 }, (_, index) => `settled-${index + 1}`)].toSorted(),
474 );
475 expect(cut.olderSettled?.counts).toEqual([{ projectId: thread.projectId, count: 1 }]);
476​
477 // A client that holds rows the socket can replay from keeps them; any other cursor reloads.
478 expect(full.projectIdentities).toBeTypeOf("string");
479 expect(yield* shell(`?resumeFrom=${full.snapshotSequence}`)).toEqual({ resumable: true });
480 expect(yield* shell(`?resumeFrom=${full.snapshotSequence - 1}`)).toEqual({ resumable: true });
481 for (const cursor of [full.snapshotSequence + 1, "x"]) {
482 expect((yield* shell(`?omitOlderSettled=1&resumeFrom=${cursor}`)).threads).toHaveLength(26);
483 }
484 }),
485);