The best way to control Claude Code, Codex and more from any computer or phone
fix(terminal): show shell startup failures across attachments (#37088)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 15, 2026 at 09:43 UTC
e101cae1b9e96049eabb342eecd23283913a1b55
9 files changed
+190
-5
apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+1
-1
@@ -893,7 +893,7 @@ function ThreadTerminal(props: {
893
title="No terminal sessions"
894
detail="Existing terminals will appear here when another client opens one."
895
/>
896
- ) : !canOperateTerminal && terminal.error !== null ? (
896
+ ) : terminal.error !== null && (!canOperateTerminal || terminal.status === "error") ? (
897
<EmptyState title="Terminal unavailable" detail={terminal.error} />
898
) : (
899
<>
apps/server/src/terminal/Manager.test.ts
+35
@@ -1940,6 +1940,41 @@ it.layer(
1940
}),
1941
);
1942
1943
+ it.effect("keeps a startup failure in the snapshot every later attachment receives", () =>
1944
+ Effect.gen(function* () {
1945
+ const { manager, ptyAdapter } = yield* createManager();
1946
+ ptyAdapter.spawnFailures.push(new Error("forkpty(3) failed."));
1947
+ const startupFailure = {
1948
+ type: "snapshot",
1949
+ snapshot: {
1950
+ status: "error",
1951
+ error: expect.stringContaining("Failed to spawn PTY process"),
1952
+ },
1953
+ };
1954
+ const record = (events: TerminalAttachStreamEvent[]) => (event: TerminalAttachStreamEvent) =>
1955
+ Effect.sync(() => events.push(event));
1956
+
1957
+ const creating: TerminalAttachStreamEvent[] = [];
1958
+ (yield* manager.attachStream(openInput(), record(creating)))();
1959
+ const resumed: TerminalAttachStreamEvent[] = [];
1960
+ (yield* manager.attachStream({ ...openInput(), resume: true }, record(resumed)))();
1961
+ const observed: TerminalAttachStreamEvent[] = [];
1962
+ (yield* manager.observeStream(
1963
+ { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID },
1964
+ record(observed),
1965
+ ))();
1966
+ expect([creating, resumed, observed]).toMatchObject([
1967
+ [startupFailure],
1968
+ [startupFailure],
1969
+ [startupFailure],
1970
+ ]);
1971
+
1972
+ const restarted = yield* manager.open(openInput());
1973
+ expect(restarted.status).toBe("running");
1974
+ expect(restarted).not.toHaveProperty("error");
1975
+ }),
1976
+ );
1977
+
1978
it.effect("retries with fallback shells when preferred shell spawn fails", () =>
1979
Effect.gen(function* () {
1980
const platform = yield* HostProcess.Platform;
apps/server/src/terminal/Manager.ts
+6
-1
@@ -316,6 +316,7 @@ interface TerminalSessionState {
316
childCommandLabel: string | null;
317
runtimeEnv: Record<string, string> | null;
318
stopOnSettle: boolean;
319
+ startupError: string | null;
320
}
321
322
interface TerminalGrid {
@@ -411,6 +412,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
412
sequence: session.eventSequence,
413
cols: session.cols,
414
rows: session.rows,
415
+ ...(session.startupError === null ? {} : { error: session.startupError }),
416
};
417
}
418
@@ -2680,6 +2682,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2682
const startingAt = yield* nowIso;
2683
yield* modifyManagerState((state) => {
2684
session.status = "starting";
2685
+ session.startupError = null;
2686
session.shell = null;
2687
session.cwd = input.cwd;
2688
session.worktreePath = input.worktreePath ?? null;
@@ -2800,6 +2803,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2803
2804
{
2805
const error = startResult.failure;
2806
+ const message = error.message;
2807
if (ptyProcess) {
2808
yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId);
2809
}
@@ -2807,6 +2811,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2811
yield* modifyManagerState((state) => {
2812
cleanupProcessHandles(session);
2813
session.status = "error";
2814
+ session.startupError = message;
2815
session.pid = null;
2816
session.process = null;
2817
session.hasRunningSubprocess = false;
@@ -2824,7 +2829,6 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2829
2830
yield* evictInactiveSessionsIfNeeded();
2831
2827
- const message = error.message;
2832
yield* publishEvent({
2833
type: "error",
2834
threadId: session.threadId,
@@ -3143,6 +3147,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3147
childCommandLabel: null,
3148
runtimeEnv: normalizedRuntimeEnv(input.env),
3149
stopOnSettle: input.stopOnSettle ?? false,
3150
+ startupError: null,
3151
};
3152
3153
const createdSession = session;
apps/web/src/components/ThreadTerminalDrawer.test.ts
+30
@@ -98,4 +98,34 @@ it("reports an attach failure that leaves the output unchanged", () => {
98
expect(terminal.getSelection).not.toHaveBeenCalled();
99
expect(terminal.getSelectionCellCount).not.toHaveBeenCalled();
100
expect(terminal.clearSelection).not.toHaveBeenCalled();
101
+
102
+ const snapshot = {
103
+ threadId: "thread",
104
+ terminalId: "term-1",
105
+ cwd: "/repo",
106
+ worktreePath: null,
107
+ status: "error" as const,
108
+ pid: null,
109
+ history: "",
110
+ exitCode: null,
111
+ exitSignal: null,
112
+ label: "Terminal",
113
+ updatedAt: "2026-11-15T00:00:00.000Z",
114
+ error: "Terminal attach failed",
115
+ };
116
+ const attached = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
117
+ type: "snapshot",
118
+ snapshot,
119
+ });
120
+ const cursor = synchronizeTerminalSession(
121
+ terminal,
122
+ failed,
123
+ attached,
124
+ INITIAL_TERMINAL_OUTPUT_CURSOR,
125
+ );
126
+ terminal.write.mockClear();
127
+ const reconnected = applyTerminalAttachStreamEvent(attached, { type: "snapshot", snapshot });
128
+ synchronizeTerminalSession(terminal, attached, reconnected, cursor);
129
+ expect(terminal.resetAndWrite).toHaveBeenLastCalledWith("");
130
+ expect(terminal.write).toHaveBeenCalledWith("\r\n[terminal] Terminal attach failed\r\n");
131
});
apps/web/src/components/ThreadTerminalDrawer.tsx
+7
-2
@@ -191,7 +191,7 @@ export function synchronizeTerminalOutput(
191
return update.cursor;
192
}
193
194
-/** Writes what changed between two session notifications: new output, then a new error. */
194
+/** Writes what changed between two session notifications: new output, then the error, again after a reset. */
195
export function synchronizeTerminalSession(
196
terminal: Parameters<typeof synchronizeTerminalOutput>[0],
197
previous: Pick<TerminalSessionState, "output" | "version" | "error">,
@@ -203,7 +203,12 @@ export function synchronizeTerminalSession(
203
? cursor
204
: synchronizeTerminalOutput(terminal, session, cursor);
205
// An attach failure can change only the error, keeping the last buffer.
206
- if (session.error !== null && session.error !== previous.error) {
206
+ if (
207
+ session.error !== null &&
208
+ (session.error !== previous.error ||
209
+ nextCursor.generation !== cursor.generation ||
210
+ nextCursor.resetVersion !== cursor.resetVersion)
211
+ ) {
212
writeSystemMessage(terminal, session.error);
213
}
214
return nextCursor;
packages/client-runtime/src/state/terminalSession.test.ts
+9
@@ -72,6 +72,15 @@ describe("terminal session reducers", () => {
72
});
73
});
74
75
+ it("keeps a startup failure carried by an attach snapshot", () => {
76
+ const attached = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
77
+ type: "snapshot",
78
+ snapshot: { ...BASE_SNAPSHOT, status: "error", pid: null, error: "Failed to spawn PTY." },
79
+ });
80
+
81
+ expect(attached).toMatchObject({ status: "error", error: "Failed to spawn PTY." });
82
+ });
83
+
84
it("follows the shared PTY grid from snapshots and activity without disturbing output", () => {
85
const attached = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
86
type: "snapshot",
packages/client-runtime/src/state/terminalSession.ts
+1
-1
@@ -118,7 +118,7 @@ function terminalBufferStateFromSnapshot(
118
output: resetOutput(current.output, snapshot.history, maxBufferBytes),
119
grid: nextGrid(current.grid, snapshot),
120
status: snapshot.status,
121
- error: null,
121
+ error: snapshot.error ?? null,
122
updatedAt: snapshot.updatedAt,
123
version: current.version + 1,
124
lifecycleVersion: current.lifecycleVersion,
packages/contracts/src/terminal.ts
+2
@@ -232,6 +232,8 @@ export const TerminalSessionSnapshot = Schema.Struct({
232
// The PTY grid every renderer of this terminal should draw; absent from older servers.
233
cols: Schema.optional(TerminalColsSchema),
234
rows: Schema.optional(TerminalRowsSchema),
235
+ // Why the shell failed to start, kept so later attachments can show it.
236
+ error: Schema.optional(Schema.String.check(Schema.isNonEmpty())),
237
});
238
export type TerminalSessionSnapshot = typeof TerminalSessionSnapshot.Type;
239
scripts/scenarios/terminal-shows-startup-failure.e2e.ts
new
+99
@@ -0,0 +1,99 @@
1
+/// <reference lib="dom" />
2
+// The DOM lib types the function this scenario runs in the page.
3
+import { expect } from "e2e";
4
+import * as Effect from "effect/Effect";
5
+import * as FileSystem from "effect/FileSystem";
6
+import * as Path from "effect/Path";
7
+import * as Schema from "effect/Schema";
8
+
9
+import { APP_DIR, T3_HOME } from "../e2e.config.ts";
10
+import { run } from "./shell.ts";
11
+import { runPromise, test, WEB } from "./t3.ts";
12
+
13
+const decodeRuntime = Schema.decodeUnknownEffect(
14
+ Schema.fromJsonString(Schema.Struct({ pid: Schema.Int })),
15
+);
16
+
17
+/** The scenario's own server: the pid its T3 home records, running from the app checkout. */
18
+const scenarioServerPid = Effect.gen(function* () {
19
+ const fs = yield* FileSystem.FileSystem;
20
+ const path = yield* Path.Path;
21
+ const runtime = yield* Effect.firstSuccessOf(
22
+ ["userdata", "dev"].map((dir) =>
23
+ fs.readFileString(path.join(T3_HOME, dir, "server-runtime.json")),
24
+ ),
25
+ );
26
+ const { pid } = yield* decodeRuntime(runtime);
27
+ const cwd = yield* fs.readLink(`/proc/${pid}/cwd`);
28
+ if (!cwd.startsWith(path.resolve(APP_DIR))) {
29
+ return yield* Effect.die(new Error(`pid ${pid} runs in ${cwd}, not ${APP_DIR}`));
30
+ }
31
+ return pid;
32
+});
33
+
34
+/**
35
+ * Linux only: leaves the server no free file descriptor, so node-pty's forkpty(3) fails as it does when a
36
+ * host runs out. Returns the restore; only this process's soft limit changes.
37
+ */
38
+const exhaustFileDescriptors = Effect.fn("scenario.exhaustFileDescriptors")(function* (
39
+ pid: number,
40
+) {
41
+ const limits = yield* run("prlimit", [
42
+ `--pid=${pid}`,
43
+ "--nofile",
44
+ "--raw",
45
+ "--noheadings",
46
+ "--output=SOFT,HARD",
47
+ ]);
48
+ const [soft = "", hard = ""] = limits.stdout.trim().split(/\s+/);
49
+ yield* run("prlimit", [`--pid=${pid}`, `--nofile=0:${hard}`]);
50
+ return run("prlimit", [`--pid=${pid}`, `--nofile=${soft}:${hard}`]);
51
+});
52
+
53
+test(
54
+ "A terminal whose shell cannot start says why, also after its drawer reopens",
55
+ WEB,
56
+ async ({ t3, app, browser, screen }) => {
57
+ const project = await t3.project("demo");
58
+ const thread = await t3.thread({ project, title: "Shell", messages: ["hello"] });
59
+ await t3.open(thread);
60
+ const pid = await runPromise(scenarioServerPid);
61
+
62
+ const toggle = screen.getByRole("button", "Toggle terminal drawer");
63
+ const terminal = screen.getByLabel("Terminal input");
64
+ // The canvas has no DOM text: select all and read what the terminal's copy hands over.
65
+ const terminalText = async () => {
66
+ await browser.evaluate(() => {
67
+ delete document.body.dataset.terminalCopy;
68
+ window.addEventListener(
69
+ "copy",
70
+ (event) => {
71
+ document.body.dataset.terminalCopy = event.clipboardData?.getData("text/plain") ?? "";
72
+ },
73
+ { once: true },
74
+ );
75
+ return null;
76
+ });
77
+ await terminal.focus();
78
+ await browser.keyboard.press("Control+Shift+A");
79
+ await browser.keyboard.press("Control+Shift+C");
80
+ return browser.evaluate(() => document.body.dataset.terminalCopy ?? "");
81
+ };
82
+
83
+ await expect(toggle).toBeVisible();
84
+ const restore = await runPromise(exhaustFileDescriptors(pid));
85
+ try {
86
+ await toggle.tap();
87
+ await expect.poll(terminalText, { timeout: 15_000 }).toContain("Failed to spawn PTY process");
88
+ } finally {
89
+ await runPromise(restore);
90
+ }
91
+ await app.screenshot("startup-failure");
92
+
93
+ await toggle.tap();
94
+ await expect(terminal).toBeHidden();
95
+ await toggle.tap();
96
+ await expect.poll(terminalText, { timeout: 15_000 }).toContain("Failed to spawn PTY process");
97
+ await app.screenshot("after-reopen");
98
+ },
99
+);