Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import {
3 type TerminalAttachStreamEvent,
4 TerminalAttachStreamEvent as TerminalAttachStreamEventSchema,
5 TerminalEvent as TerminalEventSchema,
6 WS_METHODS,
7} from "@t3tools/contracts";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as Queue from "effect/Queue";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14import * as TestClock from "effect/testing/TestClock";
15import { Rpc, RpcGroup, RpcMessage, RpcSerialization, RpcServer } from "effect/rpc";
16
17import { terminalOutputStream, withTerminalOutputWindow } from "./OutputProtocol.ts";
18
19describe("terminal output window", () => {
20 it.effect.each([
21 { tag: WS_METHODS.terminalAttach, size: 1, limit: 8 },
22 { tag: WS_METHODS.terminalObserve, size: 1, limit: 8 },
23 { tag: WS_METHODS.subscribeTerminalEvents, size: 1, limit: 8 },
24 { tag: WS_METHODS.terminalAttach, size: 64 * 1024, limit: 1 },
25 { tag: WS_METHODS.terminalObserve, size: 64 * 1024, limit: 1 },
26 { tag: WS_METHODS.subscribeTerminalMetadata, size: 1, limit: 1 },
27 ])("limits $tag with $size-byte values to $limit pending chunks", ({ tag, size, limit }) =>
28 Effect.gen(function* () {
29 const group = RpcGroup.make(Rpc.make(tag, { success: Schema.String, stream: true }));
30 const output = yield* Queue.unbounded<string>();
31 const responses = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
32 const receive = yield* Deferred.make<Parameters<RpcServer.Protocol["Service"]["run"]>[0]>();
33 const protocol = yield* RpcServer.Protocol.make((write) =>
34 Effect.gen(function* () {
35 yield* Deferred.succeed(receive, write);
36 const serialization = yield* RpcSerialization.RpcSerialization;
37 return {
38 disconnects: yield* Queue.unbounded<number>(),
39 send: (_clientId, response) => Queue.offer(responses, response),
40 end: () => Effect.void,
41 clientIds: Effect.succeed(new Set([0])),
42 initialMessage: Effect.succeedNone,
43 supportsAck: true,
44 supportsTransferables: false,
45 supportsSpanPropagation: false,
46 supportsNotifications: true,
47 codecFor: serialization.codecFor,
48 };
49 }),
50 );
51 yield* RpcServer.make(group).pipe(
52 Effect.provide(group.toLayerHandler(tag, () => Stream.fromQueue(output))),
53 Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)),
54 Effect.forkScoped,
55 );
56 const write = yield* Deferred.await(receive);
57 yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] });
58
59 for (let index = 0; index < limit; index++) {
60 const value = String(index).repeat(size);
61 yield* Queue.offer(output, value);
62 yield* TestClock.adjust(0);
63 assert.equal(yield* Queue.size(responses), 1);
64 assert.deepEqual(yield* Queue.take(responses), {
65 _tag: "Chunk",
66 requestId: "1",
67 values: [value],
68 });
69 }
70 yield* Queue.offer(output, "i".repeat(size));
71 yield* TestClock.adjust(0);
72 assert.equal(yield* Queue.size(responses), 0);
73 yield* write(0, { _tag: "Ack", requestId: "1" });
74 const resumed = yield* Queue.take(responses);
75 assert.equal(resumed._tag, "Chunk");
76 if (resumed._tag === "Chunk") assert.deepEqual(resumed.values, ["i".repeat(size)]);
77
78 yield* Queue.offer(output, "j");
79 yield* TestClock.adjust(0);
80 assert.equal(yield* Queue.size(responses), 0);
81 yield* write(0, { _tag: "Interrupt", requestId: "1" });
82 assert.equal((yield* Queue.take(responses))._tag, "Exit");
83 }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),
84 );
85});
86
87const output = (data: string): TerminalAttachStreamEvent => ({
88 type: "output",
89 threadId: "thread-1",
90 terminalId: "default",
91 data,
92});
93
94const snapshot = (history: string): TerminalAttachStreamEvent => ({
95 type: "snapshot",
96 snapshot: {
97 threadId: "thread-1",
98 terminalId: "default",
99 cwd: "/repo",
100 worktreePath: null,
101 status: "running",
102 pid: 1,
103 history,
104 exitCode: null,
105 exitSignal: null,
106 label: "bash",
107 updatedAt: "2026-01-01T00:00:00.000Z",
108 },
109});
110
111// Stands in for TerminalManager's fanout: listeners run in publish order and
112// may release themselves while it iterates.
113const makePublisher = () => {
114 const listeners = new Set<(event: TerminalAttachStreamEvent) => Effect.Effect<void>>();
115 return {
116 listeners,
117 subscribe: (
118 listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
119 registerCleanup?: (stop: () => void) => void,
120 ) =>
121 Effect.sync(() => {
122 listeners.add(listener);
123 const stop = () => {
124 listeners.delete(listener);
125 };
126 registerCleanup?.(stop);
127 return stop;
128 }),
129 publish: (event: TerminalAttachStreamEvent) =>
130 Effect.forEach(listeners, (listener) => listener(event), { discard: true }),
131 };
132};
133
134// Like TerminalManager.attachStream: a snapshot, then live events.
135const attach =
136 (publisher: ReturnType<typeof makePublisher>, history: string) =>
137 (
138 listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
139 registerCleanup: (stop: () => void) => void,
140 ) =>
141 publisher
142 .subscribe(listener, registerCleanup)
143 .pipe(Effect.tap(() => listener(snapshot(history))));
144
145const chunkBytes = (message: RpcMessage.FromServerEncoded) =>
146 Buffer.byteLength(JSON.stringify(message));
147
148describe("terminal output stream", () => {
149 it.effect.each([
150 WS_METHODS.terminalAttach,
151 WS_METHODS.terminalObserve,
152 WS_METHODS.subscribeTerminalEvents,
153 ])("releases only the ACK-stalled subscriber on %s and resumes safely", (tag) =>
154 Effect.gen(function* () {
155 const legacy = tag === WS_METHODS.subscribeTerminalEvents;
156 const group = RpcGroup.make(
157 Rpc.make(tag, {
158 success: legacy ? TerminalEventSchema : TerminalAttachStreamEventSchema,
159 stream: true,
160 }),
161 );
162 const publisher = makePublisher();
163 const stalled = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
164 const healthy = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
165 const receive = yield* Deferred.make<Parameters<RpcServer.Protocol["Service"]["run"]>[0]>();
166 const protocol = yield* RpcServer.Protocol.make((write) =>
167 Effect.gen(function* () {
168 yield* Deferred.succeed(receive, write);
169 const serialization = yield* RpcSerialization.RpcSerialization;
170 return {
171 disconnects: yield* Queue.unbounded<number>(),
172 send: (clientId, response) => Queue.offer(clientId === 0 ? stalled : healthy, response),
173 end: () => Effect.void,
174 clientIds: Effect.succeed(new Set([0, 1])),
175 initialMessage: Effect.succeedNone,
176 supportsAck: true,
177 supportsTransferables: false,
178 supportsSpanPropagation: false,
179 supportsNotifications: true,
180 codecFor: serialization.codecFor,
181 };
182 }),
183 );
184 const initial = legacy ? output("ready") : snapshot("");
185 yield* RpcServer.make(group).pipe(
186 Effect.provide(
187 group.toLayerHandler(tag, () =>
188 terminalOutputStream(
189 (listener, registerCleanup) =>
190 publisher
191 .subscribe(listener, registerCleanup)
192 .pipe(Effect.tap(() => listener(initial))),
193 legacy ? undefined : attach(publisher, "fresh history"),
194 256 * 1024,
195 ),
196 ),
197 ),
198 Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)),
199 Effect.forkScoped,
200 );
201 const write = yield* Deferred.await(receive);
202 const takeChunk = Effect.fnUntraced(function* (queue: typeof stalled) {
203 const response = yield* Queue.take(queue);
204 assert.equal(response._tag, "Chunk");
205 if (response._tag !== "Chunk") throw new Error("Expected an RPC chunk");
206 assert.isAtMost(chunkBytes(response), 70 * 1024);
207 return response.values;
208 });
209 yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] });
210 assert.deepEqual(yield* takeChunk(stalled), [initial]);
211 yield* write(1, { _tag: "Request", id: "2", tag, payload: null, headers: [] });
212 assert.deepEqual(yield* takeChunk(healthy), [initial]);
213 yield* write(1, { _tag: "Ack", requestId: "2" });
214
215 // Eight unacknowledged chunks fill only client 0's output window.
216 for (let index = 0; index < 7; index++) {
217 const event = output("before-stall-" + index);
218 yield* publisher.publish(event);
219 assert.deepEqual(yield* takeChunk(stalled), [event]);
220 assert.deepEqual(yield* takeChunk(healthy), [event]);
221 yield* write(1, { _tag: "Ack", requestId: "2" });
222 }
223 assert.equal(publisher.listeners.size, 2);
224 for (let index = 0; index < 100; index++) {
225 const event = output(index + ":" + "界".repeat(1365));
226 yield* publisher.publish(event);
227 assert.deepEqual(yield* takeChunk(healthy), [event]);
228 yield* write(1, { _tag: "Ack", requestId: "2" });
229 if (index === 31) assert.equal(publisher.listeners.size, 2);
230 }
231 assert.equal(yield* Queue.size(stalled), 0);
232 assert.equal(publisher.listeners.size, 1);
233
234 yield* write(0, { _tag: "Ack", requestId: "1" });
235 if (legacy) {
236 assert.deepEqual(yield* Queue.take(stalled), {
237 _tag: "Exit",
238 requestId: "1",
239 exit: { _tag: "Success", value: null },
240 });
241 } else {
242 assert.deepEqual(yield* takeChunk(stalled), [snapshot("fresh history")]);
243 assert.equal(publisher.listeners.size, 2);
244 for (let index = 0; index < 7; index++) {
245 yield* write(0, { _tag: "Ack", requestId: "1" });
246 }
247 }
248 const after = output("unique output after recovery");
249 yield* publisher.publish(after);
250 assert.deepEqual(yield* takeChunk(healthy), [after]);
251 if (!legacy) assert.deepEqual(yield* takeChunk(stalled), [after]);
252 assert.equal(yield* Queue.size(stalled), 0);
253 }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),
254 );
255
256 it.effect("interrupts recovery while its subscription is still waiting", () =>
257 Effect.gen(function* () {
258 const publisher = makePublisher();
259 const recovering = yield* Deferred.make<void>();
260 const interrupted = yield* Deferred.make<void>();
261 const pull = yield* Stream.toPull(
262 terminalOutputStream(
263 attach(publisher, ""),
264 () =>
265 Deferred.succeed(recovering, undefined).pipe(
266 Effect.andThen(Effect.never),
267 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
268 ),
269 1024,
270 ),
271 );
272 yield* pull;
273 yield* publisher.publish(output("x".repeat(1024)));
274 yield* publisher.publish(output("x".repeat(1024)));
275 assert.equal(publisher.listeners.size, 0);
276
277 const recovery = yield* pull.pipe(Effect.forkChild({ startImmediately: true }));
278 yield* Deferred.await(recovering);
279 yield* Fiber.interrupt(recovery);
280 yield* Deferred.await(interrupted);
281 assert.equal(publisher.listeners.size, 0);
282 }).pipe(Effect.scoped),
283 );
284
285 it.effect("cleans listeners when cancelled during a successful acquisition handoff", () =>
286 Effect.gen(function* () {
287 const publisher = makePublisher();
288 for (const recovering of [false, true, false, true]) {
289 const handoff = yield* Deferred.make<void>();
290 const complete = yield* Deferred.make<void>();
291 const acquire: ReturnType<typeof attach> = (listener, registerCleanup) =>
292 attach(publisher, "")(listener, registerCleanup).pipe(
293 // Hold the successful exit before its cleanup handle reaches the caller.
294 Effect.onExit(() =>
295 Deferred.succeed(handoff, undefined).pipe(Effect.andThen(Deferred.await(complete))),
296 ),
297 );
298 const consumer = yield* Effect.gen(function* () {
299 const pull = yield* Stream.toPull(
300 terminalOutputStream(recovering ? attach(publisher, "") : acquire, acquire, 1024),
301 );
302 yield* pull;
303 yield* publisher.publish(output("x".repeat(1024)));
304 yield* publisher.publish(output("x".repeat(1024)));
305 yield* pull;
306 }).pipe(Effect.scoped, Effect.forkChild({ startImmediately: true }));
307 yield* Deferred.await(handoff);
308 assert.equal(publisher.listeners.size, 1);
309 const cancellation = yield* Fiber.interrupt(consumer).pipe(
310 Effect.forkChild({ startImmediately: true }),
311 );
312 yield* Deferred.succeed(complete, undefined);
313 yield* Fiber.join(cancellation);
314 assert.equal(publisher.listeners.size, 0);
315 }
316 }).pipe(Effect.scoped),
317 );
318
319 it.effect("caps each delivered batch at the output window in UTF-8 bytes", () =>
320 Effect.gen(function* () {
321 const publisher = makePublisher();
322 const pull = yield* Stream.toPull(terminalOutputStream(attach(publisher, "")));
323 assert.deepEqual(yield* pull, [snapshot("")]);
324 // 1,024 code units but 3 KiB of UTF-8.
325 const data = "界".repeat(1024);
326 for (let index = 0; index < 1024; index++) yield* publisher.publish(output(data));
327
328 let delivered = 0;
329 while (delivered < 1024) {
330 const batch = yield* pull;
331 assert.isAtMost(
332 batch.reduce(
333 (bytes, event) => bytes + (event.type === "output" ? Buffer.byteLength(event.data) : 0),
334 0,
335 ),
336 64 * 1024,
337 );
338 delivered += batch.length;
339 }
340 assert.equal(delivered, 1024);
341 }).pipe(Effect.scoped),
342 );
343
344 it.effect("charges snapshot history but never overflows on one snapshot", () =>
345 Effect.gen(function* () {
346 const publisher = makePublisher();
347 const history = "界".repeat(16 * 1024);
348 const events = terminalOutputStream(attach(publisher, history), undefined, 32 * 1024);
349 const pull = yield* Stream.toPull(events);
350 // A snapshot larger than the budget is still delivered.
351 assert.deepEqual(yield* pull, [snapshot(history)]);
352 assert.equal(publisher.listeners.size, 1);
353
354 // Queued snapshots count their history: a second one overflows.
355 yield* publisher.publish(snapshot(history));
356 assert.equal(publisher.listeners.size, 1);
357 yield* publisher.publish(snapshot(history));
358 assert.equal(publisher.listeners.size, 0);
359 }).pipe(Effect.scoped),
360 );
361});