Skip to content
TypeScript

fix(web): keep terminal close confirmations on their original thread (#24020)

Victor Vogel8f79233ccb05
diff --git a/apps/web/src/components/PersistentThreadTerminals.tsx b/apps/web/src/components/PersistentThreadTerminals.tsx
index 5e2fe0dbe91..a387349b4c0 100644
--- a/apps/web/src/components/PersistentThreadTerminals.tsx
+++ b/apps/web/src/components/PersistentThreadTerminals.tsx
@@ -294,7 +294,7 @@ export interface PersistentThreadTerminalPanelProps {
onSplitTerminalVertical: () => void;
onNewTerminal: () => void;
onActiveTerminalChange: (terminalId: string) => void;
- onCloseTerminal: (terminalId: string) => void;
+ onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
splitShortcutLabel?: string | undefined;
splitVerticalShortcutLabel?: string | undefined;
newShortcutLabel?: string | undefined;
diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
new file mode 100644
index 00000000000..a99434f6659
--- /dev/null
+++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
@@ -0,0 +1,129 @@
+import { EMPTY_TERMINAL_SESSION_STATE } from "@t3tools/client-runtime/state/terminal";
+import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
+import { expect, it, vi } from "vite-plus/test";
+import { act, fakeTimers, render } from "../../test/render";
+import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
+
+const fixture = vi.hoisted(() => ({
+ statusByThreadId: new Map<string, "running" | "exited">(),
+ pendingSurfaces: [] as Array<() => void>,
+}));
+
+// Every surface method is a no-op; `then` stays undefined so awaiting the surface resolves to it.
+const fakeSurface: object = new Proxy(
+ { input: document.createElement("textarea") },
+ {
+ get: (target, key) =>
+ key === "then" ? undefined : key in target ? Reflect.get(target, key) : () => undefined,
+ },
+);
+vi.mock("~/terminal/ghostty/surface", () => ({
+ GhosttyTerminalSurface: {
+ create: () =>
+ new Promise((resolve) => {
+ fixture.pendingSurfaces.push(() => resolve(fakeSurface));
+ }),
+ },
+}));
+vi.mock("../state/terminalSessions", async () => {
+ const Atom = await import("effect/reactivity/Atom");
+ const sessions = Atom.family((_environmentId: EnvironmentId) =>
+ Atom.family((threadId: ThreadId) =>
+ Atom.make({
+ ...EMPTY_TERMINAL_SESSION_STATE,
+ status: fixture.statusByThreadId.get(threadId) ?? "closed",
+ version: 1,
+ }),
+ ),
+ );
+ return {
+ attachedTerminalSessionAtom: (environmentId: EnvironmentId, terminal: { threadId: ThreadId }) =>
+ sessions(environmentId)(terminal.threadId),
+ };
+});
+vi.mock("../state/session", () => ({
+ useEnvironmentScope: () => true,
+ readEnvironmentScope: () => true,
+}));
+vi.mock("../state/use-atom-command", () => ({
+ useAtomCommand: () => async () => ({ _tag: "Success" }),
+}));
+// The commands are replaced above; importing their runtime would connect a client.
+vi.mock("../state/server", async () => {
+ const Atom = await import("effect/reactivity/Atom");
+ const config = Atom.make(null);
+ return { serverEnvironment: { configValueAtom: () => config } };
+});
+vi.mock("../state/terminal", () => ({ terminalEnvironment: { write: {}, resize: {} } }));
+vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } }));
+vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => () => {} }));
+vi.mock("./preview/openTerminalLinkInPreview", () => ({ openTerminalLinkInPreview: () => {} }));
+vi.mock("~/localApi", () => ({ readLocalApi: () => null }));
+vi.mock("../hooks/useSettings", async () => {
+ const { DEFAULT_CLIENT_SETTINGS } = await import("@t3tools/contracts/settings");
+ return {
+ useClientSettings: <T,>(select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => T) =>
+ select(DEFAULT_CLIENT_SETTINGS),
+ };
+});
+
+function Drawer(props: {
+ threadRef: ScopedThreadRef;
+ onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
+}) {
+ return (
+ <ThreadTerminalDrawer
+ threadRef={props.threadRef}
+ threadId={props.threadRef.threadId}
+ cwd="/repo"
+ height={240}
+ terminalIds={["term-1"]}
+ activeTerminalId="term-1"
+ terminalGroups={[{ id: "group-1", terminalIds: ["term-1"] }]}
+ activeTerminalGroupId="group-1"
+ onSplitTerminal={() => {}}
+ onSplitTerminalVertical={() => {}}
+ onNewTerminal={() => {}}
+ onActiveTerminalChange={() => {}}
+ onCloseTerminal={props.onCloseTerminal}
+ onHeightChange={() => {}}
+ onAddTerminalContext={() => {}}
+ keybindings={[]}
+ />
+ );
+}
+
+function setup() {
+ const original: ScopedThreadRef = {
+ environmentId: EnvironmentId.make("environment-a"),
+ threadId: ThreadId.make("thread-a"),
+ };
+ const other: ScopedThreadRef = {
+ environmentId: EnvironmentId.make("environment-b"),
+ threadId: ThreadId.make("thread-b"),
+ };
+ fixture.statusByThreadId = new Map([
+ [original.threadId, "exited"],
+ [other.threadId, "running"],
+ ]);
+ fixture.pendingSurfaces = [];
+ return { original, other };
+}
+
+it("closes an exited terminal on its own thread after navigating to one reusing its ID", async () => {
+ const { original, other } = setup();
+ const onCloseTerminal = vi.fn();
+ await using screen = await render(
+ <Drawer threadRef={original} onCloseTerminal={onCloseTerminal} />,
+ );
+ using _timers = fakeTimers();
+ // The exit is seen once the surface loads, and its close waits for the next task.
+ await act(async () => {
+ fixture.pendingSurfaces.shift()?.();
+ });
+ await screen.rerender(<Drawer threadRef={other} onCloseTerminal={onCloseTerminal} />);
+ await act(async () => {
+ vi.runOnlyPendingTimers();
+ });
+ expect(onCloseTerminal.mock.calls).toEqual([["term-1", original]]);
+});
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index 295c553827f..e8a2967a319 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -1178,7 +1178,7 @@ interface ThreadTerminalDrawerProps {
newShortcutLabel?: string | undefined;
closeShortcutLabel?: string | undefined;
onActiveTerminalChange: (terminalId: string) => void;
- onCloseTerminal: (terminalId: string) => void;
+ onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
onHeightChange: (height: number) => void;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
keybindings: ResolvedKeybindingsConfig;
@@ -1251,7 +1251,7 @@ function TerminalSplitPanes({
terminalLabelById: ReadonlyMap<string, string>;
resolveLaunchLocation: (terminalId: string) => TerminalLaunchLocation;
onActiveTerminalChange: (terminalId: string) => void;
- onCloseTerminal: (terminalId: string) => void;
+ onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
advancedTypography: boolean;
threadRef: ScopedThreadRef;
threadId: ThreadId;
@@ -1302,7 +1302,7 @@ function TerminalSplitPanes({
{...(terminalLaunchLocation.runtimeEnv
? { runtimeEnv: terminalLaunchLocation.runtimeEnv }
: {})}
- onSessionExited={() => onCloseTerminal(terminalId)}
+ onSessionExited={() => onCloseTerminal(terminalId, threadRef)}
onAddTerminalContext={onAddTerminalContext}
visible={visible}
keybindings={keybindings}
@@ -1626,7 +1626,7 @@ export default function ThreadTerminalDrawer({
const label = terminalLabelById.get(terminalId) ?? getTerminalLabel(terminalId);
void confirmTerminalClose([label]).then((confirmed) => {
if (confirmed && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)) {
- onCloseTerminal(terminalId);
+ onCloseTerminal(terminalId, threadRef);
}
});
};
diff --git a/apps/web/src/components/chat/useChatTerminalActions.ts b/apps/web/src/components/chat/useChatTerminalActions.ts
index 462ea18e0f9..55c2a8380da 100644
--- a/apps/web/src/components/chat/useChatTerminalActions.ts
+++ b/apps/web/src/components/chat/useChatTerminalActions.ts
@@ -23,7 +23,11 @@ import {
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { MAX_TERMINALS_PER_GROUP } from "../../types";
-import { type RightPanelSurface, useRightPanelStore } from "../../rightPanelStore";
+import {
+ selectThreadRightPanelState,
+ type RightPanelSurface,
+ useRightPanelStore,
+} from "../../rightPanelStore";
import { isPreviewSupportedInRuntime } from "../../previewStateStore";
import { openUrlInPreview } from "../../browser/openFileInPreview";
import { resolveDiscoveredServerUrl } from "../../browser/browserTargetResolver";
@@ -190,7 +194,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
const createNewTerminalStable = useStableCallback(createNewTerminal);
const closeTerminal = (terminalId: string) => {
if (!hasTerminalWriteAccess() || !activeThreadRef) return;
- terminalActions.closeTerminalSession(terminalId);
+ terminalActions.closeTerminalSession(terminalId, activeThreadRef);
storeCloseTerminal(activeThreadRef, terminalId);
focusActiveDrawerTerminal(activeThreadRef);
};
@@ -360,21 +364,17 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
focusTerminal(activeThreadRef, terminalId);
};
const activatePanelTerminalStable = useStableCallback(activatePanelTerminal);
- const closePanelTerminal = (terminalId: string) => {
- if (
- !hasTerminalWriteAccess() ||
- !activeThreadRef ||
- activeRightPanelSurface?.kind !== "terminal"
- )
- return;
- terminalActions.closeTerminalSession(terminalId);
- storeCloseTerminal(activeThreadRef, terminalId);
- useRightPanelStore
- .getState()
- .closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
- // Closing a surface's last terminal falls back to a neighbouring surface,
- // which can be another terminal surface.
- focusActivePanelTerminal(activeThreadRef);
+ const closePanelTerminal = (terminalId: string, target = activeThreadRef) => {
+ if (!target || !readEnvironmentScope(target.environmentId, AuthTerminalOperateScope)) return;
+ const store = useRightPanelStore.getState();
+ const surface = selectThreadRightPanelState(store.byThreadKey, target).surfaces.find(
+ (entry) => entry.kind === "terminal" && entry.terminalIds.includes(terminalId),
+ );
+ if (!surface) return;
+ terminalActions.closeTerminalSession(terminalId, target);
+ storeCloseTerminal(target, terminalId);
+ store.closeTerminal(target, surface.id, terminalId);
+ focusActivePanelTerminal(target);
};
const closePanelTerminalStable = useStableCallback(closePanelTerminal);
const requestCloseTerminal = (terminalId: string) => {
diff --git a/apps/web/src/components/terminal/useThreadTerminalActions.ts b/apps/web/src/components/terminal/useThreadTerminalActions.ts
index bec8d828ea6..6fb18cc6208 100644
--- a/apps/web/src/components/terminal/useThreadTerminalActions.ts
+++ b/apps/web/src/components/terminal/useThreadTerminalActions.ts
@@ -113,10 +113,10 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
};
/** Ends a session and deletes its history. A failed close falls back to typing `exit`. */
- const closeTerminalSession = (terminalId: string) => {
- if (!threadRef || !canWrite()) return;
- const environmentId = threadRef.environmentId;
- const threadId = threadRef.threadId;
+ const closeTerminalSession = (terminalId: string, target = threadRef) => {
+ if (!target || !readEnvironmentScope(target.environmentId, AuthTerminalOperateScope)) return;
+ const environmentId = target.environmentId;
+ const threadId = target.threadId;
void (async () => {
const closeResult = await closeTerminalCommand({
environmentId,
diff --git a/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx b/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx
new file mode 100644
index 00000000000..d394c67c9df
--- /dev/null
+++ b/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx
@@ -0,0 +1,134 @@
+import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
+import { scopedThreadKey } from "@t3tools/client-runtime/environment";
+import { expect, it, vi } from "vite-plus/test";
+import { act, render } from "../../test/render";
+import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";
+import { useTerminalUiStateStore } from "../terminalUiStateStore";
+import { useRightPanelSurfaceClose } from "./useRightPanelSurfaceClose";
+
+const fixture = vi.hoisted(() => ({
+ confirm: (_labels: readonly string[]): Promise<boolean> => Promise.resolve(false),
+ allowed: new Set<string>(),
+ sessions: new Map<string, string>(),
+ failClose: false,
+}));
+vi.mock("../lib/terminalCloseConfirm", () => ({
+ confirmTerminalClose: (labels: readonly string[]) => fixture.confirm(labels),
+}));
+vi.mock("../components/ChatView.logic", () => ({
+ agentControlledBrowserCloseConfirmation: () => null,
+}));
+vi.mock("../previewStateStore", () => ({
+ useThreadPreviewState: () => ({ sessions: {}, desktopByTabId: {} }),
+ setActivePreviewTab: () => {},
+ beginPreviewSessionClose: () => {},
+ cancelPreviewSessionClose: () => {},
+}));
+vi.mock("../state/session", () => ({
+ useEnvironmentScope: (id: string) => fixture.allowed.has(id),
+ readEnvironmentScope: (id: string) => fixture.allowed.has(id),
+}));
+vi.mock("../state/entities", () => ({
+ useQuietThreadShell: () => null,
+ useProject: () => null,
+}));
+vi.mock("../state/terminalSessions", () => ({ useKnownTerminalSessions: () => null }));
+vi.mock("../composerDraftStore", async () => {
+ const Schema = await import("effect/Schema");
+ return {
+ useComposerDraftStore: () => null,
+ DraftId: Schema.String.pipe(Schema.brand("DraftId")),
+ };
+});
+vi.mock("../state/use-atom-command", () => ({
+ useAtomCommand:
+ (_command: unknown, label: string) =>
+ async (request: {
+ environmentId: string;
+ input: { threadId: string; terminalId: string; data?: string };
+ }) => {
+ const key = `${request.environmentId}/${request.input.threadId}/${request.input.terminalId}`;
+ if (label === "terminal close" && fixture.failClose) return { _tag: "Failure" };
+ if (label === "terminal close" || label === "terminal write") fixture.sessions.delete(key);
+ return { _tag: "Success" };
+ },
+}));
+// The commands are replaced above; importing their runtime would connect a client.
+vi.mock("../state/terminal", () => ({ terminalEnvironment: { open: {}, close: {}, write: {} } }));
+vi.mock("../state/preview", () => ({ previewEnvironment: { close: {} } }));
+vi.mock("@t3tools/client-runtime/state/runtime", () => ({
+ isAtomCommandInterrupted: () => false,
+}));
+
+function setup() {
+ fixture.allowed = new Set(["environment-a", "environment-b"]);
+ fixture.sessions = new Map();
+ fixture.failClose = false;
+ useRightPanelStore.setState({ byThreadKey: {} });
+ useTerminalUiStateStore.setState({ terminalUiStateByThreadKey: {} });
+ const original: ScopedThreadRef = {
+ environmentId: EnvironmentId.make("environment-a"),
+ threadId: ThreadId.make("thread-a"),
+ };
+ const other: ScopedThreadRef = {
+ environmentId: EnvironmentId.make("environment-b"),
+ threadId: ThreadId.make("thread-b"),
+ };
+ for (const ref of [original, other]) {
+ fixture.sessions.set(`${ref.environmentId}/${ref.threadId}/term-1`, "history to preserve");
+ useRightPanelStore.getState().openTerminal(ref, "term-1");
+ }
+ const surface = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, original)
+ .surfaces[0]!;
+ let resolve!: (confirmed: boolean) => void;
+ const confirmation = new Promise<boolean>((done) => {
+ resolve = done;
+ });
+ fixture.confirm = () => confirmation;
+ function Harness({ threadRef }: { threadRef: ScopedThreadRef }) {
+ const { closeSurface } = useRightPanelSurfaceClose({
+ threadRef,
+ terminalLabelsById: new Map(),
+ });
+ return <button onClick={() => closeSurface(surface)}>Close original terminal</button>;
+ }
+ return { original, other, Harness, resolve };
+}
+
+it.each([false, true])(
+ "keeps a pending close on its original environment and thread, fallback=%s",
+ async (failClose) => {
+ const { original, other, Harness, resolve } = setup();
+ fixture.failClose = failClose;
+ await using screen = await render(<Harness threadRef={original} />);
+ await screen.getByRole("button").click();
+ await screen.rerender(<Harness threadRef={other} />);
+ await act(async () => {
+ resolve(true);
+ });
+ expect([...fixture.sessions]).toEqual([
+ ["environment-b/thread-b/term-1", "history to preserve"],
+ ]);
+ const panels = useRightPanelStore.getState().byThreadKey;
+ expect(selectThreadRightPanelState(panels, original).surfaces).toEqual([]);
+ expect(selectThreadRightPanelState(panels, other).surfaces).toHaveLength(1);
+ },
+);
+
+it.each(["cancel", "revoked"])(
+ "leaves both sessions intact when confirmation is %s",
+ async (outcome) => {
+ const { original, other, Harness, resolve } = setup();
+ await using screen = await render(<Harness threadRef={original} />);
+ await screen.getByRole("button").click();
+ await screen.rerender(<Harness threadRef={other} />);
+ if (outcome === "revoked") fixture.allowed.delete(original.environmentId);
+ await act(async () => {
+ resolve(outcome !== "cancel");
+ });
+ expect(fixture.sessions.size).toBe(2);
+ expect(
+ useRightPanelStore.getState().byThreadKey[scopedThreadKey(other)]?.surfaces,
+ ).toHaveLength(1);
+ },
+);
diff --git a/apps/web/src/hooks/useRightPanelSurfaceClose.ts b/apps/web/src/hooks/useRightPanelSurfaceClose.ts
index 294112b6ce1..e79042ec375 100644
--- a/apps/web/src/hooks/useRightPanelSurfaceClose.ts
+++ b/apps/web/src/hooks/useRightPanelSurfaceClose.ts
@@ -57,7 +57,7 @@ export function useRightPanelSurfaceClose(input: {
) {
for (const terminalId of surface.terminalIds) {
storeCloseTerminal(ref, terminalId);
- terminalActions.closeTerminalSession(terminalId);
+ terminalActions.closeTerminalSession(terminalId, ref);
}
}
};