Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(clipboard): preserve presentation style in shared snapshots
ldm08df3ad554c99
diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/clipboard.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/clipboard.rsindex 99bb906f4..1df935f8e 100644--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/clipboard.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/clipboard.rs@@ -2,6 +2,7 @@ use super::super::{SIMPLE_EVENT_TARGET_ORDERED_HANDLERS_SLOT, SIMPLE_EVENT_TARGEuse crate::web_api_interfaces;use crate::{blob,+ runtime::{ClipboardPresentationStyle as PresentationStyle, ClipboardSnapshot},util::{context_host_ptr_from_context_slot, get_private_value, throw_type_error, v8_string},webidl,};@@ -77,25 +78,6 @@ struct ClipboardItemConstructorDeclaration {supports: (),}-#[derive(Clone, Copy, Default, webidl::WebIdlEnum)]-#[webidl(name = "PresentationStyle", rename_all = "kebab-case")]-enum PresentationStyle {- #[default]- Unspecified,- Inline,- Attachment,-}--impl PresentationStyle {- const fn as_str(self) -> &'static str {- match self {- Self::Unspecified => "unspecified",- Self::Inline => "inline",- Self::Attachment => "attachment",- }- }-}-#[derive(Default, webidl::WebIdlDictionary)]#[webidl(prefix = "ClipboardItemOptions")]struct ClipboardItemOptions {@@ -358,17 +340,17 @@ fn initialize_clipboard_item<'s>(fn build_clipboard_item<'s>(scope: &mut v8::PinScope<'s, '_>,entries: Vec<(String, v8::Local<'s, v8::Promise>)>,+ presentation_style: PresentationStyle,) -> Option<v8::Local<'s, v8::Object>> {let object = ClipboardItemObjectDeclaration::new(v8::Object::new(scope),v8::Object::new(scope),v8::Array::new(scope, 0),- PresentationStyle::Unspecified.as_str().to_owned(),+ presentation_style.as_str().to_owned(),).bind(scope).ok()?;- initialize_clipboard_item(scope, object, entries, PresentationStyle::Unspecified)- .then_some(object)+ initialize_clipboard_item(scope, object, entries, presentation_style).then_some(object)}fn clipboard_item_data_to_blob_callback<'s>(@@ -695,7 +677,10 @@ fn clipboard_write_text_callback<'s>(if reject_denied_clipboard_access(scope, args.this(), "clipboard-write", &mut rv) {return;}- runtime.set_clipboard_data(vec![("text/plain".to_owned(), parsed.data.into_bytes())]);+ runtime.set_clipboard_snapshot(ClipboardSnapshot {+ presentation_style: PresentationStyle::Unspecified,+ representations: vec![("text/plain".to_owned(), parsed.data.into_bytes())],+ });set_resolved_promise(scope, &mut rv, v8::undefined(scope).into());}@@ -897,12 +882,12 @@ fn clipboard_store_validated_item_callback<'s>(let _ = resolver.reject(scope, reason);return;}- let Some(data) = clipboard_item_bytes(scope, item) else {+ let Some(snapshot) = clipboard_item_snapshot(scope, item) else {let reason = type_error_value(scope, "Failed to read validated ClipboardItem data.");let _ = resolver.reject(scope, reason);return;};- runtime.set_clipboard_data(data);+ runtime.set_clipboard_snapshot(snapshot);let _ = resolver.resolve(scope, v8::undefined(scope).into());}@@ -1005,28 +990,36 @@ fn copy_clipboard_items<'s>(scope: &mut v8::PinScope<'s, '_>,runtime: &crate::runtime::RendererBrowserContextRuntime,) -> Option<v8::Local<'s, v8::Array>> {- let data = runtime.clipboard_data();- let result = v8::Array::new(scope, i32::from(!data.is_empty()));- if !data.is_empty() {- let mut entries = Vec::with_capacity(data.len());- for (mime_type, bytes) in data {+ let ClipboardSnapshot {+ presentation_style,+ representations,+ } = runtime.clipboard_snapshot();+ let result = v8::Array::new(scope, i32::from(!representations.is_empty()));+ if !representations.is_empty() {+ let mut entries = Vec::with_capacity(representations.len());+ for (mime_type, bytes) in representations {let blob = blob::build_blob_object(scope, bytes, mime_type.clone())?;let promise = resolved_promise(scope, blob.into())?;entries.push((mime_type, promise));}- let item = build_clipboard_item(scope, entries)?;+ let item = build_clipboard_item(scope, entries, presentation_style)?;result.set_index(scope, 0, item.into())?;}Some(result)}-fn clipboard_item_bytes<'s>(+fn clipboard_item_snapshot<'s>(scope: &mut v8::PinScope<'s, '_>,item: v8::Local<'s, v8::Object>,-) -> Option<Vec<(String, Vec<u8>)>> {+) -> Option<ClipboardSnapshot> {+ let style = get_private_value(scope, item, CLIPBOARD_ITEM_PRESENTATION_STYLE_SLOT)?;+ let style = v8::Local::<v8::String>::try_from(style)+ .ok()?+ .to_rust_string_lossy(scope);+ let presentation_style = <PresentationStyle as webidl::WebIdlEnum>::parse_token(&style)?;let types = get_private_value(scope, item, CLIPBOARD_ITEM_TYPES_SLOT).and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())?;- let mut data = Vec::with_capacity(types.length() as usize);+ let mut representations = Vec::with_capacity(types.length() as usize);for index in 0..types.length() {let mime_type = types.get_index(scope, index)?@@ -1037,9 +1030,12 @@ fn clipboard_item_bytes<'s>(return None;}let blob = v8::Local::<v8::Object>::try_from(promise.result(scope)).ok()?;- data.push((mime_type, blob::blob_bytes_from_object(scope, blob)?));+ representations.push((mime_type, blob::blob_bytes_from_object(scope, blob)?));}- Some(data)+ Some(ClipboardSnapshot {+ presentation_style,+ representations,+ })}fn clipboard_item_data_promise<'s>(diff --git a/moli-renderer-v8/src/runtime/browser_context_runtime.rs b/moli-renderer-v8/src/runtime/browser_context_runtime.rsindex 4f475ab63..75d8b1b53 100644--- a/moli-renderer-v8/src/runtime/browser_context_runtime.rs+++ b/moli-renderer-v8/src/runtime/browser_context_runtime.rs@@ -168,12 +168,37 @@ pub(crate) struct RendererStoragePartitionIdentity {profile_partition_id: String,}+#[derive(Clone, Copy, Debug, Default, moli_webidl::WebIdlEnum)]+#[webidl(name = "PresentationStyle", rename_all = "kebab-case")]+pub(crate) enum ClipboardPresentationStyle {+ #[default]+ Unspecified,+ Inline,+ Attachment,+}++impl ClipboardPresentationStyle {+ pub(crate) const fn as_str(self) -> &'static str {+ match self {+ Self::Unspecified => "unspecified",+ Self::Inline => "inline",+ Self::Attachment => "attachment",+ }+ }+}++#[derive(Clone, Debug, Default)]+pub(crate) struct ClipboardSnapshot {+ pub(crate) presentation_style: ClipboardPresentationStyle,+ pub(crate) representations: Vec<(String, Vec<u8>)>,+}+#[derive(Debug)]struct RendererBrowserContextRuntimeInner {id: super::RendererBrowserContextRuntimeId,- // Keep clipboard representations independent of any page's V8 objects so- // other pages and replacement documents can read them in their own realm.- clipboard_data: Mutex<Vec<(String, Vec<u8>)>>,+ // Commit style and representations together, independently of any page's+ // V8 objects, so other pages can read a coherent snapshot in their own realm.+ clipboard_snapshot: Mutex<ClipboardSnapshot>,message_port_registry: crate::message_port_runtime::SharedMessagePortRegistry,broadcast_channel_registry: crate::broadcast_channel_runtime::SharedBroadcastChannelRegistry,browser_resource_runtime: crate::network::BrowserResourceRuntimeBinding,@@ -343,21 +368,22 @@ impl Default for RendererBrowserContextRuntimeOwner {}impl RendererBrowserContextRuntime {- pub(crate) fn clipboard_data(&self) -> Vec<(String, Vec<u8>)> {- self.inner.clipboard_data.lock().clone()+ pub(crate) fn clipboard_snapshot(&self) -> ClipboardSnapshot {+ self.inner.clipboard_snapshot.lock().clone()}pub(crate) fn clipboard_data_for_type(&self, mime_type: &str) -> Option<Vec<u8>> {self.inner- .clipboard_data+ .clipboard_snapshot.lock()+ .representations.iter().find(|(candidate, _)| candidate == mime_type).map(|(_, bytes)| bytes.clone())}- pub(crate) fn set_clipboard_data(&self, data: Vec<(String, Vec<u8>)>) {- *self.inner.clipboard_data.lock() = data;+ pub(crate) fn set_clipboard_snapshot(&self, snapshot: ClipboardSnapshot) {+ *self.inner.clipboard_snapshot.lock() = snapshot;}// A browser-context runtime is only valid while its thread-affine owner is@@ -548,7 +574,7 @@ impl RendererBrowserContextRuntime {Self {inner: Arc::new(RendererBrowserContextRuntimeInner {id,- clipboard_data: Mutex::new(Vec::new()),+ clipboard_snapshot: Mutex::new(ClipboardSnapshot::default()),message_port_registry,broadcast_channel_registry,browser_resource_runtime: browser_resource_runtime.clone(),@@ -976,7 +1002,7 @@ mod tests {use moli_fetch::{FetchCancelHandle, Request};- use super::RendererBrowserContextRuntime;+ use super::{ClipboardSnapshot, RendererBrowserContextRuntime};use crate::{network::ResourceRequestClient,runtime::{@@ -1017,10 +1043,13 @@ mod tests {#[test]fn clipboard_data_for_type_returns_an_independent_copy_of_the_matching_bytes() {let runtime = RendererBrowserContextRuntime::new();- runtime.set_clipboard_data(vec![- ("image/png".to_owned(), vec![0; 1024]),- ("text/plain".to_owned(), b"hello".to_vec()),- ]);+ runtime.set_clipboard_snapshot(ClipboardSnapshot {+ representations: vec![+ ("image/png".to_owned(), vec![0; 1024]),+ ("text/plain".to_owned(), b"hello".to_vec()),+ ],+ ..ClipboardSnapshot::default()+ });let mut text = runtime.clipboard_data_for_type("text/plain").unwrap();assert_eq!(text, b"hello");@@ -1031,7 +1060,7 @@ mod tests {);assert!(runtime.clipboard_data_for_type("text/html").is_none());- runtime.set_clipboard_data(Vec::new());+ runtime.set_clipboard_snapshot(ClipboardSnapshot::default());assert!(runtime.clipboard_data_for_type("text/plain").is_none());}diff --git a/moli-renderer-v8/src/runtime/mod.rs b/moli-renderer-v8/src/runtime/mod.rsindex 53a9ed6f1..4d278c9c1 100644--- a/moli-renderer-v8/src/runtime/mod.rs+++ b/moli-renderer-v8/src/runtime/mod.rs@@ -250,14 +250,15 @@ use self::access::{script_execution_lane_path,};pub(crate) use self::browser_context_runtime::ServiceWorkerControlState;+pub(crate) use self::browser_context_runtime::{+ ClipboardPresentationStyle, ClipboardSnapshot, RendererStoragePartitionIdentity,+ RendererWorkerContextRuntime,+};pub use self::browser_context_runtime::{DetachedParserScriptFetchContinuation, RendererBrowserContextRuntime,RendererBrowserContextRuntimeOwner, RendererBrowserContextRuntimeOwnerAccess,RendererReservedServiceWorkerClient, RendererServiceWorkerMainResourceFetch,};-pub(crate) use self::browser_context_runtime::{- RendererStoragePartitionIdentity, RendererWorkerContextRuntime,-};pub(crate) use self::document_lifecycle::{RendererDocumentLifecycleDriveAdmission, RendererDocumentLifecycleJournalHandle,RendererDocumentLifecycleTransition,diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/clipboard_storage.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/clipboard_storage.rsindex 31cd32774..0bfbea568 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/clipboard_storage.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/clipboard_storage.rs@@ -45,6 +45,36 @@ fn clipboard_storage_reads_new_items_and_blobs_from_byte_snapshots() {assert_clipboard_probe(&mut vm, CLIPBOARD_SNAPSHOT_PROBE);}+#[test]+fn clipboard_storage_preserves_presentation_style_and_write_text_resets_it() {+ let mut vm = new_storage_test_vm("https://clipboard-storage.test/");+ assert_clipboard_probe(+ &mut vm,+ r#"+(async () => {+ const clipboard = navigator.clipboard;+ for (const style of ['unspecified', 'attachment', 'inline']) {+ const input = new ClipboardItem({'text/plain': style}, {presentationStyle: style});+ Object.defineProperty(input, 'presentationStyle', {get() {throw Error('author style getter');}});+ await clipboard.write([input]);+ const output = (await clipboard.read())[0];+ if (output.presentationStyle !== style) return style + ' was not preserved';+ if (output === input || await (await output.getType('text/plain')).text() !== style) {+ return 'incorrect item snapshot';+ }+ await clipboard.write([output]);+ if ((await clipboard.read())[0].presentationStyle !== style) return 'rewritten style changed';+ }+ await clipboard.writeText('replacement');+ const replacement = (await clipboard.read())[0];+ if (replacement.presentationStyle !== 'unspecified') return 'writeText retained previous style';+ if (await (await replacement.getType('text/plain')).text() !== 'replacement') return 'wrong replacement';+ return 'ok';+})()+"#,+ );+}+#[test]fn clipboard_storage_detached_handles_cannot_access_shared_data() {let mut vm = new_parsed_test_vm(@@ -174,16 +204,18 @@ fn clipboard_storage_waits_for_all_representations_and_preserves_data_after_rejer#"(async () => {const clipboard = navigator.clipboard;- await clipboard.writeText('before');+ await clipboard.write([new ClipboardItem({'text/plain': 'before'}, {presentationStyle: 'inline'})]);let resolve;const pending = new Promise(done => resolve = done);const write = clipboard.write([new ClipboardItem({'text/plain': Promise.resolve('after'), 'text/html': pending- })]);+ }, {presentationStyle: 'attachment'})]);if (await clipboard.readText() !== 'before') return 'partially committed write';+ if ((await clipboard.read())[0].presentationStyle !== 'inline') return 'partially committed style';resolve(new Blob(['<b>after</b>'], {type: 'text/html'}));await write;const item = (await clipboard.read())[0];+ if (item.presentationStyle !== 'attachment') return 'style was not committed with data';if (item.types.join(',') !== 'text/plain,text/html') return 'representation order';if (await clipboard.readText() !== 'after' ||await (await item.getType('text/html')).text() !== '<b>after</b>') return 'representation bytes';@@ -191,12 +223,13 @@ fn clipboard_storage_waits_for_all_representations_and_preserves_data_after_rejeawait clipboard.write([new ClipboardItem({'text/plain': 'bad replacement','text/html': new Blob(['wrong type'], {type: 'text/plain'})- })]);+ }, {presentationStyle: 'inline'})]);return 'accepted mismatched representation';} catch (error) {if (error.name !== 'NotAllowedError') return 'wrong rejection';}if (await clipboard.readText() !== 'after') return 'failed write replaced clipboard';+ if ((await clipboard.read())[0].presentationStyle !== 'attachment') return 'failed write replaced style';const sentinel = Error('rejected representation');let reject;const rejection = new Promise((_, fail) => reject = fail);@@ -205,6 +238,7 @@ fn clipboard_storage_waits_for_all_representations_and_preserves_data_after_rejetry {await failedWrite; return 'accepted rejected representation';}catch (error) {if (error !== sentinel) return 'replaced rejection reason';}if (await clipboard.readText() !== 'after') return 'rejection cleared clipboard';+ if ((await clipboard.read())[0].presentationStyle !== 'attachment') return 'rejection cleared style';return 'ok';})()"#,@@ -323,13 +357,15 @@ const CLIPBOARD_FRAME_PROBE: &str = r#"await navigator.clipboard.writeText('parent → child');if (await child.navigator.clipboard.readText() !== 'parent → child') return 'parent write invisible';const childItem = (await child.navigator.clipboard.read())[0];+ if (childItem.presentationStyle !== 'unspecified') return 'wrong writeText style in child';const childBlob = await childItem.getType('text/plain');if (!(childItem instanceof child.ClipboardItem) || !(childBlob instanceof child.Blob)) return 'child realm';await child.navigator.clipboard.write([new child.ClipboardItem({'text/plain': new child.Blob(['child → parent'], {type: 'text/plain'})- })]);+ }, {presentationStyle: 'attachment'})]);if (await navigator.clipboard.readText() !== 'child → parent') return 'child write invisible';const parentItem = (await navigator.clipboard.read())[0];+ if (parentItem.presentationStyle !== 'attachment') return 'child style invisible';if (!(parentItem instanceof ClipboardItem) || !((await parentItem.getType('text/plain')) instanceof Blob)) {return 'parent realm';}@@ -337,6 +373,7 @@ const CLIPBOARD_FRAME_PROBE: &str = r#"document.body.focus();frame.remove();if (await navigator.clipboard.readText() !== 'child → parent') return 'frame removal cleared clipboard';+ if ((await navigator.clipboard.read())[0].presentationStyle !== 'attachment') return 'frame removal cleared style';return 'ok';})()"#;