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 DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
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(
36 EventStore.layer,
37 ProjectionStore.layer.pipe(Layer.provide(NodeCrypto.layerDigest)),
38).pipe(Layer.provide(layerTestDatabase));
39const layerTestEventSink = EventSink.layer.pipe(
40 Layer.provide(Layer.mergeAll(layerTestStores, layerTestDatabase)),
41);
42const layerTest = Layer.mergeAll(
43 layerTestEventSink,
44 IdAllocator.layer,
45 CommandOutputHub.layer.pipe(Layer.provide(Layer.merge(layerTestEventSink, layerTestStores))),
46);
47
48const modelSelection = {
49 instanceId: ProviderInstanceId.make("codex"),
50 model: "gpt-5.4",
51} satisfies ModelSelection;
52const CODEX_DRIVER = ProviderDriverKind.make("codex");
53const CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent");
54const ITEM_ID = TurnItemId.make("turn-item:command");
55
56function applyFrame(
57 state: TerminalOutputState,
58 frame: OrchestrationV2CommandOutputFrame,
59): TerminalOutputState {
60 return frame.kind === "replace"
61 ? appendTerminalOutput({ ...EMPTY_TERMINAL_OUTPUT, truncated: frame.truncated }, frame.text)
62 : appendTerminalOutput(state, frame.text);
63}
64
65const seedThread = Effect.gen(function* () {
66 const idAllocator = yield* IdAllocator.IdAllocatorV2;
67 const eventSink = yield* EventSink.EventSinkV2;
68 const now = yield* DateTime.now;
69 const projectId = yield* idAllocator.allocate.project({ fixtureName: "command-output" });
70 const threadId = yield* idAllocator.allocate.thread({ fixtureName: "command-output", projectId });
71 const thread: OrchestrationV2AppThread = {
72 createdBy: "user",
73 creationSource: "web",
74 id: threadId,
75 projectId,
76 title: "Command output",
77 providerInstanceId: modelSelection.instanceId,
78 modelSelection,
79 runtimeMode: "full-access",
80 interactionMode: "default",
81 branch: null,
82 worktreePath: null,
83 branchPullRequest: null,
84 activeOrderKey: null,
85 activeProviderThreadId: null,
86 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
87 forkedFrom: null,
88 createdAt: now,
89 updatedAt: now,
90 archivedAt: null,
91 settledOverride: null,
92 settledAt: null,
93 lastVisitedAt: null,
94 deletedAt: null,
95 };
96 yield* eventSink.write({
97 events: [
98 {
99 id: yield* idAllocator.allocate.event({ threadId }),
100 type: "thread.created",
101 threadId,
102 occurredAt: now,
103 payload: thread,
104 },
105 ],
106 });
107 return threadId;
108});
109
110const writeCommandItem = (
111 threadId: ThreadId,
112 fields: Pick<
113 Extract<OrchestrationV2TurnItem, { type: "command_execution" }>,
114 "status" | "output" | "exitCode"
115 > & {
116 readonly driver?: ProviderDriverKind;
117 readonly startedAt?: DateTime.Utc;
118 },
119) =>
120 Effect.gen(function* () {
121 const idAllocator = yield* IdAllocator.IdAllocatorV2;
122 const eventSink = yield* EventSink.EventSinkV2;
123 const { driver = CODEX_DRIVER, startedAt = yield* DateTime.now, ...itemFields } = fields;
124 const settled = fields.status !== "running";
125 const item: OrchestrationV2TurnItem = {
126 id: ITEM_ID,
127 threadId,
128 runId: null,
129 nodeId: null,
130 providerThreadId: null,
131 providerTurnId: null,
132 nativeItemRef: { driver, nativeId: "tool-1", strength: "strong" },
133 parentItemId: null,
134 ordinal: 1,
135 title: null,
136 startedAt,
137 completedAt: settled ? startedAt : null,
138 updatedAt: startedAt,
139 type: "command_execution",
140 input: "yes | head -n 1000000",
141 ...itemFields,
142 };
143 yield* eventSink.write({
144 events: [
145 {
146 id: yield* idAllocator.allocate.event({ threadId }),
147 type: "turn-item.updated",
148 threadId,
149 driver,
150 providerInstanceId: modelSelection.instanceId,
151 occurredAt: startedAt,
152 payload: item,
153 },
154 ],
155 });
156 });
157
158const subscribeFrames = (threadId: ThreadId) =>
159 Effect.gen(function* () {
160 const hub = yield* CommandOutputHub.CommandOutputHub;
161 const frames = yield* Queue.unbounded<OrchestrationV2CommandOutputFrame | "ended">();
162 yield* hub.subscribe({ threadId, itemId: ITEM_ID }).pipe(
163 Stream.runForEach((frame) => Queue.offer(frames, frame)),
164 Effect.andThen(Queue.offer(frames, "ended")),
165 Effect.forkScoped,
166 );
167 return frames;
168 });
169
170const takeFrame = (frames: Queue.Queue<OrchestrationV2CommandOutputFrame | "ended">) =>
171 Queue.take(frames).pipe(
172 Effect.filterOrElse(
173 (frame) => !(frame === "ended"),
174 (_frame) => Effect.die("command output stream ended early"),
175 ),
176 );
177
178const layer = it.layer(layerTest);
179
180layer("CommandOutputHub", (it) => {
181 it.effect(
182 "a late subscriber gets the running tail, then live appends, then the final output",
183 () =>
184 Effect.gen(function* () {
185 const hub = yield* CommandOutputHub.CommandOutputHub;
186 const threadId = yield* seedThread;
187 yield* writeCommandItem(threadId, { status: "running" });
188 yield* hub.append({
189 threadId,
190 itemId: ITEM_ID,
191 chunk: "\u001b[32mbuilding\u001b[0m\n10%",
192 });
193 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r55%\u001b[3" });
194
195 const frames = yield* subscribeFrames(threadId);
196 const first = yield* takeFrame(frames);
197 assert.equal(first.kind, "replace");
198 assert.isTrue(first.running);
199 let client = applyFrame(EMPTY_TERMINAL_OUTPUT, first);
200 assert.equal(client.text, "\u001b[0;32mbuilding\u001b[0m\n55%");
201
202 yield* TestClock.adjust("1 second");
203 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "1m" });
204 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r100%\u001b[0m\ndone\n" });
205 const append = yield* takeFrame(frames);
206 assert.equal(append.kind, "append");
207 client = applyFrame(client, append);
208 assert.equal(
209 client.text,
210 normalizeTerminalOutput(
211 "\u001b[32mbuilding\u001b[0m\n10%\r55%\u001b[31m\r100%\u001b[0m\ndone\n",
212 ).text,
213 );
214
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 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.gen(function* () {
246 const hub = yield* CommandOutputHub.CommandOutputHub;
247 const threadId = yield* seedThread;
248 yield* writeCommandItem(threadId, { status: "running" });
249 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "abc" });
250 const frames = yield* subscribeFrames(threadId);
251 let client = applyFrame(EMPTY_TERMINAL_OUTPUT, yield* takeFrame(frames));
252 assert.equal(client.text, "abc");
253 for (let index = 0; index < 64; index += 1) {
254 yield* hub.append({
255 threadId,
256 itemId: TurnItemId.make(`turn-item:other-${index}`),
257 chunk: "x",
258 });
259 }
260 yield* TestClock.adjust("1 second");
261 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\rX" });
262 const next = yield* takeFrame(frames);
263 assert.equal(next.kind, "replace");
264 client = applyFrame(client, next);
265 assert.equal(client.text, "X");
266 }),
267 );
268
269 it.effect("a finished command sends only its bounded final output", () =>
270 Effect.gen(function* () {
271 const threadId = yield* seedThread;
272 const huge = Array.from({ length: 400_000 }, (_, index) => `line ${index}`).join("\n");
273 yield* writeCommandItem(threadId, { status: "failed", exitCode: 1, output: huge });
274 const frames = yield* subscribeFrames(threadId);
275 const final = yield* takeFrame(frames);
276 assert.equal(final.kind, "replace");
277 assert.isFalse(final.running);
278 assert.isTrue(final.truncated);
279 assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
280 assert.isTrue(final.text.endsWith("line 399999"));
281 assert.equal(yield* Queue.take(frames), "ended");
282 }),
283 );
284
285 it.effect("a finished command keeps the tail of a huge line before a short footer", () =>
286 Effect.gen(function* () {
287 const threadId = yield* seedThread;
288 const output = `${"x".repeat(TERMINAL_OUTPUT_TAIL_CHARS * 8)}\nOK`;
289 yield* writeCommandItem(threadId, { status: "completed", exitCode: 0, output });
290 const frames = yield* subscribeFrames(threadId);
291 const final = yield* takeFrame(frames);
292 const normalized = normalizeTerminalOutput(output);
293 assert.deepEqual(final, {
294 kind: "replace",
295 text: normalized.text,
296 truncated: normalized.truncated,
297 running: false,
298 });
299 }),
300 );
301
302 it.effect("an early Claude row's raw Bash result shows as its stdout and stderr", () =>
303 Effect.gen(function* () {
304 const threadId = yield* seedThread;
305 yield* writeCommandItem(threadId, {
306 status: "completed",
307 exitCode: 0,
308 output: '{"stdout":"built","stderr":"1 warning","interrupted":false}',
309 driver: CLAUDE_DRIVER,
310 startedAt: DateTime.makeUnsafe("2026-10-03T12:00:00Z"),
311 });
312 const frames = yield* subscribeFrames(threadId);
313 const final = yield* takeFrame(frames);
314 assert.equal(final.text, "built\n1 warning");
315 }),
316 );
317
318 it.effect("providers that only report output in item snapshots still stream", () =>
319 Effect.gen(function* () {
320 const threadId = yield* seedThread;
321 yield* writeCommandItem(threadId, { status: "running", output: "step 1\n" });
322 const frames = yield* subscribeFrames(threadId);
323 assert.equal((yield* takeFrame(frames)).text, "step 1\n");
324 yield* TestClock.adjust("1 second");
325 yield* writeCommandItem(threadId, { status: "running", output: "step 1\nstep 2\n" });
326 const update = yield* takeFrame(frames);
327 assert.deepEqual(update, {
328 kind: "replace",
329 text: "step 1\nstep 2\n",
330 truncated: false,
331 running: true,
332 });
333 }),
334 );
335
336 it.effect("an interrupted command ends the stream with the output it printed", () =>
337 Effect.gen(function* () {
338 const hub = yield* CommandOutputHub.CommandOutputHub;
339 const threadId = yield* seedThread;
340 yield* writeCommandItem(threadId, { status: "running" });
341 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "waiting for server\n" });
342 const frames = yield* subscribeFrames(threadId);
343 yield* takeFrame(frames);
344 yield* TestClock.adjust("1 second");
345 // Some providers omit stopped-command output; the live tail is released before the settled item persists.
346 yield* hub.finish({ threadId, itemId: ITEM_ID });
347 yield* writeCommandItem(threadId, { status: "interrupted" });
348 const final = yield* takeFrame(frames);
349 assert.deepEqual(final, {
350 kind: "replace",
351 text: "waiting for server\n",
352 truncated: false,
353 running: false,
354 });
355 assert.equal(yield* Queue.take(frames), "ended");
356 }),
357 );
358});