Skip to content

Commit 10a8bf9

Browse files
committed
fix(web): terminal paste no longer doubles when the clipboard read wins
The paste shortcut races navigator.clipboard.readText() against the browser's native paste event. The token only covered the native event landing first; when the read resolved first, the native paste that followed was sent again. A read delivered while the shortcut is held now records its text, and onPaste drops the one matching native paste. Any key event ends the gesture, so a later Edit > Paste of the same text still lands.
1 parent 78af372 commit 10a8bf9

2 files changed

Lines changed: 100 additions & 7 deletions

File tree

‎apps/web/src/terminal/ghostty/surface.test.ts‎

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ describe("GhosttyTerminalSurface visibility", () => {
9797

9898
const canvas = new TerminalTestElement();
9999
const mount = new TerminalTestElement();
100+
let input: TerminalTestElement | undefined;
100101
const context = {
101102
canvas,
102103
beginPath() {},
@@ -116,7 +117,12 @@ describe("GhosttyTerminalSurface visibility", () => {
116117
}),
117118
};
118119
vi.stubGlobal("document", {
119-
createElement: (tag: string) => (tag === "canvas" ? canvas : new TerminalTestElement()),
120+
createElement: (tag: string) => {
121+
if (tag === "canvas") return canvas;
122+
const element = new TerminalTestElement();
123+
if (tag === "textarea") input = element;
124+
return element;
125+
},
120126
fonts: Object.assign(new EventTarget(), { load: async () => [], add() {} }),
121127
});
122128
vi.stubGlobal(
@@ -179,6 +185,31 @@ describe("GhosttyTerminalSurface visibility", () => {
179185
}),
180186
);
181187
},
188+
key(
189+
key: string,
190+
modifiers: { ctrlKey?: boolean; metaKey?: boolean; shiftKey?: boolean },
191+
type: "keydown" | "keyup" = "keydown",
192+
) {
193+
input?.dispatchEvent(
194+
Object.assign(new Event(type, { cancelable: true }), {
195+
key,
196+
code: `Key${key.toUpperCase()}`,
197+
altKey: false,
198+
ctrlKey: false,
199+
metaKey: false,
200+
shiftKey: false,
201+
...modifiers,
202+
getModifierState: () => false,
203+
}),
204+
);
205+
},
206+
paste(text: string) {
207+
input?.dispatchEvent(
208+
Object.assign(new Event("paste", { cancelable: true }), {
209+
clipboardData: { getData: () => text },
210+
}),
211+
);
212+
},
182213
async create(options: Partial<GhosttyTerminalSurfaceOptions> = {}) {
183214
const surface = await GhosttyTerminalSurface.create(mount as unknown as HTMLElement, {
184215
theme: {
@@ -305,6 +336,49 @@ describe("GhosttyTerminalSurface visibility", () => {
305336
expect(readText).not.toHaveBeenCalled();
306337
});
307338

339+
it("pastes once when the shortcut's clipboard read lands before the native paste", async () => {
340+
const harness = createHarness();
341+
const readText = vi.fn(async () => "echo hi");
342+
vi.stubGlobal("navigator", { platform: "MacIntel", clipboard: { readText } });
343+
await harness.create({ beforeKey: () => true });
344+
345+
harness.key("v", { metaKey: true });
346+
await readText.mock.results[0]?.value;
347+
expect(harness.onData).toHaveBeenCalledTimes(1);
348+
harness.paste("echo hi");
349+
harness.key("v", { metaKey: true }, "keyup");
350+
expect(harness.onData).toHaveBeenCalledTimes(1);
351+
352+
// The next paste gesture is a new paste, not the tail of the last one, and
353+
// its read must not land on top of the native paste that won.
354+
harness.key("v", { metaKey: true });
355+
harness.paste("echo hi");
356+
await readText.mock.results[1]?.value;
357+
expect(harness.onData).toHaveBeenCalledTimes(2);
358+
});
359+
360+
it("keeps a later menu paste once the shortcut that only the read served ends", async () => {
361+
const harness = createHarness();
362+
const readText = vi.fn(async () => "echo hi");
363+
vi.stubGlobal("navigator", { platform: "MacIntel", clipboard: { readText } });
364+
await harness.create({ beforeKey: () => true });
365+
366+
// No native paste for the shortcut: the read is the only delivery. An
367+
// Edit → Paste of the same text afterwards has no keydown of its own.
368+
harness.key("v", { metaKey: true });
369+
await readText.mock.results[0]?.value;
370+
harness.key("v", { metaKey: true }, "keyup");
371+
harness.paste("echo hi");
372+
expect(harness.onData).toHaveBeenCalledTimes(2);
373+
374+
// Same when the read only settles after the shortcut was released.
375+
harness.key("v", { metaKey: true });
376+
harness.key("v", { metaKey: true }, "keyup");
377+
await readText.mock.results[1]?.value;
378+
harness.paste("echo hi");
379+
expect(harness.onData).toHaveBeenCalledTimes(4);
380+
});
381+
308382
it("starts a selection when dragging from a link", async () => {
309383
const harness = createHarness();
310384
const onLinkActivate = vi.fn();

‎apps/web/src/terminal/ghostty/surface.ts‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,10 @@ export class GhosttyTerminalSurface {
625625
private theme: GhosttyTheme;
626626
private readonly suppressedKeyCodes = new Set<string>();
627627
private pasteShortcutToken = 0;
628+
/** Whether the paste shortcut is still held, so its native paste can still follow. */
629+
private pasteShortcutHeld = false;
630+
/** Text the held paste shortcut's clipboard read already sent. */
631+
private shortcutPasteReadText: string | null = null;
628632
private copyShortcutToken = 0;
629633
private clearSelectionAfterCopy = false;
630634
private primedCopySelection = "";
@@ -1053,6 +1057,8 @@ export class GhosttyTerminalSurface {
10531057
}
10541058

10551059
private readonly onKeyDown = (event: KeyboardEvent) => {
1060+
this.pasteShortcutHeld = false;
1061+
this.shortcutPasteReadText = null;
10561062
// Presses handled outside the terminal must also swallow their release:
10571063
// beforeKey runs side effects (keybindings, navigation sends), so it cannot
10581064
// be consulted again on keyup, and Kitty report-event-types sessions would
@@ -1118,19 +1124,24 @@ export class GhosttyTerminalSurface {
11181124
}
11191125
if (isTerminalPasteShortcut(event)) {
11201126
this.suppressedKeyCodes.add(event.code);
1127+
this.pasteShortcutHeld = true;
11211128
const clipboard = navigator.clipboard;
11221129
if (typeof clipboard?.readText === "function") {
1123-
// Race the async clipboard read against the browser's own paste event:
1124-
// the native event (dispatched synchronously with the default action)
1125-
// always claims the token first when it fires, and the read covers
1126-
// browsers whose paste shortcut produces no paste event. Not preventing
1127-
// the default keeps the native path alive when the read is denied.
1130+
// Race the async clipboard read against the browser's own paste event;
1131+
// the read covers browsers whose paste shortcut produces no paste
1132+
// event. Not preventing the default keeps the native path alive when
1133+
// the read is denied. Either side can land first: a native paste
1134+
// claims the token, and a read delivered while the shortcut is held
1135+
// records its text so the native paste that follows it is dropped in
1136+
// onPaste. The keyboard paste fires before keyup, which ends the window.
11281137
const token = ++this.pasteShortcutToken;
11291138
void clipboard.readText().then(
11301139
(text) => {
11311140
if (this.disposed || this.pasteShortcutToken !== token) return;
11321141
this.pasteShortcutToken += 1;
1133-
if (text.length > 0) this.options.onData(this.core.encodePaste(text));
1142+
if (text.length === 0) return;
1143+
if (this.pasteShortcutHeld) this.shortcutPasteReadText = text;
1144+
this.options.onData(this.core.encodePaste(text));
11341145
},
11351146
() => {
11361147
// Clipboard read denied; the native paste event remains the path.
@@ -1155,6 +1166,10 @@ export class GhosttyTerminalSurface {
11551166
};
11561167

11571168
private readonly onKeyUp = (event: KeyboardEvent) => {
1169+
// Any release ends the paste gesture: macOS never delivers V's keyup while
1170+
// Cmd is held, so the Cmd release is often the only one.
1171+
this.pasteShortcutHeld = false;
1172+
this.shortcutPasteReadText = null;
11581173
if (this.suppressedKeyCodes.delete(event.code)) return;
11591174
if (isTerminalCompositionKey(event, this.composing)) {
11601175
return;
@@ -1235,6 +1250,10 @@ export class GhosttyTerminalSurface {
12351250
event.preventDefault();
12361251
const data = event.clipboardData?.getData("text/plain") ?? "";
12371252
if (data.length === 0) return;
1253+
if (data === this.shortcutPasteReadText) {
1254+
this.shortcutPasteReadText = null;
1255+
return;
1256+
}
12381257
// The native paste won the race with actual text; a pending clipboard read
12391258
// must not double. An empty native paste leaves the read as the only path.
12401259
this.pasteShortcutToken += 1;

0 commit comments

Comments
 (0)