TypeScript
fix(server): reconnecting no longer reopens a closed terminal (#18444)
Guillermo Casanovaf3e5a165e043
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.tsindex 65197ab61fa..40abb1a76a4 100644--- a/apps/server/src/terminal/Manager.test.ts+++ b/apps/server/src/terminal/Manager.test.ts@@ -501,6 +501,109 @@ it.layer(}),);+ it.effect("resumed attaches after close never respawn until the terminal is reopened", () =>+ Effect.gen(function* () {+ const { manager, ptyAdapter } = yield* createManager();+ yield* manager.open(openInput());+ yield* manager.close({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID });++ const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);+ const unsubscribe = yield* manager.attachStream(+ { ...openInput(), restartIfNotRunning: true, resume: true },+ (event) => Ref.update(attachEvents, (events) => [...events, event]),+ );+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));+ expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual(["closed"]);+ expect(ptyAdapter.spawnInputs).toHaveLength(1);++ yield* manager.open(openInput());+ const events = yield* Ref.get(attachEvents);+ expect(events.map((event) => event.type)).toEqual(["closed", "snapshot"]);+ expect(ptyAdapter.spawnInputs).toHaveLength(2);+ }),+ );++ it.effect("resumed attaches respect closes before this server has seen a terminal", () =>+ Effect.gen(function* () {+ const { manager, ptyAdapter } = yield* createManager();+ yield* manager.close({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID });++ const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);+ const unsubscribe = yield* manager.attachStream(+ { ...openInput(), restartIfNotRunning: true, resume: true },+ (event) => Ref.update(attachEvents, (events) => [...events, event]),+ );+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));+ expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual(["closed"]);+ expect(ptyAdapter.spawnInputs).toHaveLength(0);++ const restarted = yield* manager.restart(restartInput());+ expect(restarted.status).toBe("running");+ expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual([+ "closed",+ "restarted",+ ]);+ expect(ptyAdapter.spawnInputs).toHaveLength(1);+ }),+ );++ it.effect("resumed attaches leave exited and evicted terminals stopped", () =>+ Effect.gen(function* () {+ const { manager, ptyAdapter } = yield* createManager(5, {+ maxRetainedInactiveSessions: 1,+ });+ const exited = yield* Deferred.make<void>();+ const unsubscribeEvents = yield* manager.subscribe((event) =>+ event.type === "exited"+ ? Deferred.succeed(exited, undefined).pipe(Effect.asVoid)+ : Effect.void,+ );+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribeEvents));+ yield* manager.open(openInput());+ ptyAdapter.processes[0]?.emitExit({ exitCode: 0, signal: 0 });+ yield* Deferred.await(exited);++ const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);+ const unsubscribe = yield* manager.attachStream(+ { ...openInput(), restartIfNotRunning: true, resume: true },+ (event) => Ref.update(attachEvents, (events) => [...events, event]),+ );+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));+ expect(yield* Ref.get(attachEvents)).toEqual([+ { type: "snapshot", snapshot: expect.objectContaining({ status: "exited" }) },+ ]);+ expect(ptyAdapter.spawnInputs).toHaveLength(1);++ // Opening another terminal completes eviction before the next resumed attach.+ yield* manager.open(openInput({ threadId: "thread-2" }));+ const unsubscribeEvicted = yield* manager.attachStream(+ { ...openInput(), restartIfNotRunning: true, resume: true },+ (event) => Ref.update(attachEvents, (events) => [...events, event]),+ );+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribeEvicted));+ expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual([+ "snapshot",+ "closed",+ ]);+ expect(ptyAdapter.spawnInputs).toHaveLength(2);+ }),+ );++ it.effect("resumed attaches recreate terminals this server has never seen", () =>+ Effect.gen(function* () {+ const { manager, ptyAdapter } = yield* createManager();+ const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);+ const unsubscribe = yield* manager.attachStream({ ...openInput(), resume: true }, (event) =>+ Ref.update(attachEvents, (events) => [...events, event]),+ );+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));+ expect(yield* Ref.get(attachEvents)).toEqual([+ { type: "snapshot", snapshot: expect.objectContaining({ status: "running" }) },+ ]);+ expect(ptyAdapter.spawnInputs).toHaveLength(1);+ }),+ );+it.effect("attaches to exited sessions without restarting them", () =>Effect.gen(function* () {const { manager, ptyAdapter, getEvents } = yield* createManager();diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.tsindex 3bb561aef25..898ba964444 100644--- a/apps/server/src/terminal/Manager.ts+++ b/apps/server/src/terminal/Manager.ts@@ -1510,6 +1510,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcsessions: new Map(),killFibers: new Map(),});+ // Keep close markers in memory so unknown IDs recover after a server restart.+ const closedSessionKeys = new Set<string>();const threadLocks = yield* KeyedLock.make<string>();const terminalEventListeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();const workerScope = yield* Scope.make("sequential");@@ -1955,6 +1957,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcfor (const session of inactiveSessions.slice(0, toEvict)) {const key = toSessionKey(session.threadId, session.terminalId);sessions.delete(key);+ closedSessionKeys.add(key);}return [undefined, { ...state, sessions }] as const;@@ -2359,6 +2362,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcyield* flushPersist(threadId, terminalId);const removed = yield* modifyManagerState((state) => {+ closedSessionKeys.add(key);if (!state.sessions.has(key)) {return [false, state] as const;}@@ -2587,6 +2591,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcyield* modifyManagerState((state) => {const sessions = new Map(state.sessions);sessions.set(sessionKey, createdSession);+ closedSessionKeys.delete(sessionKey);return [undefined, { ...state, sessions }] as const;});@@ -2689,6 +2694,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcconst 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,@@ -2708,7 +2716,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcconst targetCols = input.cols ?? session.cols;const targetRows = input.rows ?? session.rows;- if (!session.process && input.cwd && input.restartIfNotRunning === true) {+ if (!input.resume && !session.process && input.cwd && input.restartIfNotRunning === true) {const resolvedInput = yield* resolveLaunchInputEnvironment({...input,terminalId,@@ -2765,7 +2773,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcconst streamSession = (input: TerminalObserveInput,- initial: Effect.Effect<TerminalSessionSnapshot, TerminalError>,+ initial: Effect.Effect<TerminalSessionSnapshot | null, TerminalError>,listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,) => {let unsubscribe: (() => void) | null = null;@@ -2790,13 +2798,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcconst initialSnapshot = yield* initial;- yield* listener({- type: "snapshot",- snapshot: initialSnapshot,- });+ yield* listener(+ initialSnapshot === null+ ? { type: "closed", threadId: input.threadId, terminalId: input.terminalId }+ : { type: "snapshot", snapshot: initialSnapshot },+ );for (const event of bufferedEvents) {- if (isDuplicateAttachSnapshotEvent(event, initialSnapshot)) {+ if (initialSnapshot !== null && isDuplicateAttachSnapshotEvent(event, initialSnapshot)) {continue;}@@ -3025,6 +3034,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcyield* modifyManagerState((state) => {const sessions = new Map(state.sessions);sessions.set(sessionKey, createdSession);+ closedSessionKeys.delete(sessionKey);return [undefined, { ...state, sessions }] as const;});yield* evictInactiveSessionsIfNeeded();diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.tsindex c36bcaf3bd3..b1cc4f83506 100644--- a/packages/client-runtime/src/state/runtime.test.ts+++ b/packages/client-runtime/src/state/runtime.test.ts@@ -1,5 +1,10 @@import { describe, expect, it, vi } from "@effect/vitest";-import { EnvironmentId } from "@t3tools/contracts";+import {+ EnvironmentId,+ type TerminalAttachInput,+ type TerminalAttachStreamEvent,+ WS_METHODS,+} from "@t3tools/contracts";import * as Cause from "effect/Cause";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";@@ -27,6 +32,7 @@ import * as EnvironmentSupervisor from "../connection/supervisor.ts";import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";import type * as RpcSession from "../rpc/session.ts";import type { QueryPersistence } from "./queryPersistence.ts";+import { createTerminalEnvironmentAtoms } from "./terminal.ts";import {environmentRpcKey,createAtomCommandScheduler,@@ -100,6 +106,7 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness") {const supervisorState = yield* SubscriptionRef.make(initialState ?? queryConnectionState());const supervisorSession = yield* SubscriptionRef.make(Option.some(QUERY_RPC_SESSION));+ const streamGeneration = yield* SubscriptionRef.make(0);const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({target: QUERY_ENVIRONMENT,state: supervisorState,@@ -114,7 +121,12 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (_environmentId,stream,- ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);+ ) =>+ SubscriptionRef.changes(streamGeneration).pipe(+ Stream.switchMap(() =>+ Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),+ ),+ );const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({run,followStream,@@ -134,9 +146,11 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"});return {+ runtime,atom: family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }),supervisorSession,supervisorState,+ streamGeneration,};});@@ -374,6 +388,76 @@ describe("finite environment subscription lifecycle", () => {});describe("environment query lifecycle", () => {+ it.effect("terminal attach resubscribes with resume only after the stream replied", () =>+ Effect.gen(function* () {+ const harness = yield* makeEnvironmentQueryHarness(Effect.void);+ const inputs = yield* Queue.unbounded<TerminalAttachInput>();+ const events = yield* Queue.unbounded<TerminalAttachStreamEvent>();+ const received = yield* Deferred.make<void>();+ const client = {+ [WS_METHODS.terminalAttach]: (input: TerminalAttachInput) =>+ Stream.fromEffect(Queue.offer(inputs, input)).pipe(+ Stream.drain,+ Stream.concat(Stream.fromQueue(events)),+ ),+ } as unknown as RpcSession.RpcSession["client"];+ const firstSession = { ...QUERY_RPC_SESSION, client };+ yield* SubscriptionRef.set(harness.supervisorSession, Option.some(firstSession));+ const input = {+ threadId: "thread-1",+ terminalId: "terminal-1",+ cwd: "/tmp/project",+ restartIfNotRunning: true,+ };+ const atoms = createTerminalEnvironmentAtoms(harness.runtime);+ const registry = AtomRegistry.make();+ const atom = atoms.attach({ environmentId: QUERY_ENVIRONMENT.environmentId, input });+ const unmount = registry.subscribe(+ atom,+ (result) => {+ if (AsyncResult.isSuccess(result) && result.value.version > 0) {+ Deferred.doneUnsafe(received, Exit.void);+ }+ },+ { immediate: true },+ );+ yield* Effect.addFinalizer(() =>+ Effect.sync(() => {+ unmount();+ registry.dispose();+ }),+ );++ expect(yield* Queue.take(inputs)).toEqual(input);+ yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession }));+ expect(yield* Queue.take(inputs)).toEqual(input);+ yield* Queue.offer(events, {+ type: "closed",+ threadId: input.threadId,+ terminalId: input.terminalId,+ });+ yield* Deferred.await(received);++ yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession }));+ expect(yield* Queue.take(inputs)).toEqual({ ...input, resume: true });+ // Catalog replacements rerun the same stream through followStream's switchMap.+ yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1);+ expect(yield* Queue.take(inputs)).toEqual({ ...input, resume: true });++ unmount();+ registry.dispose();+ const remountedRegistry = AtomRegistry.make();+ const remount = remountedRegistry.subscribe(atom, () => {}, { immediate: true });+ yield* Effect.addFinalizer(() =>+ Effect.sync(() => {+ remount();+ remountedRegistry.dispose();+ }),+ );+ expect(yield* Queue.take(inputs)).toEqual(input);+ }),+ );+it.effect("keeps the previous value when a refetch returns equal content", () =>Effect.scoped(Effect.gen(function* () {diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.tsindex 155a709e786..94530b88113 100644--- a/packages/client-runtime/src/state/runtime.ts+++ b/packages/client-runtime/src/state/runtime.ts@@ -712,9 +712,9 @@ export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(const target = parseEnvironmentRpcKey<Input>(key);return runtime.atom(- followStreamInEnvironment(target.environmentId, options.subscribe(target.input)).pipe(- options.completeWhen ? Stream.takeUntil(options.completeWhen) : (stream) => stream,- ),+ Stream.suspend(() =>+ followStreamInEnvironment(target.environmentId, options.subscribe(target.input)),+ ).pipe(options.completeWhen ? Stream.takeUntil(options.completeWhen) : (stream) => stream),).pipe(Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),diff --git a/packages/client-runtime/src/state/terminal.ts b/packages/client-runtime/src/state/terminal.tsindex 8a3e3e74903..59da22c1859 100644--- a/packages/client-runtime/src/state/terminal.ts+++ b/packages/client-runtime/src/state/terminal.ts@@ -1,4 +1,5 @@import { type TerminalSummary, WS_METHODS } from "@t3tools/contracts";+import * as Effect from "effect/Effect";import * as Stream from "effect/Stream";import { Atom } from "effect/reactivity";@@ -9,7 +10,7 @@ import {createEnvironmentSubscriptionAtomFamily,} from "./runtime.ts";import type { EnvironmentRegistry } from "../connection/registry.ts";-import { subscribe, type EnvironmentRpcInput } from "../rpc/client.ts";+import { subscribe, subscribeDynamic, type EnvironmentRpcInput } from "../rpc/client.ts";import {applyTerminalAttachStreamEvent,applyTerminalMetadataStreamEvent,@@ -48,12 +49,20 @@ export function createTerminalEnvironmentAtoms<R, E>(}),attach: createEnvironmentSubscriptionAtomFamily(runtime, {label: "environment-data:terminal:attach",- subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalAttach>) =>- Stream.suspend(() =>- subscribe(WS_METHODS.terminalAttach, input).pipe(- Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent),+ subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalAttach>) => {+ // Retry an unanswered first attach unchanged so it can still open the shell.+ let replied = false;+ return subscribeDynamic(WS_METHODS.terminalAttach, () =>+ Effect.sync(() => (replied ? { ...input, resume: true } : input)),+ ).pipe(+ Stream.onFirst(() =>+ Effect.sync(() => {+ replied = true;+ }),),- ),+ Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent),+ );+ },}),events: createEnvironmentRpcSubscriptionAtomFamily(runtime, {label: "environment-data:terminal:events",diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.tsindex 7e9edf3a99c..e4824657a6e 100644--- a/packages/contracts/src/terminal.ts+++ b/packages/contracts/src/terminal.ts@@ -52,6 +52,8 @@ export const TerminalAttachInput = Schema.Struct({env: Schema.optional(TerminalEnvSchema),providerInstanceId: Schema.optional(ProviderInstanceId),restartIfNotRunning: Schema.optional(Schema.Boolean),+ // Resubscriptions preserve stopped terminals; unknown IDs recover after a server restart.+ resume: Schema.optional(Schema.Boolean),});export type TerminalAttachInput = typeof TerminalAttachInput.Type;