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

CommandOutputHub.test.ts

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