@devries-cameron20 / t3code-1 / commits / 43a71d9b1a
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): a terminal reopened while its open is pending no longer closes itself (#29654)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Salloxy committed Nov 14, 2026 at 10:00 UTC 43a71d9b1acbd8b18257591344296f8e7d1c1d68
8 files changed +173 -32
apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
+75 -14
@@ -18,8 +18,17 @@ import { act, fakeTimers, render } from "../../test/render";
18 import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
19
20 const fixture = vi.hoisted(() => ({
21 - statusByThreadId: new Map<string, "running" | "exited">(),
21 + statusByThreadId: new Map<string, "starting" | "running" | "exited">(),
22 pendingSurfaces: [] as Array<() => void>,
23 + typeIntoSurface: null as ((data: string) => void) | null,
24 + pressKey: null as ((event: KeyboardEvent) => boolean) | null,
25 + writes: [] as Array<{ threadId: string; data: string }>,
26 + resetSessions: () => {},
27 + setSession: (
28 + _thread: ScopedThreadRef,
29 + _status: "closed" | "starting" | "running",
30 + _version: number,
31 + ) => {},
32 surfaceOptions: [] as GhosttyTerminalSurfaceOptions[],
33 metadata: new Map<
34 string,
@@ -40,21 +49,38 @@ vi.mock("~/terminal/ghostty/surface", () => ({
49 create: (_mount: HTMLElement, options: GhosttyTerminalSurfaceOptions) =>
50 new Promise((resolve) => {
51 fixture.surfaceOptions.push(options);
43 - fixture.pendingSurfaces.push(() => resolve(fakeSurface));
52 + fixture.pendingSurfaces.push(() => {
53 + fixture.typeIntoSurface = options.onData;
54 + fixture.pressKey = options.beforeKey ?? null;
55 + resolve(fakeSurface);
56 + });
57 }),
58 },
59 }));
60 vi.mock("../state/terminalSessions", async () => {
61 const Atom = await import("effect/reactivity/Atom");
49 - const sessions = Atom.family((_environmentId: EnvironmentId) =>
50 - Atom.family((threadId: ThreadId) =>
51 - Atom.make({
52 - ...EMPTY_TERMINAL_SESSION_STATE,
53 - status: fixture.statusByThreadId.get(threadId) ?? "closed",
54 - version: 1,
55 - }),
56 - ),
57 - );
62 + // Families cache their atoms, so each test needs fresh ones for its own statuses.
63 + const makeSessions = () =>
64 + Atom.family((_environmentId: EnvironmentId) =>
65 + Atom.family((threadId: ThreadId) =>
66 + Atom.make({
67 + ...EMPTY_TERMINAL_SESSION_STATE,
68 + status: fixture.statusByThreadId.get(threadId) ?? "closed",
69 + version: 1,
70 + }),
71 + ),
72 + );
73 + let sessions = makeSessions();
74 + fixture.resetSessions = () => {
75 + sessions = makeSessions();
76 + };
77 + fixture.setSession = (thread, status, version) => {
78 + appAtomRegistry.set(sessions(thread.environmentId)(thread.threadId), {
79 + ...EMPTY_TERMINAL_SESSION_STATE,
80 + status,
81 + version,
82 + });
83 + };
84 return {
85 attachedTerminalSessionAtom: (environmentId: EnvironmentId, terminal: { threadId: ThreadId }) =>
86 sessions(environmentId)(terminal.threadId),
@@ -65,7 +91,12 @@ vi.mock("../state/session", () => ({
91 readEnvironmentScope: () => true,
92 }));
93 vi.mock("../state/use-atom-command", () => ({
68 - useAtomCommand: () => async () => ({ _tag: "Success" }),
94 + useAtomCommand: () => async (args: { input: { threadId: string; data?: string } }) => {
95 + if (args.input.data !== undefined) {
96 + fixture.writes.push({ threadId: args.input.threadId, data: args.input.data });
97 + }
98 + return { _tag: "Success" };
99 + },
100 }));
101 // The commands are replaced above; importing their runtime would connect a client.
102 vi.mock("../state/server", async () => {
@@ -138,7 +169,8 @@ function Drawer(props: {
169 );
170 }
171
141 -function setup() {
172 +function setup(originalStatus: "starting" | "exited" = "exited") {
173 + fixture.resetSessions();
174 const original: ScopedThreadRef = {
175 environmentId: EnvironmentId.make("environment-a"),
176 threadId: ThreadId.make("thread-a"),
@@ -148,10 +180,13 @@ function setup() {
180 threadId: ThreadId.make("thread-b"),
181 };
182 fixture.statusByThreadId = new Map([
151 - [original.threadId, "exited"],
183 + [original.threadId, originalStatus],
184 [other.threadId, "running"],
185 ]);
186 fixture.pendingSurfaces = [];
187 + fixture.typeIntoSurface = null;
188 + fixture.pressKey = null;
189 + fixture.writes = [];
190 fixture.surfaceOptions = [];
191 fixture.metadata.clear();
192 useRightPanelStore.setState(useRightPanelStore.getInitialState());
@@ -159,6 +194,32 @@ function setup() {
194 return { original, other };
195 }
196
197 +it("drops input until the shell runs instead of failing a write for every key", async () => {
198 + const { original } = setup("starting");
199 + fixture.setSession(original, "closed", 0);
200 + await using _screen = await render(<Drawer threadRef={original} onCloseTerminal={() => {}} />);
201 + await act(async () => {
202 + fixture.pendingSurfaces.shift()?.();
203 + });
204 + const clearShortcut = () => new KeyboardEvent("keydown", { key: "l", ctrlKey: true });
205 + fixture.typeIntoSurface?.("before attach");
206 + fixture.pressKey?.(clearShortcut());
207 + await act(() => fixture.setSession(original, "running", 0));
208 + fixture.typeIntoSurface?.("stale metadata");
209 + fixture.pressKey?.(clearShortcut());
210 + await act(() => fixture.setSession(original, "starting", 1));
211 + fixture.typeIntoSurface?.("early");
212 + fixture.pressKey?.(clearShortcut());
213 + expect(fixture.writes).toEqual([]);
214 + await act(() => fixture.setSession(original, "running", 1));
215 + fixture.typeIntoSurface?.("ready");
216 + fixture.pressKey?.(clearShortcut());
217 + expect(fixture.writes).toEqual([
218 + { threadId: original.threadId, data: "ready" },
219 + { threadId: original.threadId, data: "\u000c" },
220 + ]);
221 +});
222 +
223 it("closes an exited terminal on its own thread after navigating to one reusing its ID", async () => {
224 const { original, other } = setup();
225 const onCloseTerminal = vi.fn();
apps/web/src/components/ThreadTerminalDrawer.tsx
+5 -11
@@ -916,7 +916,10 @@ function TerminalSessionViewport({
916 };
917
918 const sendTerminalInput = async (data: string, fallbackError: string) => {
919 - if (!hasTerminalWriteAccess()) return;
919 + // The server rejects input until the shell runs, and each rejection would print an error.
920 + if (writableSessionGeneration(readTerminalSession(), hasTerminalWriteAccess()) === null) {
921 + return;
922 + }
923 const activeTerminal = terminalRef.current;
924 if (!activeTerminal) return;
925 const result = await writeTerminal(data);
@@ -1025,16 +1028,7 @@ function TerminalSessionViewport({
1028 }
1029
1030 function handleData(data: string): void {
1028 - if (!hasTerminalWriteAccess()) return;
1029 - void (async () => {
1030 - const result = await writeTerminal(data);
1031 - if (result._tag === "Success" || isAtomCommandInterrupted(result)) return;
1032 - const error = squashAtomCommandFailure(result);
1033 - writeSystemMessage(
1034 - terminal,
1035 - error instanceof Error ? error.message : "Terminal write failed",
1036 - );
1037 - })();
1031 + void sendTerminalInput(data, "Terminal write failed");
1032 }
1033
1034 const themeObserver = new MutationObserver(() => {
apps/web/src/components/chat/useChatTerminalActions.ts
+6 -2
@@ -34,6 +34,7 @@ import { resolveDiscoveredServerUrl } from "../../browser/browserTargetResolver"
34 import { stackedThreadToast, toastManager } from "../ui/toast";
35 import { confirmTerminalClose } from "../../lib/terminalCloseConfirm";
36 import { findReusableProjectScriptTerminal } from "../../lib/projectScriptTerminal";
37 +import { closingTerminalIds } from "../terminal/closingTerminals";
38 import { type TerminalContextSelection } from "../../lib/terminalContext";
39 import {
40 focusActiveDrawerTerminal,
@@ -152,9 +153,11 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
153 if (nextOpen && hasTerminalWriteAccess() && terminalUiState.terminalIds.length === 0) {
154 // Server-created setup terminals exist before this client's drawer mounts.
155 // Reuse them before allocating a shell from the still-empty UI state.
156 + // The server lists a closing terminal until its close finishes, which would end the reopen.
157 + const closingIds = new Set(closingTerminalIds(activeThreadRef));
158 + const isReusable = (id: string) => !panelTerminalIds.has(id) && !closingIds.has(id);
159 const existingTerminalId =
156 - runningTerminalIds.find((id) => !panelTerminalIds.has(id)) ??
157 - activeServerOrderedTerminalIds.find((id) => !panelTerminalIds.has(id));
160 + runningTerminalIds.find(isReusable) ?? activeServerOrderedTerminalIds.find(isReusable);
161 if (existingTerminalId !== undefined) {
162 storeEnsureTerminal(activeThreadRef, existingTerminalId, { open: true, active: true });
163 focusActiveDrawerTerminal(activeThreadRef);
@@ -232,6 +235,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
235 activeTerminalId: terminalUiState.activeTerminalId,
236 panelTerminalIds,
237 runningTerminalIds,
238 + closingTerminalIds: activeThreadRef ? closingTerminalIds(activeThreadRef) : [],
239 });
240 const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
241
apps/web/src/components/terminal/closingTerminals.test.ts new
+34
@@ -0,0 +1,34 @@
1 +import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 +import { expect, it } from "vite-plus/test";
3 +
4 +import { closingTerminalIds, holdTerminalIdWhileClosing } from "./closingTerminals";
5 +
6 +function deferred() {
7 + let resolve!: () => void;
8 + let reject!: (error: Error) => void;
9 + const promise = new Promise<void>((onResolve, onReject) => {
10 + resolve = onResolve;
11 + reject = onReject;
12 + });
13 + return { promise, resolve, reject };
14 +}
15 +
16 +it("keeps a closing terminal's ID out of reach until its last close settles", async () => {
17 + const thread = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };
18 + const otherThread = { ...thread, threadId: ThreadId.make("other") };
19 + const first = deferred();
20 + const second = deferred();
21 +
22 + const firstClose = holdTerminalIdWhileClosing(thread, "term-1", () => first.promise);
23 + const secondClose = holdTerminalIdWhileClosing(thread, "term-1", () => second.promise);
24 + expect(closingTerminalIds(thread)).toEqual(["term-1"]);
25 + expect(closingTerminalIds(otherThread)).toEqual([]);
26 +
27 + first.reject(new Error("close failed"));
28 + await expect(firstClose).rejects.toThrow("close failed");
29 + expect(closingTerminalIds(thread)).toEqual(["term-1"]);
30 +
31 + second.resolve();
32 + await secondClose;
33 + expect(closingTerminalIds(thread)).toEqual([]);
34 +});
apps/web/src/components/terminal/closingTerminals.ts new
+29
@@ -0,0 +1,29 @@
1 +import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2 +import type { ScopedThreadRef } from "@t3tools/contracts";
3 +
4 +// Lifecycle commands run in order, so a queued close ends whichever shell holds its ID by then.
5 +const closingIdsByThread = new Map<string, Map<string, number>>();
6 +
7 +/** IDs a new terminal must not take until their pending closes settle. */
8 +export function closingTerminalIds(threadRef: ScopedThreadRef): ReadonlyArray<string> {
9 + return [...(closingIdsByThread.get(scopedThreadKey(threadRef))?.keys() ?? [])];
10 +}
11 +
12 +export async function holdTerminalIdWhileClosing<A>(
13 + threadRef: ScopedThreadRef,
14 + terminalId: string,
15 + close: () => Promise<A>,
16 +): Promise<A> {
17 + const key = scopedThreadKey(threadRef);
18 + const closing = closingIdsByThread.get(key) ?? new Map<string, number>();
19 + closingIdsByThread.set(key, closing);
20 + closing.set(terminalId, (closing.get(terminalId) ?? 0) + 1);
21 + try {
22 + return await close();
23 + } finally {
24 + const remaining = (closing.get(terminalId) ?? 1) - 1;
25 + if (remaining > 0) closing.set(terminalId, remaining);
26 + else closing.delete(terminalId);
27 + if (closing.size === 0) closingIdsByThread.delete(key);
28 + }
29 +}
apps/web/src/components/terminal/useThreadTerminalActions.ts
+4 -2
@@ -17,6 +17,7 @@ import { terminalEnvironment } from "../../state/terminal";
17 import { useKnownTerminalSessions } from "../../state/terminalSessions";
18 import { useAtomCommand } from "../../state/use-atom-command";
19 import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../../terminalUiStateStore";
20 +import { closingTerminalIds, holdTerminalIdWhileClosing } from "./closingTerminals";
21
22 /** Where a new terminal starts. Omitted fields fall back to the thread's project and worktree. */
23 export interface TerminalLaunchLocation {
@@ -62,6 +63,7 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
63 ...panelSurfaces.flatMap((surface) =>
64 surface.kind === "terminal" ? surface.terminalIds : [],
65 ),
66 + ...(threadRef ? closingTerminalIds(threadRef) : []),
67 ]);
68 const canReuse =
69 knownSessions !== null &&
@@ -119,7 +121,7 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
121 if (!target || !readEnvironmentScope(target.environmentId, AuthTerminalOperateScope)) return;
122 const environmentId = target.environmentId;
123 const threadId = target.threadId;
122 - void (async () => {
124 + void holdTerminalIdWhileClosing(target, terminalId, async () => {
125 const closeResult = await closeTerminalCommand({
126 environmentId,
127 input: { threadId, terminalId, deleteHistory: true },
@@ -131,7 +133,7 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
133 ) {
134 await writeTerminal({ environmentId, input: { threadId, terminalId, data: "exit\n" } });
135 }
134 - })();
136 + });
137 };
138
139 const writeToTerminal = (terminalId: string, data: string) => {
apps/web/src/lib/projectScriptTerminal.test.ts
+15 -2
@@ -36,9 +36,22 @@ describe("findReusableProjectScriptTerminal", () => {
36 runningTerminalIds: ["term-1"],
37 expected: null,
38 },
39 - ])("$name", ({ panelTerminalIds, expected, ...input }) => {
39 + {
40 + name: "skips an idle terminal whose close is still pending",
41 + drawerTerminalIds: ["term-1"],
42 + activeTerminalId: "term-1",
43 + panelTerminalIds: [],
44 + runningTerminalIds: [],
45 + closingTerminalIds: ["term-1"],
46 + expected: null,
47 + },
48 + ])("$name", ({ panelTerminalIds, closingTerminalIds = [], expected, ...input }) => {
49 expect(
41 - findReusableProjectScriptTerminal({ ...input, panelTerminalIds: new Set(panelTerminalIds) }),
50 + findReusableProjectScriptTerminal({
51 + ...input,
52 + panelTerminalIds: new Set(panelTerminalIds),
53 + closingTerminalIds,
54 + }),
55 ).toBe(expected);
56 });
57 });
apps/web/src/lib/projectScriptTerminal.ts
+5 -1
@@ -8,10 +8,14 @@ export function findReusableProjectScriptTerminal(input: {
8 readonly activeTerminalId: string;
9 readonly panelTerminalIds: ReadonlySet<string>;
10 readonly runningTerminalIds: ReadonlyArray<string>;
11 + /** A pending close would end the script's shell once the reopen runs. */
12 + readonly closingTerminalIds: ReadonlyArray<string>;
13 }): string | null {
14 const idleDrawerTerminalIds = input.drawerTerminalIds.filter(
15 (terminalId) =>
14 - !input.panelTerminalIds.has(terminalId) && !input.runningTerminalIds.includes(terminalId),
16 + !input.panelTerminalIds.has(terminalId) &&
17 + !input.runningTerminalIds.includes(terminalId) &&
18 + !input.closingTerminalIds.includes(terminalId),
19 );
20 if (idleDrawerTerminalIds.includes(input.activeTerminalId)) return input.activeTerminalId;
21 return idleDrawerTerminalIds[0] ?? null;