TypeScript
fix(server): slow terminal clients no longer queue unbounded output (#18429)
Alex Southwell3284143b454f
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.tsindex f5a645349af..d7babfbeac8 100644--- a/apps/server/src/terminal/Manager.test.ts+++ b/apps/server/src/terminal/Manager.test.ts@@ -45,6 +45,7 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts";import * as ProcessRunner from "../processRunner.ts";import * as ServerSettings from "../serverSettings.ts";import * as TerminalManager from "./Manager.ts";+import { terminalOutputStream } from "./OutputProtocol.ts";import * as PtyAdapter from "@t3tools/shared/PtyAdapter";import {applyTerminalAttachStreamEvent,@@ -185,6 +186,44 @@ class FakePtyAdapter {}}+// Publishes 9 MiB of output, past a stream's 8 MiB budget, while nothing pulls.+const publishPastOutputBudget = (+ manager: TerminalManager.TerminalManager["Service"],+ process: FakePtyProcess,+) =>+ Effect.gen(function* () {+ const published = yield* Deferred.make<void>();+ const unsubscribe = yield* manager.subscribe((event) =>+ event.type === "output" && event.data === "last\n"+ ? Deferred.succeed(published, undefined).pipe(Effect.asVoid)+ : Effect.void,+ );+ for (let index = 0; index < 9; index++) process.emitData("x".repeat(1024 * 1024));+ process.emitData("last\n");+ yield* Deferred.await(published);+ unsubscribe();+ });++// Holds the next spawn, and with it the thread lock, until `release` succeeds.+class GatedPtyAdapter extends FakePtyAdapter {+ gate: {+ readonly spawning: Deferred.Deferred<void>;+ readonly release: Deferred.Deferred<void>;+ } | null = null;++ override spawn(+ input: PtyAdapter.PtySpawnInput,+ ): Effect.Effect<PtyAdapter.PtyProcess, PtyAdapter.PtySpawnError> {+ const gate = this.gate;+ this.gate = null;+ if (!gate) return super.spawn(input);+ return Deferred.succeed(gate.spawning, undefined).pipe(+ Effect.andThen(Deferred.await(gate.release)),+ Effect.andThen(super.spawn(input)),+ );+ }+}+const waitFor = <E, R>(predicate: Effect.Effect<boolean, E, R>,timeout: Duration.Input = 800,@@ -3206,6 +3245,154 @@ it.layer(}),);+ it.effect("finishes shell startup when its creating attachment is cancelled", () =>+ Effect.gen(function* () {+ const ptyAdapter = new GatedPtyAdapter();+ const { manager } = yield* createManager(5, { ptyAdapter });+ const input = openInput();+ const gate = {+ spawning: yield* Deferred.make<void>(),+ release: yield* Deferred.make<void>(),+ };+ ptyAdapter.gate = gate;+ const consumer = yield* Stream.runDrain(+ terminalOutputStream(+ (listener, registerCleanup) => manager.attachStream(input, listener, registerCleanup),+ (listener, registerCleanup) => manager.resyncStream(input, listener, registerCleanup),+ ),+ ).pipe(Effect.forkChild({ startImmediately: true }));+ yield* Deferred.await(gate.spawning);+ const cancelled = yield* Fiber.interrupt(consumer).pipe(+ Effect.forkChild({ startImmediately: true }),+ );+ yield* Deferred.succeed(gate.release, undefined);+ yield* Fiber.join(cancelled);++ const snapshots: TerminalAttachStreamEvent[] = [];+ const stop = yield* manager.attachStream(input, (event) =>+ Effect.sync(() => {+ snapshots.push(event);+ }),+ );+ stop();+ expect(snapshots).toMatchObject([+ { type: "snapshot", snapshot: { status: "running", pid: ptyAdapter.processes[0]?.pid } },+ ]);+ expect(ptyAdapter.processes).toHaveLength(1);+ }).pipe(Effect.scoped),+ );++ it.effect("resyncs bounded history and follows close/reopen across a stalled stream", () =>+ Effect.gen(function* () {+ const ptyAdapter = new GatedPtyAdapter();+ const historyByteLimit = 64 * 1024;+ const { manager } = yield* createManager(5, { ptyAdapter, historyByteLimit });+ const input = openInput();+ const pull = yield* Stream.toPull(+ terminalOutputStream(+ (listener, registerCleanup) => manager.attachStream(input, listener, registerCleanup),+ (listener, registerCleanup) => manager.resyncStream(input, listener, registerCleanup),+ ),+ );+ expect(yield* pull).toMatchObject([{ type: "snapshot", snapshot: { history: "" } }]);+ const process = ptyAdapter.processes[0]!;+ yield* publishPastOutputBudget(manager, process);++ const resumed = yield* pull;+ expect(resumed).toHaveLength(1);+ expect(resumed[0]?.type).toBe("snapshot");+ if (resumed[0]?.type !== "snapshot") throw new Error("Expected a recovery snapshot");+ expect(Buffer.byteLength(resumed[0].snapshot.history)).toBeLessThanOrEqual(historyByteLimit);+ expect(resumed[0].snapshot.history.endsWith("last\n")).toBe(true);+ process.emitData("after recovery\n");+ expect(yield* pull).toMatchObject([{ type: "output", data: "after recovery\n" }]);+ expect(ptyAdapter.spawnInputs).toHaveLength(1);++ yield* publishPastOutputBudget(manager, process);+ yield* manager.close(input);+ expect(yield* pull).toEqual([+ { type: "closed", threadId: input.threadId, terminalId: input.terminalId },+ ]);+ expect(ptyAdapter.spawnInputs).toHaveLength(1);+ yield* manager.open(input);+ expect(yield* pull).toMatchObject([+ { type: "snapshot", snapshot: { status: "running", pid: ptyAdapter.processes[1]!.pid } },+ ]);+ const reopenedProcess = ptyAdapter.processes[1]!;+ reopenedProcess.emitData("after reopen\n");+ expect(yield* pull).toMatchObject([{ type: "output", data: "after reopen\n" }]);++ yield* publishPastOutputBudget(manager, reopenedProcess);+ // Queue close/reopen ahead of recovery while another spawn owns the thread lock.+ const gate = {+ spawning: yield* Deferred.make<void>(),+ release: yield* Deferred.make<void>(),+ };+ ptyAdapter.gate = gate;+ const holder = yield* manager+ .open(openInput({ terminalId: "other" }))+ .pipe(Effect.forkChild({ startImmediately: true }));+ yield* Deferred.await(gate.spawning);+ const closed = yield* manager.close(input).pipe(Effect.forkChild({ startImmediately: true }));+ const reopened = yield* manager+ .open(input)+ .pipe(Effect.forkChild({ startImmediately: true }));+ const recovery = yield* pull.pipe(Effect.forkChild({ startImmediately: true }));+ reopenedProcess.emitData("old session\n");+ yield* Deferred.succeed(gate.release, undefined);+ yield* Fiber.join(holder);+ yield* Fiber.join(closed);+ yield* Fiber.join(reopened);++ const batch = yield* Fiber.join(recovery);+ expect(batch).toHaveLength(1);+ expect(batch[0]).toMatchObject({+ type: "snapshot",+ snapshot: { status: "running", pid: ptyAdapter.processes.at(-1)!.pid },+ });+ ptyAdapter.processes.at(-1)!.emitData("new session only\n");+ expect(yield* pull).toMatchObject([{ type: "output", data: "new session only\n" }]);+ expect(ptyAdapter.spawnInputs).toHaveLength(4);+ }).pipe(Effect.scoped),+ );++ it.effect("does not replay in-flight output already included in an observer snapshot", () =>+ Effect.gen(function* () {+ const { manager, ptyAdapter } = yield* createManager();+ const input = openInput();+ yield* manager.open(input);+ const reached = yield* Deferred.make<void>();+ const release = yield* Deferred.make<void>();+ const delivered = yield* Deferred.make<void>();+ // The snapshot sees history before this earlier fanout listener releases it.+ const unsubscribe = yield* manager.subscribe((event) =>+ event.type === "output" && event.data === "in flight\n"+ ? Deferred.succeed(reached, undefined).pipe(Effect.andThen(Deferred.await(release)))+ : Effect.void,+ );+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));+ ptyAdapter.processes[0]!.emitData("in flight\n");+ yield* Deferred.await(reached);+ const observed: TerminalAttachStreamEvent[] = [];+ const stopObserving = yield* manager.observeStream(input, (event) =>+ Effect.gen(function* () {+ observed.push(event);+ if (event.type === "output" && event.data === "after\n") {+ yield* Deferred.succeed(delivered, undefined);+ }+ }),+ );+ yield* Effect.addFinalizer(() => Effect.sync(stopObserving));+ expect(observed).toMatchObject([{ type: "snapshot", snapshot: { history: "in flight\n" } }]);+ yield* Deferred.succeed(release, undefined);+ ptyAdapter.processes[0]!.emitData("after\n");+ yield* Deferred.await(delivered);+ expect(observed.filter((event) => event.type === "output")).toMatchObject([+ { data: "after\n" },+ ]);+ }).pipe(Effect.scoped),+ );+it.effect("observes terminal history and live output without changing the process", () =>Effect.gen(function* () {const { manager, ptyAdapter } = yield* createManager();diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.tsindex 406847e1717..e10d263dc33 100644--- a/apps/server/src/terminal/Manager.ts+++ b/apps/server/src/terminal/Manager.ts@@ -163,11 +163,19 @@ export class TerminalManager extends Context.Service<readonly attachStream: (input: TerminalAttachInput,listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,+ registerCleanup?: (stop: () => void) => void,) => Effect.Effect<() => void, TerminalError>;readonly observeStream: (input: TerminalObserveInput,listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,+ registerCleanup?: (stop: () => void) => void,+ ) => Effect.Effect<() => void, TerminalError>;++ readonly resyncStream: (+ input: TerminalObserveInput,+ listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,+ registerCleanup?: (stop: () => void) => void,) => Effect.Effect<() => void, TerminalError>;readonly write: (input: TerminalWriteInput) => Effect.Effect<void, TerminalError>;@@ -195,6 +203,7 @@ export class TerminalManager extends Context.Service<readonly subscribe: (listener: (event: TerminalEvent) => Effect.Effect<void>,+ registerCleanup?: (stop: () => void) => void,) => Effect.Effect<() => void>;readonly subscribeMetadata: (@@ -2761,60 +2770,56 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcresolveLaunchInputEnvironment(input).pipe(Effect.flatMap(openLocked)),);- const openOrAttachForStream = (input: TerminalAttachInput) =>- withThreadLock(- input.threadId,- Effect.gen(function* () {- const terminalId = input.terminalId;- const existing = yield* getSession(input.threadId, terminalId);+ const openOrAttachForStream = Effect.fnUntraced(function* (input: TerminalAttachInput) {+ const terminalId = input.terminalId;+ const existing = yield* getSession(input.threadId, terminalId);- if (Option.isNone(existing)) {- if (input.resume && closedSessionKeys.has(toSessionKey(input.threadId, terminalId))) {- return null;- }- if (!input.cwd) {- return yield* new TerminalSessionLookupError({- threadId: input.threadId,- terminalId,- });- }+ if (Option.isNone(existing)) {+ if (input.resume && closedSessionKeys.has(toSessionKey(input.threadId, terminalId))) {+ return null;+ }+ if (!input.cwd) {+ return yield* new TerminalSessionLookupError({+ threadId: input.threadId,+ terminalId,+ });+ }- const resolvedInput = yield* resolveLaunchInputEnvironment({- ...input,- terminalId,- cwd: input.cwd,- });- return yield* openLocked(resolvedInput);- }+ const resolvedInput = yield* resolveLaunchInputEnvironment({+ ...input,+ terminalId,+ cwd: input.cwd,+ });+ return yield* Effect.uninterruptible(openLocked(resolvedInput));+ }- const session = existing.value;- const targetCols = input.cols ?? session.cols;- const targetRows = input.rows ?? session.rows;+ const session = existing.value;+ const targetCols = input.cols ?? session.cols;+ const targetRows = input.rows ?? session.rows;- if (!input.resume && !session.process && input.cwd && input.restartIfNotRunning === true) {- const resolvedInput = yield* resolveLaunchInputEnvironment({- ...input,- terminalId,- cwd: input.cwd,- });- return yield* openLocked(resolvedInput);- }+ if (!input.resume && !session.process && input.cwd && input.restartIfNotRunning === true) {+ const resolvedInput = yield* resolveLaunchInputEnvironment({+ ...input,+ terminalId,+ cwd: input.cwd,+ });+ return yield* Effect.uninterruptible(openLocked(resolvedInput));+ }- if (- session.process &&- session.status === "running" &&- (session.cols !== targetCols || session.rows !== targetRows)- ) {- const process = session.process;- yield* resizePtyProcess(session, process, targetCols, targetRows);- session.cols = targetCols;- session.rows = targetRows;- session.updatedAt = yield* nowIso;- }+ if (+ session.process &&+ session.status === "running" &&+ (session.cols !== targetCols || session.rows !== targetRows)+ ) {+ const process = session.process;+ yield* resizePtyProcess(session, process, targetCols, targetRows);+ session.cols = targetCols;+ session.rows = targetRows;+ session.updatedAt = yield* nowIso;+ }- return snapshot(session);- }),- );+ return snapshot(session);+ });const readAllTerminalMetadata = () =>readManagerState.pipe(@@ -2838,38 +2843,70 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcEffect.map((session) => (Option.isSome(session) ? summary(session.value) : null)),);- const subscribe: TerminalManager["Service"]["subscribe"] = (listener) =>+ const subscribe: TerminalManager["Service"]["subscribe"] = (listener, registerCleanup) =>Effect.sync(() => {terminalEventListeners.add(listener);- return () => {+ const stop = () => {terminalEventListeners.delete(listener);};+ // Transfer ownership before an interrupt can discard the returned handle.+ registerCleanup?.(stop);+ return stop;});+ // Subscribe after taking the lock so contention cannot accumulate an unbounded replay.+ // Snapshot listeners run under that lock and must not block.const streamSession = (input: TerminalObserveInput,initial: Effect.Effect<TerminalSessionSnapshot | null, TerminalError>,listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,+ registerCleanup?: (stop: () => void) => void,) => {let unsubscribe: (() => void) | null = null;+ const stop = () => {+ unsubscribe?.();+ unsubscribe = null;+ };return Effect.gen(function* () {const bufferedEvents: TerminalEvent[] = [];let deliverLive = false;+ let snapshotFloor: number | null = null;- unsubscribe = yield* subscribe((event) => {- if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {- return Effect.void;- }+ yield* subscribe(+ (event) => {+ if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {+ return Effect.void;+ }- if (!deliverLive) {- bufferedEvents.push(event);- return Effect.void;- }+ if (!deliverLive) {+ bufferedEvents.push(event);+ return Effect.void;+ }- const attachEvent = terminalEventToAttachEvent(event);- return attachEvent ? listener(attachEvent) : Effect.void;- });+ // Fanout can finish after a snapshot that already includes the event.+ // Keep only its sequence, not its history, until the session changes.+ if (snapshotFloor !== null) {+ if (+ event.type === "started" ||+ event.type === "restarted" ||+ event.type === "error" ||+ event.type === "closed"+ ) {+ snapshotFloor = null;+ } else if (typeof event.sequence === "number" && event.sequence <= snapshotFloor) {+ return Effect.void;+ }+ }++ const attachEvent = terminalEventToAttachEvent(event);+ return attachEvent ? listener(attachEvent) : Effect.void;+ },+ (cleanup) => {+ unsubscribe = cleanup;+ registerCleanup?.(stop);+ },+ );const initialSnapshot = yield* initial;@@ -2889,36 +2926,48 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcyield* listener(attachEvent);}}+ // The live listener keeps this closure, so release replayed output.+ bufferedEvents.length = 0;+ snapshotFloor = initialSnapshot?.sequence ?? null;deliverLive = true;- return () => {- unsubscribe?.();- unsubscribe = null;- };+ return stop;}).pipe(- Effect.catchCause((cause) =>- Effect.flatMap(- Effect.sync(() => {- unsubscribe?.();- unsubscribe = null;- }),- () => Effect.failCause(cause),- ),- ),+ (effect) => withThreadLock(input.threadId, effect),+ Effect.onError(() => Effect.sync(stop)),);};- const attachStream: TerminalManager["Service"]["attachStream"] = (input, listener) =>- streamSession(input, openOrAttachForStream(input), listener);+ const attachStream: TerminalManager["Service"]["attachStream"] = (+ input,+ listener,+ registerCleanup,+ ) => streamSession(input, openOrAttachForStream(input), listener, registerCleanup);++ const observeStream: TerminalManager["Service"]["observeStream"] = (+ input,+ listener,+ registerCleanup,+ ) =>+ streamSession(+ input,+ requireSession(input.threadId, input.terminalId).pipe(Effect.map(snapshot)),+ listener,+ registerCleanup,+ );- const observeStream: TerminalManager["Service"]["observeStream"] = (input, listener) =>+ const resyncStream: TerminalManager["Service"]["resyncStream"] = (+ input,+ listener,+ registerCleanup,+ ) =>streamSession(input,- withThreadLock(- input.threadId,- requireSession(input.threadId, input.terminalId).pipe(Effect.map(snapshot)),+ getSession(input.threadId, input.terminalId).pipe(+ Effect.map((session) => (Option.isSome(session) ? snapshot(session.value) : null)),),listener,+ registerCleanup,);const metadataEventFromTerminalEvent = (@@ -3228,6 +3277,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcopen,attachStream,observeStream,+ resyncStream,write,resize,clear,diff --git a/apps/server/src/terminal/OutputProtocol.test.ts b/apps/server/src/terminal/OutputProtocol.test.tsindex a12f9d6ecbf..a05d635361b 100644--- a/apps/server/src/terminal/OutputProtocol.test.ts+++ b/apps/server/src/terminal/OutputProtocol.test.ts@@ -1,14 +1,20 @@import { assert, describe, it } from "@effect/vitest";-import { WS_METHODS } from "@t3tools/contracts";+import {+ type TerminalAttachStreamEvent,+ TerminalAttachStreamEvent as TerminalAttachStreamEventSchema,+ TerminalEvent as TerminalEventSchema,+ WS_METHODS,+} from "@t3tools/contracts";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";import * as Queue from "effect/Queue";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import * as TestClock from "effect/testing/TestClock";import { Rpc, RpcGroup, RpcMessage, RpcSerialization, RpcServer } from "effect/rpc";-import { withTerminalOutputWindow } from "./OutputProtocol.ts";+import { terminalOutputStream, withTerminalOutputWindow } from "./OutputProtocol.ts";describe("terminal output window", () => {it.effect.each([@@ -77,3 +83,279 @@ describe("terminal output window", () => {}).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),);});++const output = (data: string): TerminalAttachStreamEvent => ({+ type: "output",+ threadId: "thread-1",+ terminalId: "default",+ data,+});++const snapshot = (history: string): TerminalAttachStreamEvent => ({+ type: "snapshot",+ snapshot: {+ threadId: "thread-1",+ terminalId: "default",+ cwd: "/repo",+ worktreePath: null,+ status: "running",+ pid: 1,+ history,+ exitCode: null,+ exitSignal: null,+ label: "bash",+ updatedAt: "2026-01-01T00:00:00.000Z",+ },+});++// Stands in for TerminalManager's fanout: listeners run in publish order and+// may release themselves while it iterates.+const makePublisher = () => {+ const listeners = new Set<(event: TerminalAttachStreamEvent) => Effect.Effect<void>>();+ return {+ listeners,+ subscribe: (+ listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,+ registerCleanup?: (stop: () => void) => void,+ ) =>+ Effect.sync(() => {+ listeners.add(listener);+ const stop = () => {+ listeners.delete(listener);+ };+ registerCleanup?.(stop);+ return stop;+ }),+ publish: (event: TerminalAttachStreamEvent) =>+ Effect.forEach(listeners, (listener) => listener(event), { discard: true }),+ };+};++// Like TerminalManager.attachStream: a snapshot, then live events.+const attach =+ (publisher: ReturnType<typeof makePublisher>, history: string) =>+ (+ listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,+ registerCleanup: (stop: () => void) => void,+ ) =>+ publisher+ .subscribe(listener, registerCleanup)+ .pipe(Effect.tap(() => listener(snapshot(history))));++const chunkBytes = (message: RpcMessage.FromServerEncoded) =>+ Buffer.byteLength(JSON.stringify(message));++describe("terminal output stream", () => {+ it.effect.each([+ WS_METHODS.terminalAttach,+ WS_METHODS.terminalObserve,+ WS_METHODS.subscribeTerminalEvents,+ ])("releases only the ACK-stalled subscriber on %s and resumes safely", (tag) =>+ Effect.gen(function* () {+ const legacy = tag === WS_METHODS.subscribeTerminalEvents;+ const group = RpcGroup.make(+ Rpc.make(tag, {+ success: legacy ? TerminalEventSchema : TerminalAttachStreamEventSchema,+ stream: true,+ }),+ );+ const publisher = makePublisher();+ const stalled = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();+ const healthy = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();+ const receive = yield* Deferred.make<Parameters<RpcServer.Protocol["Service"]["run"]>[0]>();+ const protocol = yield* RpcServer.Protocol.make((write) =>+ Effect.gen(function* () {+ yield* Deferred.succeed(receive, write);+ const serialization = yield* RpcSerialization.RpcSerialization;+ return {+ disconnects: yield* Queue.unbounded<number>(),+ send: (clientId, response) => Queue.offer(clientId === 0 ? stalled : healthy, response),+ end: () => Effect.void,+ clientIds: Effect.succeed(new Set([0, 1])),+ initialMessage: Effect.succeedNone,+ supportsAck: true,+ supportsTransferables: false,+ supportsSpanPropagation: false,+ supportsNotifications: true,+ codecFor: serialization.codecFor,+ };+ }),+ );+ const initial = legacy ? output("ready") : snapshot("");+ yield* RpcServer.make(group).pipe(+ Effect.provide(+ group.toLayerHandler(tag, () =>+ terminalOutputStream(+ (listener, registerCleanup) =>+ publisher+ .subscribe(listener, registerCleanup)+ .pipe(Effect.tap(() => listener(initial))),+ legacy ? undefined : attach(publisher, "fresh history"),+ 256 * 1024,+ ),+ ),+ ),+ Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)),+ Effect.forkScoped,+ );+ const write = yield* Deferred.await(receive);+ const takeChunk = Effect.fnUntraced(function* (queue: typeof stalled) {+ const response = yield* Queue.take(queue);+ assert.equal(response._tag, "Chunk");+ if (response._tag !== "Chunk") throw new Error("Expected an RPC chunk");+ assert.isAtMost(chunkBytes(response), 70 * 1024);+ return response.values;+ });+ yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] });+ assert.deepEqual(yield* takeChunk(stalled), [initial]);+ yield* write(1, { _tag: "Request", id: "2", tag, payload: null, headers: [] });+ assert.deepEqual(yield* takeChunk(healthy), [initial]);+ yield* write(1, { _tag: "Ack", requestId: "2" });++ // Eight unacknowledged chunks fill only client 0's output window.+ for (let index = 0; index < 7; index++) {+ const event = output("before-stall-" + index);+ yield* publisher.publish(event);+ assert.deepEqual(yield* takeChunk(stalled), [event]);+ assert.deepEqual(yield* takeChunk(healthy), [event]);+ yield* write(1, { _tag: "Ack", requestId: "2" });+ }+ assert.equal(publisher.listeners.size, 2);+ for (let index = 0; index < 100; index++) {+ const event = output(index + ":" + "界".repeat(1365));+ yield* publisher.publish(event);+ assert.deepEqual(yield* takeChunk(healthy), [event]);+ yield* write(1, { _tag: "Ack", requestId: "2" });+ if (index === 31) assert.equal(publisher.listeners.size, 2);+ }+ assert.equal(yield* Queue.size(stalled), 0);+ assert.equal(publisher.listeners.size, 1);++ yield* write(0, { _tag: "Ack", requestId: "1" });+ if (legacy) {+ assert.deepEqual(yield* Queue.take(stalled), {+ _tag: "Exit",+ requestId: "1",+ exit: { _tag: "Success", value: null },+ });+ } else {+ assert.deepEqual(yield* takeChunk(stalled), [snapshot("fresh history")]);+ assert.equal(publisher.listeners.size, 2);+ for (let index = 0; index < 7; index++) {+ yield* write(0, { _tag: "Ack", requestId: "1" });+ }+ }+ const after = output("unique output after recovery");+ yield* publisher.publish(after);+ assert.deepEqual(yield* takeChunk(healthy), [after]);+ if (!legacy) assert.deepEqual(yield* takeChunk(stalled), [after]);+ assert.equal(yield* Queue.size(stalled), 0);+ }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),+ );++ it.effect("interrupts recovery while its subscription is still waiting", () =>+ Effect.gen(function* () {+ const publisher = makePublisher();+ const recovering = yield* Deferred.make<void>();+ const interrupted = yield* Deferred.make<void>();+ const pull = yield* Stream.toPull(+ terminalOutputStream(+ attach(publisher, ""),+ () =>+ Deferred.succeed(recovering, undefined).pipe(+ Effect.andThen(Effect.never),+ Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),+ ),+ 1024,+ ),+ );+ yield* pull;+ yield* publisher.publish(output("x".repeat(1024)));+ yield* publisher.publish(output("x".repeat(1024)));+ assert.equal(publisher.listeners.size, 0);++ const recovery = yield* pull.pipe(Effect.forkChild({ startImmediately: true }));+ yield* Deferred.await(recovering);+ yield* Fiber.interrupt(recovery);+ yield* Deferred.await(interrupted);+ assert.equal(publisher.listeners.size, 0);+ }).pipe(Effect.scoped),+ );++ it.effect("cleans listeners when cancelled during a successful acquisition handoff", () =>+ Effect.gen(function* () {+ const publisher = makePublisher();+ for (const recovering of [false, true, false, true]) {+ const handoff = yield* Deferred.make<void>();+ const complete = yield* Deferred.make<void>();+ const acquire: ReturnType<typeof attach> = (listener, registerCleanup) =>+ attach(publisher, "")(listener, registerCleanup).pipe(+ // Hold the successful exit before its cleanup handle reaches the caller.+ Effect.onExit(() =>+ Deferred.succeed(handoff, undefined).pipe(Effect.andThen(Deferred.await(complete))),+ ),+ );+ const consumer = yield* Effect.gen(function* () {+ const pull = yield* Stream.toPull(+ terminalOutputStream(recovering ? attach(publisher, "") : acquire, acquire, 1024),+ );+ yield* pull;+ yield* publisher.publish(output("x".repeat(1024)));+ yield* publisher.publish(output("x".repeat(1024)));+ yield* pull;+ }).pipe(Effect.scoped, Effect.forkChild({ startImmediately: true }));+ yield* Deferred.await(handoff);+ assert.equal(publisher.listeners.size, 1);+ const cancellation = yield* Fiber.interrupt(consumer).pipe(+ Effect.forkChild({ startImmediately: true }),+ );+ yield* Deferred.succeed(complete, undefined);+ yield* Fiber.join(cancellation);+ assert.equal(publisher.listeners.size, 0);+ }+ }).pipe(Effect.scoped),+ );++ it.effect("caps each delivered batch at the output window in UTF-8 bytes", () =>+ Effect.gen(function* () {+ const publisher = makePublisher();+ const pull = yield* Stream.toPull(terminalOutputStream(attach(publisher, "")));+ assert.deepEqual(yield* pull, [snapshot("")]);+ // 1,024 code units but 3 KiB of UTF-8.+ const data = "界".repeat(1024);+ for (let index = 0; index < 1024; index++) yield* publisher.publish(output(data));++ let delivered = 0;+ while (delivered < 1024) {+ const batch = yield* pull;+ assert.isAtMost(+ batch.reduce(+ (bytes, event) => bytes + (event.type === "output" ? Buffer.byteLength(event.data) : 0),+ 0,+ ),+ 64 * 1024,+ );+ delivered += batch.length;+ }+ assert.equal(delivered, 1024);+ }).pipe(Effect.scoped),+ );++ it.effect("charges snapshot history but never overflows on one snapshot", () =>+ Effect.gen(function* () {+ const publisher = makePublisher();+ const history = "界".repeat(16 * 1024);+ const events = terminalOutputStream(attach(publisher, history), undefined, 32 * 1024);+ const pull = yield* Stream.toPull(events);+ // A snapshot larger than the budget is still delivered.+ assert.deepEqual(yield* pull, [snapshot(history)]);+ assert.equal(publisher.listeners.size, 1);++ // Queued snapshots count their history: a second one overflows.+ yield* publisher.publish(snapshot(history));+ assert.equal(publisher.listeners.size, 1);+ yield* publisher.publish(snapshot(history));+ assert.equal(publisher.listeners.size, 0);+ }).pipe(Effect.scoped),+ );+});diff --git a/apps/server/src/terminal/OutputProtocol.ts b/apps/server/src/terminal/OutputProtocol.tsindex 402ed32c022..5a0f596e847 100644--- a/apps/server/src/terminal/OutputProtocol.ts+++ b/apps/server/src/terminal/OutputProtocol.ts@@ -1,5 +1,9 @@-import { WS_METHODS } from "@t3tools/contracts";+import { type TerminalAttachStreamEvent, type TerminalEvent, WS_METHODS } from "@t3tools/contracts";+import type * as Arr from "effect/Array";+import * as Cause from "effect/Cause";import * as Effect from "effect/Effect";+import * as Latch from "effect/Latch";+import * as Stream from "effect/Stream";import type { RpcServer } from "effect/rpc";const MAX_PENDING_CHUNKS = 8;@@ -66,3 +70,117 @@ export function withTerminalOutputWindow(}),};}++const MAX_QUEUED_OUTPUT = 8 * 1024 * 1024;+// Charge an envelope so tiny events cannot bypass the byte budget.+const EVENT_OVERHEAD = 128;++type Listener<A> = (event: A) => Effect.Effect<void>;+// Acquisition must register cleanup synchronously with installing the listener.+type Subscribe<A, E> = (+ listener: Listener<A>,+ registerCleanup: (stop: () => void) => void,+) => Effect.Effect<() => void, E>;++const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) =>+ EVENT_OVERHEAD ++ (event.type === "output"+ ? Buffer.byteLength(event.data)+ : "snapshot" in event+ ? Buffer.byteLength(event.snapshot.history)+ : 0);++export function terminalOutputStream<A extends TerminalEvent | TerminalAttachStreamEvent, E>(+ subscribe: Subscribe<A, E>,+ resync?: Subscribe<A, E>,+ maxQueued = MAX_QUEUED_OUTPUT,+): Stream.Stream<A, E> {+ return Stream.unwrap(+ Effect.gen(function* () {+ const ready = yield* Latch.make();+ let pending: Array<A | undefined> = [];+ let sizes: number[] = [];+ let head = 0;+ let queued = 0;+ let overflowed = false;+ let subscription = 0;+ let unsubscribe: (() => void) | null = null;+ const release = () => {+ subscription += 1;+ unsubscribe?.();+ unsubscribe = null;+ pending = [];+ sizes = [];+ head = 0;+ queued = 0;+ };+ yield* Effect.addFinalizer(() => Effect.sync(release));++ const listen = (from: Subscribe<A, E>) =>+ Effect.suspend(() => {+ const id = ++subscription;+ return from(+ (event) =>+ Effect.sync(() => {+ if (id !== subscription) return;+ const size = queuedSize(event);+ pending.push(event);+ sizes.push(size);+ queued += size;+ // A single snapshot must fit even when history fills the budget.+ if (queued - sizes[head]! > maxQueued) {+ release();+ overflowed = true;+ }+ ready.openUnsafe();+ }),+ (stop) => {+ // Overflow or cancellation may invalidate acquisition before registration.+ if (id === subscription) unsubscribe = stop;+ else stop();+ },+ ).pipe(+ Effect.asVoid,+ Effect.onError(() => Effect.sync(release)),+ );+ });++ const take = () => {+ const event = pending[head]!;+ pending[head] = undefined;+ head += 1;+ return event;+ };+ const takeBatch = (): Arr.NonEmptyReadonlyArray<A> => {+ let bytes = sizes[head]!;+ const batch: [A, ...A[]] = [take()];+ while (head < pending.length && bytes + sizes[head]! <= MAX_PENDING_BYTES) {+ bytes += sizes[head]!;+ batch.push(take());+ }+ queued -= bytes;+ if (head * 2 >= pending.length) {+ pending = pending.slice(head);+ sizes = sizes.slice(head);+ head = 0;+ }+ return batch;+ };++ const pull: Effect.Effect<Arr.NonEmptyReadonlyArray<A>, E | Cause.Done> = Effect.suspend(+ () => {+ if (overflowed) {+ overflowed = false;+ return resync ? listen(resync).pipe(Effect.andThen(pull)) : Cause.done();+ }+ if (head < pending.length) return Effect.succeed(takeBatch());+ ready.closeUnsafe();+ return ready.await.pipe(Effect.andThen(pull));+ },+ );++ yield* listen(subscribe);+ return Stream.fromPull(Effect.succeed(pull));+ }),+ );+}diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex e19a47e1fe3..ae32d3626ad 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -91,9 +91,6 @@ import {type ProviderDriverKind,type ProviderInstanceId,ThreadId,- type TerminalAttachStreamEvent,- type TerminalError,- type TerminalEvent,type TerminalMetadataStreamEvent,type PullRequestRef,WS_METHODS,@@ -177,7 +174,7 @@ import * as ServerSettings from "./serverSettings.ts";import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";import * as StorageCleanup from "./storageCleanup.ts";import * as TerminalManager from "./terminal/Manager.ts";-import { withTerminalOutputWindow } from "./terminal/OutputProtocol.ts";+import { terminalOutputStream, withTerminalOutputWindow } from "./terminal/OutputProtocol.ts";import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";import * as ServerBrowser from "./preview/ServerBrowser.ts";import * as DeviceService from "./device/DeviceService.ts";@@ -2824,11 +2821,11 @@ const layerWsRpc = ([WS_METHODS.reviewGetDiffFileContents]: (input) => review.getDiffFileContents(input),[WS_METHODS.terminalOpen]: (input) => terminalManager.open(input),[WS_METHODS.terminalAttach]: (input) =>- Stream.callback<TerminalAttachStreamEvent, TerminalError>((queue) =>- Effect.acquireRelease(- terminalManager.attachStream(input, (event) => Queue.offer(queue, event)),- (unsubscribe) => Effect.sync(unsubscribe),- ).pipe(Effect.catchCause((cause) => Queue.failCause(queue, cause))),+ terminalOutputStream(+ (listener, registerCleanup) =>+ terminalManager.attachStream(input, listener, registerCleanup),+ (listener, registerCleanup) =>+ terminalManager.resyncStream(input, listener, registerCleanup),),[WS_METHODS.terminalWrite]: (input) => terminalManager.write(input),[WS_METHODS.terminalResize]: (input) => terminalManager.resize(input),@@ -2836,19 +2833,14 @@ const layerWsRpc = ([WS_METHODS.terminalRestart]: (input) => terminalManager.restart(input),[WS_METHODS.terminalClose]: (input) => terminalManager.close(input),[WS_METHODS.terminalObserve]: (input) =>- Stream.callback<TerminalAttachStreamEvent, TerminalError>((queue) =>- Effect.acquireRelease(- terminalManager.observeStream(input, (event) => Queue.offer(queue, event)),- (unsubscribe) => Effect.sync(unsubscribe),- ).pipe(Effect.catchCause((cause) => Queue.failCause(queue, cause))),+ terminalOutputStream(+ (listener, registerCleanup) =>+ terminalManager.observeStream(input, listener, registerCleanup),+ (listener, registerCleanup) =>+ terminalManager.resyncStream(input, listener, registerCleanup),),[WS_METHODS.subscribeTerminalEvents]: (_input) =>- Stream.callback<TerminalEvent>((queue) =>- Effect.acquireRelease(- terminalManager.subscribe((event) => Queue.offer(queue, event)),- (unsubscribe) => Effect.sync(unsubscribe),- ),- ),+ terminalOutputStream(terminalManager.subscribe),[WS_METHODS.subscribeTerminalMetadata]: (_input) =>Stream.callback<TerminalMetadataStreamEvent>((queue) =>Effect.acquireRelease(