diff --git a/crates/tinycomputer-browser/src/sessions/mod.rs b/crates/tinycomputer-browser/src/sessions/mod.rs index a9aec2962..acde2480d 100644 --- a/crates/tinycomputer-browser/src/sessions/mod.rs +++ b/crates/tinycomputer-browser/src/sessions/mod.rs @@ -396,6 +396,26 @@ impl Browser { Ok(info) } + /// Updates the host action-gate context for an existing browser session. + /// A retained payment checkout can therefore adopt its verified payment + /// mode without opening or claiming another browser session. + /// + /// # Errors + /// + /// Returns an error when the session has gone away, is closing, or its + /// state could not be read safely. + pub async fn update_action_context( + &self, + id: &SessionId, + action_context: ActionContext, + ) -> Result<()> { + let session = self.session(id)?; + let mut session = session.lock().await; + session.check(false).await?; + session.action_context = action_context; + Ok(()) + } + /// Closes a session and everything it owns. Closing one that is already /// gone succeeds. /// diff --git a/crates/tinycomputer-browser/src/surface/mod.rs b/crates/tinycomputer-browser/src/surface/mod.rs index 564ec55dd..156e31df0 100644 --- a/crates/tinycomputer-browser/src/surface/mod.rs +++ b/crates/tinycomputer-browser/src/surface/mod.rs @@ -130,7 +130,7 @@ const EARLY_LOAD_MS: u64 = 10_000; pub struct BrowserSurface { browser: Arc, options: SessionOptions, - action_context: ActionContext, + action_context: Arc>, session: Arc>>, handle: tokio::runtime::Handle, platform: Platform, @@ -174,7 +174,7 @@ impl BrowserSurface { Self { browser, options, - action_context: ActionContext::default(), + action_context: Arc::new(Mutex::new(ActionContext::default())), session: Arc::new(Mutex::new(None)), handle, platform: Platform::current(), @@ -198,10 +198,32 @@ impl BrowserSurface { /// Supplies the task facts included in each host action-gate request. #[must_use] pub fn with_action_context(mut self, context: ActionContext) -> Self { - self.action_context = context; + self.action_context = Arc::new(Mutex::new(context)); self } + /// Updates the gate context on this retained session, if it is already + /// open, and on any future session opened by this surface. + /// + /// # Errors + /// + /// Returns an error when the current session is unavailable or either + /// the surface or session state is poisoned. + pub async fn update_action_context(&self, context: ActionContext) -> Result<()> { + let id = self.session(); + if let Some(id) = id { + self.browser + .update_action_context(&id, context.clone()) + .await?; + } + *self + .action_context + .lock() + .map_err(|_| Error::failed("the browser surface context was poisoned by a panic"))? = + context; + Ok(()) + } + /// The same surface, reading pages with `perception` /// ([`Perception::Sight`] unless told otherwise). #[must_use] @@ -318,9 +340,14 @@ impl BrowserSurface { if early && self.closed.load(Ordering::Acquire) { return Err(Error::failed("the browser surface was let go")); } + let context = self + .action_context + .lock() + .map_err(|_| Error::failed("the browser surface context was poisoned by a panic"))? + .clone(); let info = self.block( self.browser - .open_session_with_context(self.options.clone(), self.action_context.clone()), + .open_session_with_context(self.options.clone(), context), )?; *slot = Some(info.id.clone()); Ok(info.id) diff --git a/crates/tinycomputer-engine/src/task/browser.rs b/crates/tinycomputer-engine/src/task/browser.rs index 3ff676230..569934c80 100644 --- a/crates/tinycomputer-engine/src/task/browser.rs +++ b/crates/tinycomputer-engine/src/task/browser.rs @@ -6,7 +6,7 @@ use std::sync::{Arc, Mutex}; use tinycomputer_browser::{ActionContext, Browser, BrowserSurface, SessionOptions}; use tinycomputer_bus::agent::{PaymentMode, TaskConstraints, TaskId}; use tinycomputer_bus::browser::{ScreenshotRequest, SessionId}; -use tinycomputer_bus::{DesktopResponse, RunFlowRequest}; +use tinycomputer_bus::{DesktopError, DesktopResponse, RunFlowRequest}; use tinycomputer_core::surface::{Depth, Surface}; use super::{CaptureFuture, FlowFuture, FlowRunner, PrepareFuture, TextFuture}; @@ -272,14 +272,25 @@ impl BrowserRunner { ) -> FlowFuture { let runtime = runtime.journaled_as(&format!("task-{task}")); let surface = self.surface(task, constraints); + let context = ActionContext { + task_id: Some(task.0.clone()), + payment_in_play: constraints.payment == PaymentMode::FillThenApprove, + }; let mut request = request; request.task_id = Some(task.0.clone()); - Box::pin(tinycomputer_engine_flow( - surface, - runtime, - request, - self.secret_host.clone(), - )) + let secret_host = self.secret_host.clone(); + Box::pin(async move { + if surface.update_action_context(context).await.is_err() { + return DesktopResponse::err( + "update-action-context", + DesktopError::new( + "ACTION_CONTEXT_FAILED", + "the retained browser session could not update its host payment context", + ), + ); + } + tinycomputer_engine_flow(surface, runtime, request, secret_host).await + }) } } diff --git a/crates/tinycomputer-engine/src/task/browser_tests.rs b/crates/tinycomputer-engine/src/task/browser_tests.rs index b16b2d843..340e285bf 100644 --- a/crates/tinycomputer-engine/src/task/browser_tests.rs +++ b/crates/tinycomputer-engine/src/task/browser_tests.rs @@ -267,6 +267,58 @@ async fn public_task_manager_runs_the_real_browser_runner_without_a_model() Ok(()) } +#[tokio::test] +async fn retained_browser_updates_payment_gate_context_without_reopening() +-> Result<(), Box> { + let script = BrowserScript::default(); + let gate = Arc::new(RecordingGate::default()); + let browser = Arc::new(Browser::new(Arc::new(script)).with_action_gate(gate.clone())); + let runner = BrowserRunner::new(browser, runtime()?).with_session_options(SessionOptions { + headless: true, + ..SessionOptions::default() + }); + let task = tinycomputer_bus::agent::TaskId::new("t-payment-context"); + let mut constraints = TaskConstraints { + surfaces: vec![SurfaceKind::Browser], + origins: vec!["http://127.0.0.1:8765".to_owned()], + payment: PaymentMode::StopAtPayment, + ..TaskConstraints::default() + }; + runner.prepare(&task, &constraints).await; + let session = runner + .session_id(&task) + .ok_or("prepared task session was not retained")?; + let make_request = || RunFlowRequest { + flow: Flow { + app: "browser".to_owned(), + vars: std::collections::BTreeMap::new(), + steps: vec![FlowStep::Action(FlowAction::Browse( + "http://127.0.0.1:8765/index.html".to_owned(), + ))], + }, + ..RunFlowRequest::default() + }; + let first = runner.run(&task, &constraints, make_request()).await; + assert!(first.ok, "{:?}", first.error); + + constraints.payment = PaymentMode::FillThenApprove; + let second = runner.run(&task, &constraints, make_request()).await; + assert!(second.ok, "{:?}", second.error); + assert_eq!(runner.session_id(&task).as_ref(), Some(&session)); + let contexts = gate + .contexts + .lock() + .map_err(|error| std::io::Error::other(error.to_string()))?; + assert!(contexts.iter().any(|context| { + context.task_id.as_deref() == Some(task.0.as_str()) && !context.payment_in_play + })); + assert!(contexts.iter().any(|context| { + context.task_id.as_deref() == Some(task.0.as_str()) && context.payment_in_play + })); + runner.release(&task); + Ok(()) +} + #[tokio::test] async fn browser_action_refusal_from_the_real_runner_survives_rescue_and_report() -> Result<(), Box> { diff --git a/crates/tinycomputer-engine/src/task/drive.rs b/crates/tinycomputer-engine/src/task/drive.rs index 56388e247..dc9506bce 100644 --- a/crates/tinycomputer-engine/src/task/drive.rs +++ b/crates/tinycomputer-engine/src/task/drive.rs @@ -27,7 +27,7 @@ pub(super) async fn plan_then_drive( task: String, surfaces: Vec, ) { - plan_then_drive_with_page(cell, runner, planner, task, surfaces, true).await; + plan_then_drive_with_page(cell, runner, planner, task, surfaces, true, true).await; } /// Plans a payment continuation against the retained current page without @@ -39,7 +39,7 @@ pub(super) async fn plan_payment_then_drive( task: String, surfaces: Vec, ) { - plan_then_drive_with_page(cell, runner, planner, task, surfaces, false).await; + plan_then_drive_with_page(cell, runner, planner, task, surfaces, false, false).await; } async fn plan_then_drive_with_page( @@ -49,6 +49,7 @@ async fn plan_then_drive_with_page( task: String, surfaces: Vec, open_named_page: bool, + prepare_runner: bool, ) { let (names, secrets, constraints, votes, capped) = cell.state.lock().map_or_else( |_| { @@ -97,12 +98,13 @@ async fn plan_then_drive_with_page( let page = open_named_page .then(|| super::page::named_page(&task)) .flatten(); - let preparing = async { - runner.prepare(&id, &constraints).await; - if let Some(page) = &page { - runner.open_page(&id, page).await; - } - }; + let preparing = prepare_page( + runner.clone(), + id.clone(), + constraints.clone(), + page, + prepare_runner, + ); tokio::join!(planning, preparing).0 } else { planning.await @@ -163,6 +165,21 @@ async fn plan_then_drive_with_page( } } +async fn prepare_page( + runner: Arc, + id: tinycomputer_bus::agent::TaskId, + constraints: TaskConstraints, + page: Option, + prepare_runner: bool, +) { + if prepare_runner { + runner.prepare(&id, &constraints).await; + if let Some(page) = page { + runner.open_page(&id, &page).await; + } + } +} + /// Runs a task's flows in order until one stops it or all finish. /// /// A task's [`TaskBudget`] bounds the whole task, not one run of it: an diff --git a/crates/tinycomputer-engine/src/task/task_tests/payment_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/payment_tests.rs index fd122e0f1..65627eb26 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/payment_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/payment_tests.rs @@ -260,3 +260,53 @@ async fn a_held_payment_replans_the_same_task_and_keeps_its_current_page() { TaskStatus::Done { .. } )); } + +#[tokio::test] +async fn payment_continuation_reuses_the_already_prepared_task_surface() { + let (tasks, script) = controller(vec![payment_checkpoint(), payment_approval()]); + let tasks = tasks.with_planner(crate::planner::Planner::new(Arc::new(FixedPlan( + r#"{"app":"browser","steps":[{"enter":{"item":"one"}},{"enter":{"item":"two"}},{"enter":{"item":"three"}},{"enter":{"item":"four"}},{"stop_before":"Pay now"}]}"#.to_owned(), + script.planner_text.clone(), + )))); + let started = tasks + .start(&StartTaskRequest { + task: Some("buy the item in the current cart".to_owned()), + constraints: TaskConstraints { + payment: PaymentMode::StopAtPayment, + surfaces: vec![tinycomputer_bus::agent::SurfaceKind::Browser], + origins: vec!["https://.shop.example".to_owned()], + ..TaskConstraints::default() + }, + ..StartTaskRequest::default() + }) + .data + .unwrap(); + let stopped = settle(&tasks, &started.id).await; + assert!(matches!(stopped.status, TaskStatus::Checkpoint { .. })); + assert_eq!( + script.prepared.lock().unwrap().as_slice(), + std::slice::from_ref(&started.id) + ); + + tasks + .continue_payment(payment_request(started.id.clone(), payment_handles())) + .data + .unwrap(); + let paused = settle(&tasks, &started.id).await; + assert!(matches!(paused.status, TaskStatus::NeedsApproval { .. })); + assert_eq!( + script.prepared.lock().unwrap().as_slice(), + std::slice::from_ref(&started.id), + "continuing on the held payment form must not prepare or claim it again" + ); + assert_eq!( + script + .events + .lock() + .unwrap() + .iter() + .filter(|event| **event == "prepare") + .count(), + 1 + ); +}