@@ -262,8 +262,6 @@ interface ViewerState {
262262 readonly pause : ( ) => Promise < void > ;
263263 readonly resume : ( ) => Promise < void > ;
264264 scrolledAt : number ;
265- /** Last input from this viewer; page copies reach its clipboard only right after. */
266- inputAt : number ;
267265 /** Panel bounds, retained in fixed mode; passive viewers never request a size. */
268266 requestedSize : { width : number ; height : number ; order : number } | null ;
269267}
@@ -434,43 +432,38 @@ const editingCommand = (key: string, modifiers: number) => {
434432} ;
435433
436434const CLIPBOARD_TEXT_LIMIT = 1024 * 1024 ;
437- /** Copies reach the viewer only this soon after it last touched the page. */
438- const CLIPBOARD_GESTURE_MS = 5_000 ;
439- const CLIPBOARD_BINDING = "__t3PreviewClipboard" ;
440- // Headless Chromium shares one clipboard between every context, so pages
441- // report their own copies instead of the clipboard being read back .
435+ const CLIPBOARD_WORLD = "t3-preview-clipboard" ;
436+ // Headless Chromium shares one clipboard between every context, so the copy
437+ // a viewer's copy or cut key makes is read from this world instead of the
438+ // clipboard. Page scripts cannot see the world, and only a copy made while a
439+ // real key is handled counts .
442440const CLIPBOARD_SCRIPT = `(() => {
443- const send = (text) => {
444- if (typeof text !== "string" || text.length === 0) return;
445- try { globalThis.${ CLIPBOARD_BINDING } ?.(text.slice(0, ${ CLIPBOARD_TEXT_LIMIT } )); } catch {}
446- };
441+ let keying = false;
442+ let copied = "";
443+ addEventListener("keydown", (event) => {
444+ if (!event.isTrusted) return;
445+ keying = true;
446+ copied = "";
447+ setTimeout(() => { keying = false; });
448+ }, true);
447449 const selection = () => {
448450 const field = document.activeElement;
449451 if ((field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement) && field.selectionStart !== null)
450452 return field.value.slice(field.selectionStart, field.selectionEnd ?? field.selectionStart);
451453 return String(document.getSelection() ?? "");
452454 };
453455 // Bubbling to window runs after page handlers, before cut removes the selection.
454- const copied = (event) =>
455- send(event.defaultPrevented ? event.clipboardData?.getData("text/plain") : selection());
456- addEventListener("copy", copied);
457- addEventListener("cut", copied);
458- const proto = globalThis.Clipboard?.prototype;
459- if (!proto) return;
460- const writeText = proto.writeText;
461- proto.writeText = function (text) {
462- const result = writeText.call(this, text);
463- result.then(() => send(String(text)), () => {});
464- return result;
456+ const record = (event) => {
457+ if (!keying || !event.isTrusted) return;
458+ const text = event.defaultPrevented ? event.clipboardData?.getData("text/plain") : selection();
459+ copied = String(text ?? "").slice(0, ${ CLIPBOARD_TEXT_LIMIT } );
465460 };
466- const write = proto.write;
467- proto.write = function (items) {
468- const result = write.call(this, items);
469- result.then(async () => {
470- const item = [...items].find((candidate) => candidate.types.includes("text/plain"));
471- if (item) send(await (await item.getType("text/plain")).text());
472- }, () => {});
473- return result;
461+ addEventListener("copy", record);
462+ addEventListener("cut", record);
463+ globalThis.takeCopy = () => {
464+ const text = copied;
465+ copied = "";
466+ return text;
474467 };
475468})();` ;
476469
@@ -763,13 +756,14 @@ const make = Effect.gen(function* () {
763756 isolatedContext ? tabKey ( snapshot . threadId , snapshot . tabId ) : undefined ,
764757 ) ) ;
765758 if ( adopted ?. page . isClosed ( ) ) throw new Error ( "The popup closed before it opened." ) ;
766- // The desktop page already has its own clipboard; the bridge script is for headless tabs .
759+ // The desktop page already has its own clipboard.
767760 if ( ! desktop ) await prepareContext ( context ) ;
768761 const page = adopted ?. page ?? desktop ?. page ?? ( await context . newPage ( ) ) ;
769762 const cdp = await context . newCDPSession ( page ) ;
770763 // The desktop's page is already a normal browser. A popup's first request
771764 // went out before it became a tab; everything after presents as Chrome.
772765 if ( ! desktop ) await presentAsChrome ( cdp , host ) ;
766+ if ( ! desktop ) await recordCopies ( cdp ) ;
773767 page . setDefaultTimeout ( NAVIGATION_TIMEOUT_MS ) ;
774768 page . setDefaultNavigationTimeout ( NAVIGATION_TIMEOUT_MS ) ;
775769 const control = new SessionControl ( snapshot . automationOwner ?? null , ( ) =>
@@ -1129,16 +1123,45 @@ const make = Effect.gen(function* () {
11291123 if ( preparedContexts . has ( context ) ) return ;
11301124 preparedContexts . add ( context ) ;
11311125 await context . grantPermissions ( [ "clipboard-write" ] ) ;
1132- await context . exposeBinding ( CLIPBOARD_BINDING , ( { page } , text : unknown ) => {
1133- if ( typeof text !== "string" ) return ;
1134- const tab = [ ...tabs . values ( ) ] . find ( ( candidate ) => candidate . page === page ) ;
1135- const controller = tab
1136- ? [ ...tab . viewers ] . find ( ( viewer ) => viewer . id === tab . control . controller )
1137- : undefined ;
1138- if ( ! controller || Date . now ( ) - controller . inputAt > CLIPBOARD_GESTURE_MS ) return ;
1139- controller . push ( { _tag : "clipboard" , text : text . slice ( 0 , CLIPBOARD_TEXT_LIMIT ) } ) ;
1126+ } ;
1127+
1128+ /** Records the copies made in each of a headless page's frames. */
1129+ const recordCopies = async ( cdp : CDPSession ) => {
1130+ // Scripts for new documents run only while this session's Page domain is on.
1131+ await cdp . send ( "Page.enable" ) ;
1132+ await cdp . send ( "Page.addScriptToEvaluateOnNewDocument" , {
1133+ source : CLIPBOARD_SCRIPT ,
1134+ worldName : CLIPBOARD_WORLD ,
1135+ runImmediately : true ,
11401136 } ) ;
1141- await context . addInitScript ( CLIPBOARD_SCRIPT ) ;
1137+ } ;
1138+
1139+ /** What the key just handled copied or cut in any of the tab's frames, once. */
1140+ const takeCopiedText = async ( tab : ServerTab ) => {
1141+ const { frameTree } = await tab . cdp . send ( "Page.getFrameTree" ) ;
1142+ const frameIds = ( node : typeof frameTree ) : Array < string > => [
1143+ node . frame . id ,
1144+ ...( node . childFrames ?? [ ] ) . flatMap ( frameIds ) ,
1145+ ] ;
1146+ const copies = await Promise . all (
1147+ frameIds ( frameTree ) . map ( ( frameId ) =>
1148+ tab . cdp
1149+ . send ( "Page.createIsolatedWorld" , { frameId, worldName : CLIPBOARD_WORLD } )
1150+ . then ( ( { executionContextId } ) =>
1151+ tab . cdp . send ( "Runtime.evaluate" , {
1152+ contextId : executionContextId ,
1153+ expression : "globalThis.takeCopy?.()" ,
1154+ returnByValue : true ,
1155+ } ) ,
1156+ )
1157+ . then (
1158+ ( { result } ) => ( typeof result . value === "string" ? result . value : "" ) ,
1159+ // A frame that detached meanwhile copied nothing.
1160+ ( ) => "" ,
1161+ ) ,
1162+ ) ,
1163+ ) ;
1164+ return copies . find ( ( text ) => text . length > 0 ) ;
11421165 } ;
11431166
11441167 const adoptPopup = async ( opener : ServerTab , popup : Page ) => {
@@ -2058,7 +2081,6 @@ const make = Effect.gen(function* () {
20582081 ) => {
20592082 const message = asRecord ( raw ) ;
20602083 if ( ! message ) return ;
2061- viewer . inputAt = Date . now ( ) ;
20622084 const modifiers = modifiersOf ( message ) ;
20632085 switch ( message . type ) {
20642086 case "mouse" : {
@@ -2104,19 +2126,26 @@ const make = Effect.gen(function* () {
21042126 viewer . pressedKeys . delete ( code || key ) ;
21052127 return ;
21062128 }
2129+ const command = editingCommand ( key , modifiers ) ;
21072130 await session . send ( "Input.dispatchKeyEvent" , {
21082131 type : text ? "keyDown" : "rawKeyDown" ,
21092132 key,
21102133 code,
21112134 modifiers,
21122135 ...( text ? { text, unmodifiedText : text } : { } ) ,
2113- ...editingCommand ( key , modifiers ) ,
2136+ ...command ,
21142137 windowsVirtualKeyCode : num (
21152138 message . keyCode ,
21162139 key . length === 1 ? key . toUpperCase ( ) . charCodeAt ( 0 ) : 0 ,
21172140 ) ,
21182141 } ) ;
21192142 viewer . pressedKeys . set ( code || key , { key, code } ) ;
2143+ // Only the controlling viewer's own copy and cut reach its clipboard.
2144+ const copying = command ?. commands [ 0 ] === "copy" || command ?. commands [ 0 ] === "cut" ;
2145+ if ( copying && ! tab . desktop ) {
2146+ const copied = await takeCopiedText ( tab ) ;
2147+ if ( copied ) viewer . push ( { _tag : "clipboard" , text : copied } ) ;
2148+ }
21202149 return ;
21212150 }
21222151 case "text" :
@@ -2251,7 +2280,6 @@ const make = Effect.gen(function* () {
22512280 } ,
22522281 resume : ( ) => startScreencast ( screencastScale ) ,
22532282 scrolledAt : 0 ,
2254- inputAt : 0 ,
22552283 requestedSize : null ,
22562284 } ;
22572285 yield * Effect . acquireRelease (
0 commit comments