diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index c32947b30b995..89d0d5a12728b 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -129,9 +129,13 @@ function makeSession( return { result: { value: [] } }; } if (method === "Page.addScriptToEvaluateOnNewDocument") frame?.recording.resolve(); - if (method === "Input.dispatchKeyEvent" && (input as { commands?: unknown }).commands) { - if (focusedFrame) focusedFrame.copy = keyCopy || focusedFrame.copy; - else pageCopy = keyCopy || pageCopy; + // The recorder drops its last copy on every copy or cut key it sees. + if ( + method === "Input.dispatchKeyEvent" && + ["copy", "cut"].includes((input as { commands?: Array }).commands?.[0] ?? "") + ) { + if (focusedFrame) focusedFrame.copy = keyCopy; + else pageCopy = keyCopy; } if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7) { const value = frame ? frame.copy : pageCopy; @@ -1409,6 +1413,54 @@ it.live("only the controlling viewer's copy and cut keys reach its clipboard", ( ).pipe(Effect.provide(layer)), ); +it.live("a busy embedded frame does not hold a copy key back from the page", () => + Effect.scoped( + Effect.gen(function* () { + const { browser, tabId } = yield* ready; + const context = contexts[0]!; + const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); + yield* viewer.input({ type: "takeControl" }); + const pageSession = context.sessions.at(-1)!; + const frame = makeFrame(); + 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(); + const pageSend = pageSession.send.getMockImplementation()!; + pageSession.send.mockImplementation(async (method, input) => { + if (method === "Input.dispatchKeyEvent" && (input as { type?: string }).type === "keyUp") + keyReached.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; + } + return frameSend(method, input); + }); + + keyCopy = "copied"; + const copying = yield* viewer + .input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* viewer.input({ type: "key", action: "up", key: "c", code: "KeyC", modifiers: 4 }); + yield* Fiber.join(copying); + expect(pageSession.send).toHaveBeenCalledWith( + "Input.dispatchKeyEvent", + expect.objectContaining({ key: "c", commands: ["copy"] }), + ); + const clipboard = yield* Queue.clear(viewer.output); + expect(clipboard.filter((item) => item._tag === "clipboard")).toEqual([ + { _tag: "clipboard", text: "copied" }, + ]); + }), + ).pipe(Effect.provide(layer)), +); + it.live.each([false, true])( "a page download is saved, offered to the controller, and listed for the agent (delete fails: %s)", (deleteFails) => diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index ee31b17cc5889..c6ff6d51a3f23 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -295,6 +295,10 @@ interface ServerTab { readonly page: Page; readonly cdp: CDPSession; readonly frameSessions: Map; + /** Copy reads run in key order, outside the input queue. */ + copyReads: Promise; + /** When the last copy or cut key was acknowledged; the next one starts after it. */ + copyKeyedUntil: number; readonly createdAt: number; usedAt: number; readonly viewers: Set; @@ -427,14 +431,15 @@ 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_SCRIPT = `(() => { let keying = false; - let copied = ""; + // One entry per copy or cut key, oldest first, so a later key cannot overwrite an unread copy. + const copies = []; // 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; - copied = ""; + copies.push({ at: Date.now(), text: "" }); setTimeout(() => { keying = false; }); }, true); const selection = () => { @@ -445,7 +450,8 @@ const CLIPBOARD_SCRIPT = `(() => { return String(document.getSelection() ?? ""); }; const record = (text) => { - copied = String(text ?? "").slice(0, ${CLIPBOARD_TEXT_LIMIT}); + const copy = copies.at(-1); + if (copy) copy.text = String(text ?? "").slice(0, ${CLIPBOARD_TEXT_LIMIT}); }; // Capturing at window runs before page handlers can stop the event, and // before cut removes the selection. @@ -460,10 +466,10 @@ const CLIPBOARD_SCRIPT = `(() => { addEventListener(type, snapshot, true); addEventListener(type, replace); } - globalThis.takeCopy = () => { - const text = copied; - copied = ""; - return text; + // 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 : ""; }; })();`; @@ -867,6 +873,8 @@ const make = Effect.gen(function* () { page, cdp, frameSessions: new Map(), + copyReads: Promise.resolve(), + copyKeyedUntil: 0, createdAt: Date.now(), usedAt: Date.now(), viewers: new Set(), @@ -1310,7 +1318,7 @@ const make = Effect.gen(function* () { await recordCopies(cdp).catch(constVoid); }; - const takeSessionCopies = async (cdp: CDPSession) => { + 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 => [ @@ -1324,7 +1332,7 @@ const make = Effect.gen(function* () { .then(({ executionContextId }) => cdp.send("Runtime.evaluate", { contextId: executionContextId, - expression: "globalThis.takeCopy?.()", + expression: `globalThis.takeCopy?.(${since}, ${until})`, returnByValue: true, }), ) @@ -1336,9 +1344,9 @@ const make = Effect.gen(function* () { ); }; - const takeCopiedText = async (tab: ServerTab) => { + const takeCopiedText = async (tab: ServerTab, since: number, until: number) => { const copies = await Promise.all( - [tab.cdp, ...tab.frameSessions.values()].map(takeSessionCopies), + [tab.cdp, ...tab.frameSessions.values()].map((cdp) => takeSessionCopies(cdp, since, until)), ); return copies.flat().find((text) => text.length > 0); }; @@ -2447,7 +2455,10 @@ const make = Effect.gen(function* () { const copying = !tab.desktop && (command?.commands[0] === "copy" || command?.commands[0] === "cut"); - if (copying) await takeCopiedText(tab); + // Copy keys get disjoint millisecond windows so each frame's copy belongs to one key. + if (copying) + while (Date.now() <= tab.copyKeyedUntil) await sleepUntil(tab.copyKeyedUntil + 1); + const since = Date.now(); await session.send("Input.dispatchKeyEvent", { type: text ? "keyDown" : "rawKeyDown", key, @@ -2461,11 +2472,16 @@ const make = Effect.gen(function* () { ), }); viewer.pressedKeys.set(code || key, { key, code }); - if (copying) { - const copied = await takeCopiedText(tab); + if (!copying) return; + const until = Date.now(); + 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 }); - } - return; + }); + tab.copyReads = read; + return () => read; } case "text": if (typeof message.text === "string" && message.text.length > 0) { @@ -2721,8 +2737,9 @@ const make = Effect.gen(function* () { : {}), }); } else { - const dispatch = (input: Record) => - dispatchViewerInput(tab, session, viewer, input); + const dispatch = async (input: Record) => { + await dispatchViewerInput(tab, session, viewer, input); + }; if ( message.type === "mouse" && message.action === "move" && @@ -2749,7 +2766,10 @@ const make = Effect.gen(function* () { }), ); } else { - await tab.control.human(viewer.id, () => dispatch(message)); + const copyRead = await tab.control.human(viewer.id, () => + dispatchViewerInput(tab, session, viewer, message), + ); + await copyRead?.(); } } } catch {