Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import {
3 AuthOrchestrationReadScope,
4 AuthSessionId,
5 EnvironmentAuthenticatedAuth,
6 EnvironmentAuthenticatedPrincipal,
7 EnvironmentHttpApi,
8 EventId,
9 MessageId,
10 NodeId,
11 ORCHESTRATION_PROTOCOL_HEADER,
12 ORCHESTRATION_PROTOCOL_VERSION,
13 OrchestrationV2ThreadBoundedSnapshot,
14 OrchestrationV2ThreadStreamItem,
15 ProjectId,
16 ProviderDriverKind,
17 ProviderInstanceId,
18 RunId,
19 ThreadId,
20 TurnItemId,
21 type OrchestrationV2DomainEvent,
22 type OrchestrationV2ThreadProjection,
23 type OrchestrationV2TurnItem,
24} from "@t3tools/contracts";
25import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot";
26import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
27import * as NodeServices from "@effect/platform-node/NodeServices";
28import * as DateTime from "effect/DateTime";
29import * as Effect from "effect/Effect";
30import * as Layer from "effect/Layer";
31import * as Schema from "effect/Schema";
32import * as Stream from "effect/Stream";
33import * as HttpApi from "effect/http-api/HttpApi";
34import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
35import { Etag, HttpRouter } from "effect/http";
36
37import * as SqlitePersistence from "../persistence/Sqlite.ts";
38import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
39import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
40import { subscribeOrchestrationV2Thread } from "../ws.ts";
41import * as OrchestrationHttp from "./http.ts";
42import * as ProjectionStore from "./ProjectionStore.ts";
43import * as ProjectStore from "./ProjectStore.ts";
44import * as ThreadManagementService from "./ThreadManagementService.ts";
45
46const decodeBounded = Schema.decodeUnknownSync(
47 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadBoundedSnapshot)),
48);
49const decodeStreamItem = Schema.decodeUnknownSync(
50 Schema.toCodecJson(OrchestrationV2ThreadStreamItem),
51);
52const encodeStreamItem = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2ThreadStreamItem));
53
54const provider = ProviderInstanceId.make("codex");
55const modelSelection = { instanceId: provider, model: "gpt-5.4" };
56const projectId = ProjectId.make("project:compact-transport");
57const PARENT = ThreadId.make("thread:compact-transport:parent");
58const FORK = ThreadId.make("thread:compact-transport:fork");
59const LONG = ThreadId.make("thread:compact-transport:long");
60const parentRun = RunId.make("run:compact-transport:parent");
61const longRun = RunId.make("run:compact-transport:long");
62
63const store = Layer.mergeAll(
64 ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
65 SqlitePersistence.layerMemory,
66);
67const management = Layer.unwrap(
68 Effect.gen(function* () {
69 const projections = yield* ProjectionStore.ProjectionStoreV2;
70 return Layer.mock(ThreadManagementService.ThreadManagementService)({
71 ensureLegacyTranscript: () => Effect.void,
72 getThreadSnapshot: (id) => projections.getThreadSnapshot(id).pipe(Effect.orDie),
73 getThreadSnapshotWindow: (id, options) =>
74 projections.getThreadSnapshotWindow(id, options).pipe(Effect.orDie),
75 streamStoredEventsFrom: () => Stream.empty,
76 });
77 }),
78);
79
80class OrchestrationApi extends HttpApi.make("environment").add(
81 EnvironmentHttpApi.groups.orchestration,
82) {}
83const auth = Layer.succeed(EnvironmentAuthenticatedAuth, (effect) =>
84 effect.pipe(
85 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
86 sessionId: AuthSessionId.make("compact-transport"),
87 subject: "compact-transport",
88 method: "browser-session-cookie",
89 scopes: new Set([AuthOrchestrationReadScope]),
90 }),
91 ),
92);
93
94function threadCreated(id: ThreadId, at: DateTime.Utc, forkOf?: RunId): OrchestrationV2DomainEvent {
95 return {
96 id: EventId.make(`event:${id}:created`),
97 type: "thread.created",
98 threadId: id,
99 occurredAt: at,
100 payload: {
101 createdBy: "user",
102 creationSource: "web",
103 id,
104 projectId,
105 title: String(id),
106 providerInstanceId: provider,
107 modelSelection,
108 runtimeMode: "full-access",
109 interactionMode: "default",
110 branch: null,
111 worktreePath: null,
112 activeProviderThreadId: null,
113 lineage:
114 forkOf === undefined
115 ? { parentThreadId: null, relationshipToParent: null, rootThreadId: id }
116 : { parentThreadId: PARENT, relationshipToParent: "fork", rootThreadId: PARENT },
117 forkedFrom: forkOf === undefined ? null : { type: "run", threadId: PARENT, runId: forkOf },
118 createdAt: at,
119 updatedAt: at,
120 archivedAt: null,
121 settledOverride: null,
122 settledAt: null,
123 lastVisitedAt: null,
124 deletedAt: null,
125 },
126 };
127}
128
129function runCreated(
130 threadId: ThreadId,
131 runId: RunId,
132 at: DateTime.Utc,
133): OrchestrationV2DomainEvent {
134 const rootNodeId = NodeId.make(`node:${runId}`);
135 return {
136 id: EventId.make(`event:${runId}:created`),
137 type: "run.created",
138 threadId,
139 runId,
140 nodeId: rootNodeId,
141 driver: ProviderDriverKind.make("codex"),
142 occurredAt: at,
143 payload: {
144 id: runId,
145 threadId,
146 ordinal: 1,
147 providerInstanceId: provider,
148 modelSelection,
149 providerThreadId: null,
150 userMessageId: MessageId.make(`message:${runId}`),
151 rootNodeId,
152 activeAttemptId: null,
153 status: "completed",
154 requestedAt: at,
155 startedAt: at,
156 completedAt: at,
157 checkpointId: null,
158 contextHandoffId: null,
159 },
160 };
161}
162
163function itemUpdated(
164 threadId: ThreadId,
165 runId: RunId | null,
166 key: string,
167 ordinal: number,
168 at: DateTime.Utc,
169 type:
170 | "command_execution"
171 | "run_interrupt_request"
172 | "run_interrupt_result" = "command_execution",
173): OrchestrationV2DomainEvent {
174 const base = {
175 id: TurnItemId.make(`turn-item:${threadId}:${key}`),
176 threadId,
177 runId,
178 nodeId: null,
179 providerThreadId: null,
180 providerTurnId: null,
181 nativeItemRef: null,
182 parentItemId: null,
183 ordinal,
184 status: "completed" as const,
185 title: key,
186 startedAt: at,
187 completedAt: at,
188 updatedAt: at,
189 };
190 const payload: OrchestrationV2TurnItem =
191 type === "command_execution"
192 ? { ...base, type, input: `echo ${key}`, output: `output ${key}`, exitCode: 0 }
193 : { ...base, type, message: key };
194 return {
195 id: EventId.make(`event:${threadId}:${key}`),
196 type: "turn-item.updated",
197 threadId,
198 ...(runId === null ? {} : { runId }),
199 occurredAt: at,
200 payload,
201 };
202}
203
204const seed = Effect.gen(function* () {
205 const projections = yield* ProjectionStore.ProjectionStoreV2;
206 const at = yield* DateTime.now;
207 const events: OrchestrationV2DomainEvent[] = [
208 threadCreated(PARENT, at),
209 runCreated(PARENT, parentRun, at),
210 ...[1, 2, 3].map((n) => itemUpdated(PARENT, parentRun, `parent-${n}`, n, at)),
211 threadCreated(FORK, at, parentRun),
212 ...[1, 2, 3, 4].map((n) => itemUpdated(FORK, null, `fork-${n}`, n, at)),
213 threadCreated(LONG, at),
214 runCreated(LONG, longRun, at),
215 // The request sits far outside the recent window; its result is inside it.
216 itemUpdated(LONG, longRun, "request", 1, at, "run_interrupt_request"),
217 ...Array.from({ length: 90 }, (_, index) =>
218 itemUpdated(LONG, longRun, `tool-${index}`, index + 2, at),
219 ),
220 itemUpdated(LONG, longRun, "result", 92, at, "run_interrupt_result"),
221 ];
222 for (const event of events) yield* projections.apply(event);
223});
224
225// Bounded subscriptions without afterSequence never read the event store, and
226// thread routes never touch projects.
227const TestLayer = Layer.mergeAll(
228 management,
229 Layer.effectDiscard(seed),
230 Layer.mock(OrchestrationEventStore.OrchestrationEventStore)({}),
231 Layer.mock(ProjectStore.ProjectStoreV2)({}),
232 Layer.mock(ProjectEnrichmentService.ProjectEnrichmentService)({}),
233).pipe(Layer.provideMerge(store));
234
235const withHttp = <A>(use: (get: (path: string) => Promise<Response>) => Promise<A>) =>
236 Effect.gen(function* () {
237 const context = yield* Effect.context<Layer.Success<typeof TestLayer>>();
238 const appLayer = HttpApiBuilder.layer(OrchestrationApi).pipe(
239 Layer.provide(OrchestrationHttp.layer),
240 Layer.provide(auth),
241 Layer.provide(Layer.succeedContext(context)),
242 Layer.provide(NodeHttpPlatform.layer),
243 Layer.provide(Etag.layerWeak),
244 Layer.provide(NodeServices.layer),
245 );
246 return yield* Effect.acquireUseRelease(
247 Effect.sync(() => HttpRouter.toWebHandler(appLayer, { disableLogger: true })),
248 ({ handler }) =>
249 Effect.promise(() =>
250 use((path) =>
251 handler(
252 new Request(`http://environment.test${path}`, {
253 headers: {
254 [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION),
255 },
256 }),
257 ),
258 ),
259 ),
260 ({ dispose }) => Effect.promise(() => dispose()),
261 );
262 });
263
264const firstSnapshot = (input: Parameters<typeof subscribeOrchestrationV2Thread>[0]) =>
265 subscribeOrchestrationV2Thread(input).pipe(
266 Effect.flatMap((stream) => Stream.runHead(stream)),
267 Effect.map((head) => {
268 if (head._tag !== "Some" || head.value.kind !== "snapshot") throw new Error("No snapshot");
269 // Through the wire codec, as a client receives it.
270 const decoded = decodeStreamItem(JSON.parse(JSON.stringify(encodeStreamItem(head.value))));
271 if (decoded.kind !== "snapshot") throw new Error("No snapshot");
272 return { raw: head.value, decoded };
273 }),
274 );
275
276function itemIds(projection: OrchestrationV2ThreadProjection): string[] {
277 return projection.turnItems.map((item) => String(item.id));
278}
279
280it.layer(TestLayer)("compact bounded snapshot transport", (it) => {
281 describe.each([
282 ["fork", FORK],
283 ["long run with a retained interrupt request", LONG],
284 ])("%s", (_, threadId) => {
285 it.effect("HTTP: legacy, ignored and opted-in requests restore to the same snapshot", () =>
286 withHttp(async (get) => {
287 const base = `/api/orchestration/threads/${encodeURIComponent(threadId)}/bounded`;
288 const legacyBody = await (await get(base)).text();
289 const ignoredBody = await (await get(`${base}?compactTurnItems=yes&unknown=1`)).text();
290 const compactResponse = await get(`${base}?compactTurnItems=1`);
291 assert.strictEqual(compactResponse.status, 200);
292 const compactBody = await compactResponse.text();
293
294 // Requests without the exact opt-in get the unchanged representation.
295 assert.notInclude(legacyBody, "turnItemsOmitLocalVisible");
296 assert.strictEqual(ignoredBody, legacyBody);
297 assert.isBelow(compactBody.length, legacyBody.length);
298
299 const legacy = decodeBounded(legacyBody);
300 const compact = decodeBounded(compactBody);
301 assert.isTrue(compact.turnItemsOmitLocalVisible);
302 const { turnItemsOmitLocalVisible: _marker, projection: _p, ...compactRest } = compact;
303 const { projection: _legacyProjection, ...legacyRest } = legacy;
304 assert.deepStrictEqual(compactRest, legacyRest);
305 assert.deepStrictEqual(boundedSnapshotProjection(compact), legacy.projection);
306 return { legacy, compact };
307 }).pipe(
308 Effect.tap(({ legacy }) =>
309 Effect.sync(() => {
310 if (threadId === FORK) {
311 const visibility = legacy.projection.visibleTurnItems.map((row) => row.visibility);
312 assert.deepStrictEqual(visibility, [
313 "inherited",
314 "inherited",
315 "inherited",
316 "synthetic",
317 "local",
318 "local",
319 "local",
320 "local",
321 ]);
322 } else {
323 const ids = itemIds(legacy.projection);
324 assert.isTrue(legacy.hasMoreHistory);
325 // Window rows first, then the retained request outside the window.
326 assert.strictEqual(ids.at(-1), `turn-item:${LONG}:request`);
327 assert.isFalse(
328 legacy.projection.visibleTurnItems.some((row) => row.sourceItemId === ids.at(-1)),
329 );
330 }
331 }),
332 ),
333 ),
334 );
335
336 it.effect("WS: bounded snapshots stay unchanged unless the client opts in", () =>
337 Effect.gen(function* () {
338 const legacy = yield* firstSnapshot({ threadId, acceptBoundedSnapshot: true });
339 const compact = yield* firstSnapshot({
340 threadId,
341 acceptBoundedSnapshot: true,
342 acceptCompactTurnItems: true,
343 });
344 // Full snapshots ignore the compact opt-in entirely.
345 const full = yield* firstSnapshot({ threadId, acceptCompactTurnItems: true });
346
347 assert.isUndefined(legacy.decoded.turnItemsOmitLocalVisible);
348 assert.isUndefined(full.decoded.turnItemsOmitLocalVisible);
349 assert.isUndefined(full.decoded.historyCursor);
350 assert.isTrue(compact.decoded.turnItemsOmitLocalVisible);
351 assert.isBelow(
352 compact.decoded.projection.turnItems.length,
353 legacy.decoded.projection.turnItems.length,
354 );
355 assert.deepStrictEqual(
356 boundedSnapshotProjection(compact.decoded),
357 legacy.decoded.projection,
358 );
359 assert.deepStrictEqual(
360 {
361 ...compact.decoded,
362 projection: legacy.decoded.projection,
363 turnItemsOmitLocalVisible: undefined,
364 },
365 { ...legacy.decoded, turnItemsOmitLocalVisible: undefined },
366 );
367 }),
368 );
369 });
370});