Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions crates/tinycomputer-browser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -41,6 +44,7 @@ mod error;
mod fake;
#[cfg(feature = "agent-browser")]
mod linked;
mod observer;
mod origins;
mod outputs;
mod profile_lock;
Expand All @@ -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};
Expand Down
94 changes: 94 additions & 0 deletions crates/tinycomputer-browser/src/observer.rs
Original file line number Diff line number Diff line change
@@ -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<String>,
/// The snapshot reference actually dispatched.
pub reference: Option<String>,
/// 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<ObservedTarget>,
}

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);
}
19 changes: 19 additions & 0 deletions crates/tinycomputer-browser/src/sessions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -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;
Expand Down Expand Up @@ -61,6 +63,7 @@ pub struct Browser {
/// see room for the last slot.
opening: AtomicUsize,
action_gate: Arc<dyn ActionGate>,
action_observer: Arc<RwLock<Option<Arc<dyn ActionObserver>>>>,
}

impl std::fmt::Debug for Browser {
Expand Down Expand Up @@ -273,6 +276,7 @@ impl Browser {
counter: AtomicU64::new(0),
opening: AtomicUsize::new(0),
action_gate: default_gate(),
action_observer: Arc::default(),
}
}

Expand All @@ -283,6 +287,21 @@ impl Browser {
self
}

/// Installs a trusted host observer for successful browser actions.
pub fn set_action_observer(&self, observer: Option<Arc<dyn ActionObserver>>) {
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(()),
Expand Down
99 changes: 90 additions & 9 deletions crates/tinycomputer-browser/src/sessions/page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down Expand Up @@ -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,
Expand All @@ -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)
}

Expand Down Expand Up @@ -182,29 +191,42 @@ 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)?;
// The page may have moved on its own since the last call (a redirect,
// 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?,
Expand All @@ -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
Expand Down Expand Up @@ -468,6 +499,56 @@ impl Browser {
}
}

fn observed_target(
target: Option<&crate::action_gate::ActionTarget>,
refs: &[tinycomputer_bus::browser::ElementRef],
) -> Option<ObservedTarget> {
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::<Vec<_>>();
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.
Expand Down
Loading
Loading