adk_browser/frames.rs
1//! A live frame feed from a browser session: a screenshot on an interval, latest frame wins.
2//!
3//! [`BrowserSession::frames`] starts a feed that a console can relay to a person watching the
4//! agent work, for example as server-sent events. It uses only WebDriver screenshots: no
5//! remote desktop, no extra port and nothing the page can reach, so it works from a sealed
6//! browser too.
7//!
8//! | Behaviour | Why |
9//! |---|---|
10//! | Captures only while the session runs; never starts one | Watching must not launch a browser or keep one alive |
11//! | Skips a frame identical to the last one published | A still page costs nothing after its first frame |
12//! | Skips ticks missed while a screenshot is in flight | A slow page lowers the frame rate instead of queueing |
13//! | Keeps only the latest frame | A slow viewer sees the current page, not a backlog |
14//! | Holds the session weakly | The feed ends when the session is dropped, and never keeps it alive |
15
16use std::sync::Arc;
17use std::time::{Duration, SystemTime};
18
19use tokio::sync::watch;
20use tokio::task::JoinHandle;
21use tokio::time::MissedTickBehavior;
22
23use crate::session::BrowserSession;
24
25/// The shortest interval [`BrowserSession::frames`] accepts; a shorter one is raised to it.
26pub const MIN_FRAME_INTERVAL: Duration = Duration::from_millis(100);
27
28/// One frame of a session's page.
29///
30/// # Example
31///
32/// ```rust
33/// use adk_browser::Frame;
34///
35/// fn describe(frame: &Frame) -> String {
36/// format!("frame {} ({} bytes of base64 PNG)", frame.seq, frame.png_base64.len())
37/// }
38/// ```
39#[derive(Debug, Clone, PartialEq, Eq)]
40#[non_exhaustive]
41pub struct Frame {
42 /// 1 for the feed's first published frame, rising by one with each published frame.
43 pub seq: u64,
44 /// When the screenshot was taken.
45 pub taken_at: SystemTime,
46 /// The page as a base64-encoded PNG, as WebDriver returns it, ready for a data URL.
47 pub png_base64: Arc<str>,
48}
49
50/// A running frame feed from a [`BrowserSession`], made by [`BrowserSession::frames`].
51///
52/// Clones share one feed. The feed runs until its last clone is dropped or its session is
53/// dropped, whichever comes first. Receivers from [`subscribe`](Self::subscribe) do not keep
54/// it running.
55///
56/// # Example
57///
58/// ```rust,no_run
59/// use std::sync::Arc;
60/// use std::time::Duration;
61///
62/// use adk_browser::{BrowserConfig, BrowserSession};
63///
64/// # async fn example() -> adk_core::Result<()> {
65/// let session = Arc::new(BrowserSession::new(BrowserConfig::new()));
66/// session.start().await?;
67/// let mut feed = session.frames(Duration::from_secs(1));
68/// session.navigate("https://example.com").await?;
69/// while let Some(frame) = feed.next().await {
70/// // Relay `frame.png_base64` to the console, e.g. as one server-sent event.
71/// println!("frame {}", frame.seq);
72/// }
73/// # Ok(())
74/// # }
75/// ```
76#[derive(Clone)]
77pub struct FrameFeed {
78 frames: watch::Receiver<Option<Arc<Frame>>>,
79 _task: Arc<AbortOnDrop>,
80}
81
82impl std::fmt::Debug for FrameFeed {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 f.debug_struct("FrameFeed")
85 .field("latest_seq", &self.frames.borrow().as_ref().map(|frame| frame.seq))
86 .finish_non_exhaustive()
87 }
88}
89
90impl FrameFeed {
91 /// The latest frame, or `None` before the first one.
92 pub fn latest(&self) -> Option<Arc<Frame>> {
93 self.frames.borrow().clone()
94 }
95
96 /// Waits for a frame newer than the last one this handle returned, and returns it.
97 /// Returns `None` once the feed has ended because its session was dropped.
98 pub async fn next(&mut self) -> Option<Arc<Frame>> {
99 loop {
100 self.frames.changed().await.ok()?;
101 if let Some(frame) = self.frames.borrow_and_update().clone() {
102 return Some(frame);
103 }
104 }
105 }
106
107 /// A receiver of the latest frame, for a viewer that watches the feed on its own.
108 pub fn subscribe(&self) -> watch::Receiver<Option<Arc<Frame>>> {
109 self.frames.clone()
110 }
111}
112
113struct AbortOnDrop(JoinHandle<()>);
114
115impl Drop for AbortOnDrop {
116 fn drop(&mut self) {
117 self.0.abort();
118 }
119}
120
121impl BrowserSession {
122 /// Starts a feed of this session's page: a screenshot every `every` (at least
123 /// [`MIN_FRAME_INTERVAL`]), published when it differs from the last frame. See the
124 /// [module documentation](crate::frames) for its behaviour.
125 ///
126 /// # Panics
127 ///
128 /// Panics when called outside a Tokio runtime, since the feed runs as a task.
129 ///
130 /// # Example
131 ///
132 /// ```rust,no_run
133 /// use std::sync::Arc;
134 /// use std::time::Duration;
135 ///
136 /// use adk_browser::{BrowserConfig, BrowserSession};
137 ///
138 /// # async fn example() {
139 /// let session = Arc::new(BrowserSession::new(BrowserConfig::new()));
140 /// let feed = session.frames(Duration::from_secs(1));
141 /// assert!(feed.latest().is_none(), "nothing is captured before the session starts");
142 /// # }
143 /// ```
144 pub fn frames(self: &Arc<Self>, every: Duration) -> FrameFeed {
145 let session = Arc::downgrade(self);
146 let (sender, frames) = watch::channel(None);
147 let task = tokio::spawn(async move {
148 let mut ticks = tokio::time::interval(every.max(MIN_FRAME_INTERVAL));
149 ticks.set_missed_tick_behavior(MissedTickBehavior::Skip);
150 let mut seq = 0;
151 let mut last: Option<Arc<str>> = None;
152 loop {
153 ticks.tick().await;
154 let Some(session) = session.upgrade() else { break };
155 let driver = session.running_driver().await;
156 drop(session);
157 let Some(driver) = driver else { continue };
158 match driver.screenshot_as_png_base64().await {
159 Ok(png) if last.as_deref() == Some(png.as_str()) => {}
160 Ok(png) => {
161 let png: Arc<str> = png.into();
162 last = Some(png.clone());
163 seq += 1;
164 sender.send_replace(Some(Arc::new(Frame {
165 seq,
166 taken_at: SystemTime::now(),
167 png_base64: png,
168 })));
169 }
170 Err(error) => tracing::debug!(%error, "browser frame skipped"),
171 }
172 }
173 });
174 FrameFeed { frames, _task: Arc::new(AbortOnDrop(task)) }
175 }
176}