@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 357 lines 12.5 KB
Raw
1 import { assert, it } from "@effect/vitest";
2 import {
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";
12 import {
13 appendTerminalOutput,
14 EMPTY_TERMINAL_OUTPUT,
15 normalizeTerminalOutput,
16 TERMINAL_OUTPUT_TAIL_CHARS,
17 type TerminalOutputState,
18 } from "@t3tools/shared/terminalOutput";
19 import * as DateTime from "effect/DateTime";
20 import * as Effect from "effect/Effect";
21 import * as Layer from "effect/Layer";
22 import * as Queue from "effect/Queue";
23 import * as Stream from "effect/Stream";
24 import * as TestClock from "effect/testing/TestClock";
25
26 import * as SqlitePersistence from "../persistence/Sqlite.ts";
27 import * as CommandOutputHub from "./CommandOutputHub.ts";
28 import * as EventSink from "./EventSink.ts";
29 import * as EventStore from "./EventStore.ts";
30 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
31 import * as ProjectionStore from "./ProjectionStore.ts";
32
33 const layerTestDatabase = SqlitePersistence.layerMemory;
34 const layerTestStores = Layer.merge(EventStore.layer, ProjectionStore.layer).pipe(
35 Layer.provide(layerTestDatabase),
36 );
37 const layerTestEventSink = EventSink.layer.pipe(
38 Layer.provide(Layer.mergeAll(layerTestStores, layerTestDatabase)),
39 );
40 const layerTest = Layer.mergeAll(
41 layerTestEventSink,
42 IdAllocator.layer,
43 CommandOutputHub.layer.pipe(Layer.provide(Layer.merge(layerTestEventSink, layerTestStores))),
44 );
45
46 const modelSelection = {
47 instanceId: ProviderInstanceId.make("codex"),
48 model: "gpt-5.4",
49 } satisfies ModelSelection;
50 const CODEX_DRIVER = ProviderDriverKind.make("codex");
51 const CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent");
52 const ITEM_ID = TurnItemId.make("turn-item:command");
53
54 function 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);
61 }
62
63 const 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
108 const writeCommandItem = (
109 threadId: ThreadId,
110 fields: Pick<
111 Extract<OrchestrationV2TurnItem, { type: "command_execution" }>,
112 "status" | "output" | "exitCode"
113 > & {
114 readonly driver?: ProviderDriverKind;
115 readonly startedAt?: DateTime.Utc;
116 },
117 ) =>
118 Effect.gen(function* () {
119 const idAllocator = yield* IdAllocator.IdAllocatorV2;
120 const eventSink = yield* EventSink.EventSinkV2;
121 const { driver = CODEX_DRIVER, startedAt = yield* DateTime.now, ...itemFields } = fields;
122 const settled = fields.status !== "running";
123 const item: OrchestrationV2TurnItem = {
124 id: ITEM_ID,
125 threadId,
126 runId: null,
127 nodeId: null,
128 providerThreadId: null,
129 providerTurnId: null,
130 nativeItemRef: { driver, nativeId: "tool-1", strength: "strong" },
131 parentItemId: null,
132 ordinal: 1,
133 title: null,
134 startedAt,
135 completedAt: settled ? startedAt : null,
136 updatedAt: startedAt,
137 type: "command_execution",
138 input: "yes | head -n 1000000",
139 ...itemFields,
140 };
141 yield* eventSink.write({
142 events: [
143 {
144 id: yield* idAllocator.allocate.event({ threadId }),
145 type: "turn-item.updated",
146 threadId,
147 driver,
148 providerInstanceId: modelSelection.instanceId,
149 occurredAt: startedAt,
150 payload: item,
151 },
152 ],
153 });
154 });
155
156 const subscribeFrames = (threadId: ThreadId) =>
157 Effect.gen(function* () {
158 const hub = yield* CommandOutputHub.CommandOutputHub;
159 const frames = yield* Queue.unbounded<OrchestrationV2CommandOutputFrame | "ended">();
160 yield* hub.subscribe({ threadId, itemId: ITEM_ID }).pipe(
161 Stream.runForEach((frame) => Queue.offer(frames, frame)),
162 Effect.andThen(Queue.offer(frames, "ended")),
163 Effect.forkScoped,
164 );
165 return frames;
166 });
167
168 const takeFrame = (frames: Queue.Queue<OrchestrationV2CommandOutputFrame | "ended">) =>
169 Queue.take(frames).pipe(
170 Effect.filterOrElse(
171 (frame) => !(frame === "ended"),
172 (_frame) => Effect.die("command output stream ended early"),
173 ),
174 );
175
176 const layer = it.layer(layerTest);
177
178 layer("CommandOutputHub", (it) => {
179 it.effect(
180 "a late subscriber gets the running tail, then live appends, then the final output",
181 () =>
182 Effect.gen(function* () {
183 const hub = yield* CommandOutputHub.CommandOutputHub;
184 const threadId = yield* seedThread;
185 yield* writeCommandItem(threadId, { status: "running" });
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 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 yield* TestClock.adjust("1 second");
214 yield* writeCommandItem(threadId, {
215 status: "completed",
216 exitCode: 0,
217 output: "building\n100%\ndone\n",
218 });
219 const final = yield* takeFrame(frames);
220 assert.deepEqual(final, {
221 kind: "replace",
222 text: "building\n100%\ndone\n",
223 truncated: false,
224 running: false,
225 });
226 assert.equal(yield* Queue.take(frames), "ended");
227 }),
228 );
229
230 it.effect("a row that is not a known command fails instead of waiting forever", () =>
231 Effect.gen(function* () {
232 const hub = yield* CommandOutputHub.CommandOutputHub;
233 const threadId = yield* seedThread;
234 const error = yield* hub
235 .subscribe({ threadId, itemId: ITEM_ID })
236 .pipe(Stream.runDrain, Effect.flip);
237 assert.equal(error._tag, "OrchestrationV2CommandOutputError");
238 assert.equal(error.message, "No such command.");
239 }),
240 );
241
242 it.effect("a viewer whose command was evicted for newer ones is resynced, not appended to", () =>
243 Effect.gen(function* () {
244 const hub = yield* CommandOutputHub.CommandOutputHub;
245 const threadId = yield* seedThread;
246 yield* writeCommandItem(threadId, { status: "running" });
247 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "abc" });
248 const frames = yield* subscribeFrames(threadId);
249 let client = applyFrame(EMPTY_TERMINAL_OUTPUT, yield* takeFrame(frames));
250 assert.equal(client.text, "abc");
251 for (let index = 0; index < 64; index += 1) {
252 yield* hub.append({
253 threadId,
254 itemId: TurnItemId.make(`turn-item:other-${index}`),
255 chunk: "x",
256 });
257 }
258 yield* TestClock.adjust("1 second");
259 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\rX" });
260 const next = yield* takeFrame(frames);
261 assert.equal(next.kind, "replace");
262 client = applyFrame(client, next);
263 assert.equal(client.text, "X");
264 }),
265 );
266
267 it.effect("a finished command sends only its bounded final output", () =>
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 it.effect("a finished command whose output is one huge line still shows its tail", () =>
284 Effect.gen(function* () {
285 const threadId = yield* seedThread;
286 const line = "x".repeat(TERMINAL_OUTPUT_TAIL_CHARS * 8);
287 yield* writeCommandItem(threadId, {
288 status: "completed",
289 exitCode: 0,
290 output: `${line}\n`,
291 });
292 const frames = yield* subscribeFrames(threadId);
293 const final = yield* takeFrame(frames);
294 assert.equal(final.kind, "replace");
295 assert.isTrue(final.truncated);
296 assert.isTrue(final.text.includes("xxxx"));
297 assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
298 }),
299 );
300
301 it.effect("an early Claude row's raw Bash result shows as its stdout and stderr", () =>
302 Effect.gen(function* () {
303 const threadId = yield* seedThread;
304 yield* writeCommandItem(threadId, {
305 status: "completed",
306 exitCode: 0,
307 output: '{"stdout":"built","stderr":"1 warning","interrupted":false}',
308 driver: CLAUDE_DRIVER,
309 startedAt: DateTime.makeUnsafe("2026-10-03T12:00:00Z"),
310 });
311 const frames = yield* subscribeFrames(threadId);
312 const final = yield* takeFrame(frames);
313 assert.equal(final.text, "built\n1 warning");
314 }),
315 );
316
317 it.effect("providers that only report output in item snapshots still stream", () =>
318 Effect.gen(function* () {
319 const threadId = yield* seedThread;
320 yield* writeCommandItem(threadId, { status: "running", output: "step 1\n" });
321 const frames = yield* subscribeFrames(threadId);
322 assert.equal((yield* takeFrame(frames)).text, "step 1\n");
323 yield* TestClock.adjust("1 second");
324 yield* writeCommandItem(threadId, { status: "running", output: "step 1\nstep 2\n" });
325 const update = yield* takeFrame(frames);
326 assert.deepEqual(update, {
327 kind: "replace",
328 text: "step 1\nstep 2\n",
329 truncated: false,
330 running: true,
331 });
332 }),
333 );
334
335 it.effect("an interrupted command ends the stream with the output it printed", () =>
336 Effect.gen(function* () {
337 const hub = yield* CommandOutputHub.CommandOutputHub;
338 const threadId = yield* seedThread;
339 yield* writeCommandItem(threadId, { status: "running" });
340 yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "waiting for server\n" });
341 const frames = yield* subscribeFrames(threadId);
342 yield* takeFrame(frames);
343 yield* TestClock.adjust("1 second");
344 // Some providers omit stopped-command output; the live tail is released before the settled item persists.
345 yield* hub.finish({ threadId, itemId: ITEM_ID });
346 yield* writeCommandItem(threadId, { status: "interrupted" });
347 const final = yield* takeFrame(frames);
348 assert.deepEqual(final, {
349 kind: "replace",
350 text: "waiting for server\n",
351 truncated: false,
352 running: false,
353 });
354 assert.equal(yield* Queue.take(frames), "ended");
355 }),
356 );
357 });