diff --git a/Cargo.lock b/Cargo.lock index 28353f698..5b898b4db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2875,6 +2875,7 @@ dependencies = [ "tinyinference-decisions", "tinyinference-llm", "tokio", + "url", ] [[package]] diff --git a/crates/tinycomputer-browser/src/lib.rs b/crates/tinycomputer-browser/src/lib.rs index 4466a7182..17b07a80c 100644 --- a/crates/tinycomputer-browser/src/lib.rs +++ b/crates/tinycomputer-browser/src/lib.rs @@ -23,6 +23,9 @@ //! - [`ActionGate`] — an optional synchronous host policy called before typed //! actions, raw commands, evaluations, and navigations. Requests expose //! values to the trusted host callback; their `Debug` output omits values. +//! - [`ActionObserver`] — an optional host callback after a successful typed +//! action or navigation. It receives only action kind, before/after URL, and +//! the fresh snapshot target metadata; no request payload or typed value. //! - `AgentBrowser` (feature `agent-browser`) — the [`Launcher`] for //! agent-browser linked in-process. //! - [`Error`] — what can go wrong, as a taxonomy of what a caller should do @@ -41,6 +44,7 @@ mod error; mod fake; #[cfg(feature = "agent-browser")] mod linked; +mod observer; mod origins; mod outputs; mod profile_lock; @@ -56,6 +60,7 @@ pub use engine::{Engine, Launcher, Reply}; pub use error::{Error, Result}; #[cfg(feature = "agent-browser")] pub use linked::AgentBrowser; +pub use observer::{ActionObservation, ActionObserver, ObservedAction, ObservedTarget}; pub use outputs::SWEEP_INTERVAL; pub use profile_lock::{claim_profile, in_use as profile_in_use, release as release_profile}; pub use sessions::{Browser, MAX_SESSIONS}; diff --git a/crates/tinycomputer-browser/src/observer.rs b/crates/tinycomputer-browser/src/observer.rs new file mode 100644 index 000000000..61dc95cb3 --- /dev/null +++ b/crates/tinycomputer-browser/src/observer.rs @@ -0,0 +1,94 @@ +//! Successful browser actions observed by a trusted host. + +/// The kind of a successful browser action, without its input payload. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ObservedAction { + /// A page navigation completed. + Navigate, + /// A control was clicked. + Click, + /// A field was filled. + Fill, + /// Text was typed into a field. The text is not included. + Type, + /// One or more options were selected. Their values are not included. + Select, + /// A checkbox or radio was checked. + Check, + /// A checkbox or radio was unchecked. + Uncheck, + /// A control was double-clicked. + DoubleClick, + /// The pointer hovered over a control. + Hover, + /// A control received focus. + Focus, + /// The page or a control was scrolled. + Scroll, + /// A control was read or tested for visibility. + Read, + /// The browser waited for a condition. + Wait, + /// Another typed browser action completed. + Other, + /// Escape was pressed. + PressEscape, + /// Another key was pressed. The key text is not included. + Press, +} + +/// A semantic target resolved from the latest accessibility snapshot. +#[derive(Clone, PartialEq, Eq)] +pub struct ObservedTarget { + /// The target's accessibility role. + pub role: String, + /// The target's accessible name, if present. + pub name: Option, + /// The snapshot reference actually dispatched. + pub reference: Option, + /// True only when the current snapshot contains exactly one target with + /// this role and non-empty name, and the dispatched reference names it. + pub unique: bool, +} + +impl std::fmt::Debug for ObservedTarget { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ObservedTarget") + .field("role", &self.role) + .field("reference", &self.reference) + .field("unique", &self.unique) + .finish_non_exhaustive() + } +} + +/// Metadata for a successful dispatch. It deliberately carries no request +/// payload, typed text, fill values, or locator source text. +#[derive(Clone, PartialEq, Eq)] +pub struct ActionObservation { + /// The action that completed. + pub action: ObservedAction, + /// The page immediately before dispatch. + pub before_url: String, + /// The page after dispatch and origin checks. + pub after_url: String, + /// The resolved target, when the action named one. + pub target: Option, +} + +impl std::fmt::Debug for ActionObservation { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ActionObservation") + .field("action", &self.action) + .field("target", &self.target) + .finish_non_exhaustive() + } +} + +/// A trusted host sink for successful browser action metadata. +pub trait ActionObserver: Send + Sync { + /// Receives one successful dispatch. Implementations should return + /// quickly and must not retain data they do not need. + fn observed(&self, action: ActionObservation); +} diff --git a/crates/tinycomputer-browser/src/sessions/mod.rs b/crates/tinycomputer-browser/src/sessions/mod.rs index ec0709261..45423ba59 100644 --- a/crates/tinycomputer-browser/src/sessions/mod.rs +++ b/crates/tinycomputer-browser/src/sessions/mod.rs @@ -6,6 +6,7 @@ use std::collections::HashMap; use std::path::PathBuf; +use std::sync::RwLock; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; @@ -21,6 +22,7 @@ use crate::error::{Error, Result}; use crate::origins::Origins; use crate::outputs::OutputStore; use crate::reply; +use crate::{ActionObservation, ActionObserver}; mod artifacts; mod deep; @@ -61,6 +63,7 @@ pub struct Browser { /// see room for the last slot. opening: AtomicUsize, action_gate: Arc, + action_observer: Arc>>>, } impl std::fmt::Debug for Browser { @@ -273,6 +276,7 @@ impl Browser { counter: AtomicU64::new(0), opening: AtomicUsize::new(0), action_gate: default_gate(), + action_observer: Arc::default(), } } @@ -283,6 +287,21 @@ impl Browser { self } + /// Installs a trusted host observer for successful browser actions. + pub fn set_action_observer(&self, observer: Option>) { + if let Ok(mut current) = self.action_observer.write() { + *current = observer; + } + } + + pub(crate) fn observe_action(&self, observation: ActionObservation) { + if let Ok(observer) = self.action_observer.read() + && let Some(observer) = observer.as_ref() + { + observer.observed(observation); + } + } + pub(crate) fn check_action(&self, request: &ActionRequest) -> Result<()> { match self.action_gate.check(request) { ActionVerdict::Allow => Ok(()), diff --git a/crates/tinycomputer-browser/src/sessions/page.rs b/crates/tinycomputer-browser/src/sessions/page.rs index e6598f665..a1c30de1f 100644 --- a/crates/tinycomputer-browser/src/sessions/page.rs +++ b/crates/tinycomputer-browser/src/sessions/page.rs @@ -14,6 +14,7 @@ use crate::deep; use crate::error::{Error, Result}; use crate::outputs::within_cap; use crate::reply; +use crate::{ActionObservation, ObservedAction, ObservedTarget}; /// The fields of a raw command that can name a page to open or fetch. const URL_FIELDS: &[&str] = &["url", "url1", "url2"]; @@ -69,7 +70,7 @@ impl Browser { let current_url = session.action_url().await; self.check_action(&ActionRequest::raw( command.clone(), - current_url, + current_url.clone(), Some(request.url.clone()), &session.action_context, &session.refs, @@ -93,6 +94,14 @@ impl Browser { let page = session.admit(page).await?; session.info.url.clone_from(&page.url); session.info.title.clone_from(&page.title); + if let Some(before_url) = current_url { + self.observe_action(ActionObservation { + action: ObservedAction::Navigate, + before_url, + after_url: page.url.clone(), + target: None, + }); + } Ok(page) } @@ -182,15 +191,26 @@ impl Browser { // action is never sent to a refused one. session.check_if_readable(false).await?; let current_url = session.action_url().await; - self.check_action(&ActionRequest::typed( + let request = ActionRequest::typed( &action, - current_url, + current_url.clone(), None, &session.action_context, &session.refs, - ))?; + ); + let target = observed_target(request.target.as_ref(), &session.refs); + self.check_action(&request)?; let value = session.act_deep(number, &action).await?; - return session.outcome(value, None).await; + let outcome = session.outcome(value, None).await?; + if let Some(before_url) = current_url { + self.observe_action(ActionObservation { + action: observed_action(&action), + before_url, + after_url: outcome.page.url.clone(), + target, + }); + } + return Ok(outcome); } let command = convert::action(&action, session.options.default_timeout_ms)?; let keys = keys_go_to(&action)?; @@ -198,13 +218,15 @@ impl Browser { // a timer): an action is never sent to a refused one. session.check_if_readable(false).await?; let current_url = session.action_url().await; - self.check_action(&ActionRequest::typed( + let request = ActionRequest::typed( &action, - current_url, + current_url.clone(), None, &session.action_context, &session.refs, - ))?; + ); + let target = observed_target(request.target.as_ref(), &session.refs); + self.check_action(&request)?; match keys { Keys::Checked(selector) => session.focus_only(&selector).await?, Keys::Blurred => session.blur().await?, @@ -228,7 +250,16 @@ impl Browser { } => Some(format!("{:?} {:?}", value.by, value.value)), _ => None, }; - session.outcome(value, matched).await + let outcome = session.outcome(value, matched).await?; + if let Some(before_url) = current_url { + self.observe_action(ActionObservation { + action: observed_action(&action), + before_url, + after_url: outcome.page.url.clone(), + target, + }); + } + Ok(outcome) } /// Checks the configured action gate for a host-owned secret fill without @@ -468,6 +499,56 @@ impl Browser { } } +fn observed_target( + target: Option<&crate::action_gate::ActionTarget>, + refs: &[tinycomputer_bus::browser::ElementRef], +) -> Option { + let target = target?; + let name = target.name.clone(); + let reference = target.reference.clone(); + let matches = refs + .iter() + .filter(|item| Some(item.role.as_str()) == target.role.as_deref()) + .filter(|item| Some(item.name.as_str()) == target.name.as_deref()) + .collect::>(); + let unique = target + .name + .as_deref() + .is_some_and(|name| !name.trim().is_empty()) + && matches.len() == 1 + && reference.as_deref() == Some(matches[0].id.as_str()); + Some(ObservedTarget { + role: target.role.clone()?, + name, + reference, + unique, + }) +} + +fn observed_action(action: &Action) -> ObservedAction { + match action { + Action::Click { .. } => ObservedAction::Click, + Action::Fill { .. } => ObservedAction::Fill, + Action::Type { .. } => ObservedAction::Type, + Action::Select { .. } => ObservedAction::Select, + Action::Check { checked: true, .. } => ObservedAction::Check, + Action::Check { checked: false, .. } => ObservedAction::Uncheck, + Action::DoubleClick { .. } => ObservedAction::DoubleClick, + Action::Hover { .. } => ObservedAction::Hover, + Action::Focus { .. } => ObservedAction::Focus, + Action::Scroll { .. } => ObservedAction::Scroll, + Action::GetText { .. } | Action::GetAttribute { .. } | Action::IsVisible { .. } => { + ObservedAction::Read + } + Action::WaitFor { .. } => ObservedAction::Wait, + Action::Press { key, .. } if key.eq_ignore_ascii_case("escape") => { + ObservedAction::PressEscape + } + Action::Press { .. } => ObservedAction::Press, + Action::Back | Action::Forward | Action::Reload => ObservedAction::Other, + } +} + impl Session { /// What an action read, with the page it left the session on: refused, /// and left, when the allowed origins refuse it. diff --git a/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs b/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs index fda811556..93b3a4e5a 100644 --- a/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs +++ b/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs @@ -13,6 +13,7 @@ use super::open; use crate::error::Error; use crate::fake::{Fake, failure, ok}; use crate::{ActionContext, ActionGate, ActionRequest, ActionVerdict, Browser}; +use crate::{ActionObservation, ActionObserver, ObservedAction}; #[tokio::test] async fn navigation_reports_the_page_and_refusals_are_typed() { @@ -56,6 +57,123 @@ impl ActionGate for RefuseNamedAction { } } +#[derive(Default)] +struct CaptureActionObserver(std::sync::Mutex>); + +impl ActionObserver for CaptureActionObserver { + fn observed(&self, action: ActionObservation) { + self.0.lock().unwrap().push(action); + } +} + +fn observer_shop_fake(reject_click: Arc) -> Fake { + Fake::scripted(move |command| match command["action"].as_str() { + Some("url") => Some(ok(&json!({"url": "https://shop.test/"}))), + Some("navigate") => Some(ok(&json!({ + "url": command["url"], + "title": "Shop" + }))), + Some("snapshot") => Some(ok(&json!({ + "snapshot": "- button \"Add to cart\" [ref=e1]\n- button \"Add to cart\" [ref=e2]\n- textbox \"Email\" [ref=e3]", + "refs": { + "e1": {"role": "button", "name": "Add to cart"}, + "e2": {"role": "button", "name": "Add to cart"}, + "e3": {"role": "textbox", "name": "Email"} + } + }))), + Some("click") if reject_click.load(Ordering::SeqCst) => { + Some(failure("the scripted click failed")) + } + _ => None, + }) +} + +async fn click_reference(browser: &Browser, id: &tinycomputer_bus::browser::SessionId) { + browser + .perform( + id, + Action::Click { + target: Target::reference("e1"), + new_tab: false, + }, + ) + .await + .unwrap(); +} + +#[tokio::test] +async fn observer_sees_only_successful_metadata_and_snapshot_uniqueness() { + let reject_click = Arc::new(AtomicBool::new(true)); + let fake = observer_shop_fake(Arc::clone(&reject_click)); + let observer = Arc::new(CaptureActionObserver::default()); + let browser = Browser::with_scratch(Arc::new(fake), super::scratch("action-observer")); + browser.set_action_observer(Some(observer.clone())); + let id = browser + .open_session(SessionOptions::default()) + .await + .unwrap() + .id; + browser + .navigate(&id, NavigateRequest::new("https://shop.test/")) + .await + .unwrap(); + browser + .snapshot(&id, SnapshotRequest::default()) + .await + .unwrap(); + + assert!( + browser + .perform( + &id, + Action::Click { + target: Target::reference("e1"), + new_tab: false, + }, + ) + .await + .is_err() + ); + assert_eq!( + observer.0.lock().unwrap().len(), + 1, + "failed dispatch is not observed" + ); + + reject_click.store(false, Ordering::SeqCst); + click_reference(&browser, &id).await; + browser + .perform( + &id, + Action::Type { + target: Some(Target::reference("e3")), + text: "private@example.test".to_owned(), + delay_ms: None, + }, + ) + .await + .unwrap(); + let observations = observer.0.lock().unwrap().clone(); + assert_eq!(observations.len(), 3); + assert_eq!(observations[0].action, ObservedAction::Navigate); + assert_eq!(observations[0].after_url, "https://shop.test/"); + assert_eq!(observations[1].action, ObservedAction::Click); + let target = observations[1].target.as_ref().unwrap(); + assert_eq!(target.reference.as_deref(), Some("e1")); + assert!( + !target.unique, + "the latest snapshot has two matching controls" + ); + assert_eq!(observations[2].action, ObservedAction::Type); + assert!( + observations + .iter() + .all(|event| event.before_url != "private@example.test" + && event.after_url != "private@example.test") + ); + browser.close_session(&id).await.unwrap(); +} + struct RefuseUnknownCurrentUrl; impl ActionGate for RefuseUnknownCurrentUrl { diff --git a/crates/tinycomputer-bus/src/agent/types/request.rs b/crates/tinycomputer-bus/src/agent/types/request.rs index 9af380560..83cd9d4a8 100644 --- a/crates/tinycomputer-bus/src/agent/types/request.rs +++ b/crates/tinycomputer-bus/src/agent/types/request.rs @@ -50,6 +50,11 @@ pub struct StartTaskRequest { pub task: Option, /// A flow to run instead of planning one. pub flow: Option, + /// After a supplied flow completes, continue the same task by planning + /// `task` from the current surface. The task id and browser session are + /// retained; the named start page is not reopened. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub handoff_to_planner: bool, /// Values the task may type, by name — traveller name, date of birth, /// email, phone, card number. /// diff --git a/crates/tinycomputer-bus/src/version/mod.rs b/crates/tinycomputer-bus/src/version/mod.rs index b8f9bd75c..c238b7aef 100644 --- a/crates/tinycomputer-bus/src/version/mod.rs +++ b/crates/tinycomputer-bus/src/version/mod.rs @@ -8,7 +8,7 @@ //! release workflow bumps, which tracks the shipped artifact. /// The wire contract version this crate defines. -pub const CONTRACT_VERSION: (u32, u32) = (2, 23); +pub const CONTRACT_VERSION: (u32, u32) = (2, 24); /// Returns whether a host holding [`CONTRACT_VERSION`] can bind to a module /// reporting `module`. @@ -22,7 +22,7 @@ pub const CONTRACT_VERSION: (u32, u32) = (2, 23); /// ``` /// # use tinycomputer_bus::{is_compatible, CONTRACT_VERSION}; /// assert!(is_compatible(CONTRACT_VERSION)); -/// assert!(is_compatible((2, 23))); +/// assert!(is_compatible((2, 24))); /// assert!(!is_compatible((2, 11))); /// assert!(!is_compatible((1, 8))); /// ``` diff --git a/crates/tinycomputer-bus/src/version/version_tests.rs b/crates/tinycomputer-bus/src/version/version_tests.rs index fe062e574..807b21afc 100644 --- a/crates/tinycomputer-bus/src/version/version_tests.rs +++ b/crates/tinycomputer-bus/src/version/version_tests.rs @@ -6,7 +6,7 @@ use super::{CONTRACT_VERSION, binds, is_compatible}; #[test] fn the_shipped_contract_version_is_pinned() { - assert_eq!(CONTRACT_VERSION, (2, 23)); + assert_eq!(CONTRACT_VERSION, (2, 24)); } #[test] @@ -16,9 +16,9 @@ fn the_contract_binds_to_itself() { #[test] fn a_newer_minor_on_the_module_side_binds() { - assert!(is_compatible((2, 23))); + assert!(is_compatible((2, 24))); assert!(is_compatible((2, 97))); - // 2.23 adds host-held fact handles to ContinueTask. + // 2.24 adds same-task flow-to-planner handoff to StartTask. // 2.22 adds optional host-held secret handles to StartTask and RunFlow. // A host-only handle is ignored by older modules, which then refuse it // instead of trying to type its opaque identifier as a value. @@ -39,6 +39,7 @@ fn a_newer_minor_on_the_module_side_binds() { // 2.19 adds the ConsequenceHost host-callback interface (Review): a 2.19 // host serves it, which a 2.18 module does not call, so its approvals // would never reach the host's policy. + assert!(!is_compatible((2, 23))); assert!(!is_compatible((2, 22))); assert!(!is_compatible((2, 18))); assert!(!is_compatible((2, 17))); diff --git a/crates/tinycomputer-engine/Cargo.toml b/crates/tinycomputer-engine/Cargo.toml index 1a81c06d7..bc272a10f 100644 --- a/crates/tinycomputer-engine/Cargo.toml +++ b/crates/tinycomputer-engine/Cargo.toml @@ -30,6 +30,7 @@ serde = { workspace = true } getrandom = { workspace = true } # Blocking engine calls run on `spawn_blocking`; loops sleep between looks. tokio = { workspace = true } +url = { workspace = true } # The planner's OpenRouter model, only with the `planner` feature. The shipped # module links it, but it stays inert until private configuration supplies a diff --git a/crates/tinycomputer-engine/src/lib.rs b/crates/tinycomputer-engine/src/lib.rs index b3d84bad7..b1e3ff89d 100644 --- a/crates/tinycomputer-engine/src/lib.rs +++ b/crates/tinycomputer-engine/src/lib.rs @@ -65,9 +65,9 @@ pub use shape::{Harvest, RECORDS_CHARS, Shaper}; pub use task::{ BrowserRunner, CaptureFuture, ContinuePaidAtShopRequest, ContinuePaymentRequest, FailedStepRecovery, FailedStepRecoveryFuture, FailedStepRecoveryResult, FlowFuture, FlowRunner, - MAX_AWAIT_MS, MAX_TASKS, PausedTaskError, PlanRecoveryFuture, PlanRecoveryRequest, - PlanRecoveryResult, PrepareFuture, SecretHost, SecretTypeRequest, Tasks, TextFuture, - capabilities, + MAX_AWAIT_MS, MAX_TASKS, PageOriginFuture, PausedTaskError, PlanRecoveryFuture, + PlanRecoveryRequest, PlanRecoveryResult, PrepareFuture, SecretHost, SecretTypeRequest, Tasks, + TextFuture, capabilities, }; pub use tinycomputer_bus::DesktopResponse; #[cfg(feature = "desktop")] diff --git a/crates/tinycomputer-engine/src/task/browser.rs b/crates/tinycomputer-engine/src/task/browser.rs index 54049fd8d..0ab67bca8 100644 --- a/crates/tinycomputer-engine/src/task/browser.rs +++ b/crates/tinycomputer-engine/src/task/browser.rs @@ -123,6 +123,27 @@ impl FlowRunner for BrowserRunner { self.run_with_runtime(task, constraints, request, &self.runtime) } + fn page_origin(&self, task: &TaskId) -> super::PageOriginFuture { + let Some(session) = self.session_id(task) else { + return Box::pin(async { None }); + }; + let browser = self.browser.clone(); + Box::pin(async move { + let url = browser + .list_sessions() + .await + .ok()? + .into_iter() + .find(|info| info.id == session)? + .url; + let url = url::Url::parse(&url).ok()?; + if url.scheme() != "https" || !url.username().is_empty() || url.password().is_some() { + return None; + } + Some(format!("https://{}/", url.host_str()?)) + }) + } + fn run_with_usage( &self, task: &TaskId, diff --git a/crates/tinycomputer-engine/src/task/controller.rs b/crates/tinycomputer-engine/src/task/controller.rs index 59a4da78a..aacaab582 100644 --- a/crates/tinycomputer-engine/src/task/controller.rs +++ b/crates/tinycomputer-engine/src/task/controller.rs @@ -217,8 +217,8 @@ impl Tasks { )); } } - if let Some(refusal) = constraints_refusal(&request.constraints) { - return AgentResponse::err(refusal); + if let Some(error) = self.start_refusal(request) { + return AgentResponse::err(error); } let Some(flow) = request.flow.clone() else { if let (Some(task), Some(planner)) = (&request.task, &self.planner) { @@ -274,6 +274,16 @@ impl Tasks { AgentResponse::ok(cell.current_view()) } + fn start_refusal(&self, request: &StartTaskRequest) -> Option { + constraints_refusal(&request.constraints).or_else(|| { + handoff_refusal( + request, + self.planner.is_some(), + self.runner.plan_recovery_enabled(), + ) + }) + } + /// Waits until the task is no longer running, or `timeout_ms` passes. pub async fn await_task(&self, request: AwaitTaskRequest) -> AgentResponse { let Some(cell) = self.find(&request.id) else { @@ -393,6 +403,7 @@ impl Tasks { state.constraints.payment = PaymentMode::FillThenApprove; state.payment_checkpoint = PaymentCheckpointState::Transitioned; state.resume = None; + state.handoff_to_planner = false; let (done, done_rx) = tokio::sync::watch::channel(false); let completion = WorkerCompletion::new(done); let runner = self.runner.clone(); @@ -471,6 +482,7 @@ impl Tasks { let surfaces = state.constraints.surfaces.clone(); state.payment_checkpoint = PaymentCheckpointState::Transitioned; state.resume = None; + state.handoff_to_planner = false; let (done, done_rx) = tokio::sync::watch::channel(false); let completion = WorkerCompletion::new(done); let runner = self.runner.clone(); @@ -535,12 +547,16 @@ impl Tasks { ) { state.payment_checkpoint = PaymentCheckpointState::Closed; state.resume = None; + state.handoff_to_planner = false; drop(state); self.runner.release(id); return AgentResponse::ok(cell.current_view()); } } if !cell.view.borrow().status.is_final() { + if let Ok(mut state) = cell.state.lock() { + state.handoff_to_planner = false; + } if let Ok(worker) = cell.worker.lock() && let Some(worker) = worker.as_ref() { @@ -614,6 +630,33 @@ impl Tasks { } } +fn handoff_refusal( + request: &StartTaskRequest, + planner_configured: bool, + host_recovery_enabled: bool, +) -> Option { + if !request.handoff_to_planner { + return None; + } + if request.flow.is_none() + || request + .task + .as_deref() + .is_none_or(|task| task.trim().is_empty()) + { + return Some(AgentError::new( + "INVALID_REQUEST", + "planner handoff needs both a supplied flow and a non-empty task goal", + "pass `task`, `flow`, and `handoff_to_planner: true` together", + true, + )); + } + if !planner_configured && !host_recovery_enabled { + return Some(no_planner()); + } + None +} + /// Why a task's constraints cannot start it, if they cannot: a payment form /// filled with no named site to type card details on (`*` names none), a /// relative profile folder, which would land wherever the module's host diff --git a/crates/tinycomputer-engine/src/task/describe.rs b/crates/tinycomputer-engine/src/task/describe.rs index 7a75c64dd..21e97c635 100644 --- a/crates/tinycomputer-engine/src/task/describe.rs +++ b/crates/tinycomputer-engine/src/task/describe.rs @@ -71,6 +71,7 @@ fn start_task_input() -> Value { json!({ "task": {"type": "string", "description": "the goal in plain language"}, "flow": {"type": "object", "description": "a flow written from the guide"}, + "handoff_to_planner": {"type": "boolean", "default": false, "description": "after a supplied flow finishes, plan the remaining task in the same browser session"}, "facts": { "type": "object", "additionalProperties": {"type": "string"}, diff --git a/crates/tinycomputer-engine/src/task/drive.rs b/crates/tinycomputer-engine/src/task/drive.rs index bbfc84cc1..c68cb3e1f 100644 --- a/crates/tinycomputer-engine/src/task/drive.rs +++ b/crates/tinycomputer-engine/src/task/drive.rs @@ -2,11 +2,11 @@ //! flows in order, interpreting where each stopped, and finishing it. use std::collections::{BTreeMap, VecDeque}; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use std::time::{Duration, Instant}; -use tinycomputer_bus::FLOW_GUIDE; use tinycomputer_bus::agent::{SurfaceKind, TaskConstraints, TaskId, TaskStatus}; +use tinycomputer_bus::{FLOW_GUIDE, FlowAction}; use super::artifact::{capture, captured}; use super::budget::{elapsed_budget_failed, run_request, stop_task}; @@ -240,6 +240,402 @@ async fn prepare_page( } } +/// Plans the rest of a task after a supplied flow prefix. The runner is not +/// prepared or opened here: it still owns the page the prefix left current. +async fn plan_handoff( + cell: &Arc, + runner: &dyn FlowRunner, +) -> Result, String> { + let (task, surfaces, facts, planner) = { + let state = cell + .state + .lock() + .map_err(|_| "task state is unavailable".to_owned())?; + ( + state.goal.clone(), + state.constraints.surfaces.clone(), + state.facts.clone(), + cell.planner.clone(), + ) + }; + if task.trim().is_empty() { + return Err("the handoff task text is empty".to_owned()); + } + let (plan, origin) = + draft_from_current_page(cell, runner, task, surfaces, facts.clone(), planner).await?; + validate_handoff_plan(cell, plan, &facts, &origin) +} + +async fn draft_from_current_page( + cell: &Arc, + runner: &dyn FlowRunner, + task: String, + surfaces: Vec, + facts: tinycomputer_core::Facts, + planner: Option, +) -> Result<(tinycomputer_bus::agent::TaskPlan, String), String> { + let usage = task_usage(cell); + let before_calls = usage.snapshot().planner.calls; + let budget_left = { + let state = cell + .state + .lock() + .map_err(|_| "task state is unavailable".to_owned())?; + let calls_left = state + .budget + .max_model_calls + .unwrap_or(super::DEFAULT_MODEL_CALLS) + .saturating_sub(state.spent.model_calls); + let elapsed_left = state + .budget + .max_elapsed_ms + .map(|max| max.saturating_sub(state.spent.elapsed_ms)); + if calls_left == 0 { + return Err( + "the task has no model calls remaining for continuation planning".to_owned(), + ); + } + if elapsed_left == Some(0) { + return Err("the task has no time remaining for continuation planning".to_owned()); + } + elapsed_left + }; + // Drop also charges elapsed time and started planner calls if this future + // is cancelled while the model is still responding. + let mut debit = PlanningDebit::new(Arc::downgrade(cell), Arc::clone(&usage), before_calls); + let id = cell.view.borrow().id.clone(); + let origin_future = runner.page_origin(&id); + let origin = if let Some(ms) = budget_left { + tokio::time::timeout(Duration::from_millis(ms), origin_future) + .await + .map_err(|_| "reading the current page exceeded the task time budget".to_owned())? + } else { + origin_future.await + } + .ok_or_else(|| "the current browser origin is unavailable".to_owned())?; + let planning_task = runner.redact( + &id, + &format!( + "{task}\n\n{}\nContinue this same task from the current page at {origin}. The current browser session is still open. Do not open or browse to the shop start page again, and do not repeat the completed prefix actions. Inspect the current page before choosing the next action.", + successful_prefix_summary(cell) + ), + ); + let plan = run_handoff_planner( + cell, + runner, + HandoffDraft { + task: planning_task.clone(), + surfaces, + facts, + planner, + budget_left, + }, + &mut debit, + ) + .await?; + drop(debit); + ensure_handoff_budget(cell)?; + Ok((plan, origin)) +} + +fn successful_prefix_summary(cell: &Cell) -> String { + let Ok(state) = cell.state.lock() else { + return "The safe prefix completed; its action structure is unavailable.".to_owned(); + }; + let mut counts = BTreeMap::<&'static str, usize>::new(); + for report in &state.steps { + if !matches!( + report.outcome, + tinycomputer_bus::StepOutcome::Done | tinycomputer_bus::StepOutcome::AlreadyDone + ) { + continue; + } + let category = match report.kind.as_str() { + "browse" => "navigation", + "do" => "browser interaction", + "wait_for" => "page wait", + "verify" => "page check", + _ => continue, + }; + *counts.entry(category).or_default() += 1; + } + if counts.is_empty() { + return "The safe recipe prefix completed; no successful replayable action classes were recorded.".to_owned(); + } + let steps = counts + .into_iter() + .map(|(kind, count)| format!("{count} completed {kind} step(s)")) + .collect::>() + .join(", "); + format!("Completed safe-prefix structure: {steps}. Do not repeat these steps.") +} + +async fn run_handoff_planner( + cell: &Arc, + runner: &dyn FlowRunner, + draft: HandoffDraft, + debit: &mut PlanningDebit, +) -> Result { + let planning = draft_handoff( + cell, + runner, + draft.task.clone(), + draft.surfaces, + draft.facts, + draft.planner, + ); + let result = if let Some(ms) = draft.budget_left { + let remaining = ms + .saturating_sub(u64::try_from(debit.started.elapsed().as_millis()).unwrap_or(u64::MAX)); + tokio::time::timeout(Duration::from_millis(remaining), planning) + .await + .map_err(|_| "continuation planning exceeded the task time budget".to_owned())? + } else { + planning.await + }; + match result { + Ok(plan) => Ok(plan), + Err(reason) if runner.plan_recovery_enabled() => { + debit.charge(); + let remaining_calls = { + let state = cell + .state + .lock() + .map_err(|_| "task state is unavailable".to_owned())?; + state + .budget + .max_model_calls + .unwrap_or(super::DEFAULT_MODEL_CALLS) + .saturating_sub(state.spent.model_calls) + }; + if remaining_calls == 0 { + return Err(reason); + } + let flow = + super::plan_recovery::host_plan(cell, runner, draft.task, FLOW_GUIDE.to_owned()) + .await + .map_err(|recovery| format!("{reason}; host recovery failed: {recovery}"))?; + Ok(tinycomputer_bus::agent::TaskPlan { + flow, + questions: Vec::new(), + notes: Vec::new(), + }) + } + Err(reason) => Err(reason), + } +} + +struct HandoffDraft { + task: String, + surfaces: Vec, + facts: tinycomputer_core::Facts, + planner: Option, + budget_left: Option, +} + +fn ensure_handoff_budget(cell: &Cell) -> Result<(), String> { + let state = cell + .state + .lock() + .map_err(|_| "task state is unavailable".to_owned())?; + if state.spent.model_calls + > state + .budget + .max_model_calls + .unwrap_or(super::DEFAULT_MODEL_CALLS) + { + return Err("continuation planning exhausted the task model call budget".to_owned()); + } + if state + .budget + .max_elapsed_ms + .is_some_and(|max| state.spent.elapsed_ms > max) + { + return Err("continuation planning exhausted the task time budget".to_owned()); + } + Ok(()) +} + +fn validate_handoff_plan( + cell: &Arc, + plan: tinycomputer_bus::agent::TaskPlan, + facts: &tinycomputer_core::Facts, + origin: &str, +) -> Result, String> { + let known = super::names::known_names(&plan.flow, facts); + let fact_names = super::names::fact_names(facts); + let errors = crate::agentic::check_flow(&plan.flow, &known, &fact_names) + .errors + .into_iter() + .filter(|error| !super::names::is_undefined(error)) + .collect::>(); + if plan.flow.steps.is_empty() || !errors.is_empty() { + return Err(if plan.flow.steps.is_empty() { + "the planner returned an empty continuation".to_owned() + } else { + format!( + "the planner returned an invalid continuation: {}", + errors.join("; ") + ) + }); + } + if reopens_origin(&plan.flow, origin) { + return Err("the planner tried to reopen the current shop's start page".to_owned()); + } + let missing = crate::agentic::missing_inputs(&plan.flow, &known, &fact_names); + let waiting = if plan.questions.is_empty() { + (!missing.is_empty()).then(|| super::publish::needs_input(&missing)) + } else { + Some(TaskStatus::NeedsInput { + fields: plan.questions, + }) + }; + if let Ok(mut state) = cell.state.lock() { + state.flow = plan.flow.clone(); + } + if let Some(status) = waiting { + publish( + cell, + status, + "The remaining task needs values before it can continue.", + ); + return Ok(None); + } + Ok(Some(plan.flow)) +} + +struct PlanningDebit { + cell: Weak, + usage: Arc, + planner_calls_before: u64, + started: Instant, + charged: bool, +} + +impl PlanningDebit { + fn new(cell: Weak, usage: Arc, planner_calls_before: u64) -> Self { + Self { + cell, + usage, + planner_calls_before, + started: Instant::now(), + charged: false, + } + } + + fn charge(&mut self) { + if self.charged { + return; + } + self.charged = true; + let calls = self + .usage + .snapshot() + .planner + .calls + .saturating_sub(self.planner_calls_before); + let calls = u32::try_from(calls).unwrap_or(u32::MAX); + if let Some(cell) = self.cell.upgrade() + && let Ok(mut state) = cell.state.lock() + { + state.spent.model_calls = state.spent.model_calls.saturating_add(calls); + state.spent.elapsed_ms = state.spent.elapsed_ms.saturating_add( + u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX), + ); + } + } +} + +impl Drop for PlanningDebit { + fn drop(&mut self) { + self.charge(); + } +} + +fn reopens_origin(flow: &tinycomputer_bus::Flow, origin: &str) -> bool { + let Ok(origin) = url::Url::parse(origin) else { + return true; + }; + if origin.scheme() != "https" || !origin.username().is_empty() || origin.password().is_some() { + return true; + } + flow.steps.iter().any(|step| { + let FlowAction::Browse(url) = step.action() else { + return false; + }; + let Ok(url) = url::Url::parse(&url) else { + return false; + }; + url.scheme() == "https" + && url.host_str() == origin.host_str() + && url.username().is_empty() + && url.password().is_none() + && is_front_page(url.path()) + }) +} + +fn is_front_page(path: &str) -> bool { + let segments = path + .trim_matches('/') + .split('/') + .filter(|part| !part.is_empty()); + let segments = segments.collect::>(); + segments.len() <= 2 + && segments.iter().all(|segment| { + let bytes = segment.as_bytes(); + (bytes.len() == 2 && bytes.iter().all(u8::is_ascii_alphabetic)) + || (bytes.len() == 5 + && bytes[..2].iter().all(u8::is_ascii_alphabetic) + && matches!(bytes[2], b'-' | b'_') + && bytes[3..].iter().all(u8::is_ascii_alphabetic)) + }) +} + +async fn draft_handoff( + cell: &Arc, + runner: &dyn FlowRunner, + task: String, + surfaces: Vec, + facts: tinycomputer_core::Facts, + planner: Option, +) -> Result { + if let Some(planner) = planner { + let planner = planner.with_usage_recorder(task_usage(cell)); + let started = Instant::now(); + let names = facts + .names() + .into_iter() + .map(str::to_owned) + .collect::>(); + let secrets = facts + .secret_names() + .into_iter() + .map(str::to_owned) + .collect::>(); + let (outcome, used) = planner + .plan_measured(&task, &names, &secrets, &surfaces) + .await; + let id = cell.view.borrow().id.clone(); + runner.journal(Some(&id), "plan", &|| { + super::timing::planned(&outcome, used, started.elapsed(), planner.configuration()) + }); + match outcome { + Ok(plan) => Ok(plan), + Err(reason) => Err(reason), + } + } else if runner.plan_recovery_enabled() { + let flow = + super::plan_recovery::host_plan(cell, runner, task, FLOW_GUIDE.to_owned()).await?; + Ok(tinycomputer_bus::agent::TaskPlan { + flow, + questions: Vec::new(), + notes: Vec::new(), + }) + } else { + Err("no planner or host plan-recovery hook is configured".to_owned()) + } +} + /// 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 @@ -273,54 +669,29 @@ pub(super) async fn drive(cell: Arc, runner: Arc, runs: Ve }; let spent_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); let (next, result) = run_outcome(&run.flow, &reply, constraints.payment); + let completed = result + .as_ref() + .is_some_and(|result| result.stop == tinycomputer_bus::FlowStopReason::Completed); let reached = result .as_ref() .map_or_else(Vec::new, |result| result.steps.clone()); - let redacted = { - let Ok(mut state) = cell.state.lock() else { + let Some((handoff, redacted)) = record_run( + &cell, + &run, + &next, + result, + &reached, + spent_ms, + completed && runs.is_empty(), + ) else { + return; + }; + if handoff { + if !queue_handoff(&cell, runner.as_ref(), &mut runs).await { return; - }; - state.spent.elapsed_ms = state.spent.elapsed_ms.saturating_add(spent_ms); - if let Some(rescue) = run.rescue.and_then(|index| state.rescues.get_mut(index)) { - rescue.outcome = rescue_outcome(&reached, rescue.steps.len()); - } - state.dialog_left_open = result - .as_ref() - .is_some_and(|result| result.dialog_left_open); - if let Some(result) = result { - state.spent.actions = state.spent.actions.saturating_add(result.actions); - state.spent.model_calls = - state.spent.model_calls.saturating_add(result.metrics.calls); - state.finished += finished(&result.steps); - state.steps.extend(result.steps); - state.exchanges.extend(result.trace); - state.learned.extend(result.learned); - // A variable the flow declares is the caller's input unless - // a step writes it: a planner declares each read's variable - // up front, empty, while one the flow defines from the - // caller's values (`"recipient": "${email}"`) is expanded as - // the run starts, so a changed value alone tells nothing. - let written = written_names(&run.flow.steps); - for (name, value) in result.vars { - let read = match run.flow.vars.get(&name) { - None => true, - Some(declared) => written.contains(&name) && *declared != value, - }; - if read && state.facts.get(&name).is_none() { - state.reads.insert(name, value); - } - } - } - if let Next::Stop { resume, .. } = &next { - state.resume.clone_from(resume); - if state.payment_checkpoint == PaymentCheckpointState::Unavailable - && matches!(resume, Some(super::interpret::Resume::PaymentCheckpoint)) - { - state.payment_checkpoint = PaymentCheckpointState::Available; - } } - state.facts.clone() - }; + continue; + } if let Next::Stop { status, .. } = next { let status = human_wall(&cell, runner.as_ref(), *status).await; let status = match rescued(&cell, runner.as_ref(), &run, status, reached).await { @@ -331,6 +702,13 @@ pub(super) async fn drive(cell: Arc, runner: Arc, runs: Ve } }; let status = captured(&cell, runner.as_ref(), status).await; + if matches!( + status, + TaskStatus::Checkpoint { .. } | TaskStatus::Failed { .. } | TaskStatus::Cancelled + ) && let Ok(mut state) = cell.state.lock() + { + state.handoff_to_planner = false; + } let summary = redacted.redact(&stopped_summary(&status)); let ended = matches!( status, @@ -346,6 +724,92 @@ pub(super) async fn drive(cell: Arc, runner: Arc, runs: Ve finish(&cell, runner.as_ref()).await; } +async fn queue_handoff( + cell: &Arc, + runner: &dyn FlowRunner, + runs: &mut VecDeque, +) -> bool { + match plan_handoff(cell, runner).await { + Ok(Some(flow)) => { + let allow = cell + .state + .lock() + .is_ok_and(|state| state.constraints.allow_destructive); + runs.push_front(Run { + flow, + allow_destructive: allow, + rescue: None, + }); + true + } + Ok(None) => false, + Err(reason) => { + let id = cell.view.borrow().id.clone(); + runner.release(&id); + let reason = runner.redact(&id, &reason); + publish( + cell, + TaskStatus::Failed { + step: None, + reason: reason.clone(), + hint: "the recipe prefix ran, but the task could not be planned from the current page".to_owned(), + recoverable: true, + }, + &format!("Planning the remaining task failed: {reason}"), + ); + false + } + } +} + +fn record_run( + cell: &Cell, + run: &Run, + next: &Next, + result: Option, + reached: &[tinycomputer_bus::StepReport], + spent_ms: u64, + handoff_ready: bool, +) -> Option<(bool, tinycomputer_core::Facts)> { + let mut state = cell.state.lock().ok()?; + state.spent.elapsed_ms = state.spent.elapsed_ms.saturating_add(spent_ms); + if let Some(rescue) = run.rescue.and_then(|index| state.rescues.get_mut(index)) { + rescue.outcome = rescue_outcome(reached, rescue.steps.len()); + } + if let Some(result) = result { + state.dialog_left_open = result.dialog_left_open; + state.spent.actions = state.spent.actions.saturating_add(result.actions); + state.spent.model_calls = state.spent.model_calls.saturating_add(result.metrics.calls); + state.finished += finished(&result.steps); + state.steps.extend(result.steps); + state.exchanges.extend(result.trace); + state.learned.extend(result.learned); + let written = written_names(&run.flow.steps); + for (name, value) in result.vars { + let read = match run.flow.vars.get(&name) { + None => true, + Some(declared) => written.contains(&name) && *declared != value, + }; + if read && state.facts.get(&name).is_none() { + state.reads.insert(name, value); + } + } + } + let handoff = handoff_ready && state.handoff_to_planner; + if handoff { + state.handoff_to_planner = false; + } + if let Next::Stop { resume, .. } = next { + state.resume.clone_from(resume); + if state.payment_checkpoint == PaymentCheckpointState::Unavailable + && matches!(resume, Some(super::interpret::Resume::PaymentCheckpoint)) + { + state.payment_checkpoint = PaymentCheckpointState::Available; + } + } + Some((handoff, state.facts.clone())) +} + /// Every run finished: the task is done, with what it read, shaped as its /// `output` asks when it asks. pub(super) async fn finish(cell: &Cell, runner: &dyn FlowRunner) { diff --git a/crates/tinycomputer-engine/src/task/mod.rs b/crates/tinycomputer-engine/src/task/mod.rs index ed0fb57a4..59b4d6d0d 100644 --- a/crates/tinycomputer-engine/src/task/mod.rs +++ b/crates/tinycomputer-engine/src/task/mod.rs @@ -133,6 +133,9 @@ pub type FlowFuture = Pin + Send>>; /// The future [`FlowRunner::visible_text`] returns. pub type TextFuture = Pin> + Send>>; +/// The HTTPS origin of the browser page a running task currently holds. +pub type PageOriginFuture = Pin> + Send>>; + /// The future [`FlowRunner::capture`] returns: a held screenshot, if the /// task's surface could take one. pub type CaptureFuture = Pin> + Send>>; @@ -228,6 +231,13 @@ pub trait FlowRunner: Send + Sync + 'static { request: RunFlowRequest, ) -> FlowFuture; + /// Returns only the current browser origin, with path, query and + /// fragment omitted. A same-task planner handoff uses this as location + /// context without reading page contents. + fn page_origin(&self, _task: &TaskId) -> PageOriginFuture { + Box::pin(async { None }) + } + /// Runs a task flow with its usage recorder attached to model calls. /// /// Runners that do not account for model usage may keep the default. A diff --git a/crates/tinycomputer-engine/src/task/persistence.rs b/crates/tinycomputer-engine/src/task/persistence.rs index 097d73693..1aea8c0ae 100644 --- a/crates/tinycomputer-engine/src/task/persistence.rs +++ b/crates/tinycomputer-engine/src/task/persistence.rs @@ -16,7 +16,8 @@ use super::{MAX_TASKS, Tasks}; use crate::rescue::Rescuer; use crate::{UsageRecorder, shape::Shaper}; -const VERSION: u32 = 1; +const VERSION: u32 = 2; +const OLDEST_VERSION: u32 = 1; /// Why a paused task could not be saved or restored. #[derive(Debug)] @@ -89,6 +90,8 @@ struct PausedTask { id: TaskId, view: TaskView, flow: Flow, + #[serde(default)] + handoff_to_planner: bool, goal: String, shared_facts: BTreeMap, secret_handles: BTreeMap, @@ -181,6 +184,7 @@ impl Tasks { id: id.clone(), view, flow: state.flow.clone(), + handoff_to_planner: state.handoff_to_planner, goal: state.goal.clone(), shared_facts, secret_handles, @@ -244,6 +248,7 @@ impl Tasks { return_after_input, self.rescuer.clone(), self.shaper.clone(), + self.planner.clone(), ); let mut tasks = self .cells @@ -285,7 +290,7 @@ fn decode(bytes: &[u8]) -> Result { .and_then(serde_json::Value::as_u64) .and_then(|version| u32::try_from(version).ok()) .ok_or_else(|| PausedTaskError::Invalid("missing integer version".to_owned()))?; - if version != VERSION { + if !(OLDEST_VERSION..=VERSION).contains(&version) { return Err(PausedTaskError::UnsupportedVersion(version)); } Ok(serde_json::from_value::(value)?.task) @@ -406,6 +411,7 @@ fn build_cell( return_after_input: Option, rescuer: Option, shaper: Option, + planner: Option, ) -> Arc { let usage = Arc::new(UsageRecorder::from_snapshot(task.usage)); task.view.usage = usage.snapshot(); @@ -414,6 +420,7 @@ fn build_cell( state: std::sync::Mutex::new(State { usage, flow: task.flow, + handoff_to_planner: task.handoff_to_planner, goal: task.goal, facts, omitted_secrets: task.omitted_secrets, @@ -439,6 +446,7 @@ fn build_cell( worker: std::sync::Mutex::new(None), rescuer, shaper, + planner, }) } diff --git a/crates/tinycomputer-engine/src/task/store.rs b/crates/tinycomputer-engine/src/task/store.rs index 77ecc8dd1..9e4f06f39 100644 --- a/crates/tinycomputer-engine/src/task/store.rs +++ b/crates/tinycomputer-engine/src/task/store.rs @@ -33,6 +33,7 @@ pub(super) struct Cell { pub(super) rescuer: Option, /// Who turns what a finished task read into the shape it asked for. pub(super) shaper: Option, + pub(super) planner: Option, } pub(super) struct WorkerSlot { @@ -54,6 +55,9 @@ impl Cell { pub(super) struct State { pub(super) usage: Arc, pub(super) flow: Flow, + /// Run the supplied prefix once, then plan the original goal against the + /// surface it left open. + pub(super) handoff_to_planner: bool, /// The task in the caller's words, for Jev's brief; empty when only a /// flow was given. pub(super) goal: String, @@ -142,6 +146,7 @@ impl Tasks { state: Mutex::new(State { usage, flow: flow.clone(), + handoff_to_planner: request.handoff_to_planner, goal: request.task.clone().unwrap_or_default(), facts, omitted_secrets: BTreeSet::new(), @@ -167,6 +172,7 @@ impl Tasks { worker: Mutex::new(None), rescuer: self.rescuer.clone(), shaper: self.shaper.clone(), + planner: self.planner.clone(), }); let mut tasks = self.cells.lock().ok()?; while tasks.len() >= MAX_TASKS { diff --git a/crates/tinycomputer-engine/src/task/task_tests.rs b/crates/tinycomputer-engine/src/task/task_tests.rs index 381b81ad5..cfca0b7fd 100644 --- a/crates/tinycomputer-engine/src/task/task_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests.rs @@ -55,6 +55,8 @@ struct Script { host_secrets: Mutex>, /// What the task's surface shows when asked. screen: Mutex>, + /// The HTTPS origin of the still-open browser page. + origin: Mutex>, /// Tasks let go of, in order. released: Mutex>, /// The screenshot `capture` hands back, if any. @@ -75,6 +77,7 @@ struct Script { host_secret: Mutex>, /// The pages loaded while tasks were planned, with their task. opened: Mutex>, + task_ids: Mutex>, /// The host's response to a failed-step recovery request. recovery: Mutex>, /// Recovery requests, including their redacted task context. @@ -88,10 +91,11 @@ struct Script { impl FlowRunner for Script { fn run( &self, - _task: &TaskId, + task: &TaskId, constraints: &TaskConstraints, request: RunFlowRequest, ) -> FlowFuture { + self.task_ids.lock().unwrap().push(task.clone()); self.requests.lock().unwrap().push(request); self.constraints.lock().unwrap().push(constraints.clone()); let reply = self.replies.lock().unwrap().pop_front(); @@ -133,6 +137,11 @@ impl FlowRunner for Script { Box::pin(async move { texts }) } + fn page_origin(&self, _task: &TaskId) -> super::PageOriginFuture { + let origin = self.origin.lock().unwrap().clone(); + Box::pin(async move { origin }) + } + fn capture(&self, _task: &TaskId) -> super::CaptureFuture { self.events.lock().unwrap().push("capture"); let shot = self.shot.lock().unwrap().clone(); diff --git a/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs index f2ec0aa01..6be80573c 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs @@ -202,6 +202,7 @@ async fn describe_schemas_name_every_request_field() { }; let start = StartTaskRequest { + handoff_to_planner: true, output: Some(tinycomputer_bus::agent::TaskOutput::default()), fact_handles: std::collections::BTreeMap::from([( "card number".to_owned(), @@ -216,6 +217,10 @@ async fn describe_schemas_name_every_request_field() { let start = serde_json::to_value(start).unwrap(); let start_schema = schema("StartTask"); assert_eq!(documented(&start_schema), fields(&start)); + assert_eq!( + start_schema["properties"]["handoff_to_planner"]["default"], + false + ); // The host's own settings are no model's to set, so they are not offered. let offered = fields(&start["constraints"]) .into_iter() diff --git a/crates/tinycomputer-engine/src/task/task_tests/persistence_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/persistence_tests.rs index 2de8eebec..1264d8921 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/persistence_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/persistence_tests.rs @@ -401,16 +401,28 @@ async fn import_rejects_unknown_versions_and_inconsistent_pending_state() { let view = start(&tasks, json!({"app": "Mail", "steps": ["${email}"]}), &[]); let encoded = tasks.export_paused_task(&view.id).unwrap(); let mut unknown: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); - unknown["version"] = json!(2); + unknown["version"] = json!(3); let (fresh, _) = controller(Vec::new()); let unsupported = fresh .import_paused_task(&serde_json::to_vec(&unknown).unwrap()) .unwrap_err(); assert!(matches!( &unsupported, - crate::PausedTaskError::UnsupportedVersion(2) + crate::PausedTaskError::UnsupportedVersion(3) )); - assert!(unsupported.to_string().contains("version 2")); + assert!(unsupported.to_string().contains("version 3")); + let mut legacy: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); + legacy["version"] = json!(1); + legacy["task"] + .as_object_mut() + .unwrap() + .remove("handoff_to_planner"); + let (legacy_tasks, _) = controller(Vec::new()); + assert!( + legacy_tasks + .import_paused_task(&serde_json::to_vec(&legacy).unwrap()) + .is_ok() + ); let malformed = fresh .import_paused_task(br#"{"version":1,"task":{}}"#) .unwrap_err(); diff --git a/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs index e357c482e..921b098b3 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs @@ -1,6 +1,9 @@ //! Tests for planning a plain-language task before running it. +use super::super::store::Run; use super::*; +use crate::planner::{LanguageModel, Planner, Turn}; +use tinycomputer_bus::agent::SurfaceKind; struct WarmUsageRunner(Arc