Skip to content

Commit 22bd11b

Browse files
committed
fix(web): programs can copy to the clipboard from the terminal (OSC 52)
1 parent 7e289ae commit 22bd11b

6 files changed

Lines changed: 207 additions & 0 deletions

File tree

‎apps/web/src/components/ThreadTerminalDrawer.tsx‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,18 @@ function writeSystemMessage(terminal: GhosttyTerminalSurface, message: string):
142142
terminal.write(`\r\n[terminal] ${message}\r\n`);
143143
}
144144

145+
function copyTerminalProgramText(text: string): void {
146+
void writeTextToClipboard(text, "terminal output").catch((error: unknown) => {
147+
toastManager.add(
148+
stackedThreadToast({
149+
type: "error",
150+
title: "Failed to copy terminal output",
151+
description: error instanceof Error ? error.message : "An error occurred.",
152+
}),
153+
);
154+
});
155+
}
156+
145157
export function writeTerminalOutputUpdate(
146158
terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write">,
147159
update: TerminalOutputUpdate,
@@ -649,6 +661,7 @@ function TerminalSessionViewport({
649661
beforeKey: (event) => handleBeforeKey(event),
650662
onLinkActivate: (text, event) => handleLinkActivate(text, event),
651663
canActivateLink: (text) => canActivateTerminalLink(text),
664+
onClipboardWrite: copyTerminalProgramText,
652665
// The surface listens from construction, so a right-click can land
653666
// while `create` is still awaiting WASM — before the handler below it
654667
// exists.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { MAX_OSC52_PAYLOAD_LENGTH, Osc52Scanner } from "./osc52";
4+
5+
function base64(text: string): string {
6+
return btoa(String.fromCharCode(...new TextEncoder().encode(text)));
7+
}
8+
9+
function scan(chunks: Iterable<string>): string[] {
10+
const copies: string[] = [];
11+
const scanner = new Osc52Scanner((text) => copies.push(text));
12+
for (const chunk of chunks) scanner.write(chunk);
13+
return copies;
14+
}
15+
16+
describe("Osc52Scanner", () => {
17+
it("copies writes terminated by BEL or ST, however the output is chunked", () => {
18+
const stream = [
19+
"prompt$ ",
20+
`\x1b]52;c;${base64("héllo 👋")}\x07`,
21+
"\x1b]0;window title\x07",
22+
"\x1b]52;c;?\x07",
23+
`\x1b]52;;${base64("from tmux")}\x1b\\`,
24+
"done\r\n",
25+
].join("");
26+
27+
expect(scan([stream])).toEqual(["héllo 👋", "from tmux"]);
28+
expect(scan(stream)).toEqual(["héllo 👋", "from tmux"]);
29+
});
30+
31+
it("drops a write longer than the payload limit and keeps scanning", () => {
32+
const oversized = `\x1b]52;c;${"A".repeat(MAX_OSC52_PAYLOAD_LENGTH)}\x07`;
33+
34+
expect(
35+
scan([oversized.slice(0, 4096), oversized.slice(4096), `\x1b]52;c;${base64("next")}\x07`]),
36+
).toEqual(["next"]);
37+
});
38+
});
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
// libghostty-vt has no clipboard callback, so OSC 52 writes are framed here,
2+
// alongside the bytes Ghostty parses. Reads (`?`) are never answered: replying
3+
// would send this client's clipboard to whatever process asked for it.
4+
5+
// Base64 characters, about 768 KiB of copied text. Longer sequences are dropped
6+
// instead of buffered so a broken stream cannot grow memory without bound.
7+
export const MAX_OSC52_PAYLOAD_LENGTH = 1024 * 1024;
8+
9+
const PREFIX = "52;";
10+
// BEL ends the OSC, ESC may start ST, CAN and SUB abort it.
11+
// oxlint-disable-next-line no-control-regex -- matching VT control bytes is the point.
12+
const OSC_CONTROL = /[\x07\x18\x1a\x1b]/g;
13+
// The browser has one clipboard, so the system and both X11 selections map to it.
14+
const SELECTION = /^[cps0-7]*$/;
15+
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
16+
17+
function decodeClipboardWrite(body: string): string | null {
18+
const separator = body.indexOf(";", PREFIX.length);
19+
if (separator === -1) return null;
20+
const selection = body.slice(PREFIX.length, separator);
21+
if (!SELECTION.test(selection) || (selection !== "" && !/[cps]/.test(selection))) return null;
22+
const encoded = body.slice(separator + 1);
23+
if (encoded === "" || encoded === "?") return null;
24+
try {
25+
const binary = atob(encoded);
26+
const bytes = new Uint8Array(binary.length);
27+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
28+
const text = decoder.decode(bytes);
29+
return text.length > 0 ? text : null;
30+
} catch {
31+
return null;
32+
}
33+
}
34+
35+
/** Streams live terminal output and reports each complete OSC 52 clipboard write. */
36+
export class Osc52Scanner {
37+
private state: "ground" | "escape" | "osc" | "oscEscape" = "ground";
38+
// The OSC body so far, or null once it can no longer be a clipboard write.
39+
private body: string | null = null;
40+
private readonly onCopy: (text: string) => void;
41+
42+
constructor(onCopy: (text: string) => void) {
43+
this.onCopy = onCopy;
44+
}
45+
46+
/** Forgets any partial sequence, for when the terminal's contents are replaced. */
47+
reset(): void {
48+
this.state = "ground";
49+
this.body = null;
50+
}
51+
52+
write(data: string): void {
53+
let index = 0;
54+
while (index < data.length) {
55+
switch (this.state) {
56+
case "ground": {
57+
const escape = data.indexOf("\x1b", index);
58+
if (escape === -1) return;
59+
this.state = "escape";
60+
index = escape + 1;
61+
break;
62+
}
63+
case "escape": {
64+
const char = data[index];
65+
index += 1;
66+
if (char === "]") {
67+
this.state = "osc";
68+
this.body = "";
69+
} else if (char !== "\x1b") {
70+
this.state = "ground";
71+
}
72+
break;
73+
}
74+
case "osc": {
75+
OSC_CONTROL.lastIndex = index;
76+
const control = OSC_CONTROL.exec(data);
77+
const end = control?.index ?? data.length;
78+
this.append(data.slice(index, end));
79+
if (!control) return;
80+
index = end + 1;
81+
if (control[0] === "\x07") this.finish();
82+
else if (control[0] === "\x1b") this.state = "oscEscape";
83+
else this.reset();
84+
break;
85+
}
86+
case "oscEscape": {
87+
if (data[index] === "\\") {
88+
index += 1;
89+
this.finish();
90+
} else {
91+
// Any other escape aborts the OSC and begins a new sequence.
92+
this.state = "escape";
93+
this.body = null;
94+
}
95+
break;
96+
}
97+
}
98+
}
99+
}
100+
101+
private append(text: string): void {
102+
if (this.body === null || text.length === 0) return;
103+
if (this.body.length + text.length > MAX_OSC52_PAYLOAD_LENGTH) {
104+
this.body = null;
105+
return;
106+
}
107+
const checkPrefix = this.body.length < PREFIX.length;
108+
this.body += text;
109+
if (checkPrefix && !PREFIX.startsWith(this.body.slice(0, PREFIX.length))) this.body = null;
110+
}
111+
112+
private finish(): void {
113+
const body = this.body;
114+
this.reset();
115+
const text = body === null ? null : decodeClipboardWrite(body);
116+
if (text !== null) this.onCopy(text);
117+
}
118+
}

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1177,6 +1177,26 @@ describe("GhosttyTerminalSurface visibility", () => {
11771177
expect(harness.renderedSnapshot.rowData[0]?.text).toContain("ready");
11781178
},
11791179
);
1180+
1181+
it("copies OSC 52 only from live output of the focused terminal", async () => {
1182+
const harness = createHarness();
1183+
const copy = vi.fn();
1184+
const surface = await harness.create({ onClipboardWrite: copy });
1185+
const sequence = "\x1b]52;c;aGVsbG8=\x07";
1186+
1187+
surface.write(sequence);
1188+
surface.focus();
1189+
surface.resetAndWrite(sequence);
1190+
surface.write("\x1b]52;c;aGVs");
1191+
surface.resetAndWrite("replayed history");
1192+
surface.write("bG8=\x07");
1193+
surface.write("\x1b]52;c;?\x07");
1194+
expect(copy).not.toHaveBeenCalled();
1195+
expect(harness.onData).not.toHaveBeenCalled();
1196+
1197+
surface.write(sequence);
1198+
expect(copy.mock.calls).toEqual([["hello"]]);
1199+
});
11801200
});
11811201

11821202
const cell = (text: string): GhosttyCell => ({

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
type GhosttyCellRange,
1515
type GhosttyCellMetrics,
1616
} from "./renderer";
17+
import { Osc52Scanner } from "./osc52";
1718
import symbolsFontUrl from "./fonts/SymbolsNerdFontMono-Regular.woff2?url";
1819
import { isMonospaceFamily } from "../../appearanceFonts";
1920
import { observeResize } from "../../lib/observeResize";
@@ -512,6 +513,12 @@ export interface GhosttyTerminalSurfaceOptions {
512513
* whose Paste entry can never reach a canvas terminal.
513514
*/
514515
readonly onContextMenu?: (event: MouseEvent) => void;
516+
/**
517+
* Text a program copied with OSC 52. Only live output from the focused
518+
* terminal counts, so replayed history and background terminals never
519+
* overwrite the clipboard.
520+
*/
521+
readonly onClipboardWrite?: (text: string) => void;
515522
}
516523

517524
export class GhosttyTerminalSurface {
@@ -578,6 +585,9 @@ export class GhosttyTerminalSurface {
578585
private selectionMoved = false;
579586
private composing = false;
580587
private focused = false;
588+
private readonly osc52 = new Osc52Scanner((text) => {
589+
if (this.focused && this.visible) this.options.onClipboardWrite?.(text);
590+
});
581591
private resizeNotified = false;
582592
private canvasConfigured = false;
583593
private canvasDevicePixelRatio = 0;
@@ -739,6 +749,7 @@ export class GhosttyTerminalSurface {
739749
? undefined
740750
: () => this.cancelSynchronizedRenderTimer(),
741751
);
752+
if (this.options.onClipboardWrite) this.osc52.write(data);
742753
this.synchronizeMouseTrackingState();
743754
this.cursorOn = true;
744755
this.scrollbarDirty = true;
@@ -749,6 +760,7 @@ export class GhosttyTerminalSurface {
749760
if (this.disposed) return;
750761
this.cancelSynchronizedRenderTimer();
751762
this.lastMouseMotionData = "";
763+
this.osc52.reset();
752764
this.core.resetAndWrite(data);
753765
this.synchronizeMouseTrackingState();
754766
this.cursorOn = true;

‎docs/user/terminal.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ then copy. Cmd+A on macOS and Ctrl+Shift+A elsewhere select the same output.
1717
Ctrl+A still moves to the beginning of shell input on Windows and Linux.
1818
Jump to latest in the context menu returns to the current output.
1919

20+
On web and desktop, programs that copy through the terminal with OSC 52, such
21+
as tmux, Vim, or Claude Code's `/copy`, write to your clipboard while that
22+
terminal has focus. Copies from a terminal you are not focused on are ignored,
23+
and programs cannot read your clipboard this way. Some browsers block a copy
24+
that does not directly follow a click or key press.
25+
2026
## fish
2127

2228
T3 Code starts fish with `no-query-term`, avoiding startup waits for terminal

0 commit comments

Comments
 (0)