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.
fix(web): add copying terminal selection with ctrl+c in the web app (#5638)
Utkarsh Patil1add47b322ab
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsxindex c59f682c4..87f0ed4ae 100644--- a/apps/web/src/components/ThreadTerminalDrawer.tsx+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx@@ -440,7 +440,6 @@ export function TerminalViewport({onData: (data) => handleData(data),onResize: (cols, rows) => void resizeTerminal(cols, rows),onSelectionChange: () => handleSelectionChange(),- onCopy: (text) => handleCopy(text),beforeKey: (event) => handleBeforeKey(event),onLinkActivate: (text, event) => handleLinkActivate(text, event),};@@ -668,17 +667,6 @@ export function TerminalViewport({})();}- function handleCopy(text: string): void {- void writeTextToClipboard(text, "terminal selection").catch((error: unknown) => {- const activeTerminal = terminalRef.current;- if (!activeTerminal) return;- writeSystemMessage(- activeTerminal,- error instanceof Error ? error.message : "Unable to copy terminal selection",- );- });- }-function handleData(data: string): void {void (async () => {const result = await writeTerminal(data);@@ -696,6 +684,12 @@ export function TerminalViewport({return;}clearSelectionAction();+ // A copy shortcut that clears the selection (Ctrl+C) must also close+ // the context menu that appears with the selection, but a clear that+ // never opened a menu must not dismiss an unrelated one.+ if (selectionActionMenuOpenRef.current) {+ void localApi?.contextMenu.close();+ }}const handleMouseUp = (event: MouseEvent) => {diff --git a/apps/web/src/components/settings/SettingsFontPreviews.tsx b/apps/web/src/components/settings/SettingsFontPreviews.tsxindex 05ea2c9f0..a678c2ad5 100644--- a/apps/web/src/components/settings/SettingsFontPreviews.tsx+++ b/apps/web/src/components/settings/SettingsFontPreviews.tsx@@ -238,7 +238,6 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nuonData: echo,onResize: noop,onSelectionChange: noop,- onCopy: (text) => void navigator.clipboard?.writeText(text).catch(noop),// Tab keeps walking the settings page instead of feeding the echo loop.beforeKey: (event) => event.key !== "Tab",onLinkActivate: noop,diff --git a/apps/web/src/contextMenuFallback.test.ts b/apps/web/src/contextMenuFallback.test.tsindex 29596e72a..d36f1a1d1 100644--- a/apps/web/src/contextMenuFallback.test.ts+++ b/apps/web/src/contextMenuFallback.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";-import { showContextMenuFallback } from "./contextMenuFallback";+import { dismissContextMenu, showContextMenuFallback } from "./contextMenuFallback";type FakeListener = (event: FakeDomEvent) => void;@@ -236,3 +236,37 @@ describe("showContextMenuFallback", () => {await expect(selectionPromise).resolves.toBe("rename:project-b");});});++describe("dismissContextMenu", () => {+ it("resolves an open menu with null", async () => {+ const selectionPromise = showContextMenuFallback([+ { id: "rename", label: "Rename" },+ { id: "delete", label: "Delete" },+ ]);+ expect(findButton("Rename")).toBeTruthy();++ dismissContextMenu();++ await expect(selectionPromise).resolves.toBeNull();+ expect(findButton("Rename")).toBeUndefined();+ });++ it("is a no-op when no menu is open", async () => {+ dismissContextMenu();+ expect(findButton("Rename")).toBeUndefined();+ });++ it("dismisses the prior menu when a new one opens", async () => {+ const firstPromise = showContextMenuFallback([{ id: "first", label: "First" }]);+ expect(findButton("First")).toBeTruthy();++ const secondPromise = showContextMenuFallback([{ id: "second", label: "Second" }]);++ await expect(firstPromise).resolves.toBeNull();+ expect(findButton("First")).toBeUndefined();+ expect(findButton("Second")).toBeTruthy();++ dismissContextMenu();+ await expect(secondPromise).resolves.toBeNull();+ });+});diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.tsindex 50f4340e2..769826e39 100644--- a/apps/web/src/contextMenuFallback.ts+++ b/apps/web/src/contextMenuFallback.ts@@ -101,6 +101,21 @@ function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly Hreturn false;}+// Only one fallback menu exists at a time in the renderer; the active one is+// tracked so a state change (for example a terminal selection clearing) can+// dismiss it with the same result as an outside click or Escape.+let activeContextMenuDismiss: (() => void) | null = null;++/**+ * Closes the currently open fallback context menu, resolving its show() with+ * null (the same result as dismissing by outside click or Escape). No-op when+ * no fallback menu is open.+ */+export function dismissContextMenu(): void {+ activeContextMenuDismiss?.();+ activeContextMenuDismiss = null;+}+/*** Imperative DOM-based context menu for non-Electron environments.* Supports nested submenus and resolves with the clicked leaf item id.@@ -114,11 +129,16 @@ export function showContextMenuFallback<T extends string>(let isDisposed = false;let canDismissFromPointer = false;+ const dismiss = () => cleanup(null);+const cleanup = (result: T | null) => {if (isDisposed) {return;}isDisposed = true;+ if (activeContextMenuDismiss === dismiss) {+ activeContextMenuDismiss = null;+ }document.removeEventListener("keydown", onKeyDown);document.removeEventListener("pointerdown", onPointerDown, true);document.removeEventListener("contextmenu", onContextMenu, true);@@ -299,6 +319,13 @@ export function showContextMenuFallback<T extends string>(document.addEventListener("pointerdown", onPointerDown, true);document.addEventListener("contextmenu", onContextMenu, true);openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);+ // Only one fallback menu can be open at a time: a new show must dismiss+ // any prior one, or its DOM and listeners leak and close() can only ever+ // reach the newest menu.+ if (activeContextMenuDismiss) {+ activeContextMenuDismiss();+ }+ activeContextMenuDismiss = dismiss;requestAnimationFrame(() => {canDismissFromPointer = true;diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.tsindex 064b92703..9220252cb 100644--- a/apps/web/src/localApi.test.ts+++ b/apps/web/src/localApi.test.ts@@ -13,12 +13,14 @@ const showContextMenuFallbackMock =position?: { x: number; y: number },) => Promise<T | null>>();+const dismissContextMenuMock = vi.fn<() => void>();const requestConfirmDialogMock =vi.fn<(message: string, options?: ConfirmDialogOptions) => Promise<boolean> | undefined>();vi.mock("./contextMenuFallback", () => ({showContextMenuFallback: showContextMenuFallbackMock,+ dismissContextMenu: dismissContextMenuMock,}));vi.mock("./confirmDialog", () => ({@@ -85,6 +87,14 @@ describe("LocalApi", () => {expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 });});+ it("dismisses an open browser context menu without a desktop bridge", async () => {+ const { createLocalApi } = await import("./localApi");++ await createLocalApi().contextMenu.close();++ expect(dismissContextMenuMock).toHaveBeenCalledOnce();+ });+it("uses the themed confirmation host when it is available", async () => {requestConfirmDialogMock.mockResolvedValue(true);const { createLocalApi } = await import("./localApi");diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.tsindex 5c8f4ec9d..863388106 100644--- a/apps/web/src/localApi.ts+++ b/apps/web/src/localApi.ts@@ -1,7 +1,7 @@import type { ConfirmDialogOptions, ContextMenuItem, LocalApi } from "@t3tools/contracts";import { requestConfirmDialog } from "./confirmDialog";-import { showContextMenuFallback } from "./contextMenuFallback";+import { dismissContextMenu, showContextMenuFallback } from "./contextMenuFallback";import { readBrowserClientSettings, writeBrowserClientSettings } from "./clientPersistenceStorage";import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";@@ -41,6 +41,14 @@ function createBrowserLocalApi(): LocalApi {}return showContextMenuFallback(items, position);},+ // A native desktop menu blocks keyboard input and closes on outside+ // interaction, so nothing to do there; the DOM fallback needs an explicit+ // dismiss when the state behind it goes away.+ close: async () => {+ if (!window.desktopBridge) {+ dismissContextMenu();+ }+ },},persistence: {getClientSettings: async () => {diff --git a/apps/web/src/terminal/ghostty/surface.test.ts b/apps/web/src/terminal/ghostty/surface.test.tsindex 31bc47bdf..18cf95901 100644--- a/apps/web/src/terminal/ghostty/surface.test.ts+++ b/apps/web/src/terminal/ghostty/surface.test.ts@@ -219,11 +219,12 @@ describe("isTerminalCopyShortcut", () => {expect(isTerminalCopyShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);});- it("uses the conventional Ctrl+Shift+C shortcut elsewhere", () => {- expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(false);+ it("copies with Ctrl+C and Ctrl+Shift+C elsewhere", () => {+ expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(true);expect(isTerminalCopyShortcut(event({ ctrlKey: true, shiftKey: true }), "Linux x86_64")).toBe(true,);+ expect(isTerminalCopyShortcut(event({}), "Linux x86_64")).toBe(false);});it("uses the produced character instead of the physical key position", () => {diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.tsindex fc7a89c6d..8a9c796b9 100644--- a/apps/web/src/terminal/ghostty/surface.ts+++ b/apps/web/src/terminal/ghostty/surface.ts@@ -333,7 +333,7 @@ export function isTerminalCopyShortcut(platform = navigator.platform,) {if (event.key.toLowerCase() !== "c") return false;- return isMacPlatform(platform) ? event.metaKey : event.ctrlKey && event.shiftKey;+ return isMacPlatform(platform) ? event.metaKey : event.ctrlKey;}export function isTerminalPasteShortcut(@@ -463,7 +463,6 @@ export interface GhosttyTerminalSurfaceOptions {readonly onData: (data: string) => void;readonly onResize: (cols: number, rows: number) => void;readonly onSelectionChange: () => void;- readonly onCopy: (text: string) => void;readonly beforeKey: (event: KeyboardEvent) => boolean;readonly onLinkActivate: (text: string, event: MouseEvent) => void;}@@ -531,6 +530,8 @@ export class GhosttyTerminalSurface {private theme: GhosttyTheme;private readonly suppressedKeyCodes = new Set<string>();private pasteShortcutToken = 0;+ private copyShortcutToken = 0;+ private clearSelectionAfterCopy = false;private wheelRemainder = 0;private dprMedia: MediaQueryList | null = null;// Read live on every blink decision, and watched so that dropping the@@ -901,9 +902,58 @@ export class GhosttyTerminalSurface {return;}if (isTerminalCopyShortcut(event) && this.hasSelection()) {- event.preventDefault();+ // A plain Ctrl+C/Cmd+C fires the browser's native copy event, caught in+ // onCopyEvent; not preventing the default keeps that path alive. WebKit+ // omits the keyboard copy event without a DOM selection, so race the+ // clipboard write against it the same way paste races its read. The+ // Shift variant has no native event (Chrome binds Ctrl+Shift+C to+ // inspect), so synthesize one with execCommand("copy").+ if (event.shiftKey) {+ event.preventDefault();+ document.execCommand("copy");+ } else {+ // A plain Ctrl+C is also SIGINT on non-mac: clear the selection once+ // it copies so the next Ctrl+C reaches the shell. The Shift chord and+ // Cmd+C are copy-only, so they keep the selection; resetting the flag+ // up front also drops any clear owed by an earlier gesture that never+ // completed.+ this.clearSelectionAfterCopy = !event.shiftKey && !isMacPlatform(navigator.platform);+ const clipboard = navigator.clipboard;+ if (typeof clipboard?.writeText === "function") {+ // Defer the write past the default action: the native copy event+ // (dispatched synchronously with the default action) claims the+ // token first when it fires, and the write covers browsers whose+ // shortcut produces no copy event. Skipping a write the native+ // event already handled stops a stale resolution from clobbering a+ // clipboard the user filled after this copy.+ const token = ++this.copyShortcutToken;+ const selection = this.getSelection();+ void Promise.resolve().then(() => {+ if (this.disposed || this.copyShortcutToken !== token) return;+ void clipboard.writeText(selection).then(+ () => {+ // The write may have been superseded while in flight; only+ // touch the selection if this gesture still owns the token.+ if (this.disposed || this.copyShortcutToken !== token) return;+ if (this.clearSelectionAfterCopy) {+ this.clearSelectionAfterCopy = false;+ this.clearSelection();+ }+ },+ () => {+ // The write failed and the native event has already had its+ // chance, so nothing copied and no clear is owed by this+ // gesture; a newer one may have just set the flag, so only+ // drop it if this gesture still owns the token.+ if (this.copyShortcutToken === token) {+ this.clearSelectionAfterCopy = false;+ }+ },+ );+ });+ }+ }this.suppressedKeyCodes.add(event.code);- this.options.onCopy(this.getSelection());return;}if (isTerminalPasteShortcut(event)) {@@ -989,6 +1039,18 @@ export class GhosttyTerminalSurface {this.dprMedia.addEventListener("change", this.onDevicePixelRatioChange);}+ private readonly onCopyEvent = (event: ClipboardEvent) => {+ if (!this.hasSelection()) return;+ event.preventDefault();+ event.clipboardData?.setData("text/plain", this.getSelection());+ // The native event beat any deferred write; drop the in-flight fallback.+ this.copyShortcutToken += 1;+ if (this.clearSelectionAfterCopy) {+ this.clearSelectionAfterCopy = false;+ this.clearSelection();+ }+ };+private readonly onPaste = (event: ClipboardEvent) => {// Always suppress the browser's default insertion: content the textarea// would receive (for example an html-only clipboard converted to text)@@ -1384,6 +1446,7 @@ export class GhosttyTerminalSurface {this.input.addEventListener("blur", this.onBlur);this.input.addEventListener("input", this.onInput);this.input.addEventListener("paste", this.onPaste);+ this.input.addEventListener("copy", this.onCopyEvent);this.input.addEventListener("compositionstart", this.onCompositionStart);this.input.addEventListener("compositionend", this.onCompositionEnd);this.canvas.addEventListener("pointerdown", this.onPointerDown);@@ -1408,6 +1471,7 @@ export class GhosttyTerminalSurface {this.input.removeEventListener("blur", this.onBlur);this.input.removeEventListener("input", this.onInput);this.input.removeEventListener("paste", this.onPaste);+ this.input.removeEventListener("copy", this.onCopyEvent);this.input.removeEventListener("compositionstart", this.onCompositionStart);this.input.removeEventListener("compositionend", this.onCompositionEnd);this.canvas.removeEventListener("pointerdown", this.onPointerDown);diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex 4e4d4baa1..f99d4d34b 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -1189,6 +1189,7 @@ export interface LocalApi {items: readonly ContextMenuItem<T>[],position?: { x: number; y: number },) => Promise<T | null>;+ close: () => Promise<void>;};persistence: {getClientSettings: () => Promise<ClientSettings | null>;