TypeScript
fix(web): suppress terminal key releases for app-handled shortcuts (#15020)
Alex Southwelle433eeb7a35d
diff --git a/apps/web/src/components/ThreadTerminalDrawer.permissions.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.permissions.browser.test.tsxindex adbc8c9ca5b..8883e768f67 100644--- a/apps/web/src/components/ThreadTerminalDrawer.permissions.browser.test.tsx+++ b/apps/web/src/components/ThreadTerminalDrawer.permissions.browser.test.tsx@@ -82,7 +82,7 @@ vi.mock(import("../state/session"), async (original) => {};});-import { TerminalViewport } from "./ThreadTerminalDrawer";+import ThreadTerminalDrawer, { TerminalViewport } from "./ThreadTerminalDrawer";const threadRef = {environmentId: EnvironmentId.make("secondary-terminal"),@@ -110,6 +110,7 @@ afterEach(async () => {await act(async () => root.unmount());container.remove();vi.unstubAllGlobals();+ vi.restoreAllMocks();});it("rechecks the target terminal grant when a retained surface callback reports a resize", async () => {@@ -154,3 +155,103 @@ it("rechecks the target terminal grant when a retained surface callback reportsinput: { threadId: threadRef.threadId, terminalId: "terminal-1", cols: 100, rows: 30 },});});++it("keeps held Kitty keys and the original surface through split, focus, and unsplit", async () => {+ const { GhosttyTerminalSurface } = await vi.importActual<+ typeof import("~/terminal/ghostty/surface")+ >("~/terminal/ghostty/surface");+ const output: string[][] = [];+ state.createSurface.mockImplementation((mount, options) => {+ const data: string[] = [];+ output.push(data);+ return GhosttyTerminalSurface.create(mount, {+ ...options,+ onData: (chunk) => {+ data.push(chunk);+ options.onData(chunk);+ },+ });+ });+ const consumeShortcut = (event: KeyboardEvent) => {+ if ((event.code === "KeyD" && event.ctrlKey) || (event.code === "KeyB" && event.repeat)) {+ event.preventDefault();+ event.stopPropagation();+ }+ };+ // ChatView installs its capture listener before the terminal mounts.+ window.addEventListener("keydown", consumeShortcut, { capture: true });+ const composer = document.createElement("textarea");+ document.body.append(composer);+ const render = async (terminalIds: string[]) => {+ await act(async () =>+ root.render(+ <ThreadTerminalDrawer+ threadRef={threadRef}+ threadId={threadRef.threadId}+ cwd="/repo"+ height={280}+ terminalIds={terminalIds}+ activeTerminalId="original"+ terminalGroups={[{ id: "group", terminalIds }]}+ activeTerminalGroupId="group"+ focusRequestId={0}+ onSplitTerminal={state.otherCommand}+ onSplitTerminalVertical={state.otherCommand}+ onNewTerminal={state.otherCommand}+ onActiveTerminalChange={state.otherCommand}+ onCloseTerminal={state.otherCommand}+ onHeightChange={state.otherCommand}+ onAddTerminalContext={state.otherCommand}+ keybindings={[]}+ />,+ ),+ );+ await act(async () => {+ await Promise.all(state.createSurface.mock.results.map((result) => result.value));+ });+ };+ try {+ await render(["original"]);+ const original = await state.createSurface.mock.results[0]!.value;+ const disposeOriginal = vi.spyOn(original, "dispose");+ original.write("\x1b[>11u");+ const key = (type: "keydown" | "keyup", init: KeyboardEventInit) =>+ original.input.dispatchEvent(+ new KeyboardEvent(type, { bubbles: true, cancelable: true, ...init }),+ );+ original.focus();+ key("keydown", { key: "Control", code: "ControlLeft", ctrlKey: true });+ key("keydown", { key: "d", code: "KeyD", ctrlKey: true });+ await render(["original", "split"]);+ expect(state.createSurface).toHaveBeenCalledTimes(2);+ expect(container.querySelector("textarea")).toBe(original.input);+ expect(disposeOriginal).not.toHaveBeenCalled();+ const split = await state.createSurface.mock.results[1]!.value;+ const disposeSplit = vi.spyOn(split, "dispose");+ original.focus();+ key("keyup", { key: "d", code: "KeyD", ctrlKey: true });+ key("keyup", { key: "Control", code: "ControlLeft" });++ key("keydown", { key: "b", code: "KeyB" });+ composer.focus();+ original.focus();+ key("keydown", { key: "b", code: "KeyB", repeat: true });+ key("keyup", { key: "b", code: "KeyB" });++ key("keydown", { key: "c", code: "KeyC" });+ await render(["original"]);+ expect(state.createSurface).toHaveBeenCalledTimes(2);+ expect(container.querySelector("textarea")).toBe(original.input);+ expect(disposeOriginal).not.toHaveBeenCalled();+ expect(disposeSplit).toHaveBeenCalledOnce();+ original.focus();+ key("keyup", { key: "c", code: "KeyC" });+ expect(output).toEqual([+ ["\x1b[57442;5u", "\x1b[57442;1:3u", "\x1b[98u", "\x1b[98;1:3u", "\x1b[99u", "\x1b[99;1:3u"],+ [],+ ]);+ } finally {+ window.removeEventListener("keydown", consumeShortcut, { capture: true });+ composer.remove();+ }+});diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsxindex 411444f2a54..e9af425afef 100644--- a/apps/web/src/components/ThreadTerminalDrawer.tsx+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx@@ -1571,7 +1571,6 @@ export default function ThreadTerminalDrawer({const splitDirection =resolvedTerminalGroups[resolvedActiveGroupIndex]?.splitDirection ?? "horizontal";const hasTerminalSidebar = normalizedTerminalIds.length > 1;- const isSplitView = visibleTerminalIds.length > 1;const showGroupHeaders =resolvedTerminalGroups.length > 1 ||resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);@@ -1750,8 +1749,6 @@ export default function ThreadTerminalDrawer({);}- const activeTerminalLaunchLocation = resolveTerminalLaunchLocation(resolvedActiveTerminalId);-return (<asidedata-thread-terminal-drawer@@ -1831,52 +1828,24 @@ export default function ThreadTerminalDrawer({)}><div className="min-w-0 flex-1">- {isSplitView ? (- <TerminalSplitPanes- terminalIds={visibleTerminalIds}- splitDirection={splitDirection}- activeTerminalId={resolvedActiveTerminalId}- terminalLabelById={terminalLabelById}- resolveLaunchLocation={resolveTerminalLaunchLocation}- onActiveTerminalChange={onActiveTerminalChange}- onCloseTerminal={onCloseTerminal}- advancedTypography={advancedTypography}- threadRef={threadRef}- threadId={threadId}- onAddTerminalContext={onAddTerminalContext}- focusRequestId={focusRequestId}- visible={visible}- resizeEpoch={resizeEpoch}- drawerHeight={drawerHeight}- keybindings={keybindings}- />- ) : (- <div className="h-full">- <TerminalViewport- advancedTypography={advancedTypography}- key={resolvedActiveTerminalId}- threadRef={threadRef}- threadId={threadId}- terminalId={resolvedActiveTerminalId}- terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}- cwd={activeTerminalLaunchLocation.cwd}- {...(activeTerminalLaunchLocation.worktreePath !== undefined- ? { worktreePath: activeTerminalLaunchLocation.worktreePath }- : {})}- {...(activeTerminalLaunchLocation.runtimeEnv- ? { runtimeEnv: activeTerminalLaunchLocation.runtimeEnv }- : {})}- onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}- onAddTerminalContext={onAddTerminalContext}- focusRequestId={focusRequestId}- autoFocus- visible={visible}- resizeEpoch={resizeEpoch}- drawerHeight={drawerHeight}- keybindings={keybindings}- />- </div>- )}+ <TerminalSplitPanes+ terminalIds={visibleTerminalIds}+ splitDirection={splitDirection}+ activeTerminalId={resolvedActiveTerminalId}+ terminalLabelById={terminalLabelById}+ resolveLaunchLocation={resolveTerminalLaunchLocation}+ onActiveTerminalChange={onActiveTerminalChange}+ onCloseTerminal={onCloseTerminal}+ advancedTypography={advancedTypography}+ threadRef={threadRef}+ threadId={threadId}+ onAddTerminalContext={onAddTerminalContext}+ focusRequestId={focusRequestId}+ visible={visible}+ resizeEpoch={resizeEpoch}+ drawerHeight={drawerHeight}+ keybindings={keybindings}+ /></div>{hasTerminalSidebar && (diff --git a/apps/web/src/terminal/ghostty/surface.test.ts b/apps/web/src/terminal/ghostty/surface.test.tsindex 550eff2138c..258ba1deb80 100644--- a/apps/web/src/terminal/ghostty/surface.test.ts+++ b/apps/web/src/terminal/ghostty/surface.test.ts@@ -55,11 +55,13 @@ describe("GhosttyTerminalSurface visibility", () => {| "metaKey"| "shiftKey"| "isComposing"+ | "repeat"| "keyCode"| "getModifierState">> = {},type = "keydown",+ target: EventTarget = surface.input,) {const event = Object.assign(new Event(type, { cancelable: true }), {key,@@ -69,11 +71,12 @@ describe("GhosttyTerminalSurface visibility", () => {metaKey: false,shiftKey: false,isComposing: false,+ repeat: false,keyCode: 0,getModifierState: () => false,...modifiers,});- surface.input.dispatchEvent(event);+ target.dispatchEvent(event);return event;}@@ -577,6 +580,50 @@ describe("GhosttyTerminalSurface visibility", () => {expect(harness.onData.mock.calls[1]?.[0]).toContain(":3");});+ it("reports Kitty releases only for presses encoded by this surface", async () => {+ const harness = createHarness();+ const surface = await harness.create({ beforeKey: () => true });+ surface.write("\x1b[>11u");++ key(surface, "a", "KeyA");+ key(surface, "a", "KeyA", {}, "keyup");+ key(surface, "Control", "ControlLeft", { ctrlKey: true });+ // App capture stops Ctrl+D before it reaches the terminal input.+ key(surface, "d", "KeyD", { ctrlKey: true }, "keydown", window);+ key(surface, "d", "KeyD", { ctrlKey: true }, "keyup");+ key(surface, "Control", "ControlLeft", {}, "keyup");++ expect(harness.onData.mock.calls.map(([data]) => data)).toEqual([+ "\x1b[97u",+ "\x1b[97;1:3u",+ "\x1b[57442;5u",+ "\x1b[57442;1:3u",+ ]);+ });++ it("keeps a held Kitty press through focus changes and an app-consumed repeat", async () => {+ const harness = createHarness();+ let consumeRepeat = false;+ const surface = await harness.create({ beforeKey: () => !consumeRepeat });+ surface.write("\x1b[>11u");++ key(surface, "a", "KeyA");+ key(surface, "a", "KeyA", { repeat: true });+ surface.input.dispatchEvent(new Event("blur"));+ window.dispatchEvent(new Event("blur"));+ window.dispatchEvent(new Event("focus"));+ surface.input.dispatchEvent(new Event("focus"));+ consumeRepeat = true;+ key(surface, "a", "KeyA", { repeat: true });+ key(surface, "a", "KeyA", {}, "keyup");++ expect(harness.onData.mock.calls.map(([data]) => data)).toEqual([+ "\x1b[97u",+ "\x1b[97;1:2u",+ "\x1b[97;1:3u",+ ]);+ });+it("honors host interception, IME candidates, and AltGr before local shortcuts", async () => {vi.stubGlobal("navigator", { platform: "Linux x86_64" });const harness = createHarness();diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.tsindex a6edd9c4057..d47e24f9dff 100644--- a/apps/web/src/terminal/ghostty/surface.ts+++ b/apps/web/src/terminal/ghostty/surface.ts@@ -587,7 +587,8 @@ export class GhosttyTerminalSurface {readonly ratio: number;} | null = null;private theme: GhosttyTheme;- private readonly suppressedKeyCodes = new Set<string>();+ // App capture can hide keydowns, so only encoded presses qualify for Kitty releases.+ private readonly encodedKeyCodes = new Set<string>();private pasteShortcutToken = 0;// Chromium can deliver native paste after the clipboard read resolves.// Suppress its duplicate only for the current shortcut gesture.@@ -1058,18 +1059,12 @@ export class GhosttyTerminalSurface {}private readonly onKeyDown = (event: KeyboardEvent) => {- // Presses handled outside the terminal must also swallow their release:- // beforeKey runs side effects (keybindings, navigation sends), so it cannot- // be consulted again on keyup, and Kitty report-event-types sessions would- // otherwise receive a release for a press the shell never saw.- if (isTerminalAltGraphText(event) || !this.options.beforeKey(event)) {- this.suppressedKeyCodes.add(event.code);- return;- }+ // A consumed repeat still owes the original encoded press a release.+ if (!event.repeat) this.encodedKeyCodes.delete(event.code);+ if (isTerminalAltGraphText(event) || !this.options.beforeKey(event)) return;// IME candidates belong to the textarea, even if the key also resembles// a local shortcut. Safari signals the initial composition with code 229.if (isTerminalCompositionKey(event, this.composing)) {- this.suppressedKeyCodes.add(event.code);return;}const mac = isMacPlatform(navigator.platform);@@ -1082,7 +1077,6 @@ export class GhosttyTerminalSurface {if (selectAllShortcut) {event.preventDefault();event.stopPropagation();- this.suppressedKeyCodes.add(event.code);this.selectAll();return;}@@ -1102,7 +1096,6 @@ export class GhosttyTerminalSurface {if (state !== null) {event.preventDefault();event.stopPropagation();- this.suppressedKeyCodes.add(event.code);const delta =event.key === "Home"? -state.offset@@ -1153,11 +1146,9 @@ export class GhosttyTerminalSurface {});}}- this.suppressedKeyCodes.add(event.code);return;}if (isTerminalPasteShortcut(event)) {- this.suppressedKeyCodes.add(event.code);const gesture = { code: event.code, readText: "" };this.pasteShortcutGesture = gesture;const clipboard = navigator.clipboard;@@ -1181,7 +1172,7 @@ export class GhosttyTerminalSurface {this.clearPrimedCopy();const data = this.core.encodeKey(event);if (data.length === 0) return;- this.suppressedKeyCodes.delete(event.code);+ this.encodedKeyCodes.add(event.code);event.preventDefault();event.stopPropagation();this.options.onData(data);@@ -1197,7 +1188,7 @@ export class GhosttyTerminalSurface {) {this.pasteShortcutGesture = null;}- if (this.suppressedKeyCodes.delete(event.code)) return;+ if (!this.encodedKeyCodes.delete(event.code)) return;if (isTerminalCompositionKey(event, this.composing)) {return;}@@ -1210,6 +1201,17 @@ export class GhosttyTerminalSurface {this.options.onData(data);};+ // A release elsewhere must not leave a press for a later app shortcut to inherit.+ private readonly onWindowKeyUp = (event: KeyboardEvent) => {+ if (event.composedPath().includes(this.input)) return;+ this.encodedKeyCodes.delete(event.code);+ };++ // A fresh press proves a release was missed; repeats can span a focus round trip.+ private readonly onWindowKeyDown = (event: KeyboardEvent) => {+ if (!event.repeat) this.encodedKeyCodes.delete(event.code);+ };+private readonly onFocus = () => {this.focused = true;this.cursorOn = true;@@ -1220,9 +1222,6 @@ export class GhosttyTerminalSurface {this.focused = false;this.pasteShortcutGesture = null;this.refreshHoveredLink();- // Suppressions survive blur deliberately: a shortcut that moves focus (for- // example terminal-toggle) must still swallow its own keyup if focus comes- // back before release.this.cursorOn = true;this.requestRender();};@@ -1774,6 +1773,9 @@ export class GhosttyTerminalSurface {private installEvents(): void {this.input.addEventListener("keydown", this.onKeyDown);this.input.addEventListener("keyup", this.onKeyUp);+ // App shortcuts stop propagation at window, so observe the same capture target.+ window.addEventListener("keyup", this.onWindowKeyUp, { capture: true });+ window.addEventListener("keydown", this.onWindowKeyDown, { capture: true });this.input.addEventListener("focus", this.onFocus);this.input.addEventListener("blur", this.onBlur);this.input.addEventListener("input", this.onInput);@@ -1802,6 +1804,8 @@ export class GhosttyTerminalSurface {private removeEvents(): void {this.input.removeEventListener("keydown", this.onKeyDown);this.input.removeEventListener("keyup", this.onKeyUp);+ window.removeEventListener("keyup", this.onWindowKeyUp, { capture: true });+ window.removeEventListener("keydown", this.onWindowKeyDown, { capture: true });this.input.removeEventListener("focus", this.onFocus);this.input.removeEventListener("blur", this.onBlur);this.input.removeEventListener("input", this.onInput);