Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 type ModelSelection,
4 type OrchestrationV2AppThread,
5 type OrchestrationV2CommandOutputFrame,
6 type OrchestrationV2TurnItem,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 type ThreadId,
10 TurnItemId,
11} from "@t3tools/contracts";
12import {
13 appendTerminalOutput,
14 EMPTY_TERMINAL_OUTPUT,
15 normalizeTerminalOutput,
16 TERMINAL_OUTPUT_TAIL_CHARS,
17 type TerminalOutputState,
18} from "@t3tools/shared/terminalOutput";
19import * as Clock from "effect/Clock";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as Queue from "effect/Queue";
24import * as Stream from "effect/Stream";
25import * as TestClock from "effect/testing/TestClock";
26
27import * as SqlitePersistence from "../persistence/Sqlite.ts";
28import * as CommandOutputHub from "./CommandOutputHub.ts";
29import * as EventSink from "./EventSink.ts";
30import * as EventStore from "./EventStore.ts";
31import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
32import * as ProjectionStore from "./ProjectionStore.ts";
33
34const layerTestDatabase = SqlitePersistence.layerMemory;
35const layerTestStores = Layer.merge(EventStore.layer, ProjectionStore.layer).pipe(
36 Layer.provide(layerTestDatabase),
37);
38const layerTestEventSink = EventSink.layer.pipe(
39 Layer.provide(Layer.mergeAll(layerTestStores, layerTestDatabase)),
40);
41const layerTest = Layer.mergeAll(
42 layerTestEventSink,
43 IdAllocator.layer,
44 CommandOutputHub.layer.pipe(Layer.provide(Layer.merge(layerTestEventSink, layerTestStores))),
45);
46
47const modelSelection = {
48 instanceId: ProviderInstanceId.make("codex"),
49 model: "gpt-5.4",
50} satisfies ModelSelection;
51const CODEX_DRIVER = ProviderDriverKind.make("codex");
52const ITEM_ID = TurnItemId.make("turn-item:command");
53
54/** What a client holds after applying frames, using the same shared normalizer. */
55function applyFrame(
56 state: TerminalOutputState,
57 frame: OrchestrationV2CommandOutputFrame,
58): TerminalOutputState {
59 return frame.kind === "replace"
60 ? appendTerminalOutput({ ...EMPTY_TERMINAL_OUTPUT, truncated: frame.truncated }, frame.text)
61 : appendTerminalOutput(state, frame.text);
62}
63
64const seedThread = Effect.gen(function* () {
65 const idAllocator = yield* IdAllocator.IdAllocatorV2;
66 const eventSink = yield* EventSink.EventSinkV2;
67 const now = yield* DateTime.now;
68 const projectId = yield* idAllocator.allocate.project({ fixtureName: "command-output" });
69 const threadId = yield* idAllocator.allocate.thread({ fixtureName: "command-output", projectId });
70 const thread: OrchestrationV2AppThread = {
71 createdBy: "user",
72 creationSource: "web",
73 id: threadId,
74 projectId,
75 title: "Command output",
76 providerInstanceId: modelSelection.instanceId,
77 modelSelection,
78 runtimeMode: "full-access",
79 interactionMode: "default",
80 branch: null,
81 worktreePath: null,
82 branchPullRequest: null,
83 activeOrderKey: null,
84 activeProviderThreadId: null,
85 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
86 forkedFrom: null,
87 createdAt: now,
88 updatedAt: now,
89 archivedAt: null,
90 settledOverride: null,
91 settledAt: null,
92 lastVisitedAt: null,
93 deletedAt: null,
94 };
95 yield* eventSink.write({
96 events: [
97 {
98 id: yield* idAllocator.allocate.event({ threadId }),
99 type: "thread.created",
100 threadId,
101 occurredAt: now,
102 payload: thread,
103 },
104 ],
105 });
106 return threadId;
107});
108
109const writeCommandItem = (
110 threadId: ThreadId,
111 fields: Pick<
112 Extract<OrchestrationV2TurnItem, { type: "command_execution" }>,
113 "status" | "output" | "exitCode"
114 >,
115) =>
116 Effect.gen(function* () {
117 const idAllocator = yield* IdAllocator.IdAllocatorV2;
118 const eventSink = yield* EventSink.EventSinkV2;
119 const now = yield* DateTime.now;
120 const settled = fields.status !== "running";
121 const item: OrchestrationV2TurnItem = {
122 id: ITEM_ID,
123 threadId,
124 runId: null,
125 nodeId: null,
126 providerThreadId: null,
127 providerTurnId: null,
128 nativeItemRef: null,
129 parentItemId: null,
130 ordinal: 1,
131 title: null,
132 startedAt: now,
133 completedAt: settled ? now : null,
134 updatedAt: now,
135 type: "command_execution",
136 input: "yes | head -n 1000000",
137 ...fields,
138 };
139 yield* eventSink.write({
140 events: [
141 {
142 id: yield* idAllocator.allocate.event({ threadId }),
143 type: "turn-item.updated",
144 threadId,
145 driver: CODEX_DRIVER,
146 providerInstanceId: modelSelection.instanceId,
147 occurredAt: now,
148 payload: item,
149 },
150 ],
151 });
152 });
153
154/** Collect frames into a queue so the test takes them one receipt at a time. */
155const subscribeFrames = (threadId: ThreadId) =>
156 Effect.gen(function* () {
157 const hub = yield* CommandOutputHub.CommandOutputHub;
158 const frames = yield* Queue.unbounded<OrchestrationV2CommandOutputFrame | "ended">();
159 yield* hub.subscribe({ threadId, itemId: ITEM_ID }).pipe(
160 Stream.runForEach((frame) => Queue.offer(frames, frame)),
161 Effect.andThen(Queue.offer(frames, "ended")),
162 Effect.forkScoped,
163 );
164 return frames;
165 });
166
167const takeFrame = (frames: Queue.Queue<OrchestrationV2CommandOutputFrame | "ended">) =>
168 Queue.take(frames).pipe(
169 Effect.flatMap((frame) =>
170 frame === "ended" ? Effect.die("command output stream ended early") : Effect.succeed(frame),
171 ),
172 );
173
174const layer = it.layer(layerTest);
175
176layer("CommandOutputHub", (it) => {
177 it.effect(
178 "a late subscriber gets the running tail, then live appends, then the final output",
179 () =>
180 Effect.scoped(
181 Effect.gen(function* () {
182 const hub = yield* CommandOutputHub.CommandOutputHub;
183 const threadId = yield* seedThread;
184 yield* writeCommandItem(threadId, { status: "running" });
185 // Output that arrived before anyone looked, ending mid-escape and mid-redraw.
186 yield* hub.append({
187 threadId,
188 itemId: ITEM_ID,
189 chunk: "\u001b[32mbuilding\u001b[0m\n10%",
190 });
191 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r55%\u001b[3" });
192
193 const frames = yield* subscribeFrames(threadId);
194 const first = yield* takeFrame(frames);
195 assert.equal(first.kind, "replace");
196 assert.isTrue(first.running);
197 let client = applyFrame(EMPTY_TERMINAL_OUTPUT, first);
198 assert.equal(client.text, "\u001b[0;32mbuilding\u001b[0m\n55%");
199
200 // Chunks that land between frames arrive together in one append.
201 yield* TestClock.adjust("1 second");
202 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "1m" });
203 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r100%\u001b[0m\ndone\n" });
204 const append = yield* takeFrame(frames);
205 assert.equal(append.kind, "append");
206 client = applyFrame(client, append);
207 assert.equal(
208 client.text,
209 normalizeTerminalOutput(
210 "\u001b[32mbuilding\u001b[0m\n10%\r55%\u001b[31m\r100%\u001b[0m\ndone\n",
211 ).text,
212 );
213
214 // The persisted item settles the row; its output is what the client keeps.
215 yield* TestClock.adjust("1 second");
216 yield* writeCommandItem(threadId, {
217 status: "completed",
218 exitCode: 0,
219 output: "building\n100%\ndone\n",
220 });
221 const final = yield* takeFrame(frames);
222 assert.deepEqual(final, {
223 kind: "replace",
224 text: "building\n100%\ndone\n",
225 truncated: false,
226 running: false,
227 });
228 assert.equal(yield* Queue.take(frames), "ended");
229 }),
230 ),
231 );
232
233 it.effect("a row that is not a known command fails instead of waiting forever", () =>
234 Effect.gen(function* () {
235 const hub = yield* CommandOutputHub.CommandOutputHub;
236 const threadId = yield* seedThread;
237 const error = yield* hub
238 .subscribe({ threadId, itemId: ITEM_ID })
239 .pipe(Stream.runDrain, Effect.flip);
240 assert.equal(error._tag, "OrchestrationV2CommandOutputError");
241 assert.equal(error.message, "No such command.");
242 }),
243 );
244
245 it.effect("a viewer whose command was evicted for newer ones is resynced, not appended to", () =>
246 Effect.scoped(
247 Effect.gen(function* () {
248 const hub = yield* CommandOutputHub.CommandOutputHub;
249 const threadId = yield* seedThread;
250 yield* writeCommandItem(threadId, { status: "running" });
251 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "abc" });
252 const frames = yield* subscribeFrames(threadId);
253 let client = applyFrame(EMPTY_TERMINAL_OUTPUT, yield* takeFrame(frames));
254 assert.equal(client.text, "abc");
255 // 64 newer commands push this one's tail out of the hub.
256 for (let index = 0; index < 64; index += 1) {
257 yield* hub.append({
258 threadId,
259 itemId: TurnItemId.make(`turn-item:other-${index}`),
260 chunk: "x",
261 });
262 }
263 yield* TestClock.adjust("1 second");
264 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\rX" });
265 const next = yield* takeFrame(frames);
266 assert.equal(next.kind, "replace");
267 client = applyFrame(client, next);
268 assert.equal(client.text, "X");
269 }),
270 ),
271 );
272
273 it.effect("every viewer of one command reconstructs the same text", () =>
274 Effect.scoped(
275 Effect.gen(function* () {
276 const hub = yield* CommandOutputHub.CommandOutputHub;
277 const threadId = yield* seedThread;
278 yield* writeCommandItem(threadId, { status: "running" });
279 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "first\n" });
280 const viewers = [yield* subscribeFrames(threadId), yield* subscribeFrames(threadId)];
281 const states = [EMPTY_TERMINAL_OUTPUT, EMPTY_TERMINAL_OUTPUT];
282 for (const [index, frames] of viewers.entries()) {
283 states[index] = applyFrame(states[index]!, yield* takeFrame(frames));
284 }
285 yield* TestClock.adjust("1 second");
286 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "second\r\nthird" });
287 for (const [index, frames] of viewers.entries()) {
288 states[index] = applyFrame(states[index]!, yield* takeFrame(frames));
289 }
290 assert.equal(states[0]!.text, "first\nsecond\nthird");
291 assert.equal(states[1]!.text, states[0]!.text);
292 }),
293 ),
294 );
295
296 it.effect("a flood is sent as bounded tails at a slower rate, not as every chunk", () =>
297 Effect.scoped(
298 Effect.gen(function* () {
299 const hub = yield* CommandOutputHub.CommandOutputHub;
300 const threadId = yield* seedThread;
301 yield* writeCommandItem(threadId, { status: "running" });
302 const stamped = yield* Queue.unbounded<{
303 readonly frame: OrchestrationV2CommandOutputFrame;
304 readonly at: number;
305 }>();
306 yield* hub.subscribe({ threadId, itemId: ITEM_ID }).pipe(
307 Stream.runForEach((frame) =>
308 Clock.currentTimeMillis.pipe(
309 Effect.flatMap((at) => Queue.offer(stamped, { frame, at })),
310 ),
311 ),
312 Effect.forkScoped,
313 );
314 let client = applyFrame(EMPTY_TERMINAL_OUTPUT, (yield* Queue.take(stamped)).frame);
315 yield* TestClock.adjust("1 second");
316
317 // `yes | head -n 1000000`: 2 MB in 4 KB chunks, 64 KB every 100 ms.
318 const chunk = "y\n".repeat(2_048);
319 const sent: Array<{
320 readonly frame: OrchestrationV2CommandOutputFrame;
321 readonly at: number;
322 }> = [];
323 const drain = Effect.gen(function* () {
324 for (const entry of yield* Queue.clear(stamped)) {
325 sent.push(entry);
326 client = applyFrame(client, entry.frame);
327 }
328 });
329 for (let tick = 0; tick < 32; tick += 1) {
330 for (let index = 0; index < 16; index += 1) {
331 yield* hub.append({ threadId, itemId: ITEM_ID, chunk });
332 }
333 yield* TestClock.adjust(CommandOutputHub.COMMAND_OUTPUT_FRAME_INTERVAL_MS);
334 yield* drain;
335 }
336 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "tail\n" });
337 yield* TestClock.adjust("1 second");
338 yield* drain;
339
340 const bytes = sent.reduce((total, { frame }) => total + frame.text.length, 0);
341 // 3.2 s of flooding: a frame per chunk would be 512 frames and 2 MB.
342 assert.isAtMost(sent.length, 10);
343 assert.isAtMost(bytes, 10 * TERMINAL_OUTPUT_TAIL_CHARS);
344 for (const { frame } of sent) {
345 assert.isAtMost(frame.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
346 }
347 for (let index = 1; index < sent.length; index += 1) {
348 if (sent[index - 1]!.frame.kind === "replace") {
349 assert.isAtLeast(
350 sent[index]!.at - sent[index - 1]!.at,
351 CommandOutputHub.COMMAND_OUTPUT_REPLACE_INTERVAL_MS,
352 );
353 }
354 }
355 assert.isTrue(client.truncated);
356 assert.isTrue(client.text.endsWith("y\ny\ntail\n"));
357 assert.isAtMost(client.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
358 }),
359 ),
360 );
361
362 it.effect("a finished command sends only its bounded final output", () =>
363 Effect.scoped(
364 Effect.gen(function* () {
365 const threadId = yield* seedThread;
366 const huge = Array.from({ length: 400_000 }, (_, index) => `line ${index}`).join("\n");
367 yield* writeCommandItem(threadId, { status: "failed", exitCode: 1, output: huge });
368 const frames = yield* subscribeFrames(threadId);
369 const final = yield* takeFrame(frames);
370 assert.equal(final.kind, "replace");
371 assert.isFalse(final.running);
372 assert.isTrue(final.truncated);
373 assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
374 assert.isTrue(final.text.endsWith("line 399999"));
375 assert.equal(yield* Queue.take(frames), "ended");
376 }),
377 ),
378 );
379
380 it.effect("a finished command whose output is one huge line still shows its tail", () =>
381 Effect.scoped(
382 Effect.gen(function* () {
383 const threadId = yield* seedThread;
384 const line = "x".repeat(TERMINAL_OUTPUT_TAIL_CHARS * 8);
385 yield* writeCommandItem(threadId, {
386 status: "completed",
387 exitCode: 0,
388 output: `${line}\n`,
389 });
390 const frames = yield* subscribeFrames(threadId);
391 const final = yield* takeFrame(frames);
392 assert.equal(final.kind, "replace");
393 assert.isTrue(final.truncated);
394 assert.isTrue(final.text.includes("xxxx"));
395 assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
396 }),
397 ),
398 );
399
400 it.effect("an old Claude row's raw Bash result shows as its stdout and stderr", () =>
401 Effect.scoped(
402 Effect.gen(function* () {
403 const threadId = yield* seedThread;
404 yield* writeCommandItem(threadId, {
405 status: "completed",
406 exitCode: 0,
407 output: '{"stdout":"built","stderr":"1 warning","interrupted":false}',
408 });
409 const frames = yield* subscribeFrames(threadId);
410 const final = yield* takeFrame(frames);
411 assert.equal(final.text, "built\n1 warning");
412 }),
413 ),
414 );
415
416 it.effect("providers that only report output in item snapshots still stream", () =>
417 Effect.scoped(
418 Effect.gen(function* () {
419 const threadId = yield* seedThread;
420 yield* writeCommandItem(threadId, { status: "running", output: "step 1\n" });
421 const frames = yield* subscribeFrames(threadId);
422 assert.equal((yield* takeFrame(frames)).text, "step 1\n");
423 yield* TestClock.adjust("1 second");
424 yield* writeCommandItem(threadId, { status: "running", output: "step 1\nstep 2\n" });
425 const update = yield* takeFrame(frames);
426 assert.deepEqual(update, {
427 kind: "replace",
428 text: "step 1\nstep 2\n",
429 truncated: false,
430 running: true,
431 });
432 }),
433 ),
434 );
435
436 it.effect("an interrupted command ends the stream with the output it printed", () =>
437 Effect.scoped(
438 Effect.gen(function* () {
439 const hub = yield* CommandOutputHub.CommandOutputHub;
440 const threadId = yield* seedThread;
441 yield* writeCommandItem(threadId, { status: "running" });
442 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "waiting for server\n" });
443 const frames = yield* subscribeFrames(threadId);
444 yield* takeFrame(frames);
445 yield* TestClock.adjust("1 second");
446 // Some providers stop a command without reporting its output. The session
447 // manager releases the live tail before the settled item is persisted.
448 yield* hub.finish({ threadId, itemId: ITEM_ID });
449 yield* writeCommandItem(threadId, { status: "interrupted" });
450 const final = yield* takeFrame(frames);
451 assert.deepEqual(final, {
452 kind: "replace",
453 text: "waiting for server\n",
454 truncated: false,
455 running: false,
456 });
457 assert.equal(yield* Queue.take(frames), "ended");
458 }),
459 ),
460 );
461});