The best way to control Claude Code, Codex and more from any computer or phone
fix(server): reconnecting no longer reopens a closed terminal (#18444)
Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Guillermo Casanova committed
Oct 19, 2026 at 01:55 UTC
f3e5a165e043f4c1ae51568363409f94d916a811
6 files changed
+226
-18
apps/server/src/terminal/Manager.test.ts
+103
@@ -501,6 +501,109 @@ it.layer(
501
}),
502
);
503
504
+ it.effect("resumed attaches after close never respawn until the terminal is reopened", () =>
505
+ Effect.gen(function* () {
506
+ const { manager, ptyAdapter } = yield* createManager();
507
+ yield* manager.open(openInput());
508
+ yield* manager.close({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID });
509
+
510
+ const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
511
+ const unsubscribe = yield* manager.attachStream(
512
+ { ...openInput(), restartIfNotRunning: true, resume: true },
513
+ (event) => Ref.update(attachEvents, (events) => [...events, event]),
514
+ );
515
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
516
+ expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual(["closed"]);
517
+ expect(ptyAdapter.spawnInputs).toHaveLength(1);
518
+
519
+ yield* manager.open(openInput());
520
+ const events = yield* Ref.get(attachEvents);
521
+ expect(events.map((event) => event.type)).toEqual(["closed", "snapshot"]);
522
+ expect(ptyAdapter.spawnInputs).toHaveLength(2);
523
+ }),
524
+ );
525
+
526
+ it.effect("resumed attaches respect closes before this server has seen a terminal", () =>
527
+ Effect.gen(function* () {
528
+ const { manager, ptyAdapter } = yield* createManager();
529
+ yield* manager.close({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID });
530
+
531
+ const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
532
+ const unsubscribe = yield* manager.attachStream(
533
+ { ...openInput(), restartIfNotRunning: true, resume: true },
534
+ (event) => Ref.update(attachEvents, (events) => [...events, event]),
535
+ );
536
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
537
+ expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual(["closed"]);
538
+ expect(ptyAdapter.spawnInputs).toHaveLength(0);
539
+
540
+ const restarted = yield* manager.restart(restartInput());
541
+ expect(restarted.status).toBe("running");
542
+ expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual([
543
+ "closed",
544
+ "restarted",
545
+ ]);
546
+ expect(ptyAdapter.spawnInputs).toHaveLength(1);
547
+ }),
548
+ );
549
+
550
+ it.effect("resumed attaches leave exited and evicted terminals stopped", () =>
551
+ Effect.gen(function* () {
552
+ const { manager, ptyAdapter } = yield* createManager(5, {
553
+ maxRetainedInactiveSessions: 1,
554
+ });
555
+ const exited = yield* Deferred.make<void>();
556
+ const unsubscribeEvents = yield* manager.subscribe((event) =>
557
+ event.type === "exited"
558
+ ? Deferred.succeed(exited, undefined).pipe(Effect.asVoid)
559
+ : Effect.void,
560
+ );
561
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribeEvents));
562
+ yield* manager.open(openInput());
563
+ ptyAdapter.processes[0]?.emitExit({ exitCode: 0, signal: 0 });
564
+ yield* Deferred.await(exited);
565
+
566
+ const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
567
+ const unsubscribe = yield* manager.attachStream(
568
+ { ...openInput(), restartIfNotRunning: true, resume: true },
569
+ (event) => Ref.update(attachEvents, (events) => [...events, event]),
570
+ );
571
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
572
+ expect(yield* Ref.get(attachEvents)).toEqual([
573
+ { type: "snapshot", snapshot: expect.objectContaining({ status: "exited" }) },
574
+ ]);
575
+ expect(ptyAdapter.spawnInputs).toHaveLength(1);
576
+
577
+ // Opening another terminal completes eviction before the next resumed attach.
578
+ yield* manager.open(openInput({ threadId: "thread-2" }));
579
+ const unsubscribeEvicted = yield* manager.attachStream(
580
+ { ...openInput(), restartIfNotRunning: true, resume: true },
581
+ (event) => Ref.update(attachEvents, (events) => [...events, event]),
582
+ );
583
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribeEvicted));
584
+ expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual([
585
+ "snapshot",
586
+ "closed",
587
+ ]);
588
+ expect(ptyAdapter.spawnInputs).toHaveLength(2);
589
+ }),
590
+ );
591
+
592
+ it.effect("resumed attaches recreate terminals this server has never seen", () =>
593
+ Effect.gen(function* () {
594
+ const { manager, ptyAdapter } = yield* createManager();
595
+ const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
596
+ const unsubscribe = yield* manager.attachStream({ ...openInput(), resume: true }, (event) =>
597
+ Ref.update(attachEvents, (events) => [...events, event]),
598
+ );
599
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
600
+ expect(yield* Ref.get(attachEvents)).toEqual([
601
+ { type: "snapshot", snapshot: expect.objectContaining({ status: "running" }) },
602
+ ]);
603
+ expect(ptyAdapter.spawnInputs).toHaveLength(1);
604
+ }),
605
+ );
606
+
607
it.effect("attaches to exited sessions without restarting them", () =>
608
Effect.gen(function* () {
609
const { manager, ptyAdapter, getEvents } = yield* createManager();
apps/server/src/terminal/Manager.ts
+17
-7
@@ -1510,6 +1510,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
1510
sessions: new Map(),
1511
killFibers: new Map(),
1512
});
1513
+ // Keep close markers in memory so unknown IDs recover after a server restart.
1514
+ const closedSessionKeys = new Set<string>();
1515
const threadLocks = yield* KeyedLock.make<string>();
1516
const terminalEventListeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();
1517
const workerScope = yield* Scope.make("sequential");
@@ -1955,6 +1957,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
1957
for (const session of inactiveSessions.slice(0, toEvict)) {
1958
const key = toSessionKey(session.threadId, session.terminalId);
1959
sessions.delete(key);
1960
+ closedSessionKeys.add(key);
1961
}
1962
1963
return [undefined, { ...state, sessions }] as const;
@@ -2359,6 +2362,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2362
yield* flushPersist(threadId, terminalId);
2363
2364
const removed = yield* modifyManagerState((state) => {
2365
+ closedSessionKeys.add(key);
2366
if (!state.sessions.has(key)) {
2367
return [false, state] as const;
2368
}
@@ -2587,6 +2591,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2591
yield* modifyManagerState((state) => {
2592
const sessions = new Map(state.sessions);
2593
sessions.set(sessionKey, createdSession);
2594
+ closedSessionKeys.delete(sessionKey);
2595
return [undefined, { ...state, sessions }] as const;
2596
});
2597
@@ -2689,6 +2694,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2694
const existing = yield* getSession(input.threadId, terminalId);
2695
2696
if (Option.isNone(existing)) {
2697
+ if (input.resume && closedSessionKeys.has(toSessionKey(input.threadId, terminalId))) {
2698
+ return null;
2699
+ }
2700
if (!input.cwd) {
2701
return yield* new TerminalSessionLookupError({
2702
threadId: input.threadId,
@@ -2708,7 +2716,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2716
const targetCols = input.cols ?? session.cols;
2717
const targetRows = input.rows ?? session.rows;
2718
2711
- if (!session.process && input.cwd && input.restartIfNotRunning === true) {
2719
+ if (!input.resume && !session.process && input.cwd && input.restartIfNotRunning === true) {
2720
const resolvedInput = yield* resolveLaunchInputEnvironment({
2721
...input,
2722
terminalId,
@@ -2765,7 +2773,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2773
2774
const streamSession = (
2775
input: TerminalObserveInput,
2768
- initial: Effect.Effect<TerminalSessionSnapshot, TerminalError>,
2776
+ initial: Effect.Effect<TerminalSessionSnapshot | null, TerminalError>,
2777
listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
2778
) => {
2779
let unsubscribe: (() => void) | null = null;
@@ -2790,13 +2798,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2798
2799
const initialSnapshot = yield* initial;
2800
2793
- yield* listener({
2794
- type: "snapshot",
2795
- snapshot: initialSnapshot,
2796
- });
2801
+ yield* listener(
2802
+ initialSnapshot === null
2803
+ ? { type: "closed", threadId: input.threadId, terminalId: input.terminalId }
2804
+ : { type: "snapshot", snapshot: initialSnapshot },
2805
+ );
2806
2807
for (const event of bufferedEvents) {
2799
- if (isDuplicateAttachSnapshotEvent(event, initialSnapshot)) {
2808
+ if (initialSnapshot !== null && isDuplicateAttachSnapshotEvent(event, initialSnapshot)) {
2809
continue;
2810
}
2811
@@ -3025,6 +3034,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3034
yield* modifyManagerState((state) => {
3035
const sessions = new Map(state.sessions);
3036
sessions.set(sessionKey, createdSession);
3037
+ closedSessionKeys.delete(sessionKey);
3038
return [undefined, { ...state, sessions }] as const;
3039
});
3040
yield* evictInactiveSessionsIfNeeded();
packages/client-runtime/src/state/runtime.test.ts
+86
-2
@@ -1,5 +1,10 @@
1
import { describe, expect, it, vi } from "@effect/vitest";
2
-import { EnvironmentId } from "@t3tools/contracts";
2
+import {
3
+ EnvironmentId,
4
+ type TerminalAttachInput,
5
+ type TerminalAttachStreamEvent,
6
+ WS_METHODS,
7
+} from "@t3tools/contracts";
8
import * as Cause from "effect/Cause";
9
import * as Deferred from "effect/Deferred";
10
import * as Effect from "effect/Effect";
@@ -27,6 +32,7 @@ import * as EnvironmentSupervisor from "../connection/supervisor.ts";
32
import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
33
import type * as RpcSession from "../rpc/session.ts";
34
import type { QueryPersistence } from "./queryPersistence.ts";
35
+import { createTerminalEnvironmentAtoms } from "./terminal.ts";
36
import {
37
environmentRpcKey,
38
createAtomCommandScheduler,
@@ -100,6 +106,7 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"
106
) {
107
const supervisorState = yield* SubscriptionRef.make(initialState ?? queryConnectionState());
108
const supervisorSession = yield* SubscriptionRef.make(Option.some(QUERY_RPC_SESSION));
109
+ const streamGeneration = yield* SubscriptionRef.make(0);
110
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
111
target: QUERY_ENVIRONMENT,
112
state: supervisorState,
@@ -114,7 +121,12 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"
121
const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
122
_environmentId,
123
stream,
117
- ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
124
+ ) =>
125
+ SubscriptionRef.changes(streamGeneration).pipe(
126
+ Stream.switchMap(() =>
127
+ Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
128
+ ),
129
+ );
130
const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
131
run,
132
followStream,
@@ -134,9 +146,11 @@ const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness"
146
});
147
148
return {
149
+ runtime,
150
atom: family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }),
151
supervisorSession,
152
supervisorState,
153
+ streamGeneration,
154
};
155
});
156
@@ -374,6 +388,76 @@ describe("finite environment subscription lifecycle", () => {
388
});
389
390
describe("environment query lifecycle", () => {
391
+ it.effect("terminal attach resubscribes with resume only after the stream replied", () =>
392
+ Effect.gen(function* () {
393
+ const harness = yield* makeEnvironmentQueryHarness(Effect.void);
394
+ const inputs = yield* Queue.unbounded<TerminalAttachInput>();
395
+ const events = yield* Queue.unbounded<TerminalAttachStreamEvent>();
396
+ const received = yield* Deferred.make<void>();
397
+ const client = {
398
+ [WS_METHODS.terminalAttach]: (input: TerminalAttachInput) =>
399
+ Stream.fromEffect(Queue.offer(inputs, input)).pipe(
400
+ Stream.drain,
401
+ Stream.concat(Stream.fromQueue(events)),
402
+ ),
403
+ } as unknown as RpcSession.RpcSession["client"];
404
+ const firstSession = { ...QUERY_RPC_SESSION, client };
405
+ yield* SubscriptionRef.set(harness.supervisorSession, Option.some(firstSession));
406
+ const input = {
407
+ threadId: "thread-1",
408
+ terminalId: "terminal-1",
409
+ cwd: "/tmp/project",
410
+ restartIfNotRunning: true,
411
+ };
412
+ const atoms = createTerminalEnvironmentAtoms(harness.runtime);
413
+ const registry = AtomRegistry.make();
414
+ const atom = atoms.attach({ environmentId: QUERY_ENVIRONMENT.environmentId, input });
415
+ const unmount = registry.subscribe(
416
+ atom,
417
+ (result) => {
418
+ if (AsyncResult.isSuccess(result) && result.value.version > 0) {
419
+ Deferred.doneUnsafe(received, Exit.void);
420
+ }
421
+ },
422
+ { immediate: true },
423
+ );
424
+ yield* Effect.addFinalizer(() =>
425
+ Effect.sync(() => {
426
+ unmount();
427
+ registry.dispose();
428
+ }),
429
+ );
430
+
431
+ expect(yield* Queue.take(inputs)).toEqual(input);
432
+ yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession }));
433
+ expect(yield* Queue.take(inputs)).toEqual(input);
434
+ yield* Queue.offer(events, {
435
+ type: "closed",
436
+ threadId: input.threadId,
437
+ terminalId: input.terminalId,
438
+ });
439
+ yield* Deferred.await(received);
440
+
441
+ yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession }));
442
+ expect(yield* Queue.take(inputs)).toEqual({ ...input, resume: true });
443
+ // Catalog replacements rerun the same stream through followStream's switchMap.
444
+ yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1);
445
+ expect(yield* Queue.take(inputs)).toEqual({ ...input, resume: true });
446
+
447
+ unmount();
448
+ registry.dispose();
449
+ const remountedRegistry = AtomRegistry.make();
450
+ const remount = remountedRegistry.subscribe(atom, () => {}, { immediate: true });
451
+ yield* Effect.addFinalizer(() =>
452
+ Effect.sync(() => {
453
+ remount();
454
+ remountedRegistry.dispose();
455
+ }),
456
+ );
457
+ expect(yield* Queue.take(inputs)).toEqual(input);
458
+ }),
459
+ );
460
+
461
it.effect("keeps the previous value when a refetch returns equal content", () =>
462
Effect.scoped(
463
Effect.gen(function* () {
packages/client-runtime/src/state/runtime.ts
+3
-3
@@ -712,9 +712,9 @@ export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
712
const target = parseEnvironmentRpcKey<Input>(key);
713
return runtime
714
.atom(
715
- followStreamInEnvironment(target.environmentId, options.subscribe(target.input)).pipe(
716
- options.completeWhen ? Stream.takeUntil(options.completeWhen) : (stream) => stream,
717
- ),
715
+ Stream.suspend(() =>
716
+ followStreamInEnvironment(target.environmentId, options.subscribe(target.input)),
717
+ ).pipe(options.completeWhen ? Stream.takeUntil(options.completeWhen) : (stream) => stream),
718
)
719
.pipe(
720
Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),
packages/client-runtime/src/state/terminal.ts
+15
-6
@@ -1,4 +1,5 @@
1
import { type TerminalSummary, WS_METHODS } from "@t3tools/contracts";
2
+import * as Effect from "effect/Effect";
3
import * as Stream from "effect/Stream";
4
import { Atom } from "effect/reactivity";
5
@@ -9,7 +10,7 @@ import {
10
createEnvironmentSubscriptionAtomFamily,
11
} from "./runtime.ts";
12
import type { EnvironmentRegistry } from "../connection/registry.ts";
12
-import { subscribe, type EnvironmentRpcInput } from "../rpc/client.ts";
13
+import { subscribe, subscribeDynamic, type EnvironmentRpcInput } from "../rpc/client.ts";
14
import {
15
applyTerminalAttachStreamEvent,
16
applyTerminalMetadataStreamEvent,
@@ -48,12 +49,20 @@ export function createTerminalEnvironmentAtoms<R, E>(
49
}),
50
attach: createEnvironmentSubscriptionAtomFamily(runtime, {
51
label: "environment-data:terminal:attach",
51
- subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalAttach>) =>
52
- Stream.suspend(() =>
53
- subscribe(WS_METHODS.terminalAttach, input).pipe(
54
- Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent),
52
+ subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalAttach>) => {
53
+ // Retry an unanswered first attach unchanged so it can still open the shell.
54
+ let replied = false;
55
+ return subscribeDynamic(WS_METHODS.terminalAttach, () =>
56
+ Effect.sync(() => (replied ? { ...input, resume: true } : input)),
57
+ ).pipe(
58
+ Stream.onFirst(() =>
59
+ Effect.sync(() => {
60
+ replied = true;
61
+ }),
62
),
56
- ),
63
+ Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent),
64
+ );
65
+ },
66
}),
67
events: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
68
label: "environment-data:terminal:events",
packages/contracts/src/terminal.ts
+2
@@ -52,6 +52,8 @@ export const TerminalAttachInput = Schema.Struct({
52
env: Schema.optional(TerminalEnvSchema),
53
providerInstanceId: Schema.optional(ProviderInstanceId),
54
restartIfNotRunning: Schema.optional(Schema.Boolean),
55
+ // Resubscriptions preserve stopped terminals; unknown IDs recover after a server restart.
56
+ resume: Schema.optional(Schema.Boolean),
57
});
58
export type TerminalAttachInput = typeof TerminalAttachInput.Type;
59