diff --git a/crates/automation/src/bridge.rs b/crates/automation/src/bridge.rs index 77d69dd01..621f8828e 100644 --- a/crates/automation/src/bridge.rs +++ b/crates/automation/src/bridge.rs @@ -11,6 +11,9 @@ use crate::{Error, Result}; /// Slightly longer than the app's own 60 s per-request timeout, so its error reply wins. const READ_TIMEOUT: Duration = Duration::from_secs(65); +/// The desktop control protocol's request-line limit, excluding the newline. +/// Reject locally before writing, since closing an oversized request can reset the TCP stream. +const MAX_REQUEST_BYTES: usize = 4 * 1024 * 1024; pub struct BridgeClient { addr: String, @@ -56,13 +59,16 @@ impl BridgeClient { let unknown = |error| Error::Bridge(format!("`{method}` request outcome is unknown: {error}; inspect the app before retrying")); let mut last = Error::Bridge("not attempted".into()); for attempt in 0..2 { + let id = self.next_id; + let line = format!("{}\n", json!({"id": id, "method": method, "params": params})); + if line.len() - 1 > MAX_REQUEST_BYTES { + return Err(Error::BadArgs(format!("control request exceeds {MAX_REQUEST_BYTES} bytes; it was not sent; split the script into smaller calls"))); + } if self.conn.is_none() { self.conn = Some(self.connect()?); } - let id = self.next_id; self.next_id = self.next_id.checked_add(1).ok_or_else(|| Error::Bridge("control request id space exhausted".into()))?; let Some((r, w)) = self.conn.as_mut() else { continue }; - let line = format!("{}\n", json!({"id": id, "method": method, "params": params})); // `Ok(Err(_))`: transmission/reply failed (the app may have applied the request); // `Err(_)`: a timeout or bad reply (never resent: the app may have run the request). let res = (|| -> Result> { @@ -104,3 +110,21 @@ impl BridgeClient { Err(last) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn oversized_serialized_script_is_refused_before_connecting() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let mut client = BridgeClient::new(&listener.local_addr().unwrap().to_string()).unwrap(); + // Escaping doubles the bytes: checking the source length alone is insufficient. + let code = "\"".repeat(MAX_REQUEST_BYTES / 2); + let error = client.call("engine.execute", json!({"command": "script.run", "params": {"code": code}})).unwrap_err(); + assert!(error.to_string().contains("not sent"), "{error}"); + assert!(matches!(listener.accept(), Err(e) if e.kind() == std::io::ErrorKind::WouldBlock)); + assert_eq!(client.next_id, 1); + } +} diff --git a/crates/script/src/runtime.rs b/crates/script/src/runtime.rs index ab7e511e5..b696298d2 100644 --- a/crates/script/src/runtime.rs +++ b/crates/script/src/runtime.rs @@ -67,7 +67,7 @@ impl Outcome { /// The session and per-run state while a script runs (the natives reach it here; nothing /// borrowed ever enters the JS heap). pub(crate) struct Active { - pub(crate) session: Session, + pub(crate) session: crate::ui::SessionParcel, pub(crate) output: Vec, /// Open groups: name, project snapshot, original bounded history and saved-project /// identity. The history snapshot preserves earlier steps if long groups hit the limit. @@ -86,12 +86,25 @@ pub(crate) struct Active { } impl Active { - pub(crate) fn new(session: Session, name: &str, host: u32) -> Active { + pub(crate) fn new(session: impl Into, name: &str, host: u32) -> Active { + let session = session.into(); let yield_renders = session.script_ui.yield_renders; Active { session, output: vec![], groups: vec![], name: name.to_string(), host, link: None, yield_renders, loading: vec![] } } } +impl Drop for Active { + fn drop(&mut self) { + // An unexpected host unwind can bypass normal settlement. Preserve the outer group's + // pre-script history before the parcel returns the actual session to its caller. + if self.session.recoverable() + && let Some((name, snap, prior, saved)) = self.groups.first() + { + collapse(&mut self.session, name, snap, prior, saved); + } + } +} + thread_local! { pub(crate) static ACTIVE: RefCell> = const { RefCell::new(None) }; /// The Script Console's persistent context (never dropped, like the expression runtime: boa's @@ -703,8 +716,8 @@ pub(crate) struct Restore<'a> { impl Drop for Restore<'_> { fn drop(&mut self) { - if let Some(a) = ACTIVE.with(|c| c.borrow_mut().take()) { - *self.target = a.session; + if let Some(mut a) = ACTIVE.with(|c| c.borrow_mut().take()) { + *self.target = std::mem::take(&mut a.session).into_session(); } } } diff --git a/crates/script/src/tests.rs b/crates/script/src/tests.rs index 60f0ad206..ef62d6984 100644 --- a/crates/script/src/tests.rs +++ b/crates/script/src/tests.rs @@ -2124,3 +2124,53 @@ fn set_value_stores_a_string_parameter() { let (_, c) = comp_named(&s, "Str"); assert_eq!(layer(c, "s").props.prop("effects/#1/lut").unwrap().value, KV::Str("/luts/other.cube".into())); } + +#[test] +fn combined_title_script_keeps_the_project_and_undo_history() { + let mut s = session(); + let before = s.project.clone(); + let out = ok( + &mut s, + r#" + app.beginUndoGroup("Combined title"); + var comp = app.project.items.addComp("Combined title", 640, 360, 1, 5, 30); + var shape = comp.layers.addShape(); + var contents = shape.property("ADBE Root Vectors Group"); + contents.addProperty("ADBE Vector Shape - Rect"); + var pathGroup = contents.addProperty("ADBE Vector Shape - Group"); + var path = new Shape(); + path.vertices = [[0,0],[160,0],[160,80],[0,80]]; + path.inTangents = [[0,0],[0,0],[0,0],[0,0]]; + path.outTangents = [[0,0],[0,0],[0,0],[0,0]]; + path.closed = true; + pathGroup.property("ADBE Vector Shape").setValue(path); + contents.addProperty("ADBE Vector Graphic - Fill").property("ADBE Vector Fill Color").setValue([0.2,0.4,0.6]); + for (var i = 0; i < 2; i++) { + var text = comp.layers.addText("Title " + i); + var source = text.property("ADBE Text Properties").property("ADBE Text Document"); + var doc = source.value; + doc.font = "Inter"; + doc.tracking = 20; + source.setValue(doc); + var mask = text.property("ADBE Mask Parade").addProperty("ADBE Mask Atom"); + mask.property("ADBE Mask Shape").setValue(path); + var animator = text.property("ADBE Text Properties").property("ADBE Text Animators").addProperty("ADBE Text Animator"); + var position = animator.property("ADBE Text Animator Properties").addProperty("ADBE Text Position 3D"); + position.setValueAtTime(0, [0,50,0]); + position.setValueAtTime(1, [0,0,0]); + position.setTemporalEaseAtKey(1, [new KeyframeEase(0,60)], [new KeyframeEase(0,60)]); + var opacity = text.property("ADBE Transform Group").property("ADBE Opacity"); + opacity.setValueAtTime(0, 0); + opacity.setValueAtTime(1, 100); + opacity.setTemporalEaseAtKey(2, [new KeyframeEase(0,60)], [new KeyframeEase(0,60)]); + } + app.endUndoGroup(); + comp.numLayers; + "#, + ); + assert_eq!(out.result, json!(3)); + let (_, comp) = comp_named(&s, "Combined title"); + assert_eq!(comp.layers.len(), 3); + s.undo(); + assert_eq!(s.project, before); +} diff --git a/crates/script/src/ui.rs b/crates/script/src/ui.rs index 6030ae71e..5b1bd9bc1 100644 --- a/crates/script/src/ui.rs +++ b/crates/script/src/ui.rs @@ -238,18 +238,70 @@ pub(crate) fn native_file_dialog(_: &JsValue, args: &[JsValue], ctx: &mut Contex // ---------------------------------------------------------------- script-host threads +type Recovery = std::sync::Arc>>; + +/// Own the actual session throughout a handoff. Dropping an undelivered message or unwinding +/// the host returns it to the caller, including edits, history and host services, without cloning. +#[derive(Default)] +pub(crate) struct SessionParcel { + session: Session, + recovery: Option, +} + +impl From for SessionParcel { + fn from(session: Session) -> Self { + Self { session, recovery: None } + } +} + +impl std::ops::Deref for SessionParcel { + type Target = Session; + fn deref(&self) -> &Session { + &self.session + } +} + +impl std::ops::DerefMut for SessionParcel { + fn deref_mut(&mut self) -> &mut Session { + &mut self.session + } +} + +impl SessionParcel { + pub(crate) fn recoverable(&self) -> bool { + self.recovery.is_some() + } + + fn handoff(session: &mut Session, recovery: &Recovery) -> Self { + Self { session: std::mem::take(session), recovery: Some(recovery.clone()) } + } + + pub(crate) fn into_session(mut self) -> Session { + self.recovery = None; + std::mem::take(&mut self.session) + } +} + +impl Drop for SessionParcel { + fn drop(&mut self) { + if let Some(recovery) = self.recovery.take() { + *recovery.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::mem::take(&mut self.session)); + } + } +} + pub(crate) enum ToHost { /// Run the script (script-host threads exist only off the web: the browser runs scripts /// inline). #[cfg(not(target_arch = "wasm32"))] - Start(Session), - Event(Session, ScriptUiEvent), + Start(SessionParcel), + Event(SessionParcel, ScriptUiEvent), /// Run the scheduled tasks due at this time (see [`crate::tasks`]; the web has no /// script-host threads). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] - Tick(Session, Instant), + Tick(SessionParcel, Instant), /// Resume the suspended native render call, never a callback or scheduled task. - ResumeRender(Session), + ResumeRender(SessionParcel), } impl ToHost { @@ -257,14 +309,14 @@ impl ToHost { fn into_session(self) -> Session { match self { #[cfg(not(target_arch = "wasm32"))] - ToHost::Start(s) => s, - ToHost::Event(s, _) | ToHost::Tick(s, _) | ToHost::ResumeRender(s) => s, + ToHost::Start(s) => s.into_session(), + ToHost::Event(s, _) | ToHost::Tick(s, _) | ToHost::ResumeRender(s) => s.into_session(), } } } pub(crate) struct FromHost { - session: Session, + session: SessionParcel, outcome: crate::Outcome, windows: Vec, name: String, @@ -293,6 +345,9 @@ struct HostEnd { epoch: u64, /// Retained across render yields so a later error still names its included source file. source_map: Option, + recovery: Recovery, + #[cfg(not(target_arch = "wasm32"))] + thread: std::thread::JoinHandle<()>, } fn hosts() -> &'static std::sync::Mutex> { @@ -334,7 +389,8 @@ fn yield_wake(outcome: crate::Outcome, windows: Vec, done: bool, n let (session, link, name) = ACTIVE.with(|a| { let mut a = a.borrow_mut(); let a = a.as_mut()?; - Some((std::mem::take(&mut a.session), a.link.take()?, a.name.clone())) + let link = a.link.take()?; + Some((std::mem::take(&mut a.session), link, a.name.clone())) })?; if link.tx.send(FromHost { session, outcome, windows, name, done, next_due, render_wait }).is_err() { return None; @@ -397,13 +453,21 @@ fn host_main(host: u32, name: String, code: String, link: Link) { } crate::tasks::drop_host(host); })); + finish_host(file, name, body.is_err()); +} + +#[cfg(not(target_arch = "wasm32"))] +fn finish_host(file: String, name: String, panicked: bool) { // A panic: give the session back all the same. + // Close the outer undo group before its saved pre-group history is dropped with Active. + let output = if panicked { settle() } else { vec![] }; let left = ACTIVE.with(|c| c.borrow_mut().take()); if let Some(mut a) = left && let Some(link) = a.link.take() { - let message = if body.is_err() { "the script engine stopped unexpectedly" } else { "the script ended" }; - let out = crate::Outcome { error: Some(ScriptError { message: message.into(), file, ..Default::default() }), ..Default::default() }; + crate::tasks::drop_host(a.host); + let message = if panicked { "the script engine stopped unexpectedly" } else { "the script ended" }; + let out = crate::Outcome { output, error: Some(ScriptError { message: message.into(), file, ..Default::default() }), ..Default::default() }; let _ = link.tx.send(FromHost { session: std::mem::take(&mut a.session), outcome: out, @@ -420,7 +484,7 @@ fn host_main(host: u32, name: String, code: String, link: Link) { fn receive(session: &mut Session, host: u32, end: HostEnd) -> crate::Outcome { match end.rx.recv() { Ok(FromHost { session: s, mut outcome, windows, name, done, next_due, render_wait }) => { - *session = s; + *session = s.into_session(); session.script_ui.render_host = render_wait.then_some(host); if !render_wait && let Some(map) = &end.source_map @@ -436,7 +500,16 @@ fn receive(session: &mut Session, host: u32, end: HostEnd) -> crate::Outcome { } outcome } - Err(_) => crate::Outcome { error: Some(ScriptError { message: "the script host stopped".into(), ..Default::default() }), ..Default::default() }, + Err(_) => { + // The sender can drop just before the host's session. Join before taking recovery. + #[cfg(not(target_arch = "wasm32"))] + let _ = end.thread.join(); + if let Some(recovered) = end.recovery.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() { + *session = recovered; + } + forget_host(session, host); + crate::Outcome { error: Some(ScriptError { message: "the script host stopped unexpectedly".into(), ..Default::default() }), ..Default::default() } + } } } @@ -459,14 +532,21 @@ pub(crate) fn run_threaded(session: &mut Session, req: &effectcraft_engine::Scri .name(format!("script-{host}")) .stack_size(64 << 20) .spawn(move || host_main(host, name, code, Link { rx: to_rx, tx: from_tx })); - if spawned.is_err() { - return crate::runtime::run_inline(session, req); - } - if let Err(std::sync::mpsc::SendError(msg)) = to_tx.send(ToHost::Start(std::mem::take(session))) { + let thread = match spawned { + Ok(thread) => thread, + Err(_) => { + return crate::Outcome { + error: Some(ScriptError { message: "the script host could not start".into(), ..Default::default() }), + ..Default::default() + }; + } + }; + let recovery = Recovery::default(); + if let Err(std::sync::mpsc::SendError(msg)) = to_tx.send(ToHost::Start(SessionParcel::handoff(session, &recovery))) { *session = msg.into_session(); return crate::Outcome { error: Some(ScriptError { message: "the script host did not start".into(), ..Default::default() }), ..Default::default() }; } - receive(session, host, HostEnd { tx: to_tx, rx: from_rx, next_due: None, epoch: 0, source_map: None }) + receive(session, host, HostEnd { tx: to_tx, rx: from_rx, next_due: None, epoch: 0, source_map: None, recovery, thread }) } /// Suspend only the JavaScript stack, not the window's event loop (#3289). Keep the output @@ -514,7 +594,7 @@ pub(crate) fn poll_render_wait(session: &mut Session) -> Option { if end.epoch != session.script_ui.project_epoch { return Some(fail("the project changed while the script was rendering")); } - if let Err(std::sync::mpsc::SendError(msg)) = end.tx.send(ToHost::ResumeRender(std::mem::take(session))) { + if let Err(std::sync::mpsc::SendError(msg)) = end.tx.send(ToHost::ResumeRender(SessionParcel::handoff(session, &end.recovery))) { *session = msg.into_session(); return Some(fail("the script host stopped while rendering")); } @@ -574,7 +654,7 @@ pub fn dispatch_ui(session: &mut Session, ev: &ScriptUiEvent) -> Result