The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 10:45 UTC
fix(web): keep terminal close confirmations on their original thread (#24020)
Co-authored-by: GPT-6.1 Sol <noreply@openai.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com>
Victor Vogel committed
Oct 30, 2026 at 16:01 UTC
8f79233ccb0509f44ac54cb13d011676c9a6451c
7 files changed
+290
-27
apps/web/src/components/PersistentThreadTerminals.tsx
+1
-1
@@ -294,7 +294,7 @@ export interface PersistentThreadTerminalPanelProps {
294
onSplitTerminalVertical: () => void;
295
onNewTerminal: () => void;
296
onActiveTerminalChange: (terminalId: string) => void;
297
- onCloseTerminal: (terminalId: string) => void;
297
+ onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
298
splitShortcutLabel?: string | undefined;
299
splitVerticalShortcutLabel?: string | undefined;
300
newShortcutLabel?: string | undefined;
apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
new
+129
@@ -0,0 +1,129 @@
1
+import { EMPTY_TERMINAL_SESSION_STATE } from "@t3tools/client-runtime/state/terminal";
2
+import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
3
+import { expect, it, vi } from "vite-plus/test";
4
+import { act, fakeTimers, render } from "../../test/render";
5
+import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
6
+
7
+const fixture = vi.hoisted(() => ({
8
+ statusByThreadId: new Map<string, "running" | "exited">(),
9
+ pendingSurfaces: [] as Array<() => void>,
10
+}));
11
+
12
+// Every surface method is a no-op; `then` stays undefined so awaiting the surface resolves to it.
13
+const fakeSurface: object = new Proxy(
14
+ { input: document.createElement("textarea") },
15
+ {
16
+ get: (target, key) =>
17
+ key === "then" ? undefined : key in target ? Reflect.get(target, key) : () => undefined,
18
+ },
19
+);
20
+vi.mock("~/terminal/ghostty/surface", () => ({
21
+ GhosttyTerminalSurface: {
22
+ create: () =>
23
+ new Promise((resolve) => {
24
+ fixture.pendingSurfaces.push(() => resolve(fakeSurface));
25
+ }),
26
+ },
27
+}));
28
+vi.mock("../state/terminalSessions", async () => {
29
+ const Atom = await import("effect/reactivity/Atom");
30
+ const sessions = Atom.family((_environmentId: EnvironmentId) =>
31
+ Atom.family((threadId: ThreadId) =>
32
+ Atom.make({
33
+ ...EMPTY_TERMINAL_SESSION_STATE,
34
+ status: fixture.statusByThreadId.get(threadId) ?? "closed",
35
+ version: 1,
36
+ }),
37
+ ),
38
+ );
39
+ return {
40
+ attachedTerminalSessionAtom: (environmentId: EnvironmentId, terminal: { threadId: ThreadId }) =>
41
+ sessions(environmentId)(terminal.threadId),
42
+ };
43
+});
44
+vi.mock("../state/session", () => ({
45
+ useEnvironmentScope: () => true,
46
+ readEnvironmentScope: () => true,
47
+}));
48
+vi.mock("../state/use-atom-command", () => ({
49
+ useAtomCommand: () => async () => ({ _tag: "Success" }),
50
+}));
51
+// The commands are replaced above; importing their runtime would connect a client.
52
+vi.mock("../state/server", async () => {
53
+ const Atom = await import("effect/reactivity/Atom");
54
+ const config = Atom.make(null);
55
+ return { serverEnvironment: { configValueAtom: () => config } };
56
+});
57
+vi.mock("../state/terminal", () => ({ terminalEnvironment: { write: {}, resize: {} } }));
58
+vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } }));
59
+vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => () => {} }));
60
+vi.mock("./preview/openTerminalLinkInPreview", () => ({ openTerminalLinkInPreview: () => {} }));
61
+vi.mock("~/localApi", () => ({ readLocalApi: () => null }));
62
+vi.mock("../hooks/useSettings", async () => {
63
+ const { DEFAULT_CLIENT_SETTINGS } = await import("@t3tools/contracts/settings");
64
+ return {
65
+ useClientSettings: <T,>(select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => T) =>
66
+ select(DEFAULT_CLIENT_SETTINGS),
67
+ };
68
+});
69
+
70
+function Drawer(props: {
71
+ threadRef: ScopedThreadRef;
72
+ onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
73
+}) {
74
+ return (
75
+ <ThreadTerminalDrawer
76
+ threadRef={props.threadRef}
77
+ threadId={props.threadRef.threadId}
78
+ cwd="/repo"
79
+ height={240}
80
+ terminalIds={["term-1"]}
81
+ activeTerminalId="term-1"
82
+ terminalGroups={[{ id: "group-1", terminalIds: ["term-1"] }]}
83
+ activeTerminalGroupId="group-1"
84
+ onSplitTerminal={() => {}}
85
+ onSplitTerminalVertical={() => {}}
86
+ onNewTerminal={() => {}}
87
+ onActiveTerminalChange={() => {}}
88
+ onCloseTerminal={props.onCloseTerminal}
89
+ onHeightChange={() => {}}
90
+ onAddTerminalContext={() => {}}
91
+ keybindings={[]}
92
+ />
93
+ );
94
+}
95
+
96
+function setup() {
97
+ const original: ScopedThreadRef = {
98
+ environmentId: EnvironmentId.make("environment-a"),
99
+ threadId: ThreadId.make("thread-a"),
100
+ };
101
+ const other: ScopedThreadRef = {
102
+ environmentId: EnvironmentId.make("environment-b"),
103
+ threadId: ThreadId.make("thread-b"),
104
+ };
105
+ fixture.statusByThreadId = new Map([
106
+ [original.threadId, "exited"],
107
+ [other.threadId, "running"],
108
+ ]);
109
+ fixture.pendingSurfaces = [];
110
+ return { original, other };
111
+}
112
+
113
+it("closes an exited terminal on its own thread after navigating to one reusing its ID", async () => {
114
+ const { original, other } = setup();
115
+ const onCloseTerminal = vi.fn();
116
+ await using screen = await render(
117
+ <Drawer threadRef={original} onCloseTerminal={onCloseTerminal} />,
118
+ );
119
+ using _timers = fakeTimers();
120
+ // The exit is seen once the surface loads, and its close waits for the next task.
121
+ await act(async () => {
122
+ fixture.pendingSurfaces.shift()?.();
123
+ });
124
+ await screen.rerender(<Drawer threadRef={other} onCloseTerminal={onCloseTerminal} />);
125
+ await act(async () => {
126
+ vi.runOnlyPendingTimers();
127
+ });
128
+ expect(onCloseTerminal.mock.calls).toEqual([["term-1", original]]);
129
+});
apps/web/src/components/ThreadTerminalDrawer.tsx
+4
-4
@@ -1178,7 +1178,7 @@ interface ThreadTerminalDrawerProps {
1178
newShortcutLabel?: string | undefined;
1179
closeShortcutLabel?: string | undefined;
1180
onActiveTerminalChange: (terminalId: string) => void;
1181
- onCloseTerminal: (terminalId: string) => void;
1181
+ onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
1182
onHeightChange: (height: number) => void;
1183
onAddTerminalContext: (selection: TerminalContextSelection) => void;
1184
keybindings: ResolvedKeybindingsConfig;
@@ -1251,7 +1251,7 @@ function TerminalSplitPanes({
1251
terminalLabelById: ReadonlyMap<string, string>;
1252
resolveLaunchLocation: (terminalId: string) => TerminalLaunchLocation;
1253
onActiveTerminalChange: (terminalId: string) => void;
1254
- onCloseTerminal: (terminalId: string) => void;
1254
+ onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
1255
advancedTypography: boolean;
1256
threadRef: ScopedThreadRef;
1257
threadId: ThreadId;
@@ -1302,7 +1302,7 @@ function TerminalSplitPanes({
1302
{...(terminalLaunchLocation.runtimeEnv
1303
? { runtimeEnv: terminalLaunchLocation.runtimeEnv }
1304
: {})}
1305
- onSessionExited={() => onCloseTerminal(terminalId)}
1305
+ onSessionExited={() => onCloseTerminal(terminalId, threadRef)}
1306
onAddTerminalContext={onAddTerminalContext}
1307
visible={visible}
1308
keybindings={keybindings}
@@ -1626,7 +1626,7 @@ export default function ThreadTerminalDrawer({
1626
const label = terminalLabelById.get(terminalId) ?? getTerminalLabel(terminalId);
1627
void confirmTerminalClose([label]).then((confirmed) => {
1628
if (confirmed && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)) {
1629
- onCloseTerminal(terminalId);
1629
+ onCloseTerminal(terminalId, threadRef);
1630
}
1631
});
1632
};
apps/web/src/components/chat/useChatTerminalActions.ts
+17
-17
@@ -23,7 +23,11 @@ import {
23
squashAtomCommandFailure,
24
} from "@t3tools/client-runtime/state/runtime";
25
import { MAX_TERMINALS_PER_GROUP } from "../../types";
26
-import { type RightPanelSurface, useRightPanelStore } from "../../rightPanelStore";
26
+import {
27
+ selectThreadRightPanelState,
28
+ type RightPanelSurface,
29
+ useRightPanelStore,
30
+} from "../../rightPanelStore";
31
import { isPreviewSupportedInRuntime } from "../../previewStateStore";
32
import { openUrlInPreview } from "../../browser/openFileInPreview";
33
import { resolveDiscoveredServerUrl } from "../../browser/browserTargetResolver";
@@ -190,7 +194,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
194
const createNewTerminalStable = useStableCallback(createNewTerminal);
195
const closeTerminal = (terminalId: string) => {
196
if (!hasTerminalWriteAccess() || !activeThreadRef) return;
193
- terminalActions.closeTerminalSession(terminalId);
197
+ terminalActions.closeTerminalSession(terminalId, activeThreadRef);
198
storeCloseTerminal(activeThreadRef, terminalId);
199
focusActiveDrawerTerminal(activeThreadRef);
200
};
@@ -360,21 +364,17 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
364
focusTerminal(activeThreadRef, terminalId);
365
};
366
const activatePanelTerminalStable = useStableCallback(activatePanelTerminal);
363
- const closePanelTerminal = (terminalId: string) => {
364
- if (
365
- !hasTerminalWriteAccess() ||
366
- !activeThreadRef ||
367
- activeRightPanelSurface?.kind !== "terminal"
368
- )
369
- return;
370
- terminalActions.closeTerminalSession(terminalId);
371
- storeCloseTerminal(activeThreadRef, terminalId);
372
- useRightPanelStore
373
- .getState()
374
- .closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
375
- // Closing a surface's last terminal falls back to a neighbouring surface,
376
- // which can be another terminal surface.
377
- focusActivePanelTerminal(activeThreadRef);
367
+ const closePanelTerminal = (terminalId: string, target = activeThreadRef) => {
368
+ if (!target || !readEnvironmentScope(target.environmentId, AuthTerminalOperateScope)) return;
369
+ const store = useRightPanelStore.getState();
370
+ const surface = selectThreadRightPanelState(store.byThreadKey, target).surfaces.find(
371
+ (entry) => entry.kind === "terminal" && entry.terminalIds.includes(terminalId),
372
+ );
373
+ if (!surface) return;
374
+ terminalActions.closeTerminalSession(terminalId, target);
375
+ storeCloseTerminal(target, terminalId);
376
+ store.closeTerminal(target, surface.id, terminalId);
377
+ focusActivePanelTerminal(target);
378
};
379
const closePanelTerminalStable = useStableCallback(closePanelTerminal);
380
const requestCloseTerminal = (terminalId: string) => {
apps/web/src/components/terminal/useThreadTerminalActions.ts
+4
-4
@@ -113,10 +113,10 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
113
};
114
115
/** Ends a session and deletes its history. A failed close falls back to typing `exit`. */
116
- const closeTerminalSession = (terminalId: string) => {
117
- if (!threadRef || !canWrite()) return;
118
- const environmentId = threadRef.environmentId;
119
- const threadId = threadRef.threadId;
116
+ const closeTerminalSession = (terminalId: string, target = threadRef) => {
117
+ if (!target || !readEnvironmentScope(target.environmentId, AuthTerminalOperateScope)) return;
118
+ const environmentId = target.environmentId;
119
+ const threadId = target.threadId;
120
void (async () => {
121
const closeResult = await closeTerminalCommand({
122
environmentId,
apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx
new
+134
@@ -0,0 +1,134 @@
1
+import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
2
+import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3
+import { expect, it, vi } from "vite-plus/test";
4
+import { act, render } from "../../test/render";
5
+import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";
6
+import { useTerminalUiStateStore } from "../terminalUiStateStore";
7
+import { useRightPanelSurfaceClose } from "./useRightPanelSurfaceClose";
8
+
9
+const fixture = vi.hoisted(() => ({
10
+ confirm: (_labels: readonly string[]): Promise<boolean> => Promise.resolve(false),
11
+ allowed: new Set<string>(),
12
+ sessions: new Map<string, string>(),
13
+ failClose: false,
14
+}));
15
+vi.mock("../lib/terminalCloseConfirm", () => ({
16
+ confirmTerminalClose: (labels: readonly string[]) => fixture.confirm(labels),
17
+}));
18
+vi.mock("../components/ChatView.logic", () => ({
19
+ agentControlledBrowserCloseConfirmation: () => null,
20
+}));
21
+vi.mock("../previewStateStore", () => ({
22
+ useThreadPreviewState: () => ({ sessions: {}, desktopByTabId: {} }),
23
+ setActivePreviewTab: () => {},
24
+ beginPreviewSessionClose: () => {},
25
+ cancelPreviewSessionClose: () => {},
26
+}));
27
+vi.mock("../state/session", () => ({
28
+ useEnvironmentScope: (id: string) => fixture.allowed.has(id),
29
+ readEnvironmentScope: (id: string) => fixture.allowed.has(id),
30
+}));
31
+vi.mock("../state/entities", () => ({
32
+ useQuietThreadShell: () => null,
33
+ useProject: () => null,
34
+}));
35
+vi.mock("../state/terminalSessions", () => ({ useKnownTerminalSessions: () => null }));
36
+vi.mock("../composerDraftStore", async () => {
37
+ const Schema = await import("effect/Schema");
38
+ return {
39
+ useComposerDraftStore: () => null,
40
+ DraftId: Schema.String.pipe(Schema.brand("DraftId")),
41
+ };
42
+});
43
+vi.mock("../state/use-atom-command", () => ({
44
+ useAtomCommand:
45
+ (_command: unknown, label: string) =>
46
+ async (request: {
47
+ environmentId: string;
48
+ input: { threadId: string; terminalId: string; data?: string };
49
+ }) => {
50
+ const key = `${request.environmentId}/${request.input.threadId}/${request.input.terminalId}`;
51
+ if (label === "terminal close" && fixture.failClose) return { _tag: "Failure" };
52
+ if (label === "terminal close" || label === "terminal write") fixture.sessions.delete(key);
53
+ return { _tag: "Success" };
54
+ },
55
+}));
56
+// The commands are replaced above; importing their runtime would connect a client.
57
+vi.mock("../state/terminal", () => ({ terminalEnvironment: { open: {}, close: {}, write: {} } }));
58
+vi.mock("../state/preview", () => ({ previewEnvironment: { close: {} } }));
59
+vi.mock("@t3tools/client-runtime/state/runtime", () => ({
60
+ isAtomCommandInterrupted: () => false,
61
+}));
62
+
63
+function setup() {
64
+ fixture.allowed = new Set(["environment-a", "environment-b"]);
65
+ fixture.sessions = new Map();
66
+ fixture.failClose = false;
67
+ useRightPanelStore.setState({ byThreadKey: {} });
68
+ useTerminalUiStateStore.setState({ terminalUiStateByThreadKey: {} });
69
+ const original: ScopedThreadRef = {
70
+ environmentId: EnvironmentId.make("environment-a"),
71
+ threadId: ThreadId.make("thread-a"),
72
+ };
73
+ const other: ScopedThreadRef = {
74
+ environmentId: EnvironmentId.make("environment-b"),
75
+ threadId: ThreadId.make("thread-b"),
76
+ };
77
+ for (const ref of [original, other]) {
78
+ fixture.sessions.set(`${ref.environmentId}/${ref.threadId}/term-1`, "history to preserve");
79
+ useRightPanelStore.getState().openTerminal(ref, "term-1");
80
+ }
81
+ const surface = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, original)
82
+ .surfaces[0]!;
83
+ let resolve!: (confirmed: boolean) => void;
84
+ const confirmation = new Promise<boolean>((done) => {
85
+ resolve = done;
86
+ });
87
+ fixture.confirm = () => confirmation;
88
+ function Harness({ threadRef }: { threadRef: ScopedThreadRef }) {
89
+ const { closeSurface } = useRightPanelSurfaceClose({
90
+ threadRef,
91
+ terminalLabelsById: new Map(),
92
+ });
93
+ return <button onClick={() => closeSurface(surface)}>Close original terminal</button>;
94
+ }
95
+ return { original, other, Harness, resolve };
96
+}
97
+
98
+it.each([false, true])(
99
+ "keeps a pending close on its original environment and thread, fallback=%s",
100
+ async (failClose) => {
101
+ const { original, other, Harness, resolve } = setup();
102
+ fixture.failClose = failClose;
103
+ await using screen = await render(<Harness threadRef={original} />);
104
+ await screen.getByRole("button").click();
105
+ await screen.rerender(<Harness threadRef={other} />);
106
+ await act(async () => {
107
+ resolve(true);
108
+ });
109
+ expect([...fixture.sessions]).toEqual([
110
+ ["environment-b/thread-b/term-1", "history to preserve"],
111
+ ]);
112
+ const panels = useRightPanelStore.getState().byThreadKey;
113
+ expect(selectThreadRightPanelState(panels, original).surfaces).toEqual([]);
114
+ expect(selectThreadRightPanelState(panels, other).surfaces).toHaveLength(1);
115
+ },
116
+);
117
+
118
+it.each(["cancel", "revoked"])(
119
+ "leaves both sessions intact when confirmation is %s",
120
+ async (outcome) => {
121
+ const { original, other, Harness, resolve } = setup();
122
+ await using screen = await render(<Harness threadRef={original} />);
123
+ await screen.getByRole("button").click();
124
+ await screen.rerender(<Harness threadRef={other} />);
125
+ if (outcome === "revoked") fixture.allowed.delete(original.environmentId);
126
+ await act(async () => {
127
+ resolve(outcome !== "cancel");
128
+ });
129
+ expect(fixture.sessions.size).toBe(2);
130
+ expect(
131
+ useRightPanelStore.getState().byThreadKey[scopedThreadKey(other)]?.surfaces,
132
+ ).toHaveLength(1);
133
+ },
134
+);
apps/web/src/hooks/useRightPanelSurfaceClose.ts
+1
-1
@@ -57,7 +57,7 @@ export function useRightPanelSurfaceClose(input: {
57
) {
58
for (const terminalId of surface.terminalIds) {
59
storeCloseTerminal(ref, terminalId);
60
- terminalActions.closeTerminalSession(terminalId);
60
+ terminalActions.closeTerminalSession(terminalId, ref);
61
}
62
}
63
};