diff --git a/apps/mobile/src/features/browser/PreviewStreamWebView.tsx b/apps/mobile/src/features/browser/PreviewStreamWebView.tsx
index 63de59e81096f..08822fc80b21a 100644
--- a/apps/mobile/src/features/browser/PreviewStreamWebView.tsx
+++ b/apps/mobile/src/features/browser/PreviewStreamWebView.tsx
@@ -7,6 +7,7 @@ import {
previewStreamControlLabel,
previewStreamHostSetupMessage,
type PreviewStreamControl,
+ type PreviewStreamCopyOffer,
type PreviewStreamDownload,
type PreviewStreamFileChooser,
type PreviewStreamInput,
@@ -94,6 +95,23 @@ async function sendFilesToPage(chooser: PreviewStreamFileChooser, pick: boolean)
if (!response.ok) throw new Error((await response.text()) || m(msg("The upload was refused.")));
}
+/** Only this tap writes a page's own copy to the clipboard. */
+function offerPageCopy({ text, host }: PreviewStreamCopyOffer) {
+ const title = host
+ ? m(msg("{host} wants to copy text", { host }))
+ : m(msg("This page wants to copy text"));
+ Dialog.alert(title, undefined, [
+ { text: m(msg("Not now")), style: "cancel" },
+ {
+ text: m(msg("Copy", { $context: "verb, copies text to the clipboard" })),
+ onPress: () =>
+ void Clipboard.setStringAsync(text).catch(() =>
+ Dialog.alert(m(msg("Could not copy the text"))),
+ ),
+ },
+ ]);
+}
+
function offerDownload(download: PreviewStreamDownload) {
Dialog.alert(m(msg("Downloaded {fileName}", { fileName: download.fileName })), undefined, [
{ text: m(msg("Not now")), style: "cancel" },
@@ -419,6 +437,9 @@ function PreviewStreamDocumentView({
case "clipboard":
void Clipboard.setStringAsync(message.text).catch(() => undefined);
return;
+ case "copyOffer":
+ offerPageCopy(message);
+ return;
case "download":
offerDownload(message);
return;
diff --git a/apps/mobile/src/features/browser/preview-stream-document.ts b/apps/mobile/src/features/browser/preview-stream-document.ts
index 84989d8c44c05..97cea36d1be7d 100644
--- a/apps/mobile/src/features/browser/preview-stream-document.ts
+++ b/apps/mobile/src/features/browser/preview-stream-document.ts
@@ -2,6 +2,7 @@ import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access"
import type { PreviewStreamHostSetup } from "@t3tools/contracts";
import type {
PreviewStreamControl,
+ PreviewStreamCopyOffer,
PreviewStreamDownload,
PreviewStreamFileChooser,
} from "@t3tools/client-runtime/preview/server-browser-stream";
@@ -35,6 +36,7 @@ export type PreviewStreamMessage =
/** The direction a drag scrolls the page, sent every few dozen pixels of it. */
| { readonly type: "scroll"; readonly direction: "up" | "down" }
| { readonly type: "clipboard"; readonly text: string }
+ | ({ readonly type: "copyOffer" } & PreviewStreamCopyOffer)
| ({ readonly type: "download" } & PreviewStreamDownload)
| { readonly type: "fileChooser"; readonly chooser: PreviewStreamFileChooser | null }
| {
diff --git a/apps/mobile/src/features/browser/preview-stream.browser.ts b/apps/mobile/src/features/browser/preview-stream.browser.ts
index 748cecd982f93..860bfb2756f5a 100644
--- a/apps/mobile/src/features/browser/preview-stream.browser.ts
+++ b/apps/mobile/src/features/browser/preview-stream.browser.ts
@@ -174,6 +174,7 @@ export function start(configuration: PreviewStreamConfiguration) {
onFrame: (jpeg) => painter.paint(jpeg),
onPointer: showAgentCursor,
onClipboard: (text) => post({ type: "clipboard", text }),
+ onCopyOffer: (offer) => post({ type: "copyOffer", ...offer }),
onDownload: (download) => post({ type: "download", ...download }),
onFileChooser: (chooser) => post({ type: "fileChooser", chooser }),
onViewport: (page) => {
diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json
index 30116da93d8aa..e1003a124024c 100644
--- a/apps/mobile/src/i18n/translations/de.json
+++ b/apps/mobile/src/i18n/translations/de.json
@@ -1787,6 +1787,10 @@
"69e9c247d0266e9f": "Seiten auf dem localhost von {environment} laden über dessen Verbindung. Versuche es erneut, sobald die Verbindung wieder steht.",
"301045c720839f4d": "Auf {environment} lauscht nichts auf Port {port}. Starte dort den Server und versuche es dann erneut.",
"0b16434dff468d30": "Der Upload wurde abgelehnt.",
+ "6f1da9a36c248d39": "{host} möchte Text kopieren",
+ "d044949d07b00044": "Diese Seite möchte Text kopieren",
+ "4cffda9eddb15bb2": "Kopieren",
+ "c19c369300a0c9f0": "Der Text konnte nicht kopiert werden",
"bbcd3776bcd3e2c5": "{fileName} heruntergeladen",
"f746b1e0bfb2ec4a": "Nicht jetzt",
"2bbb5073f65cde97": "Der Download konnte nicht gespeichert werden",
diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json
index a7433f8a74360..8b6c7c3e95b06 100644
--- a/apps/mobile/src/i18n/translations/en.json
+++ b/apps/mobile/src/i18n/translations/en.json
@@ -1787,6 +1787,10 @@
"69e9c247d0266e9f": "Pages on {environment}’s localhost load through its connection. Try again once it reconnects.",
"301045c720839f4d": "Nothing is listening on port {port} on {environment}. Start the server there, then try again.",
"0b16434dff468d30": "The upload was refused.",
+ "6f1da9a36c248d39": "{host} wants to copy text",
+ "d044949d07b00044": "This page wants to copy text",
+ "4cffda9eddb15bb2": "Copy",
+ "c19c369300a0c9f0": "Could not copy the text",
"bbcd3776bcd3e2c5": "Downloaded {fileName}",
"f746b1e0bfb2ec4a": "Not now",
"2bbb5073f65cde97": "Could not save the download",
diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json
index 5b7e4a1df6b1f..963730990b303 100644
--- a/apps/mobile/src/i18n/translations/es.json
+++ b/apps/mobile/src/i18n/translations/es.json
@@ -1787,6 +1787,10 @@
"69e9c247d0266e9f": "Las páginas del localhost de {environment} se cargan a través de su conexión. Vuelve a intentarlo cuando se reconecte.",
"301045c720839f4d": "Nada escucha en el puerto {port} de {environment}. Inicia el servidor allí y vuelve a intentarlo.",
"0b16434dff468d30": "Se rechazó la subida.",
+ "6f1da9a36c248d39": "{host} quiere copiar texto",
+ "d044949d07b00044": "Esta página quiere copiar texto",
+ "4cffda9eddb15bb2": "Copiar",
+ "c19c369300a0c9f0": "No se pudo copiar el texto",
"bbcd3776bcd3e2c5": "Se descargó {fileName}",
"f746b1e0bfb2ec4a": "Ahora no",
"2bbb5073f65cde97": "No se pudo guardar la descarga",
diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json
index 791e9bdbb1bdd..9e9235c88b0e4 100644
--- a/apps/mobile/src/i18n/translations/fr.json
+++ b/apps/mobile/src/i18n/translations/fr.json
@@ -1787,6 +1787,10 @@
"69e9c247d0266e9f": "Les pages du localhost de {environment} passent par sa connexion. Réessaie une fois la connexion rétablie.",
"301045c720839f4d": "Rien n’écoute sur le port {port} de {environment}. Démarre le serveur là-bas, puis réessaie.",
"0b16434dff468d30": "L’envoi a été refusé.",
+ "6f1da9a36c248d39": "{host} veut copier du texte",
+ "d044949d07b00044": "Cette page veut copier du texte",
+ "4cffda9eddb15bb2": "Copier",
+ "c19c369300a0c9f0": "Impossible de copier le texte",
"bbcd3776bcd3e2c5": "{fileName} téléchargé",
"f746b1e0bfb2ec4a": "Pas maintenant",
"2bbb5073f65cde97": "Impossible d’enregistrer le téléchargement",
diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json
index 991bb7852b731..cd731b707e2ad 100644
--- a/apps/mobile/src/i18n/translations/ja.json
+++ b/apps/mobile/src/i18n/translations/ja.json
@@ -1787,6 +1787,10 @@
"69e9c247d0266e9f": "{environment} の localhost のページは、その接続を通じて読み込まれます。再接続されたらもう一度お試しください。",
"301045c720839f4d": "{environment} のポート {port} で待ち受けているものはありません。そこでサーバーを起動してから、もう一度お試しください。",
"0b16434dff468d30": "アップロードは拒否されました。",
+ "6f1da9a36c248d39": "{host} がテキストをコピーしようとしています",
+ "d044949d07b00044": "このページがテキストをコピーしようとしています",
+ "4cffda9eddb15bb2": "コピー",
+ "c19c369300a0c9f0": "テキストをコピーできませんでした",
"bbcd3776bcd3e2c5": "{fileName} をダウンロードしました",
"f746b1e0bfb2ec4a": "今はしない",
"2bbb5073f65cde97": "ダウンロードを保存できませんでした",
diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json
index 6b91487ccbbc5..185cba1cbf587 100644
--- a/apps/mobile/src/i18n/translations/ko.json
+++ b/apps/mobile/src/i18n/translations/ko.json
@@ -1787,6 +1787,10 @@
"69e9c247d0266e9f": "{environment}의 localhost 페이지는 해당 연결을 통해 로드됩니다. 다시 연결되면 다시 시도하세요.",
"301045c720839f4d": "{environment}의 포트 {port}에서 수신 대기 중인 항목이 없습니다. 그곳에서 서버를 시작한 다음 다시 시도하세요.",
"0b16434dff468d30": "업로드가 거부되었습니다.",
+ "6f1da9a36c248d39": "{host}에서 텍스트를 복사하려고 합니다",
+ "d044949d07b00044": "이 페이지에서 텍스트를 복사하려고 합니다",
+ "4cffda9eddb15bb2": "복사",
+ "c19c369300a0c9f0": "텍스트를 복사할 수 없습니다",
"bbcd3776bcd3e2c5": "{fileName} 다운로드됨",
"f746b1e0bfb2ec4a": "나중에",
"2bbb5073f65cde97": "다운로드를 저장할 수 없습니다",
diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json
index 251993b1b9210..25f3b0e383859 100644
--- a/apps/mobile/src/i18n/translations/pt-BR.json
+++ b/apps/mobile/src/i18n/translations/pt-BR.json
@@ -1787,6 +1787,10 @@
"69e9c247d0266e9f": "As páginas do localhost de {environment} carregam pela conexão dele. Tente novamente quando ela se reconectar.",
"301045c720839f4d": "Nada está escutando na porta {port} de {environment}. Inicie o servidor lá e tente novamente.",
"0b16434dff468d30": "O envio foi recusado.",
+ "6f1da9a36c248d39": "{host} quer copiar um texto",
+ "d044949d07b00044": "Esta página quer copiar um texto",
+ "4cffda9eddb15bb2": "Copiar",
+ "c19c369300a0c9f0": "Não foi possível copiar o texto",
"bbcd3776bcd3e2c5": "{fileName} baixado",
"f746b1e0bfb2ec4a": "Agora não",
"2bbb5073f65cde97": "Não foi possível salvar o download",
diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json
index eb53bc6a85093..280dea12abcf0 100644
--- a/apps/mobile/src/i18n/translations/ru.json
+++ b/apps/mobile/src/i18n/translations/ru.json
@@ -1787,6 +1787,10 @@
"69e9c247d0266e9f": "Страницы localhost окружения {environment} загружаются через его подключение. Повторите попытку, когда оно восстановится.",
"301045c720839f4d": "На порту {port} в {environment} ничего не слушает. Запустите там сервер и повторите попытку.",
"0b16434dff468d30": "Загрузка отклонена.",
+ "6f1da9a36c248d39": "{host} хочет скопировать текст",
+ "d044949d07b00044": "Эта страница хочет скопировать текст",
+ "4cffda9eddb15bb2": "Копировать",
+ "c19c369300a0c9f0": "Не удалось скопировать текст",
"bbcd3776bcd3e2c5": "Скачан {fileName}",
"f746b1e0bfb2ec4a": "Не сейчас",
"2bbb5073f65cde97": "Не удалось сохранить загруженный файл",
diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json
index 0b335f057cdce..5c2cbcd3c2b05 100644
--- a/apps/mobile/src/i18n/translations/sv.json
+++ b/apps/mobile/src/i18n/translations/sv.json
@@ -1787,6 +1787,10 @@
"69e9c247d0266e9f": "Sidor på localhost i {environment} laddas via dess anslutning. Försök igen när den har återanslutit.",
"301045c720839f4d": "Inget lyssnar på port {port} i {environment}. Starta servern där och försök sedan igen.",
"0b16434dff468d30": "Uppladdningen nekades.",
+ "6f1da9a36c248d39": "{host} vill kopiera text",
+ "d044949d07b00044": "Den här sidan vill kopiera text",
+ "4cffda9eddb15bb2": "Kopiera",
+ "c19c369300a0c9f0": "Kunde inte kopiera texten",
"bbcd3776bcd3e2c5": "Laddade ned {fileName}",
"f746b1e0bfb2ec4a": "Inte nu",
"2bbb5073f65cde97": "Kunde inte spara nedladdningen",
diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json
index 9002438aed15e..e92472e9761f8 100644
--- a/apps/mobile/src/i18n/translations/zh.json
+++ b/apps/mobile/src/i18n/translations/zh.json
@@ -1788,6 +1788,10 @@
"69e9c247d0266e9f": "{environment} 上的 localhost 页面通过其连接加载。重新连接后请再试一次。",
"301045c720839f4d": "{environment} 上的端口 {port} 没有任何服务在监听。请在那里启动服务器,然后再试一次。",
"0b16434dff468d30": "上传被拒绝。",
+ "6f1da9a36c248d39": "{host} 想要复制文字",
+ "d044949d07b00044": "此页面想要复制文字",
+ "4cffda9eddb15bb2": "复制",
+ "c19c369300a0c9f0": "无法复制文字",
"bbcd3776bcd3e2c5": "已下载 {fileName}",
"f746b1e0bfb2ec4a": "暂不",
"2bbb5073f65cde97": "无法保存下载内容",
diff --git a/apps/server/src/preview/ServerBrowser.copies.test.ts b/apps/server/src/preview/ServerBrowser.copies.test.ts
new file mode 100644
index 0000000000000..9022c4aa1da6e
--- /dev/null
+++ b/apps/server/src/preview/ServerBrowser.copies.test.ts
@@ -0,0 +1,422 @@
+import {
+ chromium,
+ type Browser,
+ type BrowserContext,
+ type CDPSession,
+ type Page,
+} from "playwright-core";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vite-plus/test";
+
+import * as ServerBrowser from "./ServerBrowser.ts";
+
+const PAGE = `
+
+
+
+
+
+
+
+
selected
`;
+
+describe("server browser page copies", () => {
+ let browser: Browser;
+ let context: BrowserContext;
+ let page: Page;
+ let cdp: CDPSession;
+
+ beforeAll(async () => {
+ browser = await chromium.launch({ headless: true });
+ });
+ afterAll(async () => {
+ await browser?.close();
+ });
+ beforeEach(async () => {
+ context = await browser.newContext();
+ await ServerBrowser.prepareContext(context);
+ page = await context.newPage();
+ cdp = await context.newCDPSession(page);
+ await ServerBrowser.recordCopies(cdp);
+ await page.route("https://copy.example/", (route) =>
+ route.fulfill({ contentType: "text/html", body: PAGE }),
+ );
+ await page.goto("https://copy.example/");
+ });
+ afterEach(async () => {
+ await context.close();
+ });
+
+ const takeCopies = (
+ session: CDPSession,
+ click: boolean,
+ since = 0,
+ until = Number.MAX_SAFE_INTEGER,
+ ) => ServerBrowser.takeSessionCopies(session, click, since, until);
+ const takeCopy = async (click: boolean, since?: number, until?: number) =>
+ (await takeCopies(cdp, click, since, until)).find((copy) => copy && copy.text.length > 0)
+ ?.text ?? "";
+ const inPage = async (expression: string) =>
+ (await cdp.send("Runtime.evaluate", { expression, returnByValue: true })).result.value;
+
+ it("keeps text the page copies after a real click apart from the copy keys", async () => {
+ await page.locator("#write").click();
+ expect(await takeCopy(true)).toBe("written");
+ await page.locator("body[data-written=yes]").waitFor();
+ await page.locator("#cached").click();
+ await page.locator("body[data-cached=yes]").waitFor();
+ expect(await takeCopy(true)).toBe("cached");
+ await page.locator("#later").click();
+ await page.locator("body[data-later=yes]").waitFor();
+ expect(await takeCopy(true)).toBe("later");
+ await page.locator("#exec").click();
+ expect(await takeCopy(true)).toBe("executed");
+ await page.locator("#plain").click();
+ expect(await takeCopy(true)).toBe("");
+
+ await page.locator("#text").selectText();
+ await cdp.send("Input.dispatchKeyEvent", {
+ type: "rawKeyDown",
+ key: "c",
+ code: "KeyC",
+ modifiers: 4,
+ commands: ["copy"],
+ });
+ expect(await takeCopy(true)).toBe("");
+ expect(await takeCopy(false)).toBe("selected");
+ });
+
+ it("takes each copy only inside its own press's window", async () => {
+ const { frameTree } = await cdp.send("Page.getFrameTree");
+ const { executionContextId } = await cdp.send("Page.createIsolatedWorld", {
+ frameId: frameTree.frame.id,
+ worldName: "t3-preview-clipboard",
+ });
+ const recordAt = (now: number) =>
+ cdp.send("Runtime.evaluate", {
+ contextId: executionContextId,
+ expression: `Date.now = () => ${now}`,
+ });
+
+ await recordAt(100);
+ await page.locator("#exec").click();
+ // A click's read leaves a copy from its own start onwards to the next read.
+ expect(await takeCopy(true, 100, 100)).toBe("");
+ expect(await takeCopy(true, 100, 101)).toBe("executed");
+ await page.locator("#exec").click();
+ expect(await takeCopy(true, 101, 200)).toBe("");
+ expect(await takeCopy(true)).toBe("");
+
+ for (const [now, text] of [
+ [100, "first"],
+ [200, "second"],
+ ] as const) {
+ await recordAt(now);
+ await inPage(`document.getElementById("text").textContent = "${text}"`);
+ await page.locator("#text").selectText();
+ await cdp.send("Input.dispatchKeyEvent", {
+ type: "rawKeyDown",
+ key: "c",
+ code: "KeyC",
+ modifiers: 4,
+ commands: ["copy"],
+ });
+ await cdp.send("Input.dispatchKeyEvent", {
+ type: "keyUp",
+ key: "c",
+ code: "KeyC",
+ modifiers: 4,
+ });
+ }
+ expect(await takeCopy(false, 150, 150)).toBe("");
+ expect(await takeCopy(false, 200, 200)).toBe("second");
+ expect(await takeCopy(false)).toBe("");
+ });
+
+ it.each([
+ { argument: "123456", text: "123456", outcome: "resolved" },
+ {
+ argument: '{ toString() { document.body.dataset.conversions++; return "converted"; } }',
+ text: "converted",
+ outcome: "resolved",
+ },
+ {
+ argument:
+ '{ n: 0, toString() { document.body.dataset.conversions++; if (this.n++ === 0) throw conversionError; return "token"; } }',
+ text: "",
+ outcome: "TypeError",
+ conversionFailure: true,
+ },
+ ])(
+ "reports native writeText conversion for $argument",
+ async ({ argument, text, outcome, conversionFailure }) => {
+ await inPage(`
+ document.body.dataset.conversions = "0";
+ const conversionError = new TypeError("invalid");
+ document.getElementById("write").onclick = () => {
+ const writing = navigator.clipboard.writeText(${argument});
+ writing.then(
+ () => document.body.dataset.outcome = "resolved",
+ (error) => {
+ document.body.dataset.outcome = error.name;
+ document.body.dataset.originalError = String(error === conversionError);
+ },
+ );
+ };
+ `);
+ await page.locator("#write").click();
+ await page.locator("body[data-outcome]").waitFor();
+ expect(await inPage("document.body.dataset.outcome")).toBe(outcome);
+ expect(await takeCopy(true)).toBe(text);
+ expect(await takeCopy(false)).toBe("");
+ expect(await inPage("document.body.dataset.conversions")).toBe(
+ text === "converted" || conversionFailure ? "1" : "0",
+ );
+ if (conversionFailure)
+ expect(await inPage("document.body.dataset.originalError")).toBe("true");
+ },
+ );
+
+ it.each([
+ { target: "document", capture: true, format: "text/plain", items: false },
+ { target: "document", capture: true, format: "text/plain", items: true },
+ ])(
+ "keeps the final copy and cut payload from $target handlers (capture: $capture, items: $items)",
+ async ({ target, capture, format, items }) => {
+ await inPage(`
+ for (const type of ["copy", "cut"]) {
+ ${target}.addEventListener(type, (event) => {
+ event.preventDefault();
+ event.clipboardData.setData("text/plain", "replaced earlier");
+ if (!${items}) event.clipboardData.setData("${format}", "page " + event.type);
+ event.clipboardData.setData("text/html", "other format
");
+ if (${items}) {
+ event.clipboardData.items.clear();
+ event.clipboardData.items.add("page " + event.type, "text/plain");
+ }
+ if (document.body.dataset.clear === "yes") {
+ if (${items}) event.clipboardData.items.clear();
+ else event.clipboardData.clearData();
+ }
+ if (document.body.dataset.clear === "remove") event.clipboardData.items.remove(0);
+ const unrelated = new DataTransfer();
+ unrelated.setData("text/plain", "unrelated transfer");
+ unrelated.items.clear();
+ unrelated.items.add("unrelated item", "text/plain");
+ event.stopImmediatePropagation();
+ }, ${capture});
+ }
+ `);
+ for (const command of ["copy", "cut"]) {
+ await page.locator("#text").selectText();
+ await inPage(`document.getElementById("replace").dataset.command = "${command}"`);
+ await page.locator("#replace").click();
+ expect(await takeCopy(true)).toBe(`page ${command}`);
+ expect(await takeCopy(false)).toBe("");
+
+ await page.locator("#text").selectText();
+ const key = command === "copy" ? "c" : "x";
+ const code = command === "copy" ? "KeyC" : "KeyX";
+ await cdp.send("Input.dispatchKeyEvent", {
+ type: "rawKeyDown",
+ key,
+ code,
+ modifiers: 4,
+ commands: [command],
+ });
+ expect(await takeCopy(true)).toBe("");
+ expect(await takeCopy(false)).toBe(`page ${command}`);
+ await cdp.send("Input.dispatchKeyEvent", { type: "keyUp", key, code, modifiers: 4 });
+ }
+ await inPage(`document.body.dataset.clear = "yes"`);
+ await page.locator("#text").selectText();
+ await page.locator("#replace").click();
+ expect(await takeCopy(true)).toBe("");
+ expect(await takeCopy(false)).toBe("");
+ if (items) {
+ await inPage(`document.body.dataset.clear = "remove"`);
+ await page.locator("#text").selectText();
+ await page.locator("#replace").click();
+ expect(await takeCopy(true)).toBe("");
+ expect(await takeCopy(false)).toBe("");
+ }
+ },
+ );
+
+ it.each([
+ { inside: false, data: true },
+ { inside: true, data: false },
+ ])(
+ "keeps a newer writeText over a pending event (inside: $inside, data: $data)",
+ async ({ inside, data }) => {
+ await inPage(`
+ const writeLatest = () => navigator.clipboard.writeText("newest").then(() => {
+ document.body.dataset.latest = "yes";
+ });
+ document.getElementById("replace").onclick = function () {
+ document.execCommand(this.dataset.command);
+ if (!${inside}) writeLatest();
+ };
+ for (const type of ["copy", "cut"]) {
+ document.addEventListener(type, (event) => {
+ event.preventDefault();
+ if (${data}) event.clipboardData.setData("text/plain", "older");
+ if (${inside}) writeLatest();
+ event.stopImmediatePropagation();
+ }, true);
+ }
+ `);
+ for (const command of ["copy", "cut"]) {
+ await page.locator("#text").selectText();
+ await inPage(`
+ document.body.removeAttribute("data-latest");
+ document.getElementById("replace").dataset.command = "${command}";
+ `);
+ await page.locator("#replace").click();
+ expect(await takeCopy(true)).toBe("newest");
+ expect(await takeCopy(false)).toBe("");
+ await page.locator("body[data-latest=yes]").waitFor();
+ expect(await takeCopy(true)).toBe("");
+ }
+ },
+ );
+
+ it("keeps a pending key copy apart from a later page write", async () => {
+ await inPage(`
+ document.addEventListener("keydown", () => {
+ setTimeout(() => navigator.clipboard.writeText("later page write").then(() => {
+ document.body.dataset.latest = "yes";
+ }));
+ }, true);
+ document.addEventListener("copy", (event) => {
+ event.preventDefault();
+ event.clipboardData.setData("text/plain", "key payload");
+ event.stopImmediatePropagation();
+ }, true);
+ `);
+ await page.locator("#plain").click();
+ await page.locator("#text").selectText();
+ await cdp.send("Input.dispatchKeyEvent", {
+ type: "rawKeyDown",
+ key: "c",
+ code: "KeyC",
+ modifiers: 4,
+ commands: ["copy"],
+ });
+ await page.locator("body[data-latest=yes]").waitFor();
+ expect(await takeCopy(false)).toBe("key payload");
+ expect(await takeCopy(true)).toBe("later page write");
+ });
+
+ it("keeps copies delegated from a child frame to its parent", async () => {
+ await inPage(`
+ globalThis.writeFromChild = async () => {
+ await navigator.permissions.query({ name: "clipboard-write" });
+ await navigator.clipboard.writeText("delegated");
+ document.body.dataset.delegated = "yes";
+ };
+ globalThis.execFromChild = (command) => {
+ const field = document.createElement("textarea");
+ field.value = "delegated " + command;
+ document.body.append(field);
+ field.select();
+ document.execCommand(command);
+ field.remove();
+ };
+ const frame = document.createElement("iframe");
+ frame.srcdoc = '';
+ document.body.append(frame);
+ `);
+ expect(await inPage("navigator.userActivation.hasBeenActive")).toBe(false);
+ const frame = page.frameLocator("iframe");
+ await frame.locator("#write").click();
+ await page.locator("body[data-delegated=yes]").waitFor();
+ expect(await takeCopy(true)).toBe("delegated");
+ expect(await takeCopy(false)).toBe("");
+ for (const command of ["copy", "cut"]) {
+ await frame.locator(`#${command}`).click();
+ expect(await takeCopy(true)).toBe(`delegated ${command}`);
+ expect(await takeCopy(false)).toBe("");
+ }
+ });
+
+ it.each([
+ { kind: "cross-origin", host: "other.example" },
+ { kind: "opaque", host: "" },
+ ])("attributes a $kind frame's copies to its own origin", async ({ kind, host }) => {
+ await page.route("https://other.example/", (route) =>
+ route.fulfill({ contentType: "text/html", body: PAGE }),
+ );
+ await inPage(`
+ const frame = document.createElement("iframe");
+ frame.setAttribute("allow", "clipboard-write");
+ if ("${kind}" === "cross-origin") frame.src = "https://other.example/";
+ else {
+ frame.setAttribute("sandbox", "allow-scripts");
+ frame.srcdoc = ${JSON.stringify(PAGE)};
+ }
+ document.body.append(frame);
+ `);
+ const frame = page.frameLocator("iframe");
+ await frame.locator("#exec").waitFor();
+ const child = page.frames().find((frame) => frame.parentFrame() === page.mainFrame())!;
+ const session = await context.newCDPSession(child).catch(() => cdp);
+ await ServerBrowser.recordCopies(session);
+ await frame.locator("#exec").click();
+ const copies = await takeCopies(session, true);
+ expect(copies.find((copy) => copy && copy.text.length > 0)).toEqual({ text: "executed", host });
+ if (kind !== "opaque") {
+ await frame.locator("#cached").click();
+ await frame.locator("body[data-cached=yes]").waitFor();
+ const cached = await takeCopies(session, true);
+ expect(cached.find((copy) => copy && copy.text.length > 0)).toEqual({ text: "cached", host });
+ }
+ expect(await takeCopy(false)).toBe("");
+ });
+
+ it("keeps a popup's clipboard function cached before adoption", async () => {
+ await context.route("https://other.example/", (route) =>
+ route.fulfill({ contentType: "text/html", body: PAGE }),
+ );
+ await inPage(
+ `document.getElementById("plain").onclick = () => window.open("https://other.example/")`,
+ );
+ const opened = page.waitForEvent("popup");
+ await page.locator("#plain").click();
+ const popup = await opened;
+ await popup.locator("#cached").waitFor();
+ const session = await context.newCDPSession(popup);
+ await ServerBrowser.recordCopies(session);
+ await popup.locator("#cached").click();
+ await popup.locator("body[data-cached=yes]").waitFor();
+ const copies = await takeCopies(session, true);
+ expect(copies.find((copy) => copy && copy.text.length > 0)).toEqual({
+ text: "cached",
+ host: "other.example",
+ });
+ expect(await takeCopy(false)).toBe("");
+ });
+
+ it("keeps nothing the page copies without a real click", async () => {
+ await inPage(`document.getElementById("write").click()`);
+ await inPage(`document.getElementById("exec").click()`);
+ await inPage(
+ `new Promise((resolve) => setTimeout(() => navigator.clipboard.writeText("timer").then(resolve, resolve)))`,
+ );
+ await inPage(
+ `dispatchEvent(new CustomEvent("t3-preview-clipboard-write", { detail: "forged" }))`,
+ );
+ await inPage(
+ `dispatchEvent(new CustomEvent("t3-preview-clipboard-data", { detail: "forged" }))`,
+ );
+ expect(await takeCopy(true)).toBe("");
+ expect(await takeCopy(false)).toBe("");
+ expect(await inPage("typeof globalThis.takeCopy")).toBe("undefined");
+ expect(await inPage("navigator.userActivation.hasBeenActive")).toBe(false);
+ await page.locator("#plain").click();
+ await inPage(
+ `dispatchEvent(new CustomEvent("t3-preview-clipboard-data", { detail: "forged after a click" }))`,
+ );
+ expect(await takeCopy(true)).toBe("");
+ expect(await takeCopy(false)).toBe("");
+ });
+});
diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts
index f345bf6f150e6..aa3a2068f3f04 100644
--- a/apps/server/src/preview/ServerBrowser.test.ts
+++ b/apps/server/src/preview/ServerBrowser.test.ts
@@ -149,11 +149,25 @@ function makeSession(
if (focusedFrame) focusedFrame.copy = keyCopy;
else pageCopy = keyCopy;
}
+ if (method === "Input.dispatchMouseEvent") {
+ const { type, button } = input as { type?: unknown; button?: unknown };
+ // The recorder ignores what was copied before a left press.
+ if (type === "mousePressed" && button === "left") pageClickCopy = "";
+ if (type === "mouseReleased") pageClickCopy = clickCopy || pageClickCopy;
+ }
+ if (
+ method === "Runtime.evaluate" &&
+ (input as { expression?: string }).expression?.startsWith("globalThis.takeCopy?.(true,")
+ ) {
+ const value = pageClickCopy;
+ pageClickCopy = "";
+ return { result: { value: { text: value, host: "other.example" } } };
+ }
if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7) {
const value = frame ? frame.copy : pageCopy;
if (frame) frame.copy = "";
else pageCopy = "";
- return { result: { value } };
+ return { result: { value: { text: value, host: "other.example" } } };
}
if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 9)
return desktopSizeAnswer?.() ?? { result: { value: { ...viewport } } };
@@ -294,6 +308,7 @@ function makeContext(onClose?: (context: BrowserContext) => void, initialUrl = "
cssViewport,
newPage: async () => page as unknown as Page,
grantPermissions: vi.fn(async () => {}),
+ addInitScript: vi.fn(async () => {}),
newCDPSession: async (target: unknown) => {
const session = makeSession(
target === page ? undefined : (target as ReturnType),
@@ -397,6 +412,8 @@ let contextGate: PromiseWithResolvers | null = null;
let heldStill: (() => Promise) | null = null;
let pageCopy = "";
let keyCopy = "";
+let clickCopy = "";
+let pageClickCopy = "";
let focusedFrame: ReturnType | null = null;
let contextFailure: Error | null = null;
let pageSetupFailure: Error | null = null;
@@ -605,6 +622,8 @@ beforeEach(() => {
initialNavigation = null;
pageCopy = "";
keyCopy = "";
+ clickCopy = "";
+ pageClickCopy = "";
focusedFrame = null;
desktopTabs.clear();
shownDesktopTabs.clear();
@@ -2392,7 +2411,113 @@ it.effect("only the controlling viewer's copy and cut keys reach its clipboard",
).pipe(Effect.provide(layer)),
);
-it.effect("a busy embedded frame does not hold a copy key back from the page", () =>
+it.effect("text the page copies after the controlling viewer's click is only offered to it", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const { browser, tabId } = yield* ready;
+ const watcher = yield* browser.attachViewer(viewerInput(tabId, false));
+ const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
+ yield* viewer.input({ type: "takeControl" });
+ yield* viewer.input({ type: "navigate", url: "https://copy.example/app" });
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ yield* Effect.addFinalizer(() => Effect.sync(() => vi.useRealTimers()));
+ const copies = () =>
+ Queue.clear(viewer.output).pipe(
+ Effect.map((items) =>
+ items.filter((item) => item._tag === "clipboard" || item._tag === "copyOffer"),
+ ),
+ );
+ const advance = (ms: number) => Effect.promise(() => vi.advanceTimersByTimeAsync(ms));
+ const mouse = (button: string, action: string, buttons: number) =>
+ viewer.input({ type: "mouse", action, x: 10, y: 10, button, buttons });
+ const click = (button: string) =>
+ Effect.forEach(["down", "up"], (action) =>
+ mouse(
+ button,
+ action,
+ action === "up" ? 0 : button === "left" ? 1 : button === "right" ? 2 : 4,
+ ),
+ );
+ const offer = (text: string) => ({ _tag: "copyOffer", text, host: "other.example" });
+ pageClickCopy = "before the click";
+ yield* click("left");
+ yield* advance(5_000);
+ expect(yield* copies()).toEqual([]);
+ for (const button of ["right", "middle"]) {
+ clickCopy = `${button} button`;
+ yield* click(button);
+ yield* advance(5_000);
+ expect(yield* copies()).toEqual([]);
+ for (const sequence of [
+ ["left", button, "left", button],
+ ["left", button, button, "left"],
+ [button, "left", "left", button],
+ [button, "left", button, "left"],
+ ]) {
+ let buttons = 0;
+ for (const [index, pressed] of sequence.entries()) {
+ const down = index < 2;
+ const bit = pressed === "left" ? 1 : pressed === "right" ? 2 : 4;
+ buttons = down ? buttons | bit : buttons & ~bit;
+ yield* mouse(pressed, down ? "down" : "up", buttons);
+ }
+ yield* advance(5_000);
+ expect(yield* copies()).toEqual([]);
+ }
+ }
+ yield* mouse("left", "down", 1);
+ yield* viewer.input({ type: "releaseControl" });
+ yield* viewer.input({ type: "takeControl" });
+ yield* mouse("left", "up", 0);
+ yield* advance(5_000);
+ expect(yield* copies()).toEqual([]);
+ clickCopy = "before the handoff";
+ yield* mouse("left", "down", 1);
+ const session = contexts[0]!.sessions.at(-1)!;
+ const send = session.send.getMockImplementation()!;
+ const started = Promise.withResolvers();
+ const finish = Promise.withResolvers();
+ yield* Effect.addFinalizer(() => Effect.sync(() => finish.resolve()));
+ session.send.mockImplementationOnce(async (method, input) => {
+ started.resolve();
+ await finish.promise;
+ return send(method, input);
+ });
+ const releasingMouse = yield* mouse("left", "up", 0).pipe(
+ Effect.forkScoped({ startImmediately: true }),
+ );
+ yield* Effect.promise(() => started.promise);
+ const releasingControl = yield* viewer
+ .input({ type: "releaseControl" })
+ .pipe(Effect.forkScoped({ startImmediately: true }));
+ const retakingControl = yield* viewer
+ .input({ type: "takeControl" })
+ .pipe(Effect.forkScoped({ startImmediately: true }));
+ finish.resolve();
+ yield* Effect.forEach([releasingMouse, releasingControl, retakingControl], Fiber.join);
+ yield* advance(5_000);
+ expect(yield* copies()).toEqual([]);
+ clickCopy = "secret";
+ yield* click("left");
+ yield* advance(0);
+ expect(yield* copies()).toEqual([offer("secret")]);
+ clickCopy = "";
+ yield* click("left");
+ yield* advance(0);
+ expect(yield* copies()).toEqual([]);
+ pageClickCopy = "after awaiting";
+ yield* advance(250);
+ expect(yield* copies()).toEqual([offer("after awaiting")]);
+ keyCopy = "keys";
+ yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 });
+ expect(yield* copies()).toEqual([{ _tag: "clipboard", text: "keys" }]);
+ const watched = yield* Queue.clear(watcher.output);
+ expect(watched.filter((item) => item._tag === "copyOffer")).toEqual([]);
+ }),
+ ).pipe(Effect.provide(layer)),
+);
+
+it.effect("a busy embedded frame does not hold a copy key or a click back from the page", () =>
Effect.scoped(
Effect.gen(function* () {
const { browser, tabId } = yield* ready;
@@ -2404,20 +2529,20 @@ it.effect("a busy embedded frame does not hold a copy key back from the page", (
context.page.emit("framenavigated", frame);
yield* Effect.promise(() => frame.recording.promise);
- // The frame answers its copy read only once the page has the key and the
- // input after it, like a frame busy for longer than the user waits.
- const keyReached = Promise.withResolvers();
+ // The frame answers its copy read only once the page has the key or press and
+ // the release after it, like a frame busy for longer than the user waits.
+ let released = Promise.withResolvers();
const pageSend = pageSession.send.getMockImplementation()!;
pageSession.send.mockImplementation(async (method, input) => {
- if (method === "Input.dispatchKeyEvent" && (input as { type?: string }).type === "keyUp")
- keyReached.resolve();
+ const { type } = input as { type?: string };
+ if (type === "keyUp" || type === "mouseReleased") released.resolve();
return pageSend(method, input);
});
const frameSession = context.sessions.at(-1)!;
const frameSend = frameSession.send.getMockImplementation()!;
frameSession.send.mockImplementation(async (method, input) => {
if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7) {
- await keyReached.promise;
+ await released.promise;
}
return frameSend(method, input);
});
@@ -2436,6 +2561,24 @@ it.effect("a busy embedded frame does not hold a copy key back from the page", (
expect(clipboard.filter((item) => item._tag === "clipboard")).toEqual([
{ _tag: "clipboard", text: "copied" },
]);
+
+ released = Promise.withResolvers();
+ clickCopy = "clicked";
+ const pressing = yield* viewer
+ .input({ type: "mouse", action: "down", x: 10, y: 10, button: "left", buttons: 1 })
+ .pipe(Effect.forkScoped({ startImmediately: true }));
+ yield* viewer.input({
+ type: "mouse",
+ action: "up",
+ x: 10,
+ y: 10,
+ button: "left",
+ buttons: 0,
+ });
+ yield* Fiber.join(pressing);
+ let offered = yield* Queue.take(viewer.output);
+ while (offered._tag !== "copyOffer") offered = yield* Queue.take(viewer.output);
+ expect(offered).toEqual({ _tag: "copyOffer", text: "clicked", host: "other.example" });
}),
).pipe(Effect.provide(layer)),
);
diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts
index 0960faa3a30bf..874ec66d84810 100644
--- a/apps/server/src/preview/ServerBrowser.ts
+++ b/apps/server/src/preview/ServerBrowser.ts
@@ -230,6 +230,7 @@ export type ServerBrowserViewerOutput =
readonly editable: boolean;
}
| { readonly _tag: "clipboard"; readonly text: string }
+ | { readonly _tag: "copyOffer"; readonly text: string; readonly host: string }
| {
readonly _tag: "pointer";
readonly phase: "move" | "click";
@@ -308,6 +309,10 @@ interface ViewerState {
readonly pause: () => Promise;
readonly resume: () => Promise;
scrolledAt: number;
+ /** Counts presses; a newer one stops an older click's copy offer. */
+ clicks: number;
+ /** The clean left press whose copies may be offered, and when it was sent. */
+ leftPress: { click: number; generation: number; since: number } | null;
requestedSize: { width: number; height: number; order: number } | null;
}
@@ -521,20 +526,35 @@ const titleChange = (reported: string) => `new Promise((resolve) => {
const CLIPBOARD_TEXT_LIMIT = 1024 * 1024;
const CLIPBOARD_WORLD = "t3-preview-clipboard";
-// Chromium shares its clipboard across contexts; capture real copy/cut keys in a page-inaccessible world instead.
+const CLIPBOARD_WRITE_EVENT = "t3-preview-clipboard-write";
+const CLIPBOARD_DATA_EVENT = "t3-preview-clipboard-data";
+// Chromium's transient user activation lasts as long, so a clicked page may copy after awaiting work.
+const CLICK_COPY_MS = 5_000;
+const CLICK_COPY_READS_MS = [0, 250, 1_000, 2_500, CLICK_COPY_MS];
+// Chromium shares its clipboard across contexts; capture copies made during real keys and clicks in a page-inaccessible world instead.
const CLIPBOARD_SCRIPT = `(() => {
let keying = false;
+ let clickedAt = -Infinity;
// One entry per copy or cut key, oldest first, so a later key cannot overwrite an unread copy.
- const copies = [];
+ const keyCopies = [];
+ let clickCopy = null;
+ let pending = null;
// The same Ctrl or Cmd + C or X that editingCommand sends as copy or cut.
addEventListener("keydown", (event) => {
if (!event.isTrusted || event.altKey || event.ctrlKey === event.metaKey) return;
const key = event.key.toLowerCase();
if (key !== "c" && key !== "x") return;
keying = true;
- copies.push({ at: Date.now(), text: "" });
+ keyCopies.push({ at: Date.now(), text: "" });
setTimeout(() => { keying = false; });
}, true);
+ for (const type of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
+ addEventListener(type, (event) => {
+ if (event.isTrusted && event.button === 0) clickedAt = performance.now();
+ }, true);
+ }
+ const canClickCopy = () =>
+ performance.now() - clickedAt < ${CLICK_COPY_MS} || navigator.userActivation?.isActive === true;
const selection = () => {
let field = document.activeElement;
while (field?.shadowRoot?.activeElement) field = field.shadowRoot.activeElement;
@@ -542,29 +562,193 @@ const CLIPBOARD_SCRIPT = `(() => {
return field.value.slice(field.selectionStart, field.selectionEnd ?? field.selectionStart);
return String(document.getSelection() ?? "");
};
- const record = (text) => {
- const copy = copies.at(-1);
+ const record = (copy, text) => {
if (copy) copy.text = String(text ?? "").slice(0, ${CLIPBOARD_TEXT_LIMIT});
};
+ const settle = () => {
+ if (!pending) return;
+ if (pending.event.defaultPrevented) record(pending.copy, pending.data ?? "");
+ pending = null;
+ };
// Capturing at window runs before page handlers can stop the event, and
// before cut removes the selection.
const snapshot = (event) => {
- if (keying && event.isTrusted) record(selection());
- };
- // Bubbling back to window picks up text a page handler set instead.
- const replace = (event) => {
- if (keying && event.isTrusted && event.defaultPrevented) record(event.clipboardData?.getData("text/plain"));
+ if (!event.isTrusted) return;
+ settle();
+ if (!keying && !canClickCopy()) return;
+ const copy = keying ? keyCopies.at(-1) : (clickCopy = { at: Date.now(), text: "" });
+ pending = { event, copy, data: undefined };
+ record(copy, selection());
+ setTimeout(settle);
};
for (const type of ["copy", "cut"]) {
addEventListener(type, snapshot, true);
- addEventListener(type, replace);
}
- // A key's copy was keyed between its dispatch and acknowledgement; older copies are stale.
- globalThis.takeCopy = (since, until) => {
- while (copies.length > 0 && copies[0].at < since) copies.shift();
- return copies[0] && copies[0].at <= until ? copies.shift().text : "";
+ addEventListener("${CLIPBOARD_DATA_EVENT}", (event) => {
+ if (pending && pending.event.eventPhase !== 0 && typeof event.detail === "string")
+ pending.data = event.detail;
+ }, true);
+ addEventListener("${CLIPBOARD_WRITE_EVENT}", (event) => {
+ if (!keying && canClickCopy() && typeof event.detail === "string") {
+ clickCopy = { at: Date.now(), text: "" };
+ record(clickCopy, event.detail);
+ }
+ }, true);
+ // Copies made before since are stale. A key's copy was made between its dispatch and
+ // acknowledgement (until). A click's read takes only what was copied before it started.
+ globalThis.takeCopy = (click, since, until) => {
+ settle();
+ let copy = null;
+ if (click) {
+ if (clickCopy && clickCopy.at < until) [copy, clickCopy] = [clickCopy, null];
+ } else {
+ while (keyCopies.length > 0 && keyCopies[0].at < since) keyCopies.shift();
+ if (keyCopies[0] && keyCopies[0].at <= until) copy = keyCopies.shift();
+ }
+ const text = copy && copy.at >= since ? copy.text : "";
+ return { text, host: URL.canParse(globalThis.origin) ? new URL(globalThis.origin).host : "" };
};
})();`;
+// navigator.clipboard.writeText fires no copy event, so the page's own world reports its text.
+// Only CLIPBOARD_SCRIPT, shortly after a real click, keeps it.
+const CLIPBOARD_WRITE_SCRIPT = `(() => {
+ const clipboard = globalThis.Clipboard?.prototype;
+ const writeText = clipboard?.writeText;
+ const reject = Promise.reject.bind(Promise);
+ const dispatch = EventTarget.prototype.dispatchEvent;
+ const Report = CustomEvent;
+ const report = (type, text) => {
+ try {
+ Reflect.apply(dispatch, globalThis, [new Report(type, { detail: text })]);
+ } catch {}
+ };
+ if (typeof writeText === "function") {
+ clipboard.writeText = new Proxy(writeText, {
+ apply(target, self, args) {
+ if (args.length > 0) {
+ let text;
+ try {
+ text = \`\${args[0]}\`;
+ } catch (error) {
+ return reject(error);
+ }
+ report("${CLIPBOARD_WRITE_EVENT}", text);
+ args[0] = text;
+ }
+ return Reflect.apply(target, self, args);
+ },
+ });
+ }
+ const transfer = globalThis.DataTransfer?.prototype;
+ const getData = transfer?.getData;
+ let copying = null;
+ for (const type of ["copy", "cut"]) {
+ addEventListener(type, (event) => {
+ if (event.isTrusted) copying = event;
+ }, true);
+ }
+ const reportData = (data) => {
+ if (copying?.eventPhase && copying.clipboardData === data)
+ report("${CLIPBOARD_DATA_EVENT}", Reflect.apply(getData, data, ["text/plain"]));
+ };
+ for (const method of ["setData", "clearData"]) {
+ const changeData = transfer?.[method];
+ if (typeof changeData !== "function" || typeof getData !== "function") continue;
+ transfer[method] = new Proxy(changeData, {
+ apply(target, self, args) {
+ const result = Reflect.apply(target, self, args);
+ reportData(self);
+ return result;
+ },
+ });
+ }
+ const owners = new WeakMap();
+ const items = transfer && Object.getOwnPropertyDescriptor(transfer, "items");
+ if (typeof items?.get === "function") {
+ Object.defineProperty(transfer, "items", {
+ ...items,
+ get: new Proxy(items.get, {
+ apply(target, self, args) {
+ const list = Reflect.apply(target, self, args);
+ owners.set(list, self);
+ return list;
+ },
+ }),
+ });
+ }
+ const itemList = globalThis.DataTransferItemList?.prototype;
+ for (const method of ["add", "remove", "clear"]) {
+ const changeItems = itemList?.[method];
+ if (typeof changeItems !== "function" || typeof getData !== "function") continue;
+ itemList[method] = new Proxy(changeItems, {
+ apply(target, self, args) {
+ const result = Reflect.apply(target, self, args);
+ const owner = owners.get(self);
+ if (owner) reportData(owner);
+ return result;
+ },
+ });
+ }
+})();`;
+
+const preparedContexts = new WeakMap>();
+export const prepareContext = (context: BrowserContext) => {
+ const prepared = preparedContexts.get(context);
+ if (prepared) return prepared;
+ const preparing = context
+ .grantPermissions(["clipboard-write"])
+ .then(() => context.addInitScript(CLIPBOARD_WRITE_SCRIPT))
+ .then(constVoid);
+ preparedContexts.set(context, preparing);
+ return preparing;
+};
+
+export const recordCopies = async (cdp: CDPSession) => {
+ // Scripts for new documents run only while this session's Page domain is on.
+ await cdp.send("Page.enable");
+ await cdp.send("Page.addScriptToEvaluateOnNewDocument", {
+ source: CLIPBOARD_SCRIPT,
+ worldName: CLIPBOARD_WORLD,
+ runImmediately: true,
+ });
+};
+
+/** Takes what each frame copied during a real copy key, or after a real click, from since to until. */
+export const takeSessionCopies = async (
+ cdp: CDPSession,
+ click: boolean,
+ since: number,
+ until: number,
+) => {
+ const tree = await cdp.send("Page.getFrameTree").catch(() => null);
+ if (!tree) return [];
+ const frameIds = (node: typeof tree.frameTree): Array => [
+ node.frame.id,
+ ...(node.childFrames ?? []).flatMap(frameIds),
+ ];
+ return Promise.all(
+ frameIds(tree.frameTree).map((frameId) =>
+ cdp
+ .send("Page.createIsolatedWorld", { frameId, worldName: CLIPBOARD_WORLD })
+ .then(({ executionContextId }) =>
+ cdp.send("Runtime.evaluate", {
+ contextId: executionContextId,
+ expression: `globalThis.takeCopy?.(${click}, ${since}, ${until})`,
+ returnByValue: true,
+ }),
+ )
+ .then(
+ ({ result }) => {
+ const copy = asRecord(result.value);
+ return typeof copy?.text === "string" && typeof copy.host === "string"
+ ? { text: copy.text, host: copy.host }
+ : null;
+ },
+ () => null,
+ ),
+ ),
+ );
+};
const make = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
@@ -1622,23 +1806,6 @@ const make = Effect.gen(function* () {
: Option.some({ path: download.path, fileName: download.fileName });
});
- const preparedContexts = new WeakSet();
- const prepareContext = async (context: BrowserContext) => {
- if (preparedContexts.has(context)) return;
- preparedContexts.add(context);
- await context.grantPermissions(["clipboard-write"]);
- };
-
- const recordCopies = async (cdp: CDPSession) => {
- // Scripts for new documents run only while this session's Page domain is on.
- await cdp.send("Page.enable");
- await cdp.send("Page.addScriptToEvaluateOnNewDocument", {
- source: CLIPBOARD_SCRIPT,
- worldName: CLIPBOARD_WORLD,
- runImmediately: true,
- });
- };
-
/** Out-of-process frames need their own copy-recording session until target closure. */
const recordFrameCopies = async (tab: ServerTab, frame: Frame) => {
if (frame === tab.page.mainFrame() || tab.frameSessions.has(frame)) return;
@@ -1662,37 +1829,39 @@ const make = Effect.gen(function* () {
await recordCopies(cdp).catch(constVoid);
};
- const takeSessionCopies = async (cdp: CDPSession, since: number, until: number) => {
- const tree = await cdp.send("Page.getFrameTree").catch(() => null);
- if (!tree) return [];
- const frameIds = (node: typeof tree.frameTree): Array => [
- node.frame.id,
- ...(node.childFrames ?? []).flatMap(frameIds),
- ];
- return Promise.all(
- frameIds(tree.frameTree).map((frameId) =>
- cdp
- .send("Page.createIsolatedWorld", { frameId, worldName: CLIPBOARD_WORLD })
- .then(({ executionContextId }) =>
- cdp.send("Runtime.evaluate", {
- contextId: executionContextId,
- expression: `globalThis.takeCopy?.(${since}, ${until})`,
- returnByValue: true,
- }),
- )
- .then(
- ({ result }) => (typeof result.value === "string" ? result.value : ""),
- () => "",
- ),
+ const takeCopy = async (tab: ServerTab, click: boolean, since: number, until: number) => {
+ const copies = await Promise.all(
+ [tab.cdp, ...tab.frameSessions.values()].map((cdp) =>
+ takeSessionCopies(cdp, click, since, until),
),
);
+ return copies.flat().find((copy) => copy !== null && copy.text.length > 0);
};
- const takeCopiedText = async (tab: ServerTab, since: number, until: number) => {
- const copies = await Promise.all(
- [tab.cdp, ...tab.frameSessions.values()].map((cdp) => takeSessionCopies(cdp, since, until)),
- );
- return copies.flat().find((text) => text.length > 0);
+ /** Offers this viewer what the page copies after its click, until another click or a control change. */
+ const offerClickCopy = async (
+ tab: ServerTab,
+ viewer: ViewerState,
+ press: NonNullable,
+ ) => {
+ const current = () =>
+ viewer.clicks === press.click &&
+ tab.control.generation === press.generation &&
+ tab.control.controller === viewer.id &&
+ tab.viewers.has(viewer) &&
+ !tab.closing;
+ let waited = 0;
+ for (const at of CLICK_COPY_READS_MS) {
+ await new Promise((resolve) => setTimeout(resolve, at - waited));
+ waited = at;
+ if (!current()) return;
+ const copied = await takeCopy(tab, true, press.since, Date.now());
+ if (!current()) return;
+ if (copied) {
+ viewer.push({ _tag: "copyOffer", ...copied });
+ return;
+ }
+ }
};
const adoptPopup = async (opener: ServerTab, popup: Page) => {
@@ -2989,6 +3158,7 @@ const make = Effect.gen(function* () {
});
const releaseViewerInput = async (viewer: ViewerState, session: CDPSession) => {
+ viewer.leftPress = null;
for (const { key, code } of viewer.pressedKeys.values()) {
await session.send("Input.dispatchKeyEvent", { type: "keyUp", key, code }).catch(constVoid);
}
@@ -3025,6 +3195,15 @@ const make = Effect.gen(function* () {
const button = ["none", "left", "middle", "right"].includes(String(message.button))
? (message.button as "none" | "left" | "middle" | "right")
: "none";
+ // Text the page copies after this viewer's own left click is offered, never written.
+ const offers = !tab.desktop && button === "left";
+ if (!tab.desktop && button !== "none" && action === "down") {
+ viewer.clicks++;
+ viewer.leftPress =
+ offers && viewer.pressedButtons.size === 0
+ ? { click: viewer.clicks, generation: tab.control.generation, since: Date.now() }
+ : null;
+ }
await session.send("Input.dispatchMouseEvent", {
type,
x: num(message.x),
@@ -3039,6 +3218,12 @@ const make = Effect.gen(function* () {
viewer.pressedButtons.set(button, { x: num(message.x), y: num(message.y) });
else if (action === "up") viewer.pressedButtons.delete(button);
}
+ if (offers && action === "up") {
+ const press = viewer.leftPress;
+ viewer.leftPress = null;
+ if (press?.click === viewer.clicks && press.generation === tab.control.generation)
+ void offerClickCopy(tab, viewer, press).catch(constVoid);
+ }
return;
}
case "wheel":
@@ -3087,8 +3272,8 @@ const make = Effect.gen(function* () {
tab.copyKeyedUntil = until;
// A busy frame answers late; its read must not hold later input.
const read = tab.copyReads.then(async () => {
- const copied = await takeCopiedText(tab, since, until);
- if (copied) viewer.push({ _tag: "clipboard", text: copied });
+ const copied = await takeCopy(tab, false, since, until);
+ if (copied) viewer.push({ _tag: "clipboard", text: copied.text });
});
tab.copyReads = read;
return () => read;
@@ -3225,6 +3410,8 @@ const make = Effect.gen(function* () {
canOperate: input.canOperate,
pressedKeys: new Map(),
pressedButtons: new Map(),
+ clicks: 0,
+ leftPress: null,
push: (next) => {
// Dropped frames must still release Chromium.
if (Queue.offerUnsafe(output, next)) return;
diff --git a/apps/server/src/preview/ServerBrowserStream.ts b/apps/server/src/preview/ServerBrowserStream.ts
index 649af3b31d0db..1673a5380bfd2 100644
--- a/apps/server/src/preview/ServerBrowserStream.ts
+++ b/apps/server/src/preview/ServerBrowserStream.ts
@@ -160,6 +160,7 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBr
case "viewport":
case "control":
case "clipboard":
+ case "copyOffer":
case "download":
case "fileChooser":
case "fileChooserClosed":
diff --git a/apps/web/src/browser/ServerBrowserSurface.browser.test.tsx b/apps/web/src/browser/ServerBrowserSurface.browser.test.tsx
index c52ff3e892cf2..8de497adfcab5 100644
--- a/apps/web/src/browser/ServerBrowserSurface.browser.test.tsx
+++ b/apps/web/src/browser/ServerBrowserSurface.browser.test.tsx
@@ -5,9 +5,10 @@ import type {
PreviewStreamInput,
} from "@t3tools/client-runtime/preview/server-browser-stream";
import { describe, expect, it, vi } from "vite-plus/test";
-import { userEvent } from "vite-plus/test/browser";
+import { page, userEvent } from "vite-plus/test/browser";
import { act, fakeTimers, render } from "../../test/render";
+import { ToastProvider } from "~/components/ui/toast";
const mocks = vi.hoisted(() => ({
createClient: vi.fn<(target: unknown, handlers: PreviewStreamEvents) => unknown>(),
@@ -73,6 +74,35 @@ async function renderSurface(controller: PreviewStreamControl["controller"]) {
const keys = () => mocks.sent.filter((input) => input.type === "key");
describe("ServerBrowserSurface clipboard commands", () => {
+ it("copies an offered value only on acceptance, or says it could not, without the Clipboard API", async () => {
+ setup();
+ const { screen } = await renderSurface("you");
+ await using _screen = screen;
+ await using _toasts = await render({null});
+ using _clipboard = vi.spyOn(navigator, "clipboard", "get").mockReturnValue(undefined as never);
+ const copied: string[] = [];
+ const onCopy = (event: ClipboardEvent) => {
+ const target = event.target;
+ if (event.isTrusted && target instanceof HTMLTextAreaElement)
+ copied.push(target.value.slice(target.selectionStart, target.selectionEnd));
+ };
+ document.addEventListener("copy", onCopy);
+ using _listener = { [Symbol.dispose]: () => document.removeEventListener("copy", onCopy) };
+ const handlers = mocks.createClient.mock.calls.at(-1)![1];
+ await act(() => handlers.onCopyOffer?.({ text: "offered value", host: "copy.example" }));
+ await expect.element(page.getByText("copy.example wants to copy text")).toBeVisible();
+ expect(copied).toEqual([]);
+
+ await userEvent.click(page.getByRole("button", { name: "Copy", exact: true }));
+ expect(copied).toEqual(["offered value"]);
+ expect(keys()).toEqual([]);
+
+ using _refused = vi.spyOn(document, "execCommand").mockReturnValue(false);
+ await act(() => handlers.onCopyOffer?.({ text: "refused value", host: "copy.example" }));
+ await userEvent.click(page.getByRole("button", { name: "Copy", exact: true }));
+ await expect.element(page.getByText("Could not copy the text")).toBeVisible();
+ });
+
it("sends a native Copy or Cut menu command to the page once", async () => {
setup();
const { screen, input, canvas } = await renderSurface("you");
diff --git a/apps/web/src/browser/ServerBrowserSurface.tsx b/apps/web/src/browser/ServerBrowserSurface.tsx
index 868da347164ab..54314de25bfc4 100644
--- a/apps/web/src/browser/ServerBrowserSurface.tsx
+++ b/apps/web/src/browser/ServerBrowserSurface.tsx
@@ -5,6 +5,7 @@ import {
previewStreamModifiers,
type PreviewStreamClient,
type PreviewStreamControl,
+ type PreviewStreamCopyOffer,
type PreviewStreamDownload,
type PreviewStreamFileChooser,
uploadPreviewStreamFiles,
@@ -39,6 +40,7 @@ import { CommandBlock } from "~/components/CommandBlock";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import { toastManager } from "~/components/ui/toast";
+import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
import { m } from "~/i18n/messages";
import { cn } from "~/lib/utils";
@@ -128,6 +130,29 @@ async function copyPageText(text: string) {
}
}
+/** Only this click writes a page's own copy to the clipboard. */
+function offerPageCopy({ text, host }: PreviewStreamCopyOffer) {
+ const id = toastManager.add({
+ type: "info",
+ title: host
+ ? m(msg("{host} wants to copy text", { host }))
+ : m(msg("This page wants to copy text")),
+ actionProps: {
+ children: m(msg("Copy", { $context: "verb, copies text to the clipboard" })),
+ onClick: () => {
+ toastManager.close(id);
+ void writeTextToClipboard(text).catch((cause: unknown) =>
+ toastManager.add({
+ type: "error",
+ title: m(msg("Could not copy the text")),
+ description: thrownErrorMessage(cause, m) ?? undefined,
+ }),
+ );
+ },
+ },
+ });
+}
+
function offerDownload(download: PreviewStreamDownload) {
const id = toastManager.add({
type: "info",
@@ -417,6 +442,7 @@ export function ServerBrowserSurface(props: {
if (placed) setAgentCursor(placed);
},
onClipboard: (text) => void copyPageText(text),
+ onCopyOffer: offerPageCopy,
onDownload: offerDownload,
onPopup: popupOpened,
onFileChooser: setFileChooser,
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json
index 46df7424ab0f2..17c81af7cbf7f 100644
--- a/apps/web/src/i18n/translations/de.json
+++ b/apps/web/src/i18n/translations/de.json
@@ -1446,6 +1446,9 @@
"44a0347dbc93ba80": "Browser-Viewport an der unteren rechten Ecke skalieren",
"982f66971bc47617": "Die Seite hat Text kopiert",
"4cffda9eddb15bb2": "Kopieren",
+ "6f1da9a36c248d39": "{host} möchte Text kopieren",
+ "d044949d07b00044": "Diese Seite möchte Text kopieren",
+ "c19c369300a0c9f0": "Der Text konnte nicht kopiert werden",
"bbcd3776bcd3e2c5": "{fileName} heruntergeladen",
"da52805f1f7bae35": "Speichern",
"16c1876c1c9e5579": "Die Dateien konnten nicht an die Seite gesendet werden",
diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json
index fc971dba6e051..6c0b403823909 100644
--- a/apps/web/src/i18n/translations/en.json
+++ b/apps/web/src/i18n/translations/en.json
@@ -1446,6 +1446,9 @@
"44a0347dbc93ba80": "Resize browser viewport from bottom-right corner",
"982f66971bc47617": "The page copied text",
"4cffda9eddb15bb2": "Copy",
+ "6f1da9a36c248d39": "{host} wants to copy text",
+ "d044949d07b00044": "This page wants to copy text",
+ "c19c369300a0c9f0": "Could not copy the text",
"bbcd3776bcd3e2c5": "Downloaded {fileName}",
"da52805f1f7bae35": "Save",
"16c1876c1c9e5579": "Could not send the files to the page",
diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json
index 797888016bd4a..32e71235b18bd 100644
--- a/apps/web/src/i18n/translations/es.json
+++ b/apps/web/src/i18n/translations/es.json
@@ -1446,6 +1446,9 @@
"44a0347dbc93ba80": "Cambiar el tamaño del viewport desde la esquina inferior derecha",
"982f66971bc47617": "La página copió texto",
"4cffda9eddb15bb2": "Copiar",
+ "6f1da9a36c248d39": "{host} quiere copiar texto",
+ "d044949d07b00044": "Esta página quiere copiar texto",
+ "c19c369300a0c9f0": "No se pudo copiar el texto",
"bbcd3776bcd3e2c5": "Se descargó {fileName}",
"da52805f1f7bae35": "Guardar",
"16c1876c1c9e5579": "No se pudieron enviar los archivos a la página",
diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json
index e06cde54989bd..63aba503b75a9 100644
--- a/apps/web/src/i18n/translations/fr.json
+++ b/apps/web/src/i18n/translations/fr.json
@@ -1446,6 +1446,9 @@
"44a0347dbc93ba80": "Redimensionner la fenêtre d’affichage depuis le coin inférieur droit",
"982f66971bc47617": "La page a copié du texte",
"4cffda9eddb15bb2": "Copier",
+ "6f1da9a36c248d39": "{host} veut copier du texte",
+ "d044949d07b00044": "Cette page veut copier du texte",
+ "c19c369300a0c9f0": "Impossible de copier le texte",
"bbcd3776bcd3e2c5": "{fileName} téléchargé",
"da52805f1f7bae35": "Enregistrer",
"16c1876c1c9e5579": "Impossible d’envoyer les fichiers à la page",
diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json
index 4473bff3ddef1..3ded597f16931 100644
--- a/apps/web/src/i18n/translations/ja.json
+++ b/apps/web/src/i18n/translations/ja.json
@@ -1446,6 +1446,9 @@
"44a0347dbc93ba80": "ブラウザーのビューポートを右下隅からサイズ変更",
"982f66971bc47617": "ページがテキストをコピーしました",
"4cffda9eddb15bb2": "コピー",
+ "6f1da9a36c248d39": "{host} がテキストをコピーしようとしています",
+ "d044949d07b00044": "このページがテキストをコピーしようとしています",
+ "c19c369300a0c9f0": "テキストをコピーできませんでした",
"bbcd3776bcd3e2c5": "{fileName} をダウンロードしました",
"da52805f1f7bae35": "保存",
"16c1876c1c9e5579": "ページにファイルを送信できませんでした",
diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json
index 68f0b20794362..3e0a508928e0d 100644
--- a/apps/web/src/i18n/translations/ko.json
+++ b/apps/web/src/i18n/translations/ko.json
@@ -1446,6 +1446,9 @@
"44a0347dbc93ba80": "오른쪽 아래 모서리에서 브라우저 뷰포트 크기 조정",
"982f66971bc47617": "페이지에서 텍스트를 복사했습니다",
"4cffda9eddb15bb2": "복사",
+ "6f1da9a36c248d39": "{host}에서 텍스트를 복사하려고 합니다",
+ "d044949d07b00044": "이 페이지에서 텍스트를 복사하려고 합니다",
+ "c19c369300a0c9f0": "텍스트를 복사할 수 없습니다",
"bbcd3776bcd3e2c5": "{fileName} 다운로드됨",
"da52805f1f7bae35": "저장",
"16c1876c1c9e5579": "페이지에 파일을 보낼 수 없습니다",
diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json
index 5a18a359ecb2a..e37fd62d06dea 100644
--- a/apps/web/src/i18n/translations/pt-BR.json
+++ b/apps/web/src/i18n/translations/pt-BR.json
@@ -1446,6 +1446,9 @@
"44a0347dbc93ba80": "Redimensionar a viewport do navegador pelo canto inferior direito",
"982f66971bc47617": "A página copiou um texto",
"4cffda9eddb15bb2": "Copiar",
+ "6f1da9a36c248d39": "{host} quer copiar um texto",
+ "d044949d07b00044": "Esta página quer copiar um texto",
+ "c19c369300a0c9f0": "Não foi possível copiar o texto",
"bbcd3776bcd3e2c5": "{fileName} baixado",
"da52805f1f7bae35": "Salvar",
"16c1876c1c9e5579": "Não foi possível enviar os arquivos para a página",
diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json
index 6c7fa00a15455..2c93f76279a33 100644
--- a/apps/web/src/i18n/translations/ru.json
+++ b/apps/web/src/i18n/translations/ru.json
@@ -1446,6 +1446,9 @@
"44a0347dbc93ba80": "Изменить размер области просмотра с нижнего правого угла",
"982f66971bc47617": "Страница скопировала текст",
"4cffda9eddb15bb2": "Копировать",
+ "6f1da9a36c248d39": "{host} хочет скопировать текст",
+ "d044949d07b00044": "Эта страница хочет скопировать текст",
+ "c19c369300a0c9f0": "Не удалось скопировать текст",
"bbcd3776bcd3e2c5": "Скачан {fileName}",
"da52805f1f7bae35": "Сохранить",
"16c1876c1c9e5579": "Не удалось передать файлы странице",
diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json
index d02de62557d73..b0693506020b2 100644
--- a/apps/web/src/i18n/translations/sv.json
+++ b/apps/web/src/i18n/translations/sv.json
@@ -1446,6 +1446,9 @@
"44a0347dbc93ba80": "Ändra storlek på webbläsarens visningsyta från nedre högra hörnet",
"982f66971bc47617": "Sidan kopierade text",
"4cffda9eddb15bb2": "Kopiera",
+ "6f1da9a36c248d39": "{host} vill kopiera text",
+ "d044949d07b00044": "Den här sidan vill kopiera text",
+ "c19c369300a0c9f0": "Kunde inte kopiera texten",
"bbcd3776bcd3e2c5": "Laddade ned {fileName}",
"da52805f1f7bae35": "Spara",
"16c1876c1c9e5579": "Kunde inte skicka filerna till sidan",
diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json
index acf5ce3045376..73c2229eb8804 100644
--- a/apps/web/src/i18n/translations/zh.json
+++ b/apps/web/src/i18n/translations/zh.json
@@ -1446,6 +1446,9 @@
"44a0347dbc93ba80": "从右下角调整浏览器视口大小",
"982f66971bc47617": "页面复制了文字",
"4cffda9eddb15bb2": "复制",
+ "6f1da9a36c248d39": "{host} 想要复制文字",
+ "d044949d07b00044": "此页面想要复制文字",
+ "c19c369300a0c9f0": "无法复制文字",
"bbcd3776bcd3e2c5": "已下载 {fileName}",
"da52805f1f7bae35": "保存",
"16c1876c1c9e5579": "无法将文件发送到页面",
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index 7a6731d9ebe10..b4e2fde66216a 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -310,9 +310,10 @@ Agent tabs have separate storage and share a Chromium process. Take control befo
typing into an agent's tab, then release control when you want the agent to
continue. Read-only connections can watch without changing the page.
-While you have control, the tab works with your device: text the page copies or
-cuts goes to your clipboard, a file picker on the page opens your device's
-picker, and a finished download is offered for you to save. Popups such as
+While you control a streamed tab, text you copy or cut goes to your clipboard.
+Text a page copies after you click it (such as a Copy button) waits for you to
+choose **Copy**. A file picker on the page opens your device's picker, and a
+finished download is offered for you to save. Popups such as
sign-in windows open as their own tabs. Downloads stay on the host until the
tab closes. Audio does not play on your device.
diff --git a/packages/client-runtime/src/preview/serverBrowserStream.ts b/packages/client-runtime/src/preview/serverBrowserStream.ts
index 24d1cddd62fc8..edf4cffeccab6 100644
--- a/packages/client-runtime/src/preview/serverBrowserStream.ts
+++ b/packages/client-runtime/src/preview/serverBrowserStream.ts
@@ -107,6 +107,12 @@ export interface PreviewStreamDownload {
readonly url: string;
}
+/** Text the page copied after the user's click; write it only on a further local action. */
+export interface PreviewStreamCopyOffer {
+ readonly text: string;
+ readonly host: string;
+}
+
export interface PreviewStreamFileChooser {
readonly multiple: boolean;
readonly accept: string;
@@ -197,6 +203,7 @@ export interface PreviewStreamEvents {
readonly onPointer?: (pointer: PreviewStreamPointer) => void;
readonly onControl?: (control: PreviewStreamControl) => void;
readonly onClipboard?: (text: string) => void;
+ readonly onCopyOffer?: (offer: PreviewStreamCopyOffer) => void;
readonly onDownload?: (download: PreviewStreamDownload) => void;
readonly onPopup?: (tabId: string) => void;
readonly onFileChooser?: (chooser: PreviewStreamFileChooser | null) => void;
@@ -286,6 +293,7 @@ export function createPreviewStreamClient(
phase,
sequence,
tabId,
+ host,
} = message as Record;
if (
type === "fileChooser" &&
@@ -316,6 +324,8 @@ export function createPreviewStreamClient(
events.onPopup?.(tabId);
} else if (type === "clipboard" && typeof text === "string") {
events.onClipboard?.(text);
+ } else if (type === "copyOffer" && typeof text === "string" && typeof host === "string") {
+ events.onCopyOffer?.({ text, host });
} else if (
type === "download" &&
typeof id === "string" &&