Skip to content
TypeScript

fix(web): pasting into the device screen types into the device (#21197)

Jai Khurana8b26d5c98b11
diff --git a/apps/web/src/components/device/DeviceStreamView.browser.test.tsx b/apps/web/src/components/device/DeviceStreamView.browser.test.tsx
index c6229faaf44..c0efd1c0689 100644
--- a/apps/web/src/components/device/DeviceStreamView.browser.test.tsx
+++ b/apps/web/src/components/device/DeviceStreamView.browser.test.tsx
@@ -35,6 +35,7 @@ vi.mock(import("./DevicePhoneViewport"), async (original) => ({
return <></>;
},
}));
+import { pasteTextToFocusComposer } from "../chat/composerFocusRedirect";
import { DeviceStreamView } from "./DeviceStreamView";
// MJPEG frames come from the device hub, so images keep their src without loading it and a
@@ -109,7 +110,7 @@ afterEach(async () => {
vi.unstubAllGlobals();
});
-async function setup(h264 = false) {
+async function setup(h264 = false, platform: "ios" | "android" = "ios") {
const touches: unknown[] = [];
vi.useFakeTimers();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
@@ -160,6 +161,7 @@ async function setup(h264 = false) {
return Promise.resolve(new Response("prime"));
});
const sockets: Array<{ onmessage?: (event: { data: ArrayBuffer }) => void }> = [];
+ const sent: unknown[] = [];
vi.stubGlobal(
"WebSocket",
class {
@@ -169,9 +171,11 @@ async function setup(h264 = false) {
sockets.push(this);
}
onmessage?: (event: { data: ArrayBuffer }) => void;
- send(packet: Uint8Array) {
- if (packet[0] === 0x03) {
- touches.push(JSON.parse(new TextDecoder().decode(packet.subarray(1))));
+ send(message: string | Uint8Array) {
+ if (typeof message === "string") {
+ sent.push(message);
+ } else if (message[0] === 0x03) {
+ touches.push(JSON.parse(new TextDecoder().decode(message.subarray(1))));
}
}
close() {}
@@ -182,7 +186,7 @@ async function setup(h264 = false) {
hostId="local"
environmentId={EnvironmentId.make("test")}
deviceId="test"
- platform="ios"
+ platform={platform}
visible={visible}
allowPhoneView={h264}
/>
@@ -190,6 +194,7 @@ async function setup(h264 = false) {
await act(async () => root.render(view(true)));
return {
images,
+ sent,
view,
touches,
configure() {
@@ -322,3 +327,33 @@ it("keeps the 3D viewer mounted across iOS video recovery and releases it when h
expect(viewerUnmounts).toBe(1);
expect(vi.getTimerCount()).toBe(0);
});
+
+it("types a paste on the Android screen into the device and lets Ctrl+V reach the paste", async () => {
+ const { sent } = await setup(true, "android");
+ const screen = container.querySelector<HTMLElement>('[role="application"]')!;
+ screen.focus();
+ expect(document.activeElement).toBe(screen);
+ const chord = new KeyboardEvent("keydown", {
+ key: "v",
+ code: "KeyV",
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ screen.dispatchEvent(chord);
+ expect(chord.defaultPrevented).toBe(false);
+ const clipboardData = new DataTransfer();
+ clipboardData.setData("text/plain", "pässwörd 1");
+ const composerPastes: Array<string | null> = [];
+ const capturePaste = (event: ClipboardEvent) =>
+ composerPastes.push(pasteTextToFocusComposer(event));
+ window.addEventListener("paste", capturePaste, true);
+ onTestFinished(() => window.removeEventListener("paste", capturePaste, true));
+ const paste = new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true });
+ screen.dispatchEvent(paste);
+ expect(paste.defaultPrevented).toBe(true);
+ expect(sent.map((message) => JSON.parse(message as string) as unknown)).toEqual([
+ { type: "text", text: "pässwörd 1" },
+ ]);
+ expect(composerPastes).toEqual([null]);
+});
diff --git a/apps/web/src/components/device/DeviceStreamView.tsx b/apps/web/src/components/device/DeviceStreamView.tsx
index 299dddb1899..18b70e5421a 100644
--- a/apps/web/src/components/device/DeviceStreamView.tsx
+++ b/apps/web/src/components/device/DeviceStreamView.tsx
@@ -378,6 +378,8 @@ export function DeviceStreamView(props: {
ref={hostRef}
className={cn(
"relative flex min-h-0 min-w-0 flex-1 items-center justify-center overflow-hidden outline-none",
+ // Overlay the stream; focus (including pointer-driven focus) marks keyboard capture.
+ "after:pointer-events-none after:absolute after:inset-0 after:z-10 focus:after:ring-2 focus:after:ring-inset focus:after:ring-ring",
controlsInset && "pr-14",
)}
tabIndex={0}
@@ -386,9 +388,21 @@ export function DeviceStreamView(props: {
onKeyDown={(event) => {
if (event.target !== event.currentTarget) return;
if (event.metaKey && !["r", "R"].includes(event.key)) return;
+ // Let browser paste chords fire the paste event.
+ if (
+ (event.ctrlKey && (event.key === "v" || event.key === "V")) ||
+ (event.shiftKey && event.key === "Insert")
+ ) {
+ return;
+ }
event.preventDefault();
clientRef.current?.sendKey(event.nativeEvent, "down");
}}
+ onPaste={(event) => {
+ if (event.target !== event.currentTarget) return;
+ event.preventDefault();
+ clientRef.current?.sendText(event.clipboardData.getData("text/plain"));
+ }}
onKeyUp={(event) => {
if (event.target !== event.currentTarget) return;
clientRef.current?.sendKey(event.nativeEvent, "up");
diff --git a/packages/client-runtime/src/device/stream.test.ts b/packages/client-runtime/src/device/stream.test.ts
index 76dae57abd9..93b786cfed9 100644
--- a/packages/client-runtime/src/device/stream.test.ts
+++ b/packages/client-runtime/src/device/stream.test.ts
@@ -114,6 +114,8 @@ describe("native device stream transport", () => {
socket.onopen?.();
expect(socket.send).not.toHaveBeenCalled();
socket.onmessage?.({ data: Uint8Array.of(0x83).buffer });
+ client.sendText("hello");
+ expect(socket.send).not.toHaveBeenCalled();
client.setOrientation("landscape_right");
client.pressButton("home");
client.sendTouch("begin", 0.25, 0.75);
@@ -148,6 +150,8 @@ describe("native device stream transport", () => {
client.setOrientation("landscape_right");
client.pressButton("home");
client.pressButton("appSwitcher");
+ const prefix = "a".repeat(299);
+ client.sendText(`${prefix}ä`);
expect(
socket.send.mock.calls.map(([message]) => JSON.parse(message as string) as unknown),
).toEqual([
@@ -156,6 +160,8 @@ describe("native device stream transport", () => {
{ type: "touch", action: "up", x: 0.2, y: 0.1 },
{ type: "home" },
{ type: "recents" },
+ { type: "text", text: prefix },
+ { type: "text", text: "ä" },
]);
client.stop();
expect(socket.close).toHaveBeenCalledTimes(1);
diff --git a/packages/client-runtime/src/device/stream.ts b/packages/client-runtime/src/device/stream.ts
index 6eeeb66cb9d..b9cdcb7a56b 100644
--- a/packages/client-runtime/src/device/stream.ts
+++ b/packages/client-runtime/src/device/stream.ts
@@ -100,6 +100,10 @@ const SEMU_MAGIC = 0x53454d55;
const SEMU_HEADER_BYTES = 16;
const SEMU_FLAG_KEY = 1;
const SOFT_DECODE_QUEUE = 8;
+// expo-device-hub 0.15.3 serve-emu input.js MAX_TEXT_BYTES limits packets to 300 UTF-8 bytes.
+const ANDROID_MAX_TEXT_BYTES = 300;
+// The pinned hub queue depth is 128; the client does not read queue rejections.
+const ANDROID_MAX_TEXT_CHUNKS = 64;
const IOS_MSG_TOUCH = 0x03;
const IOS_MSG_BUTTON = 0x04;
@@ -116,6 +120,13 @@ const isWebCodecsSupported = (): boolean =>
"VideoDecoder" in globalThis &&
"EncodedVideoChunk" in globalThis;
+function utf8ByteLength(codePoint: number): number {
+ if (codePoint <= 0x7f) return 1;
+ if (codePoint <= 0x7ff) return 2;
+ if (codePoint <= 0xffff) return 3;
+ return 4;
+}
+
function taggedJson(tag: number, payload: unknown): Uint8Array<ArrayBuffer> {
const json = encoder.encode(JSON.stringify(payload));
const out = new Uint8Array(1 + json.length);
@@ -245,6 +256,8 @@ export interface DeviceStreamClient {
/** Normalized 0..1 coordinates in the displayed frame. */
readonly sendTouch: (phase: "begin" | "move" | "end", x: number, y: number) => void;
readonly sendKey: (event: KeyboardEvent, phase: "down" | "up") => void;
+ /** Android only: iOS input is HID key codes, which cannot carry arbitrary text. */
+ readonly sendText: (text: string) => void;
readonly pressButton: (button: DeviceHardwareButton) => void;
readonly rotate: () => void;
readonly setOrientation: (orientation: DeviceScreenSize["orientation"]) => void;
@@ -1054,6 +1067,24 @@ export function createDeviceStreamClient(
send(JSON.stringify({ type: "text", text: event.key }));
}
},
+ sendText: (text) => {
+ if (platform !== "android") return;
+ let chunk = "";
+ let chunkBytes = 0;
+ let sentChunks = 0;
+ for (const character of text) {
+ const characterBytes = utf8ByteLength(character.codePointAt(0)!);
+ if (chunkBytes + characterBytes > ANDROID_MAX_TEXT_BYTES) {
+ send(JSON.stringify({ type: "text", text: chunk }));
+ if (++sentChunks >= ANDROID_MAX_TEXT_CHUNKS) return;
+ chunk = "";
+ chunkBytes = 0;
+ }
+ chunk += character;
+ chunkBytes += characterBytes;
+ }
+ if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk }));
+ },
pressButton: (button) => {
if (platform === "ios") {
const name =