Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(web): confirm before closing a terminal (#7592)

maria0508792c572a
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 8044db133..c7df43240 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -46,7 +46,11 @@ import {
import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { truncate } from "@t3tools/shared/String";
-import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
+import {
+ getTerminalLabel,
+ nextTerminalId,
+ resolveTerminalSessionLabel,
+} from "@t3tools/shared/terminalLabels";
import { Debouncer } from "@tanstack/react-pacer";
import { useAtomValue } from "@effect/atom-react";
import {
@@ -192,8 +196,12 @@ import {
import { useNowMinute } from "../hooks/useNowMinute";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
+import { confirmTerminalClose, isTerminalCloseConfirmPending } from "../lib/terminalCloseConfirm";
import { getTerminalFocusOwner } from "../lib/terminalFocus";
-import { preventRepeatedTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
+import {
+ preventRepeatedTerminalCloseShortcut,
+ preventTerminalCloseShortcut,
+} from "../lib/terminalCloseShortcut";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
import {
derivePhysicalProjectKey,
@@ -3453,6 +3461,24 @@ function ChatViewContent(props: ChatViewProps) {
},
[activeRightPanelSurface, activeThreadRef, closeTerminalMutation, storeCloseTerminal],
);
+ const requestCloseTerminal = useCallback(
+ (terminalId: string) => {
+ const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
+ void confirmTerminalClose([label]).then((confirmed) => {
+ if (confirmed) closeTerminal(terminalId);
+ });
+ },
+ [activeTerminalLabelsById, closeTerminal],
+ );
+ const requestClosePanelTerminal = useCallback(
+ (terminalId: string) => {
+ const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
+ void confirmTerminalClose([label]).then((confirmed) => {
+ if (confirmed) closePanelTerminal(terminalId);
+ });
+ },
+ [activeTerminalLabelsById, closePanelTerminal],
+ );
const activateRightPanelSurface = useCallback(
(surface: RightPanelSurface) => {
if (!activeThreadRef) return;
@@ -3527,11 +3553,33 @@ function ChatViewContent(props: ChatViewProps) {
const closeRightPanelSurface = useCallback(
(surface: RightPanelSurface) => {
if (!activeThreadRef) return;
- cleanupRightPanelSurfaces([surface]);
- useRightPanelStore.getState().closeSurface(activeThreadRef, surface.id);
- syncActivePreviewSurface();
+ const finishClose = () => {
+ cleanupRightPanelSurfaces([surface]);
+ useRightPanelStore.getState().closeSurface(activeThreadRef, surface.id);
+ syncActivePreviewSurface();
+ };
+ if (surface.kind !== "terminal") {
+ finishClose();
+ return;
+ }
+ const activeLabel =
+ activeTerminalLabelsById.get(surface.activeTerminalId) ??
+ getTerminalLabel(surface.activeTerminalId);
+ const otherLabels = surface.terminalIds
+ .filter((terminalId) => terminalId !== surface.activeTerminalId)
+ .map(
+ (terminalId) => activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId),
+ );
+ void confirmTerminalClose([activeLabel, ...otherLabels]).then((confirmed) => {
+ if (confirmed) finishClose();
+ });
},
- [activeThreadRef, cleanupRightPanelSurfaces, syncActivePreviewSurface],
+ [
+ activeThreadRef,
+ activeTerminalLabelsById,
+ cleanupRightPanelSurfaces,
+ syncActivePreviewSurface,
+ ],
);
const closeOtherRightPanelSurfaces = useCallback(
(surface: RightPanelSurface) => {
@@ -4724,6 +4772,13 @@ function ChatViewContent(props: ChatViewProps) {
event.stopPropagation();
return;
}
+ // While a close confirmation is open, terminal focus has moved to the
+ // dialog, so a deliberate second close shortcut would otherwise fall
+ // through to the native window/tab close accelerator.
+ if (isTerminalCloseConfirmPending() && preventTerminalCloseShortcut(event, keybindings)) {
+ event.stopPropagation();
+ return;
+ }
if (!activeThreadId || isCommandPaletteOpen()) {
return;
}
@@ -4807,11 +4862,11 @@ function ChatViewContent(props: ChatViewProps) {
event.preventDefault();
event.stopPropagation();
if (terminalFocusOwner === "right-panel" && activeRightPanelSurface?.kind === "terminal") {
- closePanelTerminal(activeRightPanelSurface.activeTerminalId);
+ requestClosePanelTerminal(activeRightPanelSurface.activeTerminalId);
return;
}
if (!terminalUiState.terminalOpen) return;
- closeTerminal(terminalUiState.activeTerminalId);
+ requestCloseTerminal(terminalUiState.activeTerminalId);
return;
}
@@ -4860,8 +4915,8 @@ function ChatViewContent(props: ChatViewProps) {
terminalUiState.terminalOpen,
terminalUiState.activeTerminalId,
activeThreadId,
- closeTerminal,
- closePanelTerminal,
+ requestCloseTerminal,
+ requestClosePanelTerminal,
createNewTerminal,
setTerminalOpen,
runProjectScript,
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index cf2adaca2..d9fb8973b 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -59,6 +59,7 @@ import {
type ThreadTerminalGroup,
} from "../types";
import { readLocalApi } from "~/localApi";
+import { confirmTerminalClose } from "~/lib/terminalCloseConfirm";
import { useClientSettings } from "../hooks/useSettings";
import { useLocalStorage } from "../hooks/useLocalStorage";
import { useAttachedTerminalSession } from "../state/terminalSessions";
@@ -1273,6 +1274,15 @@ export default function ThreadTerminalDrawer({
const onNewTerminalAction = useCallback(() => {
onNewTerminal();
}, [onNewTerminal]);
+ const confirmCloseTerminal = useCallback(
+ (terminalId: string) => {
+ const label = terminalLabelById.get(terminalId) ?? getTerminalLabel(terminalId);
+ void confirmTerminalClose([label]).then((confirmed) => {
+ if (confirmed) onCloseTerminal(terminalId);
+ });
+ },
+ [onCloseTerminal, terminalLabelById],
+ );
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
@@ -1463,7 +1473,7 @@ export default function ThreadTerminalDrawer({
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
- onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
+ onClick={() => confirmCloseTerminal(resolvedActiveTerminalId)}
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
@@ -1598,7 +1608,7 @@ export default function ThreadTerminalDrawer({
</TerminalActionButton>
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
- onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
+ onClick={() => confirmCloseTerminal(resolvedActiveTerminalId)}
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
@@ -1668,7 +1678,7 @@ export default function ThreadTerminalDrawer({
<button
type="button"
className="inline-flex size-3.5 items-center justify-center rounded text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
- onClick={() => onCloseTerminal(terminalId)}
+ onClick={() => confirmCloseTerminal(terminalId)}
aria-label={closeTerminalLabel}
/>
}
diff --git a/apps/web/src/lib/terminalCloseConfirm.test.ts b/apps/web/src/lib/terminalCloseConfirm.test.ts
new file mode 100644
index 000000000..58f523958
--- /dev/null
+++ b/apps/web/src/lib/terminalCloseConfirm.test.ts
@@ -0,0 +1,78 @@
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const { confirmMock, readLocalApiMock } = vi.hoisted(() => {
+ const confirmMock = vi.fn<(message: string, options?: unknown) => Promise<boolean>>();
+ const readLocalApiMock = vi.fn<
+ () =>
+ | {
+ dialogs: { confirm: (message: string, options?: unknown) => Promise<boolean> };
+ }
+ | undefined
+ >();
+ return { confirmMock, readLocalApiMock };
+});
+
+vi.mock("~/localApi", () => ({
+ readLocalApi: () => readLocalApiMock(),
+}));
+
+import { confirmTerminalClose, isTerminalCloseConfirmPending } from "./terminalCloseConfirm";
+
+describe("terminal close confirmation", () => {
+ beforeEach(() => {
+ confirmMock.mockReset();
+ readLocalApiMock.mockReset();
+ readLocalApiMock.mockReturnValue({ dialogs: { confirm: confirmMock } });
+ });
+
+ it("tracks pending state until the confirmation settles", async () => {
+ let settle: (value: boolean) => void = () => undefined;
+ confirmMock.mockImplementation(() => new Promise<boolean>((resolve) => (settle = resolve)));
+
+ expect(isTerminalCloseConfirmPending()).toBe(false);
+
+ const confirmation = confirmTerminalClose(["Terminal 1"]);
+ expect(isTerminalCloseConfirmPending()).toBe(true);
+
+ settle(true);
+ await expect(confirmation).resolves.toBe(true);
+ expect(isTerminalCloseConfirmPending()).toBe(false);
+ });
+
+ it("clears pending state and resolves false when the dialog rejects", async () => {
+ let reject: (reason?: unknown) => void = () => undefined;
+ confirmMock.mockImplementation(
+ () =>
+ new Promise<boolean>((_resolve, rejectPromise) => {
+ reject = rejectPromise;
+ }),
+ );
+
+ const confirmation = confirmTerminalClose(["Terminal 1"]);
+ expect(isTerminalCloseConfirmPending()).toBe(true);
+
+ reject(new Error("dialog failed"));
+ await expect(confirmation).resolves.toBe(false);
+ expect(isTerminalCloseConfirmPending()).toBe(false);
+ });
+
+ it("names every terminal in a multi-terminal close", async () => {
+ confirmMock.mockResolvedValue(true);
+
+ await expect(confirmTerminalClose(["Terminal 1", "Development server"])).resolves.toBe(true);
+ expect(confirmMock).toHaveBeenCalledWith(
+ [
+ "Close 2 terminals?",
+ 'This stops their running processes and clears their histories: "Terminal 1", "Development server".',
+ ].join("\n"),
+ { variant: "destructive" },
+ );
+ });
+
+ it("closes without prompting when no local API is available", async () => {
+ readLocalApiMock.mockReturnValue(undefined);
+
+ await expect(confirmTerminalClose(["Terminal 1"])).resolves.toBe(true);
+ expect(confirmMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/lib/terminalCloseConfirm.ts b/apps/web/src/lib/terminalCloseConfirm.ts
new file mode 100644
index 000000000..b1ea97a64
--- /dev/null
+++ b/apps/web/src/lib/terminalCloseConfirm.ts
@@ -0,0 +1,42 @@
+import { readLocalApi } from "~/localApi";
+
+let pendingConfirmations = 0;
+
+/** Whether a terminal-close confirmation is currently waiting on the user. */
+export function isTerminalCloseConfirmPending(): boolean {
+ return pendingConfirmations > 0;
+}
+
+/**
+ * Confirmation for individual terminal close actions: drawer buttons, panel
+ * buttons, the `terminal.close` keybinding, and closing a terminal surface from
+ * the tab strip. Auto-exit cleanup and bulk tab closes skip this path and close
+ * directly.
+ */
+export async function confirmTerminalClose(
+ labels: readonly [string, ...string[]],
+): Promise<boolean> {
+ const localApi = readLocalApi();
+ if (!localApi) return true;
+ pendingConfirmations += 1;
+ try {
+ return await localApi.dialogs.confirm(
+ labels.length === 1
+ ? [
+ `Close terminal "${labels[0]}"?`,
+ "This stops the running process and clears its history.",
+ ].join("\n")
+ : [
+ `Close ${labels.length} terminals?`,
+ `This stops their running processes and clears their histories: ${labels
+ .map((label) => `"${label}"`)
+ .join(", ")}.`,
+ ].join("\n"),
+ { variant: "destructive" },
+ );
+ } catch {
+ return false;
+ } finally {
+ pendingConfirmations -= 1;
+ }
+}