From 47399e4ec68045fc85ee6fc3d52975efd79314cf Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sun, 15 Nov 2026 04:09:10 +0800 Subject: [PATCH] fix(files): prepare shared directory selections off the protocol thread --- moli-core/src/page/command_dispatch.rs | 48 ++++ moli-core/src/page/mod.rs | 1 + .../src/page/renderer_command_support.rs | 15 +- moli-file-api/src/blob_data.rs | 15 +- .../webdriver_bidi/input_progress.rs | 2 +- .../src/protocol_server/webdriver_classic.rs | 3 +- .../src/protocol_server/webdriver_files.rs | 58 +---- .../src/domains/dom/resolve/native.rs | 6 +- .../src/domains/dom/resolve/native/files.rs | 115 +++++---- moli-protocol/src/domains/native.rs | 238 +++++++++++++++++- moli-protocol/src/file_upload.rs | 75 +++++- moli-renderer-v8/src/lib.rs | 8 +- moli-renderer-v8/src/runtime/mod.rs | 9 +- moli-renderer-v8/src/runtime/owner_local.rs | 41 +++ .../src/runtime/protocol_output/mod.rs | 6 +- .../protocol_output/native_response.rs | 36 ++- .../moli_webdriver_smoke/groups/bidi.py | 37 +++ .../moli_webdriver_smoke/groups/classic.py | 33 +++ 18 files changed, 602 insertions(+), 144 deletions(-) diff --git a/moli-core/src/page/command_dispatch.rs b/moli-core/src/page/command_dispatch.rs index b616aee641a..b7d60266529 100644 --- a/moli-core/src/page/command_dispatch.rs +++ b/moli-core/src/page/command_dispatch.rs @@ -32,6 +32,27 @@ impl PageDocumentCommandTarget { } } +/// The original Page/DevToolsSession admission, held without a Page borrow +/// while Browser work runs. Dispatch never resolves a replacement active Page. +pub struct PreparedNativeCall { + target: moli_renderer_v8::RendererPageProtocolCommandTarget, + attachment: RendererAgentAttachmentId, + session: Option, + response: moli_renderer_v8::RendererNativeCommandAdmission, +} + +impl PreparedNativeCall { + pub fn start(self, operation: crate::RendererNativeOperation) -> Result { + let mut command = RendererPageCommand::Native(self.response.bind(operation)); + command.bind_inspector_attachment(self.attachment); + let pending = self.target.enqueue(command, self.session)?; + Ok(PendingPageCommand { + pending, + renderer_agent_attachment_id: Some(self.attachment), + }) + } +} + pub struct PendingPageCommand { pending: RendererPageCommandPending, renderer_agent_attachment_id: Option, @@ -210,6 +231,33 @@ impl CompletedPageCommand { } impl Page { + pub fn prepare_cdp_call( + &self, + command_id: u64, + frontend_session_id: Option<&str>, + ) -> Result<( + PreparedNativeCall, + crate::RendererNativeCommandResponseGuard, + )> { + let attachment = self.renderer_agent_attachment_id.ok_or_else(|| { + anyhow::anyhow!("native frontend command requires a renderer attachment") + })?; + let (response, guard) = crate::RendererCdpCall::reserve( + moli_page_types::FrontendCommandId::new(command_id), + moli_page_types::DevToolsSessionKey::from_wire_session_id(frontend_session_id), + attachment, + ); + Ok(( + PreparedNativeCall { + target: self.handle.protocol_command_target(), + attachment, + session: self.renderer_devtools_command_session_id.clone(), + response, + }, + guard, + )) + } + pub fn document_command_target( &self, document: crate::RendererDocumentLifecycleIdentity, diff --git a/moli-core/src/page/mod.rs b/moli-core/src/page/mod.rs index a3fbf5b9067..2d236e47a14 100644 --- a/moli-core/src/page/mod.rs +++ b/moli-core/src/page/mod.rs @@ -42,6 +42,7 @@ pub use command_dispatch::{ CompletedDevToolsIoCommandDispatch, CompletedPageCommand, CompletedRuntimeInspectorCommandDispatch, PageDocumentCommandTarget, PendingDevToolsIoCommandDispatch, PendingPageCommand, PendingRuntimeInspectorCommandDispatch, + PreparedNativeCall, }; pub use moli_renderer_v8::RendererPageRequestPolicyUpdate; diff --git a/moli-core/src/page/renderer_command_support.rs b/moli-core/src/page/renderer_command_support.rs index 06ea06fc60d..47948636aa5 100644 --- a/moli-core/src/page/renderer_command_support.rs +++ b/moli-core/src/page/renderer_command_support.rs @@ -2050,19 +2050,8 @@ impl Page { PendingPageCommand, crate::RendererNativeCommandResponseGuard, )> { - let attachment = self.renderer_agent_attachment_id.ok_or_else(|| { - anyhow::anyhow!("native frontend command requires a renderer attachment") - })?; - let (command, guard) = crate::RendererCdpCall::new( - moli_page_types::FrontendCommandId::new(command_id), - moli_page_types::DevToolsSessionKey::from_wire_session_id(frontend_session_id), - attachment, - operation, - ); - Ok(( - self.start_page_command(RendererPageCommand::Native(command))?, - guard, - )) + let (admission, guard) = self.prepare_cdp_call(command_id, frontend_session_id)?; + Ok((admission.start(operation)?, guard)) } pub fn finish_child_frame_tree_snapshot( diff --git a/moli-file-api/src/blob_data.rs b/moli-file-api/src/blob_data.rs index 0a67dd076da..a4051b202c0 100644 --- a/moli-file-api/src/blob_data.rs +++ b/moli-file-api/src/blob_data.rs @@ -10,8 +10,14 @@ pub type BlobReadCompletion = Box>) + Send>; /// An immutable byte source. Implementations perform I/O on their owning /// backend, then complete the read without entering a JavaScript context. -pub trait BlobSource: fmt::Debug + Send + Sync + 'static { +pub trait BlobSource: fmt::Debug + Send + Sync + std::any::Any { fn read(&self, range: Range, complete: BlobReadCompletion); + + /// Compare backend snapshot identities without reading bytes. Unknown + /// sources retain allocation identity; implementations must be symmetric. + fn same_snapshot(&self, _other: &dyn BlobSource) -> bool { + false + } } /// Blob data is immutable. Slices and concatenation retain their source rather @@ -43,9 +49,12 @@ impl PartialEq for BlobData { match (self.as_bytes(), other.as_bytes()) { (Some(left), Some(right)) => left == right, _ => { - Arc::ptr_eq(&self.backing, &other.backing) - && self.offset == other.offset + self.offset == other.offset && self.length == other.length + && (Arc::ptr_eq(&self.backing, &other.backing) + || matches!((self.backing.as_ref(), other.backing.as_ref()), + (Backing::Source(left), Backing::Source(right)) + if Arc::ptr_eq(left, right) || left.same_snapshot(right.as_ref()))) } } } diff --git a/moli-protocol-server/src/protocol_server/webdriver_bidi/input_progress.rs b/moli-protocol-server/src/protocol_server/webdriver_bidi/input_progress.rs index e7b267a8131..027202a391a 100644 --- a/moli-protocol-server/src/protocol_server/webdriver_bidi/input_progress.rs +++ b/moli-protocol-server/src/protocol_server/webdriver_bidi/input_progress.rs @@ -94,7 +94,7 @@ pub(super) async fn start_bidi_input_command( )); } }; - let files = match selected_files_from_paths(&paths, "input.setFiles") { + let files = match selected_files_from_paths(&paths).await { Ok(files) => files, Err(error) => return failed(bidi_response_from_devtools_error(dispatch.id, error)), }; diff --git a/moli-protocol-server/src/protocol_server/webdriver_classic.rs b/moli-protocol-server/src/protocol_server/webdriver_classic.rs index 8d1c5e41e8b..2852de1d210 100644 --- a/moli-protocol-server/src/protocol_server/webdriver_classic.rs +++ b/moli-protocol-server/src/protocol_server/webdriver_classic.rs @@ -4616,7 +4616,8 @@ async fn webdriver_classic_send_file_input_keys( "the element can not hold multiple files", )); } - let files = selected_files_from_paths(&paths, "WebDriver Classic file upload") + let files = selected_files_from_paths(&paths) + .await .map_err(|error| ClassicError::new(ClassicErrorCode::InvalidArgument, error.message))?; let object_id = resolve_classic_remote_object( binding, diff --git a/moli-protocol-server/src/protocol_server/webdriver_files.rs b/moli-protocol-server/src/protocol_server/webdriver_files.rs index 290cef05511..ec91d6cc022 100644 --- a/moli-protocol-server/src/protocol_server/webdriver_files.rs +++ b/moli-protocol-server/src/protocol_server/webdriver_files.rs @@ -15,60 +15,14 @@ const MAX_UPLOAD_ZIP_ARCHIVE_BYTES: usize = MAX_UPLOAD_BYTES + 1024 * 1024; const MAX_UPLOAD_BASE64_CHARS: usize = MAX_UPLOAD_ZIP_ARCHIVE_BYTES.div_ceil(3) * 4; const MAX_DOWNLOAD_BYTES: usize = 50 * 1024 * 1024; -pub(super) fn selected_files_from_paths( +pub(super) async fn selected_files_from_paths( paths: &[String], - label: &str, ) -> Result, DevToolsError> { - paths - .iter() - .map(|path| selected_file_from_path(path, label)) - .collect() -} - -fn selected_file_from_path(path: &str, label: &str) -> Result { - let file_path = Path::new(path); - let metadata = fs::metadata(file_path).map_err(|_| { - DevToolsError::new( - DevToolsErrorKind::UnableToSetFileInput, - format!("File not found : {path}"), - ) - })?; - if !metadata.is_file() { - return Err(DevToolsError::new( - DevToolsErrorKind::UnableToSetFileInput, - format!("File not found : {path}"), - )); - } - let bytes = fs::read(file_path).map_err(|error| { - DevToolsError::new( - DevToolsErrorKind::UnableToSetFileInput, - format!("could not read file for {label}: {error}"), - ) - })?; - let name = file_path - .file_name() - .and_then(|name| name.to_str()) - .filter(|name| !name.is_empty()) - .unwrap_or(path) - .to_owned(); - let last_modified = metadata - .modified() - .ok() - .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok()) - .map(|duration| duration.as_millis() as f64) - .unwrap_or_else(|| { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|duration| duration.as_millis() as f64) - .unwrap_or(0.0) - }); - Ok(SelectedFile { - relative_path: String::new(), - data: bytes.into(), - mime_type: String::new(), - name, - last_modified, - }) + moli_protocol::file_upload::selected_files_from_paths_async(paths.to_vec()) + .await + .map_err(|error| { + DevToolsError::new(DevToolsErrorKind::UnableToSetFileInput, error.to_string()) + }) } pub(super) fn uploaded_file_from_base64_zip( diff --git a/moli-protocol/src/domains/dom/resolve/native.rs b/moli-protocol/src/domains/dom/resolve/native.rs index 4d3f0342fc2..0c0304ccd65 100644 --- a/moli-protocol/src/domains/dom/resolve/native.rs +++ b/moli-protocol/src/domains/dom/resolve/native.rs @@ -40,6 +40,9 @@ pub(crate) fn try_start(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Option Some(native::start_operation(conn, cmd, operation)), Ok(None) => None, @@ -58,9 +61,6 @@ fn prepare( if action == DomAction::ResolveNode { return remote_object::prepare(conn, cmd).map(Some); } - if action == DomAction::SetFileInputFiles { - return files::prepare(conn, cmd).map(Some); - } if let Some(operation) = mutation::prepare(conn, cmd, action)? { return Ok(Some(operation)); } diff --git a/moli-protocol/src/domains/dom/resolve/native/files.rs b/moli-protocol/src/domains/dom/resolve/native/files.rs index 8c46f3a0f72..aeb43738e64 100644 --- a/moli-protocol/src/domains/dom/resolve/native/files.rs +++ b/moli-protocol/src/domains/dom/resolve/native/files.rs @@ -1,62 +1,87 @@ use super::*; -pub(super) fn prepare(conn: &CdpConnection, cmd: &Cmd<'_>) -> Result { +enum FileInputTarget { + ObjectId(String), + Node(DevToolsDomNodeReference), +} + +pub(super) fn try_start(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> NativeCommandStep { #[derive(serde::Deserialize)] struct Params { #[serde(flatten)] reference: NodeReferenceParams, files: Vec, } - let params: Params = cmd - .get_params() - .ok() - .flatten() - .ok_or_else(StartError::invalid_params)?; + let params: Params = match cmd.get_params().ok().flatten() { + Some(params) => params, + None => { + return NativeCommandStep::Complete(CommandOutputPlan::error(-32602, "InvalidParams")); + } + }; let owner = CommandOwnerScope::capture(conn, cmd.session_id); let session = conn.target_renderer_runtime_inspector_session_id_for_owner(&owner); - // File access belongs to Browser admission. For node ids, retain an error - // until the renderer preflight has succeeded, preserving node-error priority. - let files = crate::domains::dom::set_file_input::selected_files_from_paths(¶ms.files); - if let Some(object_id) = params.reference.object_id { - let object_id = dom_object_reference_id_for_owner( + let target = if let Some(object_id) = params.reference.object_id { + FileInputTarget::ObjectId(dom_object_reference_id_for_owner( conn, &owner, &DevToolsRemoteHandleId::from(object_id), - ); - return Ok(Operation::new( - Command::set_file_input_files_for_object_id(session, object_id, files?, false), - project, - )); - } - let reference = devtools_node_reference_from_ids( - params.reference.node_id, - params.reference.backend_node_id, - ) - .ok_or_else(StartError::invalid_params)?; - Ok(with_backend(session, reference, move |backend_node_id| { - Operation::then( - Command::DocumentNodeExistsForBackendNodeId { backend_node_id }, - move |reply| match reply { - Ok(Reply::Bool(true)) => match files { - Ok(files) => Step::Continue(Operation::new( - Command::SetFileInputFilesForBackendNodeId { - backend_node_id, - files, - append: false, + )) + } else { + let Some(reference) = devtools_node_reference_from_ids( + params.reference.node_id, + params.reference.backend_node_id, + ) else { + return NativeCommandStep::Complete(CommandOutputPlan::error(-32602, "InvalidParams")); + }; + FileInputTarget::Node(reference) + }; + native::start_prepared_operation(conn, cmd, async move { + let files = crate::file_upload::selected_files_from_paths_async(params.files) + .await + .map_err(|error| StartError { + code: -32000, + message: error.to_string(), + }); + // Retain the result until the node preflight succeeds, so a bad node + // keeps precedence over a bad path. No filesystem work enters a Page. + match target { + FileInputTarget::ObjectId(object_id) => { + let files = files.map_err(|error| anyhow::anyhow!(error.message))?; + Ok(Operation::new( + Command::set_file_input_files_for_object_id(session, object_id, files, false), + project, + )) + } + FileInputTarget::Node(reference) => { + Ok(with_backend(session, reference, move |backend_node_id| { + Operation::then( + Command::DocumentNodeExistsForBackendNodeId { backend_node_id }, + move |reply| match reply { + Ok(Reply::Bool(true)) => match files { + Ok(files) => Step::Continue(Operation::new( + Command::SetFileInputFilesForBackendNodeId { + backend_node_id, + files, + append: false, + }, + project, + )), + Err(error) => { + Step::Complete(Response::error(error.code, error.message)) + } + }, + Ok(Reply::Bool(false)) => Step::Complete(node_not_found()), + Err(error) => Step::Complete(Response::error( + -32000, + format!("Could not preflight file input node: {error}"), + )), + _ => unreachable!("DOM file input preflight reply"), }, - project, - )), - Err(error) => Step::Complete(Response::error(error.code, error.message)), - }, - Ok(Reply::Bool(false)) => Step::Complete(node_not_found()), - Err(error) => Step::Complete(Response::error( - -32000, - format!("Could not preflight file input node: {error}"), - )), - _ => unreachable!("DOM file input preflight reply"), - }, - ) - })) + ) + })) + } + } + }) } fn project(reply: anyhow::Result) -> Response { diff --git a/moli-protocol/src/domains/native.rs b/moli-protocol/src/domains/native.rs index 7716e479996..bf4d5cfb60e 100644 --- a/moli-protocol/src/domains/native.rs +++ b/moli-protocol/src/domains/native.rs @@ -152,6 +152,40 @@ impl PendingNativeCommand { } } + fn new_prepared( + command_id: u64, + session_id: Option, + residence: TargetPageResidenceIdentity, + admission: moli_core::page::PreparedNativeCall, + guard: RendererNativeCommandResponseGuard, + prepare: impl std::future::Future> + 'static, + ) -> Self { + let scope = NativeCommandFailureCleanup::new(command_id, session_id, guard); + let wait = scope.clone(); + let cancellation = scope.wait_cancellation(); + Self { + scope, + pending: async move { + let operation = match prepare.await { + Ok(operation) => operation, + Err(error) => { + drop(admission); + return wait.settle(Err(error), residence).await; + } + }; + let completed = match admission.start(operation) { + Ok(pending) => pending.wait().await, + Err(error) => Err(error), + }; + wait.settle(completed, residence).await + } + .boxed_local(), + unpublished_failure: None, + recovering: false, + _cancellation: cancellation, + } + } + /// Browser policy may outlive a rejected old attachment. This projection /// only runs after publication lost; it cannot replace a committed reply. pub(crate) fn on_unpublished_failure( @@ -250,17 +284,13 @@ pub(crate) fn start_operation( cmd: &Cmd<'_>, operation: moli_core::RendererNativeOperation, ) -> NativeCommandStep { - let owner = CommandOwnerScope::capture(conn, cmd.session_id); - let Some(residence) = conn.target_page_residence_identity_for_owner(&owner) else { - return NativeCommandStep::Complete(CommandOutputPlan::error(-32000, "NoDocumentLoaded")); - }; - let page = match conn.loaded_page_mut_for_protocol_access_for_owner(&owner) { - Ok(page) => page, - Err(error) => return NativeCommandStep::Complete(CommandOutputPlan::error(-32000, error)), + let (residence, admission, guard) = match reserve_call(conn, cmd) { + Ok(admission) => admission, + Err(plan) => return NativeCommandStep::Complete(plan), }; let command_id = cmd.id.expect("a native frontend command has a call id"); - match page.start_cdp_call(command_id, cmd.session_id, operation) { - Ok((pending, guard)) => NativeCommandStep::Pending(PendingNativeCommand::new( + match admission.start(operation) { + Ok(pending) => NativeCommandStep::Pending(PendingNativeCommand::new( command_id, cmd.session_id.map(str::to_owned), residence, @@ -273,6 +303,52 @@ pub(crate) fn start_operation( } } +pub(crate) fn start_prepared_operation( + conn: &mut CdpConnection, + cmd: &Cmd<'_>, + prepare: impl std::future::Future> + 'static, +) -> NativeCommandStep { + let (residence, admission, guard) = match reserve_call(conn, cmd) { + Ok(admission) => admission, + Err(plan) => return NativeCommandStep::Complete(plan), + }; + NativeCommandStep::Pending(PendingNativeCommand::new_prepared( + cmd.id.expect("a native frontend command has a call id"), + cmd.session_id.map(str::to_owned), + residence, + admission, + guard, + prepare, + )) +} + +fn reserve_call( + conn: &mut CdpConnection, + cmd: &Cmd<'_>, +) -> Result< + ( + TargetPageResidenceIdentity, + moli_core::page::PreparedNativeCall, + RendererNativeCommandResponseGuard, + ), + CommandOutputPlan, +> { + let owner = CommandOwnerScope::capture(conn, cmd.session_id); + let residence = conn + .target_page_residence_identity_for_owner(&owner) + .ok_or_else(|| CommandOutputPlan::error(-32000, "NoDocumentLoaded"))?; + let page = conn + .loaded_page_mut_for_protocol_access_for_owner(&owner) + .map_err(|error| CommandOutputPlan::error(-32000, error))?; + let (admission, guard) = page + .prepare_cdp_call( + cmd.id.expect("a native frontend command has a call id"), + cmd.session_id, + ) + .map_err(|error| CommandOutputPlan::error(-32000, error.to_string()))?; + Ok((residence, admission, guard)) +} + /// Admit only frontend calls with an accessible document and renderer. /// Return the checked attachment so preparation can retain its replay identity. /// Enqueue revalidates access after preparation, which may update Browser policy. @@ -748,4 +824,148 @@ mod tests { assert_eq!(terminal["result"]["nodeId"], 7); assert!(events.next().is_none()); } + + #[tokio::test(flavor = "multi_thread")] + async fn native_browser_preparation_yields_and_does_not_retarget_a_replacement_page() { + use crate::conn::BrowserContext; + use crate::testing::TestContext; + use futures_util::poll; + for retire in [false, true] { + let mut context = TestContext::new(); + let mut browser = BrowserContext::new("BID-native-preparation".into()); + browser.set_active_target_id("TID-native-preparation"); + context.with_fixture(|conn| conn.install_browser_context_fixture_for_test(browser)); + context + .install_navigation_fixture_for_session_owner("about:blank", None) + .await; + let (residence, admission, guard) = context.with_fixture(|conn| { + let owner = CommandOwnerScope::capture(conn, None); + let residence = conn + .target_page_residence_identity_for_owner(&owner) + .unwrap(); + let (admission, guard) = conn + .loaded_page_mut_for_protocol_access(None) + .unwrap() + .prepare_cdp_call(871, None) + .unwrap(); + (residence, admission, guard) + }); + let (release, held) = tokio::sync::oneshot::channel(); + let pending = PendingNativeCommand::new_prepared( + 871, + None, + residence, + admission, + guard, + async move { + held.await?; + Ok(moli_core::RendererNativeOperation::new( + RendererPageCommand::ChildFrameTreeSnapshot, + |_| RendererNativeProtocolResponse::success(json!({"prepared":true})), + )) + }, + ); + let mut pending = Box::pin(pending.wait()); + assert!(poll!(pending.as_mut()).is_pending()); + context.process_async(json!({"id":872,"method":"Runtime.evaluate","params":{"expression":"6 * 7","returnByValue":true}})).await; + assert!( + context + .sent + .iter() + .any(|message| message["id"] == 872 + && message["result"]["result"]["value"] == 42), + "Browser preparation must not hold protocol or renderer execution" + ); + if retire { + context + .install_navigation_fixture_for_session_owner( + "data:text/html,retained replacement", + None, + ) + .await; + } + release.send(()).unwrap(); + let completed = tokio::time::timeout(std::time::Duration::from_secs(5), pending) + .await + .unwrap(); + if retire { + assert!( + matches!(completed.result, NativeCommandCompletion::Unpublished(_)), + "old admission must not publish from the replacement Page" + ); + } else { + let NativeCommandCompletion::Page { completed, .. } = completed.result else { + panic!("prepared Native command must settle normally") + }; + assert!( + completed + .into_output() + .completion() + .native_response_was_published() + ); + } + } + } + + #[tokio::test] + async fn dropping_native_browser_preparation_cancels_before_enqueue() { + use crate::conn::BrowserContext; + use crate::testing::TestContext; + use futures_util::poll; + let mut context = TestContext::new(); + let mut browser = BrowserContext::new("BID-native-preparation-drop".into()); + browser.set_active_target_id("TID-native-preparation-drop"); + context.with_fixture(|conn| conn.install_browser_context_fixture_for_test(browser)); + context + .install_navigation_fixture_for_session_owner("about:blank", None) + .await; + let (residence, admission, guard) = context.with_fixture(|conn| { + let owner = CommandOwnerScope::capture(conn, None); + let residence = conn + .target_page_residence_identity_for_owner(&owner) + .unwrap(); + let (admission, guard) = conn + .loaded_page_mut_for_protocol_access(None) + .unwrap() + .prepare_cdp_call(873, None) + .unwrap(); + (residence, admission, guard) + }); + let (release, held) = tokio::sync::oneshot::channel::<()>(); + let pending = PendingNativeCommand::new_prepared( + 873, + None, + residence, + admission, + guard, + async move { + held.await?; + Ok(moli_core::RendererNativeOperation::new( + RendererPageCommand::ChildFrameTreeSnapshot, + |_| RendererNativeProtocolResponse::success(json!({})), + )) + }, + ); + let cleanup = pending.scope.clone(); + let mut waiting = Box::pin(pending.wait()); + assert!(poll!(waiting.as_mut()).is_pending()); + drop(waiting); + assert!( + release.send(()).is_err(), + "cancelled Browser work must not resume and enqueue" + ); + let completed = cleanup + .recover(CommandOutputPlan::error(-32000, "cancelled preparation")) + .wait() + .await; + let mut dispatch = CommandDispatchContext::default(); + let plan = context.with_fixture(|conn| completed.complete(conn, &mut dispatch)); + assert!(dispatch.take_renderer_output_predecessor().is_none()); + let mut messages = Vec::new(); + plan.emit_into(&mut messages, Some(873), None); + assert_eq!( + messages, + vec![json!({"id":873,"error":{"code":-32000,"message":"cancelled preparation"}})] + ); + } } diff --git a/moli-protocol/src/file_upload.rs b/moli-protocol/src/file_upload.rs index ee3f3939648..466a49107da 100644 --- a/moli-protocol/src/file_upload.rs +++ b/moli-protocol/src/file_upload.rs @@ -69,6 +69,13 @@ impl Drop for ReadReply { } impl BlobSource for FileSource { + fn same_snapshot(&self, other: &dyn BlobSource) -> bool { + let other: &dyn std::any::Any = other; + other.downcast_ref::().is_some_and(|other| { + self.path == other.path && self.size == other.size && self.modified == other.modified + }) + } + fn read(&self, range: Range, complete: BlobReadCompletion) { let source = self.clone(); let reply = ReadReply(Some(complete)); @@ -83,6 +90,45 @@ impl BlobSource for FileSource { /// directory is enumerated in stable order; links below it are not traversed. /// An explicitly selected directory link retains its chosen display name. pub fn selected_files_from_paths(paths: &[String]) -> io::Result> { + select_files(paths, None) +} + +struct SelectionCancellation(Arc); +impl Drop for SelectionCancellation { + fn drop(&mut self) { + self.0.store(true, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Browser filesystem admission runs outside protocol and renderer turns. A +/// dropped caller stops the enumeration at its next filesystem entry boundary. +pub async fn selected_files_from_paths_async(paths: Vec) -> io::Result> { + if paths.is_empty() { + return Ok(Vec::new()); + } + let cancelled = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let _cancel = SelectionCancellation(cancelled.clone()); + tokio::task::spawn_blocking(move || select_files(&paths, Some(&cancelled))) + .await + .map_err(io::Error::other)? +} + +fn check_selection_cancelled(cancelled: Option<&std::sync::atomic::AtomicBool>) -> io::Result<()> { + if cancelled.is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Relaxed)) { + Err(io::Error::new( + io::ErrorKind::Interrupted, + "File selection cancelled", + )) + } else { + Ok(()) + } +} + +fn select_files( + paths: &[String], + cancelled: Option<&std::sync::atomic::AtomicBool>, +) -> io::Result> { + check_selection_cancelled(cancelled)?; if paths.is_empty() { return Ok(Vec::new()); } @@ -97,6 +143,7 @@ pub fn selected_files_from_paths(paths: &[String]) -> io::Result io::Result io::Result>, } +/// Revocable DevTools command destination for the exact admitted agent. It +/// carries no Page close authority and cannot follow a replacement Document. +pub struct RendererPageProtocolCommandTarget { + token: RendererPageToken, + agent: RendererDevToolsAgentToken, + target: crate::devtools::target::RendererDevToolsTargetHandle, + dialogs: RendererJavaScriptDialogBroker, +} + +impl RendererPageProtocolCommandTarget { + pub fn enqueue( + self, + command: RendererPageCommand, + session: Option, + ) -> Result { + let javascript_dialog_watch = command + .interruptible_by_javascript_dialog() + .then(|| self.dialogs.watch()); + let route = self.target.main_ref().enqueue_protocol_page_command( + self.token, + self.agent, + command, + session, + RendererPageStateCapturePolicy::ProtocolTurn, + ); + Ok(RendererPageCommandPending { + dispatch: RendererPageCommandPendingDispatch::InspectorMain(Box::new(route)), + javascript_dialog_watch, + }) + } +} + #[derive(Clone, Copy, Debug, thiserror::Error)] pub enum RendererPageAccessError { #[error("Renderer Document is no longer current")] @@ -289,6 +321,15 @@ impl RendererPageHandle { .expect("renderer page handle should remain open while in use") } + pub fn protocol_command_target(&self) -> RendererPageProtocolCommandTarget { + RendererPageProtocolCommandTarget { + token: self.token(), + agent: self.devtools_agent_token, + target: self.devtools_target.clone(), + dialogs: self.javascript_dialog_broker.clone(), + } + } + pub fn document_command_target( &self, document: RendererDocumentLifecycleIdentity, diff --git a/moli-renderer-v8/src/runtime/protocol_output/mod.rs b/moli-renderer-v8/src/runtime/protocol_output/mod.rs index 76586a888ad..6fa9dbcf91e 100644 --- a/moli-renderer-v8/src/runtime/protocol_output/mod.rs +++ b/moli-renderer-v8/src/runtime/protocol_output/mod.rs @@ -23,9 +23,9 @@ pub use item::{ RendererProtocolObservation, }; pub use native_response::{ - RendererCdpCall, RendererNativeCommandReadyResponse, RendererNativeCommandResponseGuard, - RendererNativeCommandTerminal, RendererNativeOperation, RendererNativeOperationStep, - RendererNativeProtocolError, RendererNativeProtocolNotification, + RendererCdpCall, RendererNativeCommandAdmission, RendererNativeCommandReadyResponse, + RendererNativeCommandResponseGuard, RendererNativeCommandTerminal, RendererNativeOperation, + RendererNativeOperationStep, RendererNativeProtocolError, RendererNativeProtocolNotification, RendererNativeProtocolResponse, RendererNativeProtocolStateUpdate, }; pub use transport::{ diff --git a/moli-renderer-v8/src/runtime/protocol_output/native_response.rs b/moli-renderer-v8/src/runtime/protocol_output/native_response.rs index 43bae62b63c..6d2c38f43ed 100644 --- a/moli-renderer-v8/src/runtime/protocol_output/native_response.rs +++ b/moli-renderer-v8/src/runtime/protocol_output/native_response.rs @@ -88,13 +88,30 @@ struct RendererNativeCommandResponse { lease: Lease, } +/// Reserves only the original reply authority while Browser I/O prepares an +/// operation. It does not occupy a renderer journal position or enter a Page. +pub struct RendererNativeCommandAdmission { + response: RendererNativeCommandResponse, +} + +impl RendererNativeCommandAdmission { + pub fn bind(self, operation: RendererNativeOperation) -> RendererCdpCall { + RendererCdpCall { + operation, + response: self.response, + } + } +} + impl RendererCdpCall { - pub fn new( + pub fn reserve( command_id: FrontendCommandId, session: DevToolsSessionKey, attachment_id: RendererAgentAttachmentId, - operation: RendererNativeOperation, - ) -> (Self, RendererNativeCommandResponseGuard) { + ) -> ( + RendererNativeCommandAdmission, + RendererNativeCommandResponseGuard, + ) { let authority = Authority::session(); let lease = authority .activate() @@ -103,8 +120,7 @@ impl RendererCdpCall { .take_session_response_settlement_receiver() .expect("native frontend calls retain a publication receipt"); ( - Self { - operation, + RendererNativeCommandAdmission { response: RendererNativeCommandResponse { command_id, session, @@ -118,6 +134,16 @@ impl RendererCdpCall { }, ) } + + pub fn new( + command_id: FrontendCommandId, + session: DevToolsSessionKey, + attachment_id: RendererAgentAttachmentId, + operation: RendererNativeOperation, + ) -> (Self, RendererNativeCommandResponseGuard) { + let (admission, guard) = Self::reserve(command_id, session, attachment_id); + (admission.bind(operation), guard) + } } /// Created by the native backend with fully resolved payload, then published diff --git a/moli-webdriver-smoke/moli_webdriver_smoke/groups/bidi.py b/moli-webdriver-smoke/moli_webdriver_smoke/groups/bidi.py index 33a24d3a0ec..55868244f64 100644 --- a/moli-webdriver-smoke/moli_webdriver_smoke/groups/bidi.py +++ b/moli-webdriver-smoke/moli_webdriver_smoke/groups/bidi.py @@ -819,6 +819,43 @@ async def _run_bidi_input_smoke( "input:2,change:2", "BiDi input.setFiles event order", ) + chosen = Path(directory) / "chosen" + (chosen / "nested").mkdir(parents=True) + (chosen / "a.txt").write_text("alpha", encoding="utf-8") + (chosen / "nested" / "b.txt").write_text("beta", encoding="utf-8") + await _send( + websocket, 191, "script.evaluate", + { + "expression": "const input = document.getElementById('bidi-upload'); input.multiple = false; input.webkitdirectory = true;", + "target": {"context": context}, "awaitPromise": False, + }, + ) + directory_setup = (await _recv_until_id(websocket, 191))[-1] + assert_equal(directory_setup["type"], "success", "BiDi directory setup") + await _send( + websocket, 192, "input.setFiles", + {"context": context, "element": {"sharedId": file_shared_id}, "files": [str(chosen)]}, + ) + directory_set = (await _recv_until_id(websocket, 192))[-1] + assert_equal(directory_set["type"], "success", "BiDi directory upload") + await _send( + websocket, 193, "script.evaluate", + { + "expression": ( + "Promise.all(Array.from(document.getElementById('bidi-upload').files, " + "async file => file.webkitRelativePath + ':' + await structuredClone(file).text()))" + ".then(values => values.sort().join('|'))" + ), + "target": {"context": context}, "awaitPromise": True, + }, + ) + directory_summary = (await _recv_until_id(websocket, 193))[-1] + assert_equal(directory_summary["type"], "success", "BiDi directory summary") + assert_equal( + directory_summary["result"]["result"]["value"], + "chosen/a.txt:alpha|chosen/nested/b.txt:beta", + "BiDi directory relative paths and lazy clone bytes", + ) record(results, "bidi_input_set_files", {"context": context}) input_navigation_url = f"{fixture}/webdriver/input-navigation" diff --git a/moli-webdriver-smoke/moli_webdriver_smoke/groups/classic.py b/moli-webdriver-smoke/moli_webdriver_smoke/groups/classic.py index 2e31ad3a667..9a71d897241 100644 --- a/moli-webdriver-smoke/moli_webdriver_smoke/groups/classic.py +++ b/moli-webdriver-smoke/moli_webdriver_smoke/groups/classic.py @@ -785,6 +785,39 @@ async def _run_file_upload_smoke( except WebDriverHttpError as error: assert_equal(error.response.status, 400, "Classic non-multiple upload HTTP status") assert_equal(error.response.body["value"]["error"], "invalid argument", "Classic non-multiple upload error") + chosen = Path(tempdir) / "chosen" + (chosen / "nested").mkdir(parents=True) + (chosen / "a.txt").write_text("alpha", encoding="utf-8") + (chosen / "nested" / "b.txt").write_text("beta", encoding="utf-8") + client.post( + f"/session/{session_id}/execute/sync", + { + "script": "const input = document.getElementById('upload-single'); input.webkitdirectory = true; window.__fileEvents = [];", + "args": [], + }, + ) + client.post( + f"/session/{session_id}/element/{single_id}/value", {"text": str(chosen)} + ) + directory_files = classic_value( + client.post( + f"/session/{session_id}/execute/async", + { + "script": ( + "const done = arguments[arguments.length - 1];" + "const input = document.getElementById('upload-single');" + "Promise.all(Array.from(input.files, async file => " + "file.webkitRelativePath + ':' + await structuredClone(file).text()))" + ".then(values => done(values.sort().join('|')));" + ), + "args": [], + }, + ) + ) + assert_equal( + directory_files, "chosen/a.txt:alpha|chosen/nested/b.txt:beta", + "Classic directory upload relative paths and lazy clone bytes", + ) record(results, "classic_file_upload")