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.

fix(web): copy terminal selection instead of a blank clipboard (#7678)

Seth Webster21e80a063648
diff --git a/apps/web/src/terminal/ghostty/runtimeAbi.test.ts b/apps/web/src/terminal/ghostty/runtimeAbi.test.ts
index 9f9fe189b..7d4782b4b 100644
--- a/apps/web/src/terminal/ghostty/runtimeAbi.test.ts
+++ b/apps/web/src/terminal/ghostty/runtimeAbi.test.ts
@@ -320,6 +320,89 @@ describe("vendored libghostty-vt WebAssembly", () => {
call("ghostty_wasm_free_u8_array", options, 8);
});
+ it("formats a cell-drag selection installed from screen grid refs", async () => {
+ const result = await WebAssembly.instantiate(
+ decodeWasmDataUrl(wasmDataUrl).buffer as ArrayBuffer,
+ { env: { log: () => {} } },
+ );
+ const instance = result instanceof WebAssembly.Instance ? result : result.instance;
+ const memory = instance.exports.memory as WebAssembly.Memory;
+ const call = (name: string, ...args: number[]) =>
+ (instance.exports[name] as WasmFunction)(...args);
+ const alloc = (size: number) => call("ghostty_wasm_alloc_u8_array", size);
+ const free = (pointer: number, size: number) =>
+ call("ghostty_wasm_free_u8_array", pointer, size);
+ const options = alloc(8);
+ new DataView(memory.buffer, options, 8).setUint16(0, 80, true);
+ new DataView(memory.buffer, options, 8).setUint16(2, 24, true);
+ const terminalSlot = call("ghostty_wasm_alloc_opaque");
+ expect(call("ghostty_terminal_new", 0, terminalSlot, options)).toBe(0);
+ const terminal = new DataView(memory.buffer).getUint32(terminalSlot, true);
+ const input = new TextEncoder().encode("hello\r\nworld");
+ const inputPointer = alloc(input.length);
+ new Uint8Array(memory.buffer, inputPointer, input.length).set(input);
+ call("ghostty_terminal_vt_write", terminal, inputPointer, input.length);
+
+ const gridRefAt = (x: number, y: number) => {
+ const point = alloc(24);
+ const pointView = new DataView(memory.buffer, point, 24);
+ pointView.setUint32(0, 2, true);
+ pointView.setUint16(8, x, true);
+ pointView.setUint32(12, y, true);
+ const ref = alloc(12);
+ new DataView(memory.buffer, ref, 12).setUint32(0, 12, true);
+ expect(call("ghostty_terminal_grid_ref", terminal, point, ref)).toBe(0);
+ free(point, 24);
+ return ref;
+ };
+ const start = gridRefAt(0, 0);
+ const end = gridRefAt(4, 1);
+ const selection = alloc(32);
+ const selectionBytes = new Uint8Array(memory.buffer, selection, 32);
+ selectionBytes.fill(0);
+ new DataView(memory.buffer, selection, 32).setUint32(0, 32, true);
+ selectionBytes.set(new Uint8Array(memory.buffer, start, 12), 4);
+ selectionBytes.set(new Uint8Array(memory.buffer, end, 12), 16);
+ expect(call("ghostty_terminal_set", terminal, 21, selection)).toBe(0);
+
+ const formatOptions = alloc(16);
+ new Uint8Array(memory.buffer, formatOptions, 16).fill(0);
+ const formatView = new DataView(memory.buffer, formatOptions, 16);
+ formatView.setUint32(0, 16, true);
+ formatView.setUint8(8, 1);
+ formatView.setUint8(9, 1);
+ const written = call("ghostty_wasm_alloc_usize");
+ expect(
+ call("ghostty_terminal_selection_format_buf", terminal, formatOptions, 0, 0, written),
+ ).toBe(-3);
+ const outputSize = new DataView(memory.buffer, written, 4).getUint32(0, true);
+ const output = alloc(outputSize);
+ expect(
+ call(
+ "ghostty_terminal_selection_format_buf",
+ terminal,
+ formatOptions,
+ output,
+ outputSize,
+ written,
+ ),
+ ).toBe(0);
+ expect(new TextDecoder().decode(new Uint8Array(memory.buffer, output, outputSize))).toBe(
+ "hello\nworld",
+ );
+
+ free(output, outputSize);
+ call("ghostty_wasm_free_usize", written);
+ free(formatOptions, 16);
+ free(selection, 32);
+ free(end, 12);
+ free(start, 12);
+ free(inputPointer, input.length);
+ call("ghostty_terminal_free", terminal);
+ call("ghostty_wasm_free_opaque", terminalSlot);
+ free(options, 8);
+ });
+
it("uses Ghostty for mouse encoding, word selection, and OSC 8 hit testing", async () => {
const result = await WebAssembly.instantiate(
decodeWasmDataUrl(wasmDataUrl).buffer as ArrayBuffer,
diff --git a/apps/web/src/terminal/ghostty/surface.test.ts b/apps/web/src/terminal/ghostty/surface.test.ts
index c11529e0c..1102d1b0b 100644
--- a/apps/web/src/terminal/ghostty/surface.test.ts
+++ b/apps/web/src/terminal/ghostty/surface.test.ts
@@ -5,13 +5,17 @@ import {
DEFAULT_TERMINAL_FONT_FAMILY,
DEFAULT_TERMINAL_FONT_SIZE,
advanceTerminalSelectionClickSequence,
+ applyTerminalCopyEvent,
+ clearPrimedTerminalCopyInput,
ghosttyMouseButton,
isTerminalAltGraphText,
isTerminalCompositionCommitInput,
+ isTerminalCompositionKey,
isTerminalCopyShortcut,
isTerminalLinkPointerGesture,
isTerminalPasteShortcut,
loadTerminalFontFamily,
+ primeTerminalCopyInput,
shouldBlinkTerminalCursor,
shouldReportTerminalMouse,
shouldShowTerminalLinkHover,
@@ -233,6 +237,79 @@ describe("isTerminalCopyShortcut", () => {
});
});
+describe("applyTerminalCopyEvent", () => {
+ it("writes the selection and claims the fallback when clipboardData is present", () => {
+ const setData = vi.fn();
+ expect(applyTerminalCopyEvent("ls -la", { setData })).toEqual({
+ preventDefault: true,
+ claimWriteFallback: true,
+ });
+ expect(setData).toHaveBeenCalledWith("text/plain", "ls -la");
+ });
+
+ it("leaves the writeText fallback alive when clipboardData is missing", () => {
+ // Electron's edit-menu Copy often delivers a copy event with no
+ // clipboardData. Claiming that event used to skip writeText and copy the
+ // empty IME textarea, which is the blank clipboard users paste.
+ expect(applyTerminalCopyEvent("ls -la", null)).toEqual({
+ preventDefault: false,
+ claimWriteFallback: false,
+ });
+ expect(applyTerminalCopyEvent("", { setData: vi.fn() })).toEqual({
+ preventDefault: false,
+ claimWriteFallback: false,
+ });
+ });
+
+ it("primes the current selection before a copy event with no clipboardData", () => {
+ const input = {
+ value: "stale",
+ selectionStart: 0,
+ selectionEnd: 0,
+ select() {
+ this.selectionStart = 0;
+ this.selectionEnd = this.value.length;
+ },
+ };
+ primeTerminalCopyInput(input, "git status");
+ expect(applyTerminalCopyEvent("git status", null)).toEqual({
+ preventDefault: false,
+ claimWriteFallback: false,
+ });
+ expect(input.value).toBe("git status");
+ expect(input.selectionStart).toBe(0);
+ expect(input.selectionEnd).toBe(10);
+ });
+});
+
+describe("primeTerminalCopyInput", () => {
+ it("selects the Ghostty selection in the hidden textarea so native copy has text", () => {
+ const input = {
+ value: "",
+ selectionStart: 0,
+ selectionEnd: 0,
+ select() {
+ this.selectionStart = 0;
+ this.selectionEnd = this.value.length;
+ },
+ };
+ primeTerminalCopyInput(input, "git status");
+ expect(input.value).toBe("git status");
+ expect(input.selectionStart).toBe(0);
+ expect(input.selectionEnd).toBe(10);
+ clearPrimedTerminalCopyInput(input, "git status");
+ expect(input.value).toBe("");
+ });
+
+ it("does not wipe an IME candidate that replaced the primed copy", () => {
+ const input = { value: "", select() {} };
+ primeTerminalCopyInput(input, "git status");
+ input.value = "あ";
+ clearPrimedTerminalCopyInput(input, "git status");
+ expect(input.value).toBe("あ");
+ });
+});
+
describe("isTerminalPasteShortcut", () => {
const event = (overrides: Partial<Parameters<typeof isTerminalPasteShortcut>[0]> = {}) => ({
ctrlKey: false,
@@ -283,6 +360,28 @@ describe("isTerminalCompositionCommitInput", () => {
});
});
+describe("isTerminalCompositionKey", () => {
+ const event = (
+ overrides: Partial<Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">> = {},
+ ) => ({
+ isComposing: false,
+ key: "a",
+ keyCode: 65,
+ ...overrides,
+ });
+
+ it("treats in-progress IME keydowns as composition so the copy primer cannot wipe them", () => {
+ expect(isTerminalCompositionKey(event({ isComposing: true }), false)).toBe(true);
+ expect(isTerminalCompositionKey(event(), true)).toBe(true);
+ expect(isTerminalCompositionKey(event({ key: "Process" }), false)).toBe(true);
+ expect(isTerminalCompositionKey(event({ keyCode: 229 }), false)).toBe(true);
+ });
+
+ it("lets ordinary keydowns clear a primed copy", () => {
+ expect(isTerminalCompositionKey(event(), false)).toBe(false);
+ });
+});
+
describe("application mouse reporting", () => {
const event = (overrides: Partial<Parameters<typeof shouldReportTerminalMouse>[1]> = {}) => ({
ctrlKey: false,
diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts
index 9492e2d02..8ee4b633f 100644
--- a/apps/web/src/terminal/ghostty/surface.ts
+++ b/apps/web/src/terminal/ghostty/surface.ts
@@ -336,6 +336,47 @@ export function isTerminalCopyShortcut(
return isMacPlatform(platform) ? event.metaKey : event.ctrlKey;
}
+/**
+ * Canvas terminals have no DOM selection. Native copy and Electron's Edit
+ * menu `role: "copy"` both read the focused textarea, so an empty IME field
+ * writes blankness to the clipboard. Park the Ghostty selection there first.
+ */
+export function primeTerminalCopyInput(
+ input: Pick<HTMLTextAreaElement, "value" | "select">,
+ selection: string,
+): void {
+ input.value = selection;
+ if (selection.length === 0) return;
+ input.select();
+}
+
+export function clearPrimedTerminalCopyInput(
+ input: Pick<HTMLTextAreaElement, "value">,
+ primedSelection: string,
+): void {
+ // Only blank the copy we parked. The same textarea holds the IME candidate;
+ // wiping whatever is there would cancel CJK composition.
+ if (primedSelection.length === 0 || input.value !== primedSelection) return;
+ input.value = "";
+}
+
+/**
+ * Only a copy event that actually received the selection may cancel the
+ * clipboard.writeText fallback. Claiming without clipboardData (Electron's
+ * menu Copy) used to preventDefault an empty write and skip the fallback,
+ * which is how Cmd+C copied blankness.
+ */
+export function applyTerminalCopyEvent(
+ selection: string,
+ clipboardData: { setData: (type: string, data: string) => void } | null | undefined,
+): { preventDefault: boolean; claimWriteFallback: boolean } {
+ if (selection.length === 0 || !clipboardData) {
+ return { preventDefault: false, claimWriteFallback: false };
+ }
+ clipboardData.setData("text/plain", selection);
+ return { preventDefault: true, claimWriteFallback: true };
+}
+
export function isTerminalPasteShortcut(
event: Pick<KeyboardEvent, "ctrlKey" | "key" | "metaKey" | "shiftKey">,
platform = navigator.platform,
@@ -356,6 +397,14 @@ export function isTerminalCompositionCommitInput(event: Pick<InputEvent, "inputT
);
}
+/** IME keydowns must not touch the hidden textarea; it holds the candidate. */
+export function isTerminalCompositionKey(
+ event: Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">,
+ composing: boolean,
+): boolean {
+ return event.isComposing || composing || event.key === "Process" || event.keyCode === 229;
+}
+
export function isTerminalAltGraphText(
event: Pick<KeyboardEvent, "getModifierState" | "key">,
): boolean {
@@ -542,6 +591,7 @@ export class GhosttyTerminalSurface {
private pasteShortcutToken = 0;
private copyShortcutToken = 0;
private clearSelectionAfterCopy = false;
+ private primedCopySelection = "";
private wheelRemainder = 0;
private dprMedia: MediaQueryList | null = null;
// Read live on every blink decision, and watched so that dropping the
@@ -866,6 +916,7 @@ export class GhosttyTerminalSurface {
}
clearSelection(): void {
+ this.clearPrimedCopy();
this.core.clearSelection();
this.selectionEnd = null;
this.selectionAnchorScreen = null;
@@ -941,6 +992,8 @@ export class GhosttyTerminalSurface {
// 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").
+ const selection = this.getSelection();
+ this.primeCopy(selection);
if (event.shiftKey) {
event.preventDefault();
document.execCommand("copy");
@@ -955,12 +1008,10 @@ export class GhosttyTerminalSurface {
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.
+ // token first when it actually writes, and the write covers browsers
+ // whose shortcut produces no copy event. The primed textarea is what
+ // Electron's edit-menu Copy reads if it runs after this handler.
const token = ++this.copyShortcutToken;
- const selection = this.getSelection();
void Promise.resolve().then(() => {
if (this.disposed || this.copyShortcutToken !== token) return;
void clipboard.writeText(selection).then(
@@ -1013,10 +1064,12 @@ export class GhosttyTerminalSurface {
return;
}
// keyCode 229 is Safari's only signal that this keydown opens an IME
- // composition; encoding it would double the committed text.
- if (event.isComposing || this.composing || event.key === "Process" || event.keyCode === 229) {
+ // composition; encoding it would double the committed text. Do not blank
+ // the textarea first: onInput leaves the in-progress candidate there.
+ if (isTerminalCompositionKey(event, this.composing)) {
return;
}
+ this.clearPrimedCopy();
const data = this.core.encodeKey(event);
if (data.length === 0) return;
this.suppressedKeyCodes.delete(event.code);
@@ -1028,7 +1081,7 @@ export class GhosttyTerminalSurface {
private readonly onKeyUp = (event: KeyboardEvent) => {
this.updateLinkModifier(event);
if (this.suppressedKeyCodes.delete(event.code)) return;
- if (event.isComposing || this.composing || event.key === "Process" || event.keyCode === 229) {
+ if (isTerminalCompositionKey(event, this.composing)) {
return;
}
// Ghostty's encoder only emits release codes when the terminal enabled the
@@ -1072,15 +1125,32 @@ export class GhosttyTerminalSurface {
this.dprMedia.addEventListener("change", this.onDevicePixelRatioChange);
}
+ private primeCopy(selection: string): void {
+ this.primedCopySelection = selection;
+ primeTerminalCopyInput(this.input, selection);
+ }
+
+ private clearPrimedCopy(): void {
+ clearPrimedTerminalCopyInput(this.input, this.primedCopySelection);
+ this.primedCopySelection = "";
+ }
+
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();
+ const selection = this.hasSelection() ? this.getSelection() : this.input.value;
+ // Menu-role Copy never hits the keydown primer. The native action reads
+ // this.input, so park the current selection first — including when
+ // clipboardData is missing and we must not preventDefault.
+ this.primeCopy(selection);
+ const result = applyTerminalCopyEvent(selection, event.clipboardData);
+ if (result.preventDefault) event.preventDefault();
+ if (result.claimWriteFallback) {
+ // The native event actually wrote the selection; drop the in-flight
+ // writeText so a late resolution cannot clobber a later user copy.
+ this.copyShortcutToken += 1;
+ if (this.clearSelectionAfterCopy) {
+ this.clearSelectionAfterCopy = false;
+ this.clearSelection();
+ }
}
};
@@ -1098,6 +1168,7 @@ export class GhosttyTerminalSurface {
};
private readonly onCompositionStart = () => {
+ this.clearPrimedCopy();
this.clearCompositionInputSuppression();
this.composing = true;
};