The best way to control Claude Code, Codex and more from any computer or phone
fix(web): forward native Copy and Cut from server browser tabs (#26633)
Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
shivam committed
Oct 31, 2026 at 14:31 UTC
cde362057742481f47c9a67875a60f05ccae21d8
2 files changed
+169
-47
apps/web/src/browser/ServerBrowserSurface.browser.test.tsx
+140
-41
@@ -1,102 +1,201 @@
1
-import { EnvironmentId, ThreadId } from "@t3tools/contracts";
1
+import { EnvironmentId } from "@t3tools/contracts";
2
import type {
3
+ PreviewStreamControl,
4
PreviewStreamEvents,
5
PreviewStreamInput,
6
} from "@t3tools/client-runtime/preview/server-browser-stream";
6
-
7
-import "~/index.css";
7
import { describe, expect, it, vi } from "vite-plus/test";
8
+import { userEvent } from "vite-plus/test/browser";
9
10
-import { render } from "../../test/render";
10
+import { act, render } from "../../test/render";
11
12
const mocks = vi.hoisted(() => ({
13
- send: vi.fn<(input: PreviewStreamInput) => void>(),
14
- connect: vi.fn(),
15
- events: null as PreviewStreamEvents | null,
13
+ createClient: vi.fn<(target: unknown, handlers: PreviewStreamEvents) => unknown>(),
14
+ sent: [] as PreviewStreamInput[],
15
+ access: { url: "ws://preview.test", token: "test" },
16
painted: null as (() => void) | null,
17
}));
18
19
vi.mock(import("@t3tools/client-runtime/preview/server-browser-stream"), async (original) => ({
20
...(await original()),
21
+ createPreviewStreamClient: mocks.createClient as never,
22
createPreviewFramePainter: (_canvas, onPainted) => {
23
mocks.painted = onPainted ?? null;
24
return { paint: () => undefined, stop: () => undefined };
25
},
25
- createPreviewStreamClient: (_options, events) => {
26
- mocks.events = events;
27
- mocks.connect();
28
- return { send: mocks.send, stop: () => undefined } as never;
29
- },
26
}));
27
28
vi.mock(import("~/state/previewStream"), async (original) => ({
29
...(await original()),
34
- usePreviewStreamAccess: () => ({}) as never,
30
+ usePreviewStreamAccess: () => mocks.access as never,
31
}));
32
33
import { ServerBrowserSurface } from "./ServerBrowserSurface";
34
39
-async function renderSurface() {
40
- mocks.send.mockReset();
41
- mocks.connect.mockReset();
35
+function setup() {
36
+ mocks.sent.length = 0;
37
+ mocks.painted = null;
38
+ mocks.createClient.mockReset().mockImplementation(() => ({
39
+ send: (input: PreviewStreamInput) => mocks.sent.push(input),
40
+ stop: () => undefined,
41
+ }));
42
+}
43
+
44
+async function renderSurface(controller: PreviewStreamControl["controller"]) {
45
const container = document.createElement("div");
43
- container.style.cssText = "width: 400px; height: 300px;";
46
+ container.style.cssText = "width: 400px; height: 300px; display: flex;";
47
await using stack = new AsyncDisposableStack();
45
- stack.use(
48
+ const screen = stack.use(
49
await render(
50
<ServerBrowserSurface
48
- environmentId={EnvironmentId.make("environment-1")}
49
- threadId={ThreadId.make("thread-1")}
50
- tabId="tab-1"
51
+ environmentId={EnvironmentId.make("environment-copy")}
52
+ threadId="thread-copy"
53
+ tabId="tab-copy"
54
visible
55
+ followSize={false}
56
+ className="flex-1"
57
/>,
58
{ container },
59
),
60
);
56
- const canvas = container.querySelector("canvas");
57
- if (!canvas) throw new Error("The surface did not render its canvas.");
58
- // The stream connects once the surface has measured its size.
59
- await vi.waitFor(() => expect(mocks.connect).toHaveBeenCalled());
60
- return Object.assign(stack.move(), { canvas });
61
+ await vi.waitFor(() => expect(mocks.createClient).toHaveBeenCalled());
62
+ const handlers = mocks.createClient.mock.calls.at(-1)![1];
63
+ await act(() =>
64
+ handlers.onControl?.({ canOperate: true, controller, generation: 1, dialog: null }),
65
+ );
66
+ mocks.sent.length = 0;
67
+ const input = container.querySelector("textarea")!;
68
+ const canvas = container.querySelector("canvas")!;
69
+ stack.move();
70
+ return { screen, input, canvas };
71
}
72
73
+const keys = () => mocks.sent.filter((input) => input.type === "key");
74
+
75
+describe("ServerBrowserSurface clipboard commands", () => {
76
+ it("sends a native Copy or Cut menu command to the page once", async () => {
77
+ setup();
78
+ const { screen, input, canvas } = await renderSurface("you");
79
+ await using _screen = screen;
80
+ // Chromium runs a script Copy or Cut only during a user gesture, as a menu click is.
81
+ await userEvent.click(canvas);
82
+ input.focus();
83
+ mocks.sent.length = 0;
84
+
85
+ // Like Electron's webContents.copy(): the browser's Copy command, with no key.
86
+ expect(document.execCommand("copy")).toBe(true);
87
+ expect(keys()).toEqual([
88
+ { type: "key", action: "down", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
89
+ { type: "key", action: "up", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
90
+ ]);
91
+
92
+ mocks.sent.length = 0;
93
+ expect(document.execCommand("cut")).toBe(true);
94
+ expect(input.value).toBe("\u200b");
95
+ expect(keys()).toEqual([
96
+ { type: "key", action: "down", key: "x", code: "KeyX", keyCode: 88, modifiers: 2 },
97
+ { type: "key", action: "up", key: "x", code: "KeyX", keyCode: 88, modifiers: 2 },
98
+ ]);
99
+ });
100
+
101
+ it("sends a keyboard Copy or Cut once and leaves menu Copy working after any shortcut", async () => {
102
+ setup();
103
+ const { screen, input, canvas } = await renderSurface("you");
104
+ await using _screen = screen;
105
+ await userEvent.click(canvas);
106
+ input.focus();
107
+ const prevented: boolean[] = [];
108
+ const onKeyDown = (event: KeyboardEvent) => {
109
+ if (/^[cx]$/i.test(event.key)) prevented.push(event.defaultPrevented);
110
+ };
111
+ window.addEventListener("keydown", onKeyDown);
112
+ using _listener = { [Symbol.dispose]: () => window.removeEventListener("keydown", onKeyDown) };
113
+
114
+ // An unprevented copy or cut key also makes the browser fire copy or cut: here Chromium's
115
+ // Ctrl key binding, on macOS Electron's menu after the Meta keyup.
116
+ for (const [shortcut, cancels] of [
117
+ ["{Control>}x{/Control}", true],
118
+ ["{Control>}c{/Control}", true],
119
+ ["{Meta>}{x>}{/Meta}{/x}", true],
120
+ ["{Control>}{Shift>}c{/Shift}{/Control}", false],
121
+ ["{Control>}{Alt>}x{/Alt}{/Control}", false],
122
+ ] as const) {
123
+ mocks.sent.length = 0;
124
+ prevented.length = 0;
125
+ await userEvent.keyboard(shortcut);
126
+ expect(prevented, shortcut).toEqual([cancels]);
127
+ expect(keys().filter((key) => /^[cx]$/i.test(key.key)).length, shortcut).toBe(2);
128
+ expect(input.value).toBe("\u200b");
129
+
130
+ mocks.sent.length = 0;
131
+ expect(document.execCommand("copy")).toBe(true);
132
+ expect(keys(), shortcut).toEqual([
133
+ { type: "key", action: "down", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
134
+ { type: "key", action: "up", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
135
+ ]);
136
+ }
137
+ });
138
+
139
+ it("sends nothing when another viewer controls the page", async () => {
140
+ setup();
141
+ const { screen, input } = await renderSurface("another-viewer");
142
+ await using _screen = screen;
143
+
144
+ expect(
145
+ input.dispatchEvent(new ClipboardEvent("copy", { bubbles: true, cancelable: true })),
146
+ ).toBe(false);
147
+ expect(
148
+ input.dispatchEvent(new ClipboardEvent("cut", { bubbles: true, cancelable: true })),
149
+ ).toBe(false);
150
+ expect(mocks.sent).toEqual([]);
151
+ });
152
+});
153
+
154
const mouseUp = (canvas: HTMLCanvasElement, button: number) => {
155
const event = new MouseEvent("mouseup", { button, bubbles: true, cancelable: true });
156
canvas.dispatchEvent(event);
157
return event;
158
};
159
69
-describe("ServerBrowserSurface", () => {
160
+describe("ServerBrowserSurface history", () => {
161
it("routes mouse thumb buttons to the preview's history instead of the app", async () => {
71
- await using surface = await renderSurface();
72
- const { canvas } = surface;
162
+ setup();
163
+ const { screen, input } = await renderSurface("you");
164
+ await using _screen = screen;
165
+ const canvas = input.closest("[data-server-browser-surface]")!.querySelector("canvas")!;
166
167
expect(mouseUp(canvas, 3).defaultPrevented).toBe(true);
168
expect(mouseUp(canvas, 4).defaultPrevented).toBe(true);
76
- expect(mocks.send.mock.calls).toEqual([
77
- [{ type: "history", delta: -1 }],
78
- [{ type: "history", delta: 1 }],
169
+ expect(mocks.sent).toEqual([
170
+ { type: "history", delta: -1 },
171
+ { type: "history", delta: 1 },
172
]);
173
});
174
175
it("leaves other mouse buttons alone", async () => {
83
- await using surface = await renderSurface();
84
- const { canvas } = surface;
176
+ setup();
177
+ const { screen, input } = await renderSurface("you");
178
+ await using _screen = screen;
179
+ const canvas = input.closest("[data-server-browser-surface]")!.querySelector("canvas")!;
180
181
expect(mouseUp(canvas, 0).defaultPrevented).toBe(false);
87
- expect(mocks.send).not.toHaveBeenCalled();
182
+ expect(mocks.sent).toEqual([]);
183
});
184
185
it("does not forward thumb-button presses to the page", async () => {
91
- await using surface = await renderSurface();
92
- const { canvas } = surface;
186
+ setup();
187
+ const { screen, input } = await renderSurface("you");
188
+ await using _screen = screen;
189
+ const canvas = input.closest("[data-server-browser-surface]")!.querySelector("canvas")!;
190
canvas.width = 400;
191
canvas.height = 300;
192
// Synthetic pointers have no active pointer id to capture.
193
canvas.setPointerCapture = () => undefined;
97
- mocks.painted?.();
98
- mocks.events?.onViewport({ width: 400, height: 300 });
99
- mocks.events?.onControl?.({ canOperate: true, controller: "you", generation: 1, dialog: null });
194
+ const handlers = mocks.createClient.mock.calls.at(-1)![1];
195
+ await act(() => {
196
+ mocks.painted?.();
197
+ handlers.onViewport({ width: 400, height: 300 });
198
+ });
199
const { left, top } = canvas.getBoundingClientRect();
200
const press = (type: "pointerdown" | "pointerup", button: number) =>
201
canvas.dispatchEvent(
@@ -109,7 +208,7 @@ describe("ServerBrowserSurface", () => {
208
bubbles: true,
209
}),
210
);
112
- const mouseInputs = () => mocks.send.mock.calls.filter(([input]) => input.type === "mouse");
211
+ const mouseInputs = () => mocks.sent.filter((input) => input.type === "mouse");
212
213
for (const button of [3, 4]) {
214
press("pointerdown", button);
apps/web/src/browser/ServerBrowserSurface.tsx
+29
-6
@@ -20,6 +20,7 @@ import type {
20
PreviewViewportSetting,
21
} from "@t3tools/contracts";
22
import {
23
+ type ClipboardEvent,
24
type FormEvent,
25
type KeyboardEvent,
26
type MouseEvent,
@@ -57,6 +58,9 @@ const PROBE_REUSE_MS = 10_000;
58
const INPUT_SENTINEL = "\u200b";
59
const BACKSPACE = { key: "Backspace", code: "Backspace", keyCode: 8 } as const;
60
const DELETE = { key: "Delete", code: "Delete", keyCode: 46 } as const;
61
+const COPY = { key: "c", code: "KeyC", keyCode: 67 } as const;
62
+const CUT = { key: "x", code: "KeyX", keyCode: 88 } as const;
63
+const CTRL = 2;
64
const MAX_UNAUTHORIZED_REFUSALS = 3;
65
const TAP_SLOP_PX = 8;
66
const MULTI_CLICK_MS = 500;
@@ -649,9 +653,20 @@ export function ServerBrowserSurface(props: {
653
textarea.setSelectionRange(INPUT_SENTINEL.length, INPUT_SENTINEL.length);
654
};
655
652
- const sendKeyPress = (key: typeof BACKSPACE | typeof DELETE) => {
653
- send({ type: "key", action: "down", ...key, modifiers: 0 });
654
- send({ type: "key", action: "up", ...key, modifiers: 0 });
656
+ const sendKeyPress = (
657
+ key: typeof BACKSPACE | typeof DELETE | typeof COPY | typeof CUT,
658
+ modifiers = 0,
659
+ ) => {
660
+ send({ type: "key", action: "down", ...key, modifiers });
661
+ send({ type: "key", action: "up", ...key, modifiers });
662
+ };
663
+
664
+ // Edit menu Copy and Cut fire no key, so send the shortcut the server copies on.
665
+ const handleClipboard = (key: typeof COPY | typeof CUT, event: ClipboardEvent) => {
666
+ // Keep the sentinel off the clipboard.
667
+ event.preventDefault();
668
+ if (controlRef.current?.controller !== "you") return;
669
+ sendKeyPress(key, CTRL);
670
};
671
672
const handleKey = (action: "down" | "up", event: KeyboardEvent<HTMLTextAreaElement>) => {
@@ -696,6 +711,15 @@ export function ServerBrowserSurface(props: {
711
action === "down" &&
712
!shortcut &&
713
(text !== undefined || event.key === "Backspace" || event.key === "Delete");
714
+ // The key copies or cuts in the page, so stop the browser's own copy or cut repeating it.
715
+ if (
716
+ event.ctrlKey !== event.metaKey &&
717
+ !event.altKey &&
718
+ !event.shiftKey &&
719
+ ["c", "x"].includes(event.key.toLowerCase())
720
+ ) {
721
+ event.preventDefault();
722
+ }
723
if (shortcut) return;
724
event.preventDefault();
725
event.stopPropagation();
@@ -790,9 +814,8 @@ export function ServerBrowserSurface(props: {
814
if (text) send({ type: "text", text });
815
resetInput(event.currentTarget);
816
}}
793
- // Keep the sentinel off the clipboard.
794
- onCopy={(event) => event.preventDefault()}
795
- onCut={(event) => event.preventDefault()}
817
+ onCopy={(event) => handleClipboard(COPY, event)}
818
+ onCut={(event) => handleClipboard(CUT, event)}
819
onPaste={(event) => {
820
event.preventDefault();
821
const text = event.clipboardData.getData("text/plain");