Open History to see the last commit
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 OrchestrationV2TurnItem,
13 OrchestrationV2ThreadTranscript,
14 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
15 ThreadId,
16} from "@t3tools/contracts";
17import { expect, it } from "@effect/vitest";
18import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript";
19import * as Effect from "effect/Effect";
20import * as Context from "effect/Context";
21import * as DateTime from "effect/DateTime";
22import * as Layer from "effect/Layer";
23import * as Schema from "effect/Schema";
24import * as HttpRouter from "effect/http/HttpRouter";
25import * as HttpPlatform from "effect/http/HttpPlatform";
26import * as Etag from "effect/http/Etag";
27import * as NodeServices from "@effect/platform-node/NodeServices";
28import * as HttpApi from "effect/http-api/HttpApi";
29import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
30import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
31import * as SqlitePersistence from "../persistence/Sqlite.ts";
32import * as ServerSettings from "../serverSettings.ts";
33
34import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
35import { ProjectEnrichmentService } from "../project/ProjectEnrichmentService.ts";
36import * as OrchestrationHttp from "./http.ts";
37import { EventSinkV2 } from "./EventSink.ts";
38import * as ProjectStore from "./ProjectStore.ts";
39import * as CommandReceiptStore from "./CommandReceiptStore.ts";
40import * as ThreadManagementService from "./ThreadManagementService.ts";
41import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
42import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
43
44class TranscriptTestApi extends HttpApi.make("environment").add(
45 EnvironmentHttpApi.groups.orchestration,
46) {}
47const decodeTranscript = Schema.decodeUnknownEffect(
48 Schema.toCodecJson(OrchestrationV2ThreadTranscript),
49);
50
51const now = DateTime.makeUnsafe("2026-09-29T00:00:00.000Z");
52const environmentId = EnvironmentId.make("source-بيئة");
53const output = "Full tool output. ".repeat(4_000);
54const thread = Schema.decodeSync(OrchestrationV2AppThread)({
55 id: "source-thread",
56 projectId: "source-project",
57 title: "Source 界\nconversation",
58 providerInstanceId: "codex",
59 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
60 runtimeMode: "full-access",
61 interactionMode: "default",
62 branch: null,
63 worktreePath: null,
64 activeProviderThreadId: null,
65 lineage: { rootThreadId: "source-thread", parentThreadId: null, relationshipToParent: null },
66 forkedFrom: null,
67 createdBy: "user",
68 creationSource: "web",
69 createdAt: now,
70 updatedAt: now,
71 archivedAt: null,
72 settledOverride: null,
73 settledAt: null,
74 lastVisitedAt: null,
75 deletedAt: null,
76});
77const items = Schema.decodeUnknownSync(Schema.Array(OrchestrationV2TurnItem))(
78 Array.from({ length: 200 }, (_, position) => ({
79 id: `item-${position}`,
80 threadId: "source-thread",
81 runId: null,
82 nodeId: null,
83 providerThreadId: null,
84 providerTurnId: null,
85 nativeItemRef: null,
86 parentItemId: null,
87 ordinal: position,
88 type: "command_execution",
89 status: "completed",
90 title: "Read notes",
91 input: "cat notes.md",
92 output: position === 0 ? output : "Done",
93 startedAt: now,
94 completedAt: now,
95 updatedAt: now,
96 })),
97);
98
99// Serves the orchestration HTTP routes over real stores; `allowed` gates the read scope.
100const serveOrchestrationHttp = (allowed: () => boolean) =>
101 Effect.gen(function* () {
102 const runtime = ProviderReplayHarness.layerWithRegistry(
103 { name: "thread-transcript" },
104 ProviderAdapterRegistry.layerFromAdapters([]),
105 { runEffectWorker: false },
106 );
107 const services = yield* Layer.build(
108 Layer.mergeAll(
109 runtime,
110 ThreadManagementService.layer.pipe(
111 Layer.provide(
112 Layer.mergeAll(runtime, CommandReceiptStore.layer, ServerSettings.layerTest({})),
113 ),
114 ),
115 OrchestrationEventStore.layer,
116 ProjectStore.layer,
117 ).pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
118 );
119 const eventSink = Context.get(services, EventSinkV2);
120 yield* eventSink.write({
121 events: [
122 {
123 id: EventId.make("create-source"),
124 type: "thread.created",
125 threadId: thread.id,
126 occurredAt: now,
127 payload: thread,
128 },
129 ],
130 });
131 const routes = HttpApiBuilder.layer(TranscriptTestApi).pipe(
132 Layer.provide(OrchestrationHttp.layer),
133 Layer.provide(
134 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
135 getEnvironmentId: Effect.succeed(environmentId),
136 }),
137 ),
138 Layer.provide(
139 Layer.succeed(EnvironmentAuthenticatedAuth, (effect) =>
140 Effect.suspend(() =>
141 effect.pipe(
142 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
143 sessionId: AuthSessionId.make("test-session"),
144 subject: "test",
145 method: "bearer-access-token",
146 scopes: new Set<AuthEnvironmentScope>(allowed() ? ["orchestration:read"] : []),
147 }),
148 ),
149 ),
150 ),
151 ),
152 Layer.provide(Layer.succeedContext(services)),
153 Layer.provide(Layer.mock(ProjectEnrichmentService)({})),
154 Layer.provide(HttpPlatform.layer),
155 Layer.provide(Etag.layerWeak),
156 Layer.provide(NodeServices.layer),
157 );
158 const { handler, dispose } = HttpRouter.toWebHandler(routes, { disableLogger: true });
159 yield* Effect.addFinalizer(() => Effect.promise(dispose));
160 return { services, eventSink, handler };
161 });
162
163it.effect("exports full history with size, scope, and missing-thread checks", () =>
164 Effect.gen(function* () {
165 let allowed = true;
166 const { services, eventSink, handler } = yield* serveOrchestrationHttp(() => allowed);
167 const read = (threadId: ThreadId) =>
168 Effect.promise(() =>
169 handler(
170 new Request(`http://localhost/api/orchestration/threads/${threadId}/transcript`, {
171 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT },
172 }),
173 ),
174 );
175
176 const emptyResponse = yield* read(thread.id);
177 expect(emptyResponse.status).toBe(200);
178 expect(
179 (yield* decodeTranscript(yield* Effect.promise(() => emptyResponse.json()))).items,
180 ).toEqual([]);
181 yield* eventSink.write({
182 events: items.map((item) => ({
183 id: EventId.make(`create-${item.id}`),
184 type: "turn-item.updated" as const,
185 threadId: thread.id,
186 occurredAt: now,
187 payload: item,
188 })),
189 });
190
191 const response = yield* read(thread.id);
192 expect(response.status).toBe(200);
193 const transcript = yield* decodeTranscript(yield* Effect.promise(() => response.json()));
194 expect(transcript.items).toHaveLength(200);
195 expect(transcript.items[0]?.item).toMatchObject({ output });
196 expect(transcript.items[0]?.visibility).toBe("local");
197 expect(transcript.items[199]?.position).toBe(199);
198
199 const emptyOutputRows = transcript.items.map((row, position) =>
200 position === 0 ? { ...row, item: { ...row.item, output: "" } } : row,
201 );
202 const header = threadTranscriptHeader(environmentId, transcript);
203 const baseSize =
204 Buffer.byteLength(header, "utf8") +
205 emptyOutputRows.reduce(
206 (size, row) => size + Buffer.byteLength(`${JSON.stringify(row)}\n`, "utf8"),
207 0,
208 );
209 const boundaryOutput = "界" + "x".repeat(PROVIDER_SEND_TURN_MAX_FILE_BYTES - baseSize - 3);
210 for (const [suffix, expectedStatus] of [
211 ["", 200],
212 ["x", 400],
213 ] as const) {
214 yield* eventSink.write({
215 events: [
216 {
217 id: EventId.make(`boundary-${expectedStatus}`),
218 type: "turn-item.updated",
219 threadId: thread.id,
220 occurredAt: now,
221 payload: {
222 ...items.find((item) => item.type === "command_execution")!,
223 output: boundaryOutput + suffix,
224 },
225 },
226 ],
227 });
228 const response = yield* read(thread.id);
229 expect(response.status).toBe(expectedStatus);
230 if (expectedStatus === 400) {
231 const error = yield* Context.get(services, ThreadManagementService.ThreadManagementService)
232 .getThreadTranscript(thread.id)
233 .pipe(
234 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, {
235 getEnvironmentId: Effect.succeed(environmentId),
236 }),
237 Effect.flip,
238 );
239 expect(error).toBeInstanceOf(ThreadManagementService.ThreadTranscriptTooLargeError);
240 expect(yield* Effect.promise(() => response.json())).toMatchObject({
241 _tag: "EnvironmentRequestInvalidError",
242 reason: "thread_transcript_too_large",
243 });
244 }
245 }
246
247 expect((yield* read(ThreadId.make("missing"))).status).toBe(404);
248 allowed = false;
249 expect((yield* read(thread.id)).status).toBe(403);
250 }),
251);
252
253it.effect("leaves older settled threads out of the HTTP shell only when asked", () =>
254 Effect.gen(function* () {
255 const { eventSink, handler } = yield* serveOrchestrationHttp(() => true);
256 yield* eventSink.write({
257 events: Array.from({ length: 26 }, (_, index) => {
258 const id = ThreadId.make(`settled-${index}`);
259 return {
260 id: EventId.make(`create-${id}`),
261 type: "thread.created" as const,
262 threadId: id,
263 occurredAt: now,
264 payload: {
265 ...thread,
266 id,
267 lineage: { ...thread.lineage, rootThreadId: id },
268 settledOverride: "settled" as const,
269 settledAt: DateTime.makeUnsafe(Date.UTC(2026, 8, 1 + index)),
270 },
271 };
272 }),
273 });
274 const shell = (query: string) =>
275 Effect.promise(async () => {
276 const response = await handler(
277 new Request(`http://localhost/api/orchestration/shell${query}`, {
278 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT },
279 }),
280 );
281 return (await response.json()) as {
282 readonly threads: ReadonlyArray<{ readonly id: string }>;
283 readonly olderSettled?: { readonly counts: ReadonlyArray<unknown> };
284 };
285 });
286
287 const full = yield* shell("");
288 expect(full.threads).toHaveLength(27);
289 expect(full.olderSettled).toBeUndefined();
290 const cut = yield* shell("?omitOlderSettled=1");
291 expect(cut.threads.map((row) => row.id).toSorted()).toEqual(
292 [thread.id, ...Array.from({ length: 25 }, (_, index) => `settled-${index + 1}`)].toSorted(),
293 );
294 expect(cut.olderSettled?.counts).toEqual([{ projectId: thread.projectId, count: 1 }]);
295 }),
296);