From b81831ea269b4b04b88b547c96382ee656243ecf Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 07:58:51 +0530 Subject: [PATCH 1/3] feat(browser): observe successful actions Co-authored-by: Medulla --- crates/tinycomputer-browser/src/lib.rs | 2 + crates/tinycomputer-browser/src/observer.rs | 49 +++++++++++ .../tinycomputer-browser/src/sessions/mod.rs | 15 ++++ .../tinycomputer-browser/src/sessions/page.rs | 85 +++++++++++++++++-- 4 files changed, 142 insertions(+), 9 deletions(-) create mode 100644 crates/tinycomputer-browser/src/observer.rs diff --git a/crates/tinycomputer-browser/src/lib.rs b/crates/tinycomputer-browser/src/lib.rs index 4466a7182..5be3177d4 100644 --- a/crates/tinycomputer-browser/src/lib.rs +++ b/crates/tinycomputer-browser/src/lib.rs @@ -41,6 +41,7 @@ mod error; mod fake; #[cfg(feature = "agent-browser")] mod linked; +mod observer; mod origins; mod outputs; mod profile_lock; @@ -56,6 +57,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..bd09cfe12 --- /dev/null +++ b/crates/tinycomputer-browser/src/observer.rs @@ -0,0 +1,49 @@ +//! 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, + /// Escape was pressed. + PressEscape, + /// Another typed browser action completed. + Other, +} + +/// A semantic target resolved from the latest accessibility snapshot. +#[derive(Clone, Debug, 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, +} + +/// Metadata for a successful dispatch. It deliberately carries no request +/// payload, typed text, fill values, or locator source text. +#[derive(Clone, Debug, 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, +} + +/// 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 acde2480d..e7e86d5aa 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,17 @@ impl Browser { self } + /// Installs a trusted host observer for successful browser actions. + pub fn set_action_observer(&self, observer: Option>) { + *self.action_observer.write().unwrap() = observer; + } + + pub(crate) fn observe_action(&self, observation: ActionObservation) { + if let Some(observer) = self.action_observer.read().unwrap().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..86da1edb5 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,42 @@ 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::Press { key, .. } if key.eq_ignore_ascii_case("escape") => { + ObservedAction::PressEscape + } + _ => 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. From b73c5a0fa22a68ed216cd7d27dcd41a2fe4b875f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 07:58:57 +0530 Subject: [PATCH 2/3] feat(engine): hand completed prefixes to planner Co-authored-by: Medulla --- .../src/agent/types/request.rs | 5 + crates/tinycomputer-bus/src/version/mod.rs | 4 +- .../src/version/version_tests.rs | 7 +- .../src/task/controller.rs | 28 ++ crates/tinycomputer-engine/src/task/drive.rs | 145 ++++++++++ .../src/task/persistence.rs | 12 +- crates/tinycomputer-engine/src/task/store.rs | 6 + .../src/task/task_tests.rs | 4 +- .../src/task/task_tests/persistence_tests.rs | 18 +- .../src/task/task_tests/plan_tests.rs | 252 +++++++++++++++++- 10 files changed, 466 insertions(+), 15 deletions(-) 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/src/task/controller.rs b/crates/tinycomputer-engine/src/task/controller.rs index 59a4da78a..d154af84b 100644 --- a/crates/tinycomputer-engine/src/task/controller.rs +++ b/crates/tinycomputer-engine/src/task/controller.rs @@ -221,6 +221,14 @@ impl Tasks { return AgentResponse::err(refusal); } let Some(flow) = request.flow.clone() else { + if request.handoff_to_planner { + return AgentResponse::err(AgentError::new( + "INVALID_REQUEST", + "planner handoff needs both a supplied flow and task goal", + "pass `task`, `flow`, and `handoff_to_planner: true` together", + true, + )); + } if let (Some(task), Some(planner)) = (&request.task, &self.planner) { return self.start_planned(request, facts, task, planner.clone()); } @@ -234,6 +242,20 @@ impl Tasks { true, )); }; + if request.handoff_to_planner && request.task.as_deref().is_none_or(str::is_empty) { + return AgentResponse::err(AgentError::new( + "INVALID_REQUEST", + "planner handoff needs a non-empty task goal", + "pass a task goal with the supplied prefix flow", + true, + )); + } + if request.handoff_to_planner + && self.planner.is_none() + && !self.runner.plan_recovery_enabled() + { + return AgentResponse::err(no_planner()); + } let known = known_names(&flow, &facts); let fact_names = fact_names(&facts); let validation = crate::agentic::check_flow(&flow, &known, &fact_names); @@ -393,6 +415,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 +494,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 +559,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() { diff --git a/crates/tinycomputer-engine/src/task/drive.rs b/crates/tinycomputer-engine/src/task/drive.rs index bbfc84cc1..49ac1d143 100644 --- a/crates/tinycomputer-engine/src/task/drive.rs +++ b/crates/tinycomputer-engine/src/task/drive.rs @@ -240,6 +240,102 @@ 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 = 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) => plan, + Err(reason) if runner.plan_recovery_enabled() => { + let flow = + super::plan_recovery::host_plan(cell, runner, task, FLOW_GUIDE.to_owned()) + .await + .map_err(|recovery| { + format!("{reason}; host recovery failed: {recovery}") + })?; + tinycomputer_bus::agent::TaskPlan { + flow, + questions: Vec::new(), + notes: Vec::new(), + } + } + Err(reason) => return Err(reason), + } + } else if runner.plan_recovery_enabled() { + let flow = + super::plan_recovery::host_plan(cell, runner, task, FLOW_GUIDE.to_owned()).await?; + tinycomputer_bus::agent::TaskPlan { + flow, + questions: Vec::new(), + notes: Vec::new(), + } + } else { + return Err("no planner or host plan-recovery hook is configured".to_owned()); + }; + + let known = super::names::known_names(&plan.flow, &facts); + let fact_names = super::names::fact_names(&facts); + 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 { + let id = cell.view.borrow().id.clone(); + runner.release(&id); + publish( + cell, + status, + "The remaining task needs values before it can continue.", + ); + return Ok(None); + } + Ok(Some(plan.flow)) +} + /// 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,9 +369,13 @@ 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 mut handoff = false; let redacted = { let Ok(mut state) = cell.state.lock() else { return; @@ -311,6 +411,10 @@ pub(super) async fn drive(cell: Arc, runner: Arc, runs: Ve } } } + if completed && state.handoff_to_planner { + state.handoff_to_planner = false; + handoff = true; + } if let Next::Stop { resume, .. } = &next { state.resume.clone_from(resume); if state.payment_checkpoint == PaymentCheckpointState::Unavailable @@ -321,6 +425,39 @@ pub(super) async fn drive(cell: Arc, runner: Arc, runs: Ve } state.facts.clone() }; + if handoff { + match plan_handoff(&cell, runner.as_ref()).await { + Ok(Some(flow)) => { + let allow = cell + .state + .lock() + .map_or(false, |state| state.constraints.allow_destructive); + runs.push_front(Run { + flow, + allow_destructive: allow, + rescue: None, + }); + continue; + } + Ok(None) => return, + 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}"), + ); + return; + } + } + } 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 +468,14 @@ 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 + ) { + if let Ok(mut state) = cell.state.lock() { + state.handoff_to_planner = false; + } + } let summary = redacted.redact(&stopped_summary(&status)); let ended = matches!( status, 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..7d1948460 100644 --- a/crates/tinycomputer-engine/src/task/task_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests.rs @@ -75,6 +75,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 +89,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(); 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..d9ef811a0 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,7 @@ //! Tests for planning a plain-language task before running it. use super::*; +use tinycomputer_bus::agent::SurfaceKind; struct WarmUsageRunner(Arc