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

CommandOutputHub.test.ts

371 lines13.2 KB

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