Skip to content

Commit 02b0311

Browse files
donjor-agent[bot]donjor
authored andcommitted
fix(web): terminal OSC 52 copies reach the client clipboard (#1790)
## Problem Copying out of a tmux or zmux terminal in T3 never reaches the client clipboard: drag-select and copy-mode `y` both fail. tmux copies by writing OSC 52 to each client, but libghostty-vt has no clipboard callback, so the web terminal drops it. Closes #1789 - [ ] Live OSC 52 writes from a terminal land in the focused client's clipboard - [ ] Replayed history never rewrites the clipboard, and OSC 52 read queries get no reply ## Change `osc52Clipboard.fork.ts` scans live terminal output for OSC 52 and calls `navigator.clipboard.writeText`. - **Terminators:** BEL and ST - **Split chunks:** buffered, 1 MiB cap - **Reset replay:** clears state, never copies - **`?` read query:** ignored, never answered - **Shared sessions:** focused viewer only `ThreadTerminalDrawer.tsx` gains two `zmux-estate/osc52-clipboard` fork-hook lines. Retire when upstream `pingdotgg#8361` lands. ## Scope and approval Fork bugfix for #1789. Desktop inherits it through the web app; the native mobile terminal is untouched. ## Verification Dev app in the T3 Browser panel, a throwaway tmux server with `set-clipboard on`, and a spy on `navigator.clipboard.writeText`. **Before** (hook reverted): copy-mode selection, then `y`: no clipboard write. ![before: copy-mode selection, no clipboard write](https://github.com/user-attachments/assets/b4e7906b-b4e6-46b6-8990-cd642b2d0acd) **After:** copy-mode selection, then `y`: `writeText("yanked-from-tmux-copy-mode")` resolves. ![after: copy-mode selection copied](https://github.com/user-attachments/assets/fec9eaac-7216-4d91-8503-7f40a3adf763) The clipboard is not visible on screen; the spy output is the proof. - [x] Direct `printf` OSC 52: copied - [x] tmux copy-mode `y`: copied - [x] tmux mouse drag-select: copied - [x] Drag without focus: write refused, swallowed - [x] Hook reverted, same `y`: no write - [x] `vp test run` osc52 test → exit 0 - [x] `vp run typecheck` (apps/web) → exit 0 - [x] `vp run fork:ci` → exit 0 - [ ] Not checked: desktop clipboard readback The Browser panel has its own clipboard, so the desktop clipboard was not read back. Claude Opus 5.5 via Claude Code in T3 Code. ## Fork trailers Squashes: - d17fee7 fix(web): terminal OSC 52 copies reach the client clipboard (#1790) (#1790) - 7b801e6 fixup! fix(web): terminal OSC 52 copies reach the client clipboard (#1790) (#1790) Fork-Domain: zmux-estate Fork-Tier: bugfix Fork-Upstreamable: yes Co-authored-by: donjor <[email protected]>
1 parent 850335e commit 02b0311

3 files changed

Lines changed: 133 additions & 1 deletion

File tree

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { writeToRunningTerminalFork } from "../terminal/terminalInput.fork"; // fork-hook: zmux-estate/failed-terminal-input
2+
import { copyOsc52ClipboardFork } from "../terminal/osc52Clipboard.fork"; // fork-hook: zmux-estate/osc52-clipboard-import
23
import { useAtomMount, useAtomValue } from "@effect/atom-react";
34
import {
45
isAtomCommandInterrupted,
@@ -241,6 +242,7 @@ export function writeTerminalOutputUpdate(
241242
terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write" | "clearSelection">,
242243
update: TerminalOutputUpdate,
243244
): void {
245+
copyOsc52ClipboardFork(terminal, update); // fork-hook: zmux-estate/osc52-clipboard
244246
if (update.type === "reset") {
245247
terminal.resetAndWrite(update.data);
246248
terminal.clearSelection(); // fork-hook: zmux-estate/terminal-selection-reset
@@ -730,7 +732,7 @@ function TerminalSessionViewport({
730732
void retargetTerminal();
731733
}, [attached, launchIdentity]);
732734
const writeTerminal = useEffectEvent((data: string) => {
733-
return writeToRunningTerminalFork(terminalSession.status, () =>
735+
return writeToRunningTerminalFork(readTerminalSession().status, () =>
734736
runTerminalWrite({
735737
environmentId,
736738
input: { threadId, terminalId, attachmentId, data },
@@ -765,6 +767,7 @@ function TerminalSessionViewport({
765767
}, 0);
766768
}
767769
if (version > 0) synchronizedStatusRef.current = status;
770+
terminal.input.readOnly = !hasTerminalWriteAccess() || status !== "running"; // fork-hook: zmux-estate/failed-terminal-readonly
768771
},
769772
);
770773
const openLinkInPreview = useEffectEvent(
@@ -775,6 +778,8 @@ function TerminalSessionViewport({
775778
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sets the terminal input's readOnly from the operate grant and consumes a pending focus request
776779
useLayoutEffect(() => {
777780
if (terminalRef.current) terminalRef.current.input.readOnly = !canOperateTerminal;
781+
if (terminalRef.current && readTerminalSession().status !== "running")
782+
terminalRef.current.input.readOnly = true; // fork-hook: zmux-estate/failed-terminal-readonly
778783
if (canOperateTerminal && visibleRef.current)
779784
consumePendingTerminalFocus(threadRef, terminalId);
780785
}, [canOperateTerminal, terminalId, threadRef]);
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { INITIAL_TERMINAL_OUTPUT_CURSOR } from "@t3tools/client-runtime/state/terminal";
2+
import { describe, expect, it } from "vite-plus/test";
3+
4+
import { copyOsc52ClipboardFork } from "./osc52Clipboard.fork";
5+
6+
const cursor = INITIAL_TERMINAL_OUTPUT_CURSOR;
7+
// tmux leaves the selection field empty.
8+
const osc52 = (text: string, end = "\x07") =>
9+
`\x1b]52;;${btoa(String.fromCharCode(...new TextEncoder().encode(text)))}${end}`;
10+
11+
function feed(updates: ReadonlyArray<{ type: "append" | "reset"; data: string }>) {
12+
const terminal = {};
13+
const copied: string[] = [];
14+
for (const update of updates) {
15+
copyOsc52ClipboardFork(terminal, { ...update, cursor }, (text) => copied.push(text));
16+
}
17+
return copied;
18+
}
19+
20+
describe("OSC 52 clipboard", () => {
21+
it("copies live writes, including UTF-8, ST-terminated, and chunk-split sequences", () => {
22+
const split = osc52("split ✓", "\x1b\\");
23+
expect(
24+
feed([
25+
{ type: "append", data: `before${osc52("tmux yank")}after` },
26+
{ type: "append", data: `x${split.slice(0, 3)}` },
27+
{ type: "append", data: `${split.slice(3, 12)}` },
28+
{ type: "append", data: `${split.slice(12)}y` },
29+
]),
30+
).toEqual(["tmux yank", "split ✓"]);
31+
});
32+
33+
it("never copies replayed history or answers read queries", () => {
34+
expect(
35+
feed([
36+
{ type: "reset", data: osc52("old copy") },
37+
{ type: "append", data: "\x1b]52;c;?\x07" },
38+
{ type: "append", data: osc52("half").slice(0, 8) },
39+
{ type: "reset", data: "" },
40+
{ type: "append", data: `${osc52("half").slice(8)}` },
41+
]),
42+
).toEqual([]);
43+
});
44+
});
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import type { TerminalOutputUpdate } from "@t3tools/client-runtime/state/terminal";
2+
3+
// libghostty-vt has no clipboard callback, so tmux `set-clipboard` copies
4+
// (OSC 52) are read from the live output stream here. Retire when upstream
5+
// `pingdotgg/t3code#8361` lands.
6+
const OSC52_PREFIX = "\x1b]52;";
7+
// A split sequence is held until its terminator arrives; anything larger is
8+
// not a plausible copy and is dropped rather than buffered forever.
9+
const MAX_PENDING_LENGTH = 1 << 20;
10+
11+
const pendingByTerminal = new WeakMap<object, string>();
12+
13+
function writeClipboardText(text: string): void {
14+
// Rejects unless this client's document has focus, so only the focused
15+
// viewer of a shared session takes the copy.
16+
void navigator.clipboard?.writeText(text).catch(() => undefined);
17+
}
18+
19+
function decodeOsc52Payload(payload: string): string | null {
20+
const separator = payload.indexOf(";");
21+
if (separator === -1) return null;
22+
const data = payload.slice(separator + 1);
23+
// `?` is a clipboard read query; answering it would leak the clipboard.
24+
if (data.length === 0 || data === "?") return null;
25+
try {
26+
const binary = atob(data);
27+
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
28+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
29+
} catch {
30+
return null;
31+
}
32+
}
33+
34+
function partialPrefixLength(text: string): number {
35+
for (let length = Math.min(OSC52_PREFIX.length - 1, text.length); length > 0; length--) {
36+
if (OSC52_PREFIX.startsWith(text.slice(-length))) return length;
37+
}
38+
return 0;
39+
}
40+
41+
function scanOsc52Clipboard(
42+
pending: string,
43+
data: string,
44+
): { readonly copied: string | null; readonly pending: string } {
45+
const text = pending + data;
46+
let copied: string | null = null;
47+
let position = 0;
48+
for (;;) {
49+
const start = text.indexOf(OSC52_PREFIX, position);
50+
if (start === -1) {
51+
const tail = partialPrefixLength(text.slice(position));
52+
return { copied, pending: tail === 0 ? "" : text.slice(-tail) };
53+
}
54+
const payloadStart = start + OSC52_PREFIX.length;
55+
const bell = text.indexOf("\x07", payloadStart);
56+
const st = text.indexOf("\x1b\\", payloadStart);
57+
const end = bell === -1 ? st : st === -1 ? bell : Math.min(bell, st);
58+
if (end === -1) {
59+
const rest = text.slice(start);
60+
return { copied, pending: rest.length > MAX_PENDING_LENGTH ? "" : rest };
61+
}
62+
copied = decodeOsc52Payload(text.slice(payloadStart, end)) ?? copied;
63+
position = end + (end === st ? 2 : 1);
64+
}
65+
}
66+
67+
// Only appended output is live; a reset replays history whose copies already
68+
// happened, so it must never rewrite the clipboard.
69+
export function copyOsc52ClipboardFork(
70+
terminal: object,
71+
update: TerminalOutputUpdate,
72+
writeText: (text: string) => void = writeClipboardText,
73+
): void {
74+
if (update.type === "none") return;
75+
if (update.type === "reset") {
76+
pendingByTerminal.delete(terminal);
77+
return;
78+
}
79+
const result = scanOsc52Clipboard(pendingByTerminal.get(terminal) ?? "", update.data);
80+
if (result.pending.length > 0) pendingByTerminal.set(terminal, result.pending);
81+
else pendingByTerminal.delete(terminal);
82+
if (result.copied !== null) writeText(result.copied);
83+
}

0 commit comments

Comments
 (0)