@devries-cameron20 / t3code Mirror · read-only / commits / 3284143b45
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 23, 00:30 UTC

fix(server): slow terminal clients no longer queue unbounded output (#18429)

Co-authored-by: SAPHID <saphid@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Alex Southwell committed Oct 20, 2026 at 02:05 UTC 3284143b454f2353ab3e0101c894986fe429123d
5 files changed +732 -103
apps/server/src/terminal/Manager.test.ts
+187
@@ -45,6 +45,7 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts";
45 import * as ProcessRunner from "../processRunner.ts";
46 import * as ServerSettings from "../serverSettings.ts";
47 import * as TerminalManager from "./Manager.ts";
48 +import { terminalOutputStream } from "./OutputProtocol.ts";
49 import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
50 import {
51 applyTerminalAttachStreamEvent,
@@ -185,6 +186,44 @@ class FakePtyAdapter {
186 }
187 }
188
189 +// Publishes 9 MiB of output, past a stream's 8 MiB budget, while nothing pulls.
190 +const publishPastOutputBudget = (
191 + manager: TerminalManager.TerminalManager["Service"],
192 + process: FakePtyProcess,
193 +) =>
194 + Effect.gen(function* () {
195 + const published = yield* Deferred.make<void>();
196 + const unsubscribe = yield* manager.subscribe((event) =>
197 + event.type === "output" && event.data === "last\n"
198 + ? Deferred.succeed(published, undefined).pipe(Effect.asVoid)
199 + : Effect.void,
200 + );
201 + for (let index = 0; index < 9; index++) process.emitData("x".repeat(1024 * 1024));
202 + process.emitData("last\n");
203 + yield* Deferred.await(published);
204 + unsubscribe();
205 + });
206 +
207 +// Holds the next spawn, and with it the thread lock, until `release` succeeds.
208 +class GatedPtyAdapter extends FakePtyAdapter {
209 + gate: {
210 + readonly spawning: Deferred.Deferred<void>;
211 + readonly release: Deferred.Deferred<void>;
212 + } | null = null;
213 +
214 + override spawn(
215 + input: PtyAdapter.PtySpawnInput,
216 + ): Effect.Effect<PtyAdapter.PtyProcess, PtyAdapter.PtySpawnError> {
217 + const gate = this.gate;
218 + this.gate = null;
219 + if (!gate) return super.spawn(input);
220 + return Deferred.succeed(gate.spawning, undefined).pipe(
221 + Effect.andThen(Deferred.await(gate.release)),
222 + Effect.andThen(super.spawn(input)),
223 + );
224 + }
225 +}
226 +
227 const waitFor = <E, R>(
228 predicate: Effect.Effect<boolean, E, R>,
229 timeout: Duration.Input = 800,
@@ -3206,6 +3245,154 @@ it.layer(
3245 }),
3246 );
3247
3248 + it.effect("finishes shell startup when its creating attachment is cancelled", () =>
3249 + Effect.gen(function* () {
3250 + const ptyAdapter = new GatedPtyAdapter();
3251 + const { manager } = yield* createManager(5, { ptyAdapter });
3252 + const input = openInput();
3253 + const gate = {
3254 + spawning: yield* Deferred.make<void>(),
3255 + release: yield* Deferred.make<void>(),
3256 + };
3257 + ptyAdapter.gate = gate;
3258 + const consumer = yield* Stream.runDrain(
3259 + terminalOutputStream(
3260 + (listener, registerCleanup) => manager.attachStream(input, listener, registerCleanup),
3261 + (listener, registerCleanup) => manager.resyncStream(input, listener, registerCleanup),
3262 + ),
3263 + ).pipe(Effect.forkChild({ startImmediately: true }));
3264 + yield* Deferred.await(gate.spawning);
3265 + const cancelled = yield* Fiber.interrupt(consumer).pipe(
3266 + Effect.forkChild({ startImmediately: true }),
3267 + );
3268 + yield* Deferred.succeed(gate.release, undefined);
3269 + yield* Fiber.join(cancelled);
3270 +
3271 + const snapshots: TerminalAttachStreamEvent[] = [];
3272 + const stop = yield* manager.attachStream(input, (event) =>
3273 + Effect.sync(() => {
3274 + snapshots.push(event);
3275 + }),
3276 + );
3277 + stop();
3278 + expect(snapshots).toMatchObject([
3279 + { type: "snapshot", snapshot: { status: "running", pid: ptyAdapter.processes[0]?.pid } },
3280 + ]);
3281 + expect(ptyAdapter.processes).toHaveLength(1);
3282 + }).pipe(Effect.scoped),
3283 + );
3284 +
3285 + it.effect("resyncs bounded history and follows close/reopen across a stalled stream", () =>
3286 + Effect.gen(function* () {
3287 + const ptyAdapter = new GatedPtyAdapter();
3288 + const historyByteLimit = 64 * 1024;
3289 + const { manager } = yield* createManager(5, { ptyAdapter, historyByteLimit });
3290 + const input = openInput();
3291 + const pull = yield* Stream.toPull(
3292 + terminalOutputStream(
3293 + (listener, registerCleanup) => manager.attachStream(input, listener, registerCleanup),
3294 + (listener, registerCleanup) => manager.resyncStream(input, listener, registerCleanup),
3295 + ),
3296 + );
3297 + expect(yield* pull).toMatchObject([{ type: "snapshot", snapshot: { history: "" } }]);
3298 + const process = ptyAdapter.processes[0]!;
3299 + yield* publishPastOutputBudget(manager, process);
3300 +
3301 + const resumed = yield* pull;
3302 + expect(resumed).toHaveLength(1);
3303 + expect(resumed[0]?.type).toBe("snapshot");
3304 + if (resumed[0]?.type !== "snapshot") throw new Error("Expected a recovery snapshot");
3305 + expect(Buffer.byteLength(resumed[0].snapshot.history)).toBeLessThanOrEqual(historyByteLimit);
3306 + expect(resumed[0].snapshot.history.endsWith("last\n")).toBe(true);
3307 + process.emitData("after recovery\n");
3308 + expect(yield* pull).toMatchObject([{ type: "output", data: "after recovery\n" }]);
3309 + expect(ptyAdapter.spawnInputs).toHaveLength(1);
3310 +
3311 + yield* publishPastOutputBudget(manager, process);
3312 + yield* manager.close(input);
3313 + expect(yield* pull).toEqual([
3314 + { type: "closed", threadId: input.threadId, terminalId: input.terminalId },
3315 + ]);
3316 + expect(ptyAdapter.spawnInputs).toHaveLength(1);
3317 + yield* manager.open(input);
3318 + expect(yield* pull).toMatchObject([
3319 + { type: "snapshot", snapshot: { status: "running", pid: ptyAdapter.processes[1]!.pid } },
3320 + ]);
3321 + const reopenedProcess = ptyAdapter.processes[1]!;
3322 + reopenedProcess.emitData("after reopen\n");
3323 + expect(yield* pull).toMatchObject([{ type: "output", data: "after reopen\n" }]);
3324 +
3325 + yield* publishPastOutputBudget(manager, reopenedProcess);
3326 + // Queue close/reopen ahead of recovery while another spawn owns the thread lock.
3327 + const gate = {
3328 + spawning: yield* Deferred.make<void>(),
3329 + release: yield* Deferred.make<void>(),
3330 + };
3331 + ptyAdapter.gate = gate;
3332 + const holder = yield* manager
3333 + .open(openInput({ terminalId: "other" }))
3334 + .pipe(Effect.forkChild({ startImmediately: true }));
3335 + yield* Deferred.await(gate.spawning);
3336 + const closed = yield* manager.close(input).pipe(Effect.forkChild({ startImmediately: true }));
3337 + const reopened = yield* manager
3338 + .open(input)
3339 + .pipe(Effect.forkChild({ startImmediately: true }));
3340 + const recovery = yield* pull.pipe(Effect.forkChild({ startImmediately: true }));
3341 + reopenedProcess.emitData("old session\n");
3342 + yield* Deferred.succeed(gate.release, undefined);
3343 + yield* Fiber.join(holder);
3344 + yield* Fiber.join(closed);
3345 + yield* Fiber.join(reopened);
3346 +
3347 + const batch = yield* Fiber.join(recovery);
3348 + expect(batch).toHaveLength(1);
3349 + expect(batch[0]).toMatchObject({
3350 + type: "snapshot",
3351 + snapshot: { status: "running", pid: ptyAdapter.processes.at(-1)!.pid },
3352 + });
3353 + ptyAdapter.processes.at(-1)!.emitData("new session only\n");
3354 + expect(yield* pull).toMatchObject([{ type: "output", data: "new session only\n" }]);
3355 + expect(ptyAdapter.spawnInputs).toHaveLength(4);
3356 + }).pipe(Effect.scoped),
3357 + );
3358 +
3359 + it.effect("does not replay in-flight output already included in an observer snapshot", () =>
3360 + Effect.gen(function* () {
3361 + const { manager, ptyAdapter } = yield* createManager();
3362 + const input = openInput();
3363 + yield* manager.open(input);
3364 + const reached = yield* Deferred.make<void>();
3365 + const release = yield* Deferred.make<void>();
3366 + const delivered = yield* Deferred.make<void>();
3367 + // The snapshot sees history before this earlier fanout listener releases it.
3368 + const unsubscribe = yield* manager.subscribe((event) =>
3369 + event.type === "output" && event.data === "in flight\n"
3370 + ? Deferred.succeed(reached, undefined).pipe(Effect.andThen(Deferred.await(release)))
3371 + : Effect.void,
3372 + );
3373 + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
3374 + ptyAdapter.processes[0]!.emitData("in flight\n");
3375 + yield* Deferred.await(reached);
3376 + const observed: TerminalAttachStreamEvent[] = [];
3377 + const stopObserving = yield* manager.observeStream(input, (event) =>
3378 + Effect.gen(function* () {
3379 + observed.push(event);
3380 + if (event.type === "output" && event.data === "after\n") {
3381 + yield* Deferred.succeed(delivered, undefined);
3382 + }
3383 + }),
3384 + );
3385 + yield* Effect.addFinalizer(() => Effect.sync(stopObserving));
3386 + expect(observed).toMatchObject([{ type: "snapshot", snapshot: { history: "in flight\n" } }]);
3387 + yield* Deferred.succeed(release, undefined);
3388 + ptyAdapter.processes[0]!.emitData("after\n");
3389 + yield* Deferred.await(delivered);
3390 + expect(observed.filter((event) => event.type === "output")).toMatchObject([
3391 + { data: "after\n" },
3392 + ]);
3393 + }).pipe(Effect.scoped),
3394 + );
3395 +
3396 it.effect("observes terminal history and live output without changing the process", () =>
3397 Effect.gen(function* () {
3398 const { manager, ptyAdapter } = yield* createManager();
apps/server/src/terminal/Manager.ts
+130 -80
@@ -163,11 +163,19 @@ export class TerminalManager extends Context.Service<
163 readonly attachStream: (
164 input: TerminalAttachInput,
165 listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
166 + registerCleanup?: (stop: () => void) => void,
167 ) => Effect.Effect<() => void, TerminalError>;
168
169 readonly observeStream: (
170 input: TerminalObserveInput,
171 listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
172 + registerCleanup?: (stop: () => void) => void,
173 + ) => Effect.Effect<() => void, TerminalError>;
174 +
175 + readonly resyncStream: (
176 + input: TerminalObserveInput,
177 + listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
178 + registerCleanup?: (stop: () => void) => void,
179 ) => Effect.Effect<() => void, TerminalError>;
180
181 readonly write: (input: TerminalWriteInput) => Effect.Effect<void, TerminalError>;
@@ -195,6 +203,7 @@ export class TerminalManager extends Context.Service<
203
204 readonly subscribe: (
205 listener: (event: TerminalEvent) => Effect.Effect<void>,
206 + registerCleanup?: (stop: () => void) => void,
207 ) => Effect.Effect<() => void>;
208
209 readonly subscribeMetadata: (
@@ -2761,60 +2770,56 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2770 resolveLaunchInputEnvironment(input).pipe(Effect.flatMap(openLocked)),
2771 );
2772
2764 - const openOrAttachForStream = (input: TerminalAttachInput) =>
2765 - withThreadLock(
2766 - input.threadId,
2767 - Effect.gen(function* () {
2768 - const terminalId = input.terminalId;
2769 - const existing = yield* getSession(input.threadId, terminalId);
2773 + const openOrAttachForStream = Effect.fnUntraced(function* (input: TerminalAttachInput) {
2774 + const terminalId = input.terminalId;
2775 + const existing = yield* getSession(input.threadId, terminalId);
2776
2771 - if (Option.isNone(existing)) {
2772 - if (input.resume && closedSessionKeys.has(toSessionKey(input.threadId, terminalId))) {
2773 - return null;
2774 - }
2775 - if (!input.cwd) {
2776 - return yield* new TerminalSessionLookupError({
2777 - threadId: input.threadId,
2778 - terminalId,
2779 - });
2780 - }
2777 + if (Option.isNone(existing)) {
2778 + if (input.resume && closedSessionKeys.has(toSessionKey(input.threadId, terminalId))) {
2779 + return null;
2780 + }
2781 + if (!input.cwd) {
2782 + return yield* new TerminalSessionLookupError({
2783 + threadId: input.threadId,
2784 + terminalId,
2785 + });
2786 + }
2787
2782 - const resolvedInput = yield* resolveLaunchInputEnvironment({
2783 - ...input,
2784 - terminalId,
2785 - cwd: input.cwd,
2786 - });
2787 - return yield* openLocked(resolvedInput);
2788 - }
2788 + const resolvedInput = yield* resolveLaunchInputEnvironment({
2789 + ...input,
2790 + terminalId,
2791 + cwd: input.cwd,
2792 + });
2793 + return yield* Effect.uninterruptible(openLocked(resolvedInput));
2794 + }
2795
2790 - const session = existing.value;
2791 - const targetCols = input.cols ?? session.cols;
2792 - const targetRows = input.rows ?? session.rows;
2796 + const session = existing.value;
2797 + const targetCols = input.cols ?? session.cols;
2798 + const targetRows = input.rows ?? session.rows;
2799
2794 - if (!input.resume && !session.process && input.cwd && input.restartIfNotRunning === true) {
2795 - const resolvedInput = yield* resolveLaunchInputEnvironment({
2796 - ...input,
2797 - terminalId,
2798 - cwd: input.cwd,
2799 - });
2800 - return yield* openLocked(resolvedInput);
2801 - }
2800 + if (!input.resume && !session.process && input.cwd && input.restartIfNotRunning === true) {
2801 + const resolvedInput = yield* resolveLaunchInputEnvironment({
2802 + ...input,
2803 + terminalId,
2804 + cwd: input.cwd,
2805 + });
2806 + return yield* Effect.uninterruptible(openLocked(resolvedInput));
2807 + }
2808
2803 - if (
2804 - session.process &&
2805 - session.status === "running" &&
2806 - (session.cols !== targetCols || session.rows !== targetRows)
2807 - ) {
2808 - const process = session.process;
2809 - yield* resizePtyProcess(session, process, targetCols, targetRows);
2810 - session.cols = targetCols;
2811 - session.rows = targetRows;
2812 - session.updatedAt = yield* nowIso;
2813 - }
2809 + if (
2810 + session.process &&
2811 + session.status === "running" &&
2812 + (session.cols !== targetCols || session.rows !== targetRows)
2813 + ) {
2814 + const process = session.process;
2815 + yield* resizePtyProcess(session, process, targetCols, targetRows);
2816 + session.cols = targetCols;
2817 + session.rows = targetRows;
2818 + session.updatedAt = yield* nowIso;
2819 + }
2820
2815 - return snapshot(session);
2816 - }),
2817 - );
2821 + return snapshot(session);
2822 + });
2823
2824 const readAllTerminalMetadata = () =>
2825 readManagerState.pipe(
@@ -2838,38 +2843,70 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2843 Effect.map((session) => (Option.isSome(session) ? summary(session.value) : null)),
2844 );
2845
2841 - const subscribe: TerminalManager["Service"]["subscribe"] = (listener) =>
2846 + const subscribe: TerminalManager["Service"]["subscribe"] = (listener, registerCleanup) =>
2847 Effect.sync(() => {
2848 terminalEventListeners.add(listener);
2844 - return () => {
2849 + const stop = () => {
2850 terminalEventListeners.delete(listener);
2851 };
2852 + // Transfer ownership before an interrupt can discard the returned handle.
2853 + registerCleanup?.(stop);
2854 + return stop;
2855 });
2856
2857 + // Subscribe after taking the lock so contention cannot accumulate an unbounded replay.
2858 + // Snapshot listeners run under that lock and must not block.
2859 const streamSession = (
2860 input: TerminalObserveInput,
2861 initial: Effect.Effect<TerminalSessionSnapshot | null, TerminalError>,
2862 listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
2863 + registerCleanup?: (stop: () => void) => void,
2864 ) => {
2865 let unsubscribe: (() => void) | null = null;
2866 + const stop = () => {
2867 + unsubscribe?.();
2868 + unsubscribe = null;
2869 + };
2870
2871 return Effect.gen(function* () {
2872 const bufferedEvents: TerminalEvent[] = [];
2873 let deliverLive = false;
2874 + let snapshotFloor: number | null = null;
2875
2860 - unsubscribe = yield* subscribe((event) => {
2861 - if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
2862 - return Effect.void;
2863 - }
2876 + yield* subscribe(
2877 + (event) => {
2878 + if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
2879 + return Effect.void;
2880 + }
2881
2865 - if (!deliverLive) {
2866 - bufferedEvents.push(event);
2867 - return Effect.void;
2868 - }
2882 + if (!deliverLive) {
2883 + bufferedEvents.push(event);
2884 + return Effect.void;
2885 + }
2886
2870 - const attachEvent = terminalEventToAttachEvent(event);
2871 - return attachEvent ? listener(attachEvent) : Effect.void;
2872 - });
2887 + // Fanout can finish after a snapshot that already includes the event.
2888 + // Keep only its sequence, not its history, until the session changes.
2889 + if (snapshotFloor !== null) {
2890 + if (
2891 + event.type === "started" ||
2892 + event.type === "restarted" ||
2893 + event.type === "error" ||
2894 + event.type === "closed"
2895 + ) {
2896 + snapshotFloor = null;
2897 + } else if (typeof event.sequence === "number" && event.sequence <= snapshotFloor) {
2898 + return Effect.void;
2899 + }
2900 + }
2901 +
2902 + const attachEvent = terminalEventToAttachEvent(event);
2903 + return attachEvent ? listener(attachEvent) : Effect.void;
2904 + },
2905 + (cleanup) => {
2906 + unsubscribe = cleanup;
2907 + registerCleanup?.(stop);
2908 + },
2909 + );
2910
2911 const initialSnapshot = yield* initial;
2912
@@ -2889,36 +2926,48 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2926 yield* listener(attachEvent);
2927 }
2928 }
2929 + // The live listener keeps this closure, so release replayed output.
2930 + bufferedEvents.length = 0;
2931
2932 + snapshotFloor = initialSnapshot?.sequence ?? null;
2933 deliverLive = true;
2894 - return () => {
2895 - unsubscribe?.();
2896 - unsubscribe = null;
2897 - };
2934 + return stop;
2935 }).pipe(
2899 - Effect.catchCause((cause) =>
2900 - Effect.flatMap(
2901 - Effect.sync(() => {
2902 - unsubscribe?.();
2903 - unsubscribe = null;
2904 - }),
2905 - () => Effect.failCause(cause),
2906 - ),
2907 - ),
2936 + (effect) => withThreadLock(input.threadId, effect),
2937 + Effect.onError(() => Effect.sync(stop)),
2938 );
2939 };
2940
2911 - const attachStream: TerminalManager["Service"]["attachStream"] = (input, listener) =>
2912 - streamSession(input, openOrAttachForStream(input), listener);
2941 + const attachStream: TerminalManager["Service"]["attachStream"] = (
2942 + input,
2943 + listener,
2944 + registerCleanup,
2945 + ) => streamSession(input, openOrAttachForStream(input), listener, registerCleanup);
2946 +
2947 + const observeStream: TerminalManager["Service"]["observeStream"] = (
2948 + input,
2949 + listener,
2950 + registerCleanup,
2951 + ) =>
2952 + streamSession(
2953 + input,
2954 + requireSession(input.threadId, input.terminalId).pipe(Effect.map(snapshot)),
2955 + listener,
2956 + registerCleanup,
2957 + );
2958
2914 - const observeStream: TerminalManager["Service"]["observeStream"] = (input, listener) =>
2959 + const resyncStream: TerminalManager["Service"]["resyncStream"] = (
2960 + input,
2961 + listener,
2962 + registerCleanup,
2963 + ) =>
2964 streamSession(
2965 input,
2917 - withThreadLock(
2918 - input.threadId,
2919 - requireSession(input.threadId, input.terminalId).pipe(Effect.map(snapshot)),
2966 + getSession(input.threadId, input.terminalId).pipe(
2967 + Effect.map((session) => (Option.isSome(session) ? snapshot(session.value) : null)),
2968 ),
2969 listener,
2970 + registerCleanup,
2971 );
2972
2973 const metadataEventFromTerminalEvent = (
@@ -3228,6 +3277,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3277 open,
3278 attachStream,
3279 observeStream,
3280 + resyncStream,
3281 write,
3282 resize,
3283 clear,
apps/server/src/terminal/OutputProtocol.test.ts
+284 -2
@@ -1,14 +1,20 @@
1 import { assert, describe, it } from "@effect/vitest";
2 -import { WS_METHODS } from "@t3tools/contracts";
2 +import {
3 + type TerminalAttachStreamEvent,
4 + TerminalAttachStreamEvent as TerminalAttachStreamEventSchema,
5 + TerminalEvent as TerminalEventSchema,
6 + WS_METHODS,
7 +} from "@t3tools/contracts";
8 import * as Deferred from "effect/Deferred";
9 import * as Effect from "effect/Effect";
10 +import * as Fiber from "effect/Fiber";
11 import * as Queue from "effect/Queue";
12 import * as Schema from "effect/Schema";
13 import * as Stream from "effect/Stream";
14 import * as TestClock from "effect/testing/TestClock";
15 import { Rpc, RpcGroup, RpcMessage, RpcSerialization, RpcServer } from "effect/rpc";
16
11 -import { withTerminalOutputWindow } from "./OutputProtocol.ts";
17 +import { terminalOutputStream, withTerminalOutputWindow } from "./OutputProtocol.ts";
18
19 describe("terminal output window", () => {
20 it.effect.each([
@@ -77,3 +83,279 @@ describe("terminal output window", () => {
83 }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),
84 );
85 });
86 +
87 +const output = (data: string): TerminalAttachStreamEvent => ({
88 + type: "output",
89 + threadId: "thread-1",
90 + terminalId: "default",
91 + data,
92 +});
93 +
94 +const 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.
113 +const 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.
135 +const 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 +
145 +const chunkBytes = (message: RpcMessage.FromServerEncoded) =>
146 + Buffer.byteLength(JSON.stringify(message));
147 +
148 +describe("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 +});
apps/server/src/terminal/OutputProtocol.ts
+119 -1
@@ -1,5 +1,9 @@
1 -import { WS_METHODS } from "@t3tools/contracts";
1 +import { type TerminalAttachStreamEvent, type TerminalEvent, WS_METHODS } from "@t3tools/contracts";
2 +import type * as Arr from "effect/Array";
3 +import * as Cause from "effect/Cause";
4 import * as Effect from "effect/Effect";
5 +import * as Latch from "effect/Latch";
6 +import * as Stream from "effect/Stream";
7 import type { RpcServer } from "effect/rpc";
8
9 const MAX_PENDING_CHUNKS = 8;
@@ -66,3 +70,117 @@ export function withTerminalOutputWindow(
70 }),
71 };
72 }
73 +
74 +const MAX_QUEUED_OUTPUT = 8 * 1024 * 1024;
75 +// Charge an envelope so tiny events cannot bypass the byte budget.
76 +const EVENT_OVERHEAD = 128;
77 +
78 +type Listener<A> = (event: A) => Effect.Effect<void>;
79 +// Acquisition must register cleanup synchronously with installing the listener.
80 +type Subscribe<A, E> = (
81 + listener: Listener<A>,
82 + registerCleanup: (stop: () => void) => void,
83 +) => Effect.Effect<() => void, E>;
84 +
85 +const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) =>
86 + EVENT_OVERHEAD +
87 + (event.type === "output"
88 + ? Buffer.byteLength(event.data)
89 + : "snapshot" in event
90 + ? Buffer.byteLength(event.snapshot.history)
91 + : 0);
92 +
93 +export function terminalOutputStream<A extends TerminalEvent | TerminalAttachStreamEvent, E>(
94 + subscribe: Subscribe<A, E>,
95 + resync?: Subscribe<A, E>,
96 + maxQueued = MAX_QUEUED_OUTPUT,
97 +): Stream.Stream<A, E> {
98 + return Stream.unwrap(
99 + Effect.gen(function* () {
100 + const ready = yield* Latch.make();
101 + let pending: Array<A | undefined> = [];
102 + let sizes: number[] = [];
103 + let head = 0;
104 + let queued = 0;
105 + let overflowed = false;
106 + let subscription = 0;
107 + let unsubscribe: (() => void) | null = null;
108 + const release = () => {
109 + subscription += 1;
110 + unsubscribe?.();
111 + unsubscribe = null;
112 + pending = [];
113 + sizes = [];
114 + head = 0;
115 + queued = 0;
116 + };
117 + yield* Effect.addFinalizer(() => Effect.sync(release));
118 +
119 + const listen = (from: Subscribe<A, E>) =>
120 + Effect.suspend(() => {
121 + const id = ++subscription;
122 + return from(
123 + (event) =>
124 + Effect.sync(() => {
125 + if (id !== subscription) return;
126 + const size = queuedSize(event);
127 + pending.push(event);
128 + sizes.push(size);
129 + queued += size;
130 + // A single snapshot must fit even when history fills the budget.
131 + if (queued - sizes[head]! > maxQueued) {
132 + release();
133 + overflowed = true;
134 + }
135 + ready.openUnsafe();
136 + }),
137 + (stop) => {
138 + // Overflow or cancellation may invalidate acquisition before registration.
139 + if (id === subscription) unsubscribe = stop;
140 + else stop();
141 + },
142 + ).pipe(
143 + Effect.asVoid,
144 + Effect.onError(() => Effect.sync(release)),
145 + );
146 + });
147 +
148 + const take = () => {
149 + const event = pending[head]!;
150 + pending[head] = undefined;
151 + head += 1;
152 + return event;
153 + };
154 + const takeBatch = (): Arr.NonEmptyReadonlyArray<A> => {
155 + let bytes = sizes[head]!;
156 + const batch: [A, ...A[]] = [take()];
157 + while (head < pending.length && bytes + sizes[head]! <= MAX_PENDING_BYTES) {
158 + bytes += sizes[head]!;
159 + batch.push(take());
160 + }
161 + queued -= bytes;
162 + if (head * 2 >= pending.length) {
163 + pending = pending.slice(head);
164 + sizes = sizes.slice(head);
165 + head = 0;
166 + }
167 + return batch;
168 + };
169 +
170 + const pull: Effect.Effect<Arr.NonEmptyReadonlyArray<A>, E | Cause.Done> = Effect.suspend(
171 + () => {
172 + if (overflowed) {
173 + overflowed = false;
174 + return resync ? listen(resync).pipe(Effect.andThen(pull)) : Cause.done();
175 + }
176 + if (head < pending.length) return Effect.succeed(takeBatch());
177 + ready.closeUnsafe();
178 + return ready.await.pipe(Effect.andThen(pull));
179 + },
180 + );
181 +
182 + yield* listen(subscribe);
183 + return Stream.fromPull(Effect.succeed(pull));
184 + }),
185 + );
186 +}
apps/server/src/ws.ts
+12 -20
@@ -91,9 +91,6 @@ import {
91 type ProviderDriverKind,
92 type ProviderInstanceId,
93 ThreadId,
94 - type TerminalAttachStreamEvent,
95 - type TerminalError,
96 - type TerminalEvent,
94 type TerminalMetadataStreamEvent,
95 type PullRequestRef,
96 WS_METHODS,
@@ -177,7 +174,7 @@ import * as ServerSettings from "./serverSettings.ts";
174 import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";
175 import * as StorageCleanup from "./storageCleanup.ts";
176 import * as TerminalManager from "./terminal/Manager.ts";
180 -import { withTerminalOutputWindow } from "./terminal/OutputProtocol.ts";
177 +import { terminalOutputStream, withTerminalOutputWindow } from "./terminal/OutputProtocol.ts";
178 import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
179 import * as ServerBrowser from "./preview/ServerBrowser.ts";
180 import * as DeviceService from "./device/DeviceService.ts";
@@ -2824,11 +2821,11 @@ const layerWsRpc = (
2821 [WS_METHODS.reviewGetDiffFileContents]: (input) => review.getDiffFileContents(input),
2822 [WS_METHODS.terminalOpen]: (input) => terminalManager.open(input),
2823 [WS_METHODS.terminalAttach]: (input) =>
2827 - Stream.callback<TerminalAttachStreamEvent, TerminalError>((queue) =>
2828 - Effect.acquireRelease(
2829 - terminalManager.attachStream(input, (event) => Queue.offer(queue, event)),
2830 - (unsubscribe) => Effect.sync(unsubscribe),
2831 - ).pipe(Effect.catchCause((cause) => Queue.failCause(queue, cause))),
2824 + terminalOutputStream(
2825 + (listener, registerCleanup) =>
2826 + terminalManager.attachStream(input, listener, registerCleanup),
2827 + (listener, registerCleanup) =>
2828 + terminalManager.resyncStream(input, listener, registerCleanup),
2829 ),
2830 [WS_METHODS.terminalWrite]: (input) => terminalManager.write(input),
2831 [WS_METHODS.terminalResize]: (input) => terminalManager.resize(input),
@@ -2836,19 +2833,14 @@ const layerWsRpc = (
2833 [WS_METHODS.terminalRestart]: (input) => terminalManager.restart(input),
2834 [WS_METHODS.terminalClose]: (input) => terminalManager.close(input),
2835 [WS_METHODS.terminalObserve]: (input) =>
2839 - Stream.callback<TerminalAttachStreamEvent, TerminalError>((queue) =>
2840 - Effect.acquireRelease(
2841 - terminalManager.observeStream(input, (event) => Queue.offer(queue, event)),
2842 - (unsubscribe) => Effect.sync(unsubscribe),
2843 - ).pipe(Effect.catchCause((cause) => Queue.failCause(queue, cause))),
2836 + terminalOutputStream(
2837 + (listener, registerCleanup) =>
2838 + terminalManager.observeStream(input, listener, registerCleanup),
2839 + (listener, registerCleanup) =>
2840 + terminalManager.resyncStream(input, listener, registerCleanup),
2841 ),
2842 [WS_METHODS.subscribeTerminalEvents]: (_input) =>
2846 - Stream.callback<TerminalEvent>((queue) =>
2847 - Effect.acquireRelease(
2848 - terminalManager.subscribe((event) => Queue.offer(queue, event)),
2849 - (unsubscribe) => Effect.sync(unsubscribe),
2850 - ),
2851 - ),
2843 + terminalOutputStream(terminalManager.subscribe),
2844 [WS_METHODS.subscribeTerminalMetadata]: (_input) =>
2845 Stream.callback<TerminalMetadataStreamEvent>((queue) =>
2846 Effect.acquireRelease(