Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ import { useNowMinute } from "../hooks/useNowMinute";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { getTerminalFocusOwner } from "../lib/terminalFocus";
import { isBareEscapeKey } from "../lib/terminalBeforeKey";
import { preventRepeatedTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
import {
Expand Down Expand Up @@ -4691,6 +4692,11 @@ function ChatViewContent(props: ChatViewProps) {

useEffect(() => {
const handler = (event: globalThis.KeyboardEvent) => {
// Bare Escape is for the PTY (vim/nvim). Close stays mod+w.
// Command palette / dialogs still claim Escape when they are actually open.
if (isBareEscapeKey(event) && getTerminalFocusOwner() !== null && !isCommandPaletteOpen()) {
return;
}
if (preventRepeatedTerminalCloseShortcut(event, keybindings)) {
event.stopPropagation();
return;
Expand Down
49 changes: 6 additions & 43 deletions apps/web/src/components/ThreadTerminalDrawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,6 @@ import {
import { type GhosttyColor, type GhosttyTheme } from "~/terminal/ghostty/core";
import { useOpenInPreferredEditor } from "../editorPreferences";
import { isTerminalLinkActivation, resolvePathLinkTarget } from "../terminal-links";
import {
isDiffToggleShortcut,
isTerminalClearShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalSplitVerticalShortcut,
isTerminalToggleShortcut,
terminalDeleteShortcutData,
terminalNavigationShortcutData,
} from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
MAX_TERMINALS_PER_GROUP,
Expand All @@ -67,7 +57,7 @@ import { previewEnvironment } from "../state/preview";
import { terminalEnvironment } from "../state/terminal";
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
import { useAtomCommand } from "../state/use-atom-command";
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
import { decideTerminalBeforeKey } from "../lib/terminalBeforeKey";
import {
resolveTerminalFontPreference,
resolveTerminalFontSizePreference,
Expand Down Expand Up @@ -706,41 +696,14 @@ export function TerminalViewport({
};

function handleBeforeKey(event: KeyboardEvent): boolean {
const currentKeybindings = keybindingsRef.current;
const options = { context: { terminalFocus: true, terminalOpen: true } };
if (preventTerminalCloseShortcut(event, currentKeybindings)) {
return false;
}
if (
isTerminalToggleShortcut(event, currentKeybindings, options) ||
isTerminalSplitShortcut(event, currentKeybindings, options) ||
isTerminalSplitVerticalShortcut(event, currentKeybindings, options) ||
isTerminalNewShortcut(event, currentKeybindings, options) ||
isDiffToggleShortcut(event, currentKeybindings, options)
) {
return false;
}

const navigationData = terminalNavigationShortcutData(event);
if (navigationData !== null) {
event.preventDefault();
event.stopPropagation();
void sendTerminalInput(navigationData, "Failed to move cursor");
return false;
const decision = decideTerminalBeforeKey(event, keybindingsRef.current);
if (decision.action === "encode") {
return true;
}

const deleteData = terminalDeleteShortcutData(event);
if (deleteData !== null) {
event.preventDefault();
if (decision.action === "send") {
event.stopPropagation();
void sendTerminalInput(deleteData, "Failed to delete terminal input");
return false;
void sendTerminalInput(decision.data, decision.error);
}

if (!isTerminalClearShortcut(event)) return true;
event.preventDefault();
event.stopPropagation();
void sendTerminalInput("\u000c", "Failed to clear terminal");
return false;
}

Expand Down
6 changes: 6 additions & 0 deletions apps/web/src/keybindings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,12 @@ describe("split/new/close terminal shortcuts", () => {
context: { terminalFocus: true },
}),
);
assert.isFalse(
isTerminalCloseShortcut(event({ key: "Escape" }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: true, terminalOpen: true },
}),
);
});

it("supports when expressions", () => {
Expand Down
169 changes: 169 additions & 0 deletions apps/web/src/lib/terminalBeforeKey.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import { describe, expect, it } from "vite-plus/test";

import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";

import {
decideTerminalBeforeKey,
isBareEscapeKey,
type TerminalBeforeKeyEvent,
} from "./terminalBeforeKey";

const defaultKeybindings = [
{
command: "terminal.close",
shortcut: {
key: "w",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: { type: "identifier", name: "terminalFocus" },
},
{
command: "terminal.toggle",
shortcut: {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
},
{
command: "terminal.split",
shortcut: {
key: "d",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: { type: "identifier", name: "terminalFocus" },
},
] satisfies ResolvedKeybindingsConfig;

const escapeCloseKeybindings = [
{
command: "terminal.close",
shortcut: {
key: "escape",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: false,
},
whenAst: { type: "identifier", name: "terminalFocus" },
},
] satisfies ResolvedKeybindingsConfig;

type KeyboardEventOverrides = Partial<
Pick<
TerminalBeforeKeyEvent,
"key" | "code" | "metaKey" | "ctrlKey" | "shiftKey" | "altKey" | "type"
>
>;

function keyboardEvent(
overrides: KeyboardEventOverrides = {},
): TerminalBeforeKeyEvent & { readonly defaultPrevented: boolean } {
let defaultPrevented = false;
return {
key: "Escape",
code: "Escape",
type: "keydown",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
...overrides,
preventDefault: () => {
defaultPrevented = true;
},
get defaultPrevented() {
return defaultPrevented;
},
};
}

describe("isBareEscapeKey", () => {
it("matches Escape and esc with no modifiers", () => {
expect(isBareEscapeKey(keyboardEvent())).toBe(true);
expect(isBareEscapeKey(keyboardEvent({ key: "esc" }))).toBe(true);
});

it("rejects modified Escape", () => {
expect(isBareEscapeKey(keyboardEvent({ metaKey: true }))).toBe(false);
expect(isBareEscapeKey(keyboardEvent({ ctrlKey: true }))).toBe(false);
expect(isBareEscapeKey(keyboardEvent({ shiftKey: true }))).toBe(false);
expect(isBareEscapeKey(keyboardEvent({ altKey: true }))).toBe(false);
});
});

describe("decideTerminalBeforeKey", () => {
it("lets bare Escape reach the PTY and does not treat it as close", () => {
const event = keyboardEvent();

expect(decideTerminalBeforeKey(event, defaultKeybindings, "MacIntel")).toEqual({
action: "encode",
});
expect(event.defaultPrevented).toBe(false);

const remapped = keyboardEvent();
expect(decideTerminalBeforeKey(remapped, escapeCloseKeybindings, "MacIntel")).toEqual({
action: "encode",
});
expect(remapped.defaultPrevented).toBe(false);
});

it("still suppresses the default close shortcut", () => {
const event = keyboardEvent({ key: "w", code: "KeyW", ctrlKey: true });

expect(decideTerminalBeforeKey(event, defaultKeybindings, "Linux x86_64")).toEqual({
action: "suppress",
});
expect(event.defaultPrevented).toBe(true);
});

it("still suppresses split and toggle shortcuts", () => {
const split = keyboardEvent({ key: "d", code: "KeyD", metaKey: true });
expect(decideTerminalBeforeKey(split, defaultKeybindings, "MacIntel")).toEqual({
action: "suppress",
});

const toggle = keyboardEvent({ key: "j", code: "KeyJ", ctrlKey: true });
expect(decideTerminalBeforeKey(toggle, defaultKeybindings, "Linux x86_64")).toEqual({
action: "suppress",
});
});

it("still sends navigation, delete, and clear shortcuts", () => {
const wordLeft = keyboardEvent({ key: "ArrowLeft", altKey: true });
expect(decideTerminalBeforeKey(wordLeft, defaultKeybindings, "MacIntel")).toEqual({
action: "send",
data: "\u001bb",
error: "Failed to move cursor",
});
expect(wordLeft.defaultPrevented).toBe(true);

const deleteToStart = keyboardEvent({ key: "Backspace", metaKey: true });
expect(decideTerminalBeforeKey(deleteToStart, defaultKeybindings, "MacIntel")).toEqual({
action: "send",
data: "\u0015",
error: "Failed to delete terminal input",
});
expect(deleteToStart.defaultPrevented).toBe(true);

const clear = keyboardEvent({ key: "l", code: "KeyL", ctrlKey: true });
expect(decideTerminalBeforeKey(clear, defaultKeybindings, "Linux x86_64")).toEqual({
action: "send",
data: "\u000c",
error: "Failed to clear terminal",
});
expect(clear.defaultPrevented).toBe(true);
});
});
84 changes: 84 additions & 0 deletions apps/web/src/lib/terminalBeforeKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";

import {
isDiffToggleShortcut,
isTerminalClearShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalSplitVerticalShortcut,
isTerminalToggleShortcut,
terminalDeleteShortcutData,
terminalNavigationShortcutData,
type ShortcutEventLike,
} from "../keybindings";
import { preventTerminalCloseShortcut } from "./terminalCloseShortcut";

export interface TerminalBeforeKeyEvent extends ShortcutEventLike {
readonly preventDefault: () => void;
}

export type TerminalBeforeKeyDecision =
| { readonly action: "encode" }
| { readonly action: "suppress" }
| { readonly action: "send"; readonly data: string; readonly error: string };

const TERMINAL_SHORTCUT_CONTEXT = { terminalFocus: true, terminalOpen: true } as const;

/** Escape with no modifiers. Close is `mod+w`; this must reach the PTY for vim/nvim. */
export function isBareEscapeKey(
event: Pick<ShortcutEventLike, "key" | "metaKey" | "ctrlKey" | "shiftKey" | "altKey">,
): boolean {
const key = event.key.toLowerCase();
if (key !== "escape" && key !== "esc") return false;
return !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;
}

/**
* Decides whether Ghostty should encode a key into the PTY.
* Returning `encode` means `beforeKey` is true so the surface does not swallow it.
*/
export function decideTerminalBeforeKey(
event: TerminalBeforeKeyEvent,
keybindings: ResolvedKeybindingsConfig,
platform?: string,
): TerminalBeforeKeyDecision {
if (isBareEscapeKey(event)) {
return { action: "encode" };
}

const options = {
...(platform === undefined ? {} : { platform }),
context: TERMINAL_SHORTCUT_CONTEXT,
};
if (preventTerminalCloseShortcut(event, keybindings, platform)) {
return { action: "suppress" };
}
if (
isTerminalToggleShortcut(event, keybindings, options) ||
isTerminalSplitShortcut(event, keybindings, options) ||
isTerminalSplitVerticalShortcut(event, keybindings, options) ||
isTerminalNewShortcut(event, keybindings, options) ||
isDiffToggleShortcut(event, keybindings, options)
) {
return { action: "suppress" };
}

const resolvedPlatform = platform ?? navigator.platform;
const navigationData = terminalNavigationShortcutData(event, resolvedPlatform);
if (navigationData !== null) {
event.preventDefault();
return { action: "send", data: navigationData, error: "Failed to move cursor" };
}

const deleteData = terminalDeleteShortcutData(event, resolvedPlatform);
if (deleteData !== null) {
event.preventDefault();
return { action: "send", data: deleteData, error: "Failed to delete terminal input" };
}

if (!isTerminalClearShortcut(event, resolvedPlatform)) {
return { action: "encode" };
}
event.preventDefault();
return { action: "send", data: "\u000c", error: "Failed to clear terminal" };
}
7 changes: 7 additions & 0 deletions apps/web/src/lib/terminalCloseShortcut.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,13 @@ describe("terminal close shortcut guards", () => {
);
});

it("does not treat bare Escape as terminal close", () => {
const event = keyboardEvent({ key: "Escape", code: "Escape", ctrlKey: false });

expect(preventTerminalCloseShortcut(event, keybindings, "MacIntel")).toBe(false);
expect(event.defaultPrevented).toBe(false);
});

it("leaves a non-repeated window close and unrelated repeats alone", () => {
const deliberateWindowClose = keyboardEvent({ repeat: false });
const unrelatedRepeat = keyboardEvent({ key: "q", code: "KeyQ", repeat: true });
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/routes/_chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ function ChatRouteGlobalShortcuts() {
}

if (event.key === "Escape" && selectedThreadKeysSize > 0) {
if (isTerminalFocused()) return;
event.preventDefault();
clearSelection();
return;
Expand Down
Loading
Loading