Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

browser: follow sign-in popups (Continue with Google) in the live view and bot tools (0.9.1) (#524)

Oleksandr Ivanchenko75aa08acc6d4
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index a9b51c4a..78db326e 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -1147,6 +1147,12 @@ pub struct BrowserController {
pub reads: Arc<std::sync::Mutex<super::reads::Reads>>,
/// The driving bot's site rules and the task enforcing them (see [`super::site_guard`]).
pub site_guard: Arc<super::site_guard::SiteGuard>,
+ /// The popups the bot's page opened: the newest still open is the page commands go to (see
+ /// [`super::popups`]).
+ popups: Arc<super::popups::Popups>,
+ /// [`super::popups::Popups::generation`] when `ws_conn` was opened: a newer one means the
+ /// page in front changed and the next command reconnects to it.
+ ws_generation: Arc<AtomicU64>,
}
/// Widest screenshot a bot gets, in pixels, and the narrowest width it may ask for.
@@ -1212,6 +1218,8 @@ impl BrowserController {
progress: Arc::default(),
reads: Arc::default(),
site_guard: Arc::default(),
+ popups: Arc::default(),
+ ws_generation: Arc::default(),
}
}
@@ -1311,6 +1319,11 @@ impl BrowserController {
Ok(url.to_string())
}
+ /// Bumped each time the page in front changes: a popup the bot's page opened, or its close.
+ pub fn page_changes(&self) -> tokio::sync::watch::Receiver<u64> { self.popups.changes() }
+
+ /// The DevTools address of the page commands go to: the bot's page, or the newest popup it
+ /// opened that is still open (see [`super::popups`]).
pub async fn get_ws_url(&self) -> Result<String, BrowserError> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(3))
@@ -1322,10 +1335,31 @@ impl BrowserController {
if !self.browser_level {
if let Ok(resp) = client.get(&list_url).header(reqwest::header::HOST, "localhost").send().await {
if let Ok(targets) = resp.json::<Vec<Value>>().await {
- if let Some(page) = targets.into_iter().find(|t| t["type"] == "page" &&
- self.target_id.as_ref().is_none_or(|id| t["id"] == *id)) {
+ let pages: Vec<&Value> = targets.iter().filter(|t| t["type"] == "page").collect();
+ let chain = self.popups.chain();
+ let listed = |id: &str| pages.iter().copied().find(|t| t["id"] == id);
+ // the bot's page: its session's page, else the one it had while it is open, else
+ // the first page that isn't a popup it opened
+ let home = match &self.target_id {
+ Some(id) => listed(id),
+ None => chain.home().and_then(listed).or_else(|| {
+ pages.iter().copied().find(|t| !chain.is_popup(t["id"].as_str().unwrap_or_default()))
+ }),
+ };
+ if let Some(page) = home {
if let Some(ws) = page["webSocketDebuggerUrl"].as_str() {
- return self.reachable_ws_url(ws);
+ let ws = self.reachable_ws_url(ws)?;
+ // a DevTools endpoint that names no page ids (a proxy, a test double):
+ // its page as before, with no popups to follow
+ let Some(id) = page["id"].as_str() else { return Ok(ws) };
+ self.popups.set_home(id);
+ self.follow_popups().await;
+ // a popup that just closed may still be in front until its close arrives
+ let chain = self.popups.chain();
+ if let Some(popup) = chain.active().filter(|a| Some(*a) != chain.home() && listed(a).is_some()) {
+ return Ok(super::popups::page_ws_url(&ws, popup));
+ }
+ return Ok(ws);
}
}
}
@@ -1364,11 +1398,26 @@ impl BrowserController {
resp.json().await.map_err(|e| BrowserError::Http(e.to_string()))
}
- /// The DevTools target id of this controller's page.
+ /// Starts following the popups the bot's page opens, unless that is already running.
+ async fn follow_popups(&self) {
+ if self.popups.is_watching() {
+ return;
+ }
+ let Ok(version) = self.devtools_json("/json/version").await else { return };
+ let Some(advertised) = version["webSocketDebuggerUrl"].as_str() else { return };
+ let Ok(browser_ws) = self.reachable_ws_url(advertised) else { return };
+ self.popups.watch(browser_ws).await;
+ }
+
+ /// The DevTools target id of this controller's page (the bot's page, never a popup it opened:
+ /// the site guard follows those from it).
async fn page_target_id(&self) -> Result<String, BrowserError> {
if let Some(id) = &self.target_id {
return Ok(id.clone());
}
+ if let Some(home) = self.popups.chain().home() {
+ return Ok(home.to_string());
+ }
let targets = self.devtools_json("/json/list").await?;
targets
.as_array()
@@ -1404,8 +1453,20 @@ impl BrowserController {
&self,
guard: &mut tokio::sync::MutexGuard<'_, Option<WsStream>>,
) -> Result<(), BrowserError> {
+ // a popup came to the front or closed since this connection opened: go to the page in front
+ let generation = self.popups.generation();
+ if guard.is_some() && generation != self.ws_generation.load(Ordering::SeqCst) {
+ tracing::debug!("the page in front changed; reconnecting to it");
+ **guard = None;
+ // kwnt's isolated world belonged to the other page
+ if let Ok(mut world) = self.capture_world.try_lock() {
+ *world = None;
+ }
+ }
if guard.is_none() {
let ws_url = self.get_ws_url().await?;
+ // after: finding the page may itself have announced the bot's page or a popup
+ self.ws_generation.store(self.popups.generation(), Ordering::SeqCst);
let mut ws = connect_cdp(&ws_url).await?;
tracing::debug!(target_id = ?self.target_id, "opened a DevTools connection");
self.reapply_viewport(&mut ws).await;
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
index d3e4cc9e..f4c96d5a 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -7,6 +7,7 @@ pub mod chrome_download;
pub mod computer;
pub mod credentials;
pub mod manager;
+pub mod popups;
pub mod cite;
pub mod progress;
pub mod reads;
diff --git a/src/sandbox/popups.rs b/src/sandbox/popups.rs
new file mode 100644
index 00000000..a1f33286
--- /dev/null
+++ b/src/sandbox/popups.rs
@@ -0,0 +1,279 @@
+//! Popups the bot's page opens, followed by the live view and the bot's browser tools.
+//!
+//! "Continue with Google" (and most OAuth sign-ins) calls `window.open`: Chrome opens the sign-in
+//! in a new page target whose `openerId` is the bot's page. Both the live view and the bot's
+//! DevTools connection were bound to the bot's page alone, so the popup loaded where nobody could
+//! see or reach it and the click seemed to do nothing. [`Popups`] watches the browser's targets
+//! and keeps the chain of pages opened from the bot's page: the newest one still open is the page
+//! everything acts on, and when it closes (the sign-in posted back to its opener) the page that
+//! opened it is in front again. A page opened by anything else (another bot's tab, the browser's
+//! own UI) is never followed.
+use serde_json::{json, Value};
+use std::sync::{Arc, Weak};
+use std::time::Duration;
+use tokio::sync::watch;
+
+/// The most popups followed at once, so a page that keeps opening windows can't grow the chain.
+pub const MAX_OPEN: usize = 8;
+
+/// The bot's page and the pages opened from it, oldest first.
+#[derive(Debug, Default, Clone, PartialEq)]
+pub struct Chain {
+ home: Option<String>,
+ open: Vec<String>,
+}
+
+impl Chain {
+ /// The bot's own page. A different one starts a new chain. `true` when it changed.
+ pub fn set_home(&mut self, target: &str) -> bool {
+ if self.home.as_deref() == Some(target) {
+ return false;
+ }
+ self.home = Some(target.to_string());
+ self.open.clear();
+ true
+ }
+
+ pub fn home(&self) -> Option<&str> { self.home.as_deref() }
+
+ /// The page in front: the newest popup still open, else the bot's page.
+ pub fn active(&self) -> Option<&str> { self.open.last().map(String::as_str).or(self.home.as_deref()) }
+
+ pub fn is_popup(&self, target: &str) -> bool { self.open.iter().any(|t| t == target) }
+
+ /// A page `target` opened by `opener`: followed when the bot's page or one of its popups
+ /// opened it. `true` when the page in front changed.
+ pub fn opened(&mut self, target: &str, opener: &str) -> bool {
+ if opener.is_empty() || self.home.as_deref() == Some(target) || self.is_popup(target) {
+ return false;
+ }
+ let ours = self.home.as_deref() == Some(opener) || self.is_popup(opener);
+ if !ours || self.open.len() >= MAX_OPEN {
+ return false;
+ }
+ self.open.push(target.to_string());
+ true
+ }
+
+ /// A page closed. A popup leaves the chain; the bot's page closing ends it. `true` when the
+ /// page in front changed.
+ pub fn closed(&mut self, target: &str) -> bool {
+ let before = self.active().map(str::to_string);
+ if self.home.as_deref() == Some(target) {
+ *self = Self::default();
+ } else {
+ self.open.retain(|t| t != target);
+ }
+ before.as_deref() != self.active()
+ }
+}
+
+/// The chain, kept current by a task watching the browser's targets. Every change of the page
+/// in front bumps [`Self::changes`].
+pub struct Popups {
+ chain: std::sync::Mutex<Chain>,
+ changed: watch::Sender<u64>,
+ watcher: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
+}
+
+impl Default for Popups {
+ fn default() -> Self {
+ Self { chain: Default::default(), changed: watch::channel(0).0, watcher: Default::default() }
+ }
+}
+
+impl Drop for Popups {
+ fn drop(&mut self) {
+ if let Some(task) = self.watcher.get_mut().unwrap_or_else(|e| e.into_inner()).take() {
+ task.abort();
+ }
+ }
+}
+
+impl Popups {
+ fn with<T>(&self, f: impl FnOnce(&mut Chain) -> T) -> T {
+ f(&mut self.chain.lock().unwrap_or_else(|e| e.into_inner()))
+ }
+
+ pub fn chain(&self) -> Chain { self.with(|c| c.clone()) }
+
+ /// Bumped each time the page in front changes.
+ pub fn changes(&self) -> watch::Receiver<u64> { self.changed.subscribe() }
+
+ pub fn generation(&self) -> u64 { *self.changed.borrow() }
+
+ fn bump(&self) { self.changed.send_modify(|g| *g += 1); }
+
+ pub fn set_home(&self, target: &str) {
+ if self.with(|c| c.set_home(target)) {
+ self.bump();
+ }
+ }
+
+ fn opened(&self, target: &str, opener: &str) {
+ if self.with(|c| c.opened(target, opener)) {
+ tracing::info!(target, opener, "following a popup the bot's page opened");
+ self.bump();
+ }
+ }
+
+ fn closed(&self, target: &str) {
+ if self.with(|c| c.closed(target)) {
+ tracing::info!(target, "a followed popup closed; back to the page that opened it");
+ self.bump();
+ }
+ }
+
+ /// Whether a watch is running (it ends with its browser connection).
+ pub fn is_watching(&self) -> bool {
+ self.watcher.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|task| !task.is_finished())
+ }
+
+ /// Starts watching the browser at `browser_ws` unless a watch is running, and waits briefly
+ /// until it has seen the pages already open.
+ pub async fn watch(self: &Arc<Self>, browser_ws: String) {
+ let ready = {
+ let mut slot = self.watcher.lock().unwrap_or_else(|e| e.into_inner());
+ if slot.as_ref().is_some_and(|task| !task.is_finished()) {
+ return;
+ }
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ *slot = Some(tokio::spawn(run(Arc::downgrade(self), browser_ws, tx)));
+ rx
+ };
+ let _ = tokio::time::timeout(Duration::from_secs(3), ready).await;
+ }
+}
+
+/// Follows `Target.targetCreated`/`targetInfoChanged`/`targetDestroyed` on a browser-level
+/// connection. Ends when the connection or the [`Popups`] goes away; the next connect restarts it.
+async fn run(popups: Weak<Popups>, browser_ws: String, ready: tokio::sync::oneshot::Sender<()>) {
+ use futures::{SinkExt, StreamExt};
+ use tokio_tungstenite::tungstenite::Message;
+ let Ok(mut ws) = super::browser::connect_cdp(&browser_ws).await else {
+ tracing::debug!("popups: couldn't connect to the browser");
+ return;
+ };
+ let discover = json!({"id": 1, "method": "Target.setDiscoverTargets", "params": {"discover": true}});
+ if ws.send(Message::Text(discover.to_string())).await.is_err() {
+ return;
+ }
+ let mut ready = Some(ready);
+ while let Some(Ok(message)) = ws.next().await {
+ let Message::Text(text) = message else { continue };
+ let value: Value = serde_json::from_str(&text).unwrap_or_default();
+ let Some(popups) = popups.upgrade() else { return };
+ if value["id"] == 1 {
+ // the pages already open were announced before this reply
+ if let Some(ready) = ready.take() {
+ let _ = ready.send(());
+ }
+ continue;
+ }
+ let params = &value["params"];
+ match value["method"].as_str().unwrap_or_default() {
+ "Target.targetCreated" | "Target.targetInfoChanged" => {
+ let info = &params["targetInfo"];
+ if info["type"] == "page" {
+ popups.opened(info["targetId"].as_str().unwrap_or_default(), info["openerId"].as_str().unwrap_or_default());
+ }
+ }
+ "Target.targetDestroyed" | "Target.targetCrashed" => popups.closed(params["targetId"].as_str().unwrap_or_default()),
+ _ => {}
+ }
+ }
+}
+
+/// `ws_url` (a page's DevTools address) pointed at another page of the same browser.
+pub fn page_ws_url(ws_url: &str, target: &str) -> String {
+ match ws_url.rsplit_once("/devtools/page/") {
+ Some((base, _)) => format!("{base}/devtools/page/{target}"),
+ None => ws_url.to_string(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn chain() -> Chain {
+ let mut c = Chain::default();
+ c.set_home("bot");
+ c
+ }
+
+ #[test]
+ fn a_popup_the_bots_page_opens_comes_to_the_front_and_its_close_goes_back() {
+ let mut c = chain();
+ assert_eq!(c.active(), Some("bot"));
+ assert!(c.opened("google", "bot"));
+ assert_eq!(c.active(), Some("google"));
+ assert!(!c.opened("google", "bot"), "announced again (info changed): nothing new");
+ assert!(c.closed("google"));
+ assert_eq!(c.active(), Some("bot"));
+ }
+
+ #[test]
+ fn pages_opened_by_anything_else_are_never_followed() {
+ let mut c = chain();
+ assert!(!c.opened("other-bots-tab", "other-bot"));
+ assert!(!c.opened("new-tab", ""), "a tab nobody opened (the browser's own, a bot's new tab)");
+ assert_eq!(c.active(), Some("bot"));
+ assert!(!c.closed("other-bots-tab"), "its close changes nothing");
+ }
+
+ #[test]
+ fn a_popup_of_a_popup_is_followed_and_closing_the_middle_one_keeps_the_newest() {
+ let mut c = chain();
+ assert!(c.opened("sign-in", "bot"));
+ assert!(c.opened("consent", "sign-in"));
+ assert_eq!(c.active(), Some("consent"));
+ assert!(!c.closed("sign-in"), "the newest is still in front");
+ assert!(c.closed("consent"));
+ assert_eq!(c.active(), Some("bot"));
+ }
+
+ #[test]
+ fn the_bots_page_closing_or_changing_ends_the_chain() {
+ let mut c = chain();
+ c.opened("sign-in", "bot");
+ assert!(c.closed("bot"));
+ assert_eq!(c.active(), None);
+ let mut c = chain();
+ c.opened("sign-in", "bot");
+ assert!(c.set_home("another"));
+ assert_eq!(c.active(), Some("another"));
+ assert!(!c.set_home("another"));
+ }
+
+ #[test]
+ fn a_page_that_keeps_opening_windows_is_followed_only_so_far() {
+ let mut c = chain();
+ for i in 0..MAX_OPEN {
+ assert!(c.opened(&format!("w{i}"), "bot"));
+ }
+ assert!(!c.opened("one-too-many", "bot"));
+ assert_eq!(c.active(), Some(format!("w{}", MAX_OPEN - 1).as_str()));
+ }
+
+ #[test]
+ fn a_page_address_is_pointed_at_another_page() {
+ assert_eq!(page_ws_url("ws://localhost:9222/devtools/page/AAA", "BBB"), "ws://localhost:9222/devtools/page/BBB");
+ assert_eq!(page_ws_url("ws://localhost:9222/devtools/browser/x", "BBB"), "ws://localhost:9222/devtools/browser/x");
+ }
+
+ #[tokio::test]
+ async fn every_change_of_the_page_in_front_is_announced() {
+ let p = Popups::default();
+ let mut changes = p.changes();
+ p.set_home("bot");
+ p.opened("google", "bot");
+ p.opened("elsewhere", "someone");
+ p.closed("google");
+ assert_eq!(p.generation(), 3);
+ assert!(changes.has_changed().unwrap());
+ changes.borrow_and_update();
+ p.closed("not-ours");
+ assert!(!changes.has_changed().unwrap());
+ }
+}
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index 64d60eb0..8782554e 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -212,27 +212,46 @@ type Reply = oneshot::Receiver<Result<Value, BrowserError>>;
type Waiters = Arc<std::sync::Mutex<HashMap<u64, oneshot::Sender<Result<Value, BrowserError>>>>>;
/// A DevTools socket shared by the stream's tasks: one writer keeps commands in order, one reader
-/// routes replies to whoever waits and events to the stream.
+/// routes replies to whoever waits and events to the stream. [`Cdp::attach`] moves every clone to
+/// another page's socket (a popup the page opened, and back).
#[derive(Clone)]
struct Cdp {
- out: mpsc::UnboundedSender<String>,
+ out: Arc<std::sync::Mutex<mpsc::UnboundedSender<String>>>,
pending: Waiters,
next: Arc<AtomicU64>,
+ tasks: Arc<std::sync::Mutex<CdpTasks>>,
+}
+
+/// The reader of the socket in use, and the writers of every socket not yet closed.
+#[derive(Default)]
+struct CdpTasks {
+ reader: Option<JoinHandle<()>>,
+ writers: Vec<JoinHandle<()>>,
}
impl Cdp {
- fn open(ws: crate::sandbox::browser::WsStream) -> (Self, mpsc::Receiver<Value>, [JoinHandle<()>; 2]) {
+ fn open(ws: crate::sandbox::browser::WsStream) -> (Self, mpsc::Receiver<Value>) {
+ let cdp = Cdp { out: Arc::new(std::sync::Mutex::new(mpsc::unbounded_channel().0)), pending: Arc::default(), next: Arc::new(AtomicU64::new(1)), tasks: Arc::default() };
+ let events = cdp.attach(ws);
+ (cdp, events)
+ }
+
+ /// Sends from now on to `ws`, and returns its events. The old socket gets what was already
+ /// sent to it, then closes; replies still owed on it are dropped.
+ fn attach(&self, ws: crate::sandbox::browser::WsStream) -> mpsc::Receiver<Value> {
let (mut sink, mut stream) = ws.split();
let (out, mut out_rx) = mpsc::unbounded_channel::<String>();
let (event_tx, events) = mpsc::channel::<Value>(64);
- let cdp = Cdp { out, pending: Arc::default(), next: Arc::new(AtomicU64::new(1)) };
+ // what the old socket still owes is never read now: its waiters fail at once
+ self.pending.lock().unwrap_or_else(|e| e.into_inner()).clear();
+ *self.out.lock().unwrap_or_else(|e| e.into_inner()) = out;
let writer = tokio::spawn(async move {
while let Some(text) = out_rx.recv().await {
if sink.send(CdpMessage::Text(text)).await.is_err() { break; }
}
let _ = sink.close().await;
});
- let pending = cdp.pending.clone();
+ let pending = self.pending.clone();
let reader = tokio::spawn(async move {
while let Some(message) = stream.next().await {
let text = match message {
@@ -256,11 +275,21 @@ impl Cdp {
// waiters see a closed channel; the stream sees its events end
pending.lock().unwrap_or_else(|e| e.into_inner()).clear();
});
- (cdp, events, [writer, reader])
+ let mut tasks = self.tasks.lock().unwrap_or_else(|e| e.into_inner());
+ // the old writer ends by itself once what was sent to it is out; its reader goes now
+ if let Some(old) = tasks.reader.replace(reader) { old.abort(); }
+ tasks.writers.retain(|task| !task.is_finished());
+ tasks.writers.push(writer);
+ events
+ }
+
+ fn close(&self) {
+ let mut tasks = self.tasks.lock().unwrap_or_else(|e| e.into_inner());
+ for task in tasks.reader.take().into_iter().chain(tasks.writers.drain(..)) { task.abort(); }
}
fn send(&self, id: u64, method: &str, params: Value) {
- let _ = self.out.send(json!({"id":id,"method":method,"params":params}).to_string());
+ let _ = self.out.lock().unwrap_or_else(|e| e.into_inner()).send(json!({"id":id,"method":method,"params":params}).to_string());
}
/// Sends without waiting; the reply is dropped.
@@ -296,10 +325,17 @@ fn wanted(event: &Value) -> bool {
}
}
+/// A reply that never came because the page's socket closed with the command out.
+const PAGE_CLOSED: &str = "Browser connection closed";
+
+fn page_closed(e: &BrowserError) -> bool {
+ matches!(e, BrowserError::Ws(m) if m == PAGE_CLOSED)
+}
+
async fn settle(reply: Reply, wait: Duration) -> Result<Value, BrowserError> {
match timeout(wait, reply).await {
Ok(Ok(result)) => result,
- Ok(Err(_)) => Err(BrowserError::Ws("Browser connection closed".into())),
+ Ok(Err(_)) => Err(BrowserError::Ws(PAGE_CLOSED.into())),
Err(_) => Err(BrowserError::Timeout),
}
}
@@ -481,14 +517,21 @@ fn refresh_location(cdp: &Cdp, ctrl: &BrowserController, shared: &Arc<Shared>, c
tokio::spawn(async move {
while shared.location.next().is_some() {
// blocks while a dialog is open, so never on the stream loop
- let Ok(result) = cdp.call("Runtime.evaluate", json!({"expression": "({url: location.href, title: document.title})", "returnByValue": true}), PROBE_WAIT).await else { continue };
- if let Some(url) = result["result"]["value"]["url"].as_str() { *ctrl.current_url.lock().await = Some(url.to_string()); }
- if let Some(title) = result["result"]["value"]["title"].as_str() { *ctrl.current_title.lock().await = Some(title.to_string()); }
- let _ = client.send(json!({"type":"location","url":ctrl.current_url.lock().await.clone(),"title":ctrl.current_title.lock().await.clone()}));
+ let Some(location) = read_location(&cdp, &ctrl).await else { continue };
+ let _ = client.send(location);
}
});
}
+/// The `location` message for the page `cdp` is on (its address and title, also kept on the
+/// controller); `None` when the page doesn't answer within `PROBE_WAIT` (a dialog is open).
+async fn read_location(cdp: &Cdp, ctrl: &BrowserController) -> Option<Value> {
+ let result = cdp.call("Runtime.evaluate", json!({"expression": "({url: location.href, title: document.title})", "returnByValue": true}), PROBE_WAIT).await.ok()?;
+ if let Some(url) = result["result"]["value"]["url"].as_str() { *ctrl.current_url.lock().await = Some(url.to_string()); }
+ if let Some(title) = result["result"]["value"]["title"].as_str() { *ctrl.current_title.lock().await = Some(title.to_string()); }
+ Some(json!({"type":"location","url":ctrl.current_url.lock().await.clone(),"title":ctrl.current_title.lock().await.clone()}))
+}
+
impl Shared {
fn point(&self, x: f64, y: f64) -> Result<(f64, f64), BrowserError> {
let (w, h) = *self.view.lock().unwrap_or_else(|e| e.into_inner());
@@ -783,13 +826,21 @@ impl Worker {
fn finish(&self, id: Value, replies: Vec<Reply>, editable: bool) {
let (client, cdp) = (self.client.clone(), self.cdp.clone());
tokio::spawn(async move {
+ let mut closed = false;
for reply in replies {
- if let Err(e) = settle(reply, ACTION_WAIT).await {
- let _ = client.send(error(&id, e));
- return;
+ match settle(reply, ACTION_WAIT).await {
+ Ok(_) => {}
+ // the page closed with the input out: a popup the click itself closed
+ // ("Continue" on a sign-in). The view goes back to its opener, and a browser
+ // that went away ends the stream, so the person sees no error for it.
+ Err(e) if page_closed(&e) => { closed = true; break; }
+ Err(e) => {
+ let _ = client.send(error(&id, e));
+ return;
+ }
}
}
- let extra = if editable { json!({"editable": focused_editable(&cdp).await}) } else { json!({}) };
+ let extra = if editable { json!({"editable": !closed && focused_editable(&cdp).await}) } else { json!({}) };
let _ = client.send(ack(&id, extra));
});
}
@@ -1151,6 +1202,62 @@ pub async fn upgrade(State(state): State<AppState>, Path(id): Path<String>, head
}))
}
+/// The page the live view shows: its DevTools address, and the controller's news of the page in
+/// front changing (a popup the page opened, or its close).
+struct Page {
+ ws_url: String,
+ changes: tokio::sync::watch::Receiver<u64>,
+}
+
+/// Turns on what the live view needs on the page `cdp` is on: its events, focus, the app-link
+/// guard and the screencast.
+async fn watch_page(cdp: &Cdp, shared: &Shared) -> Result<(), BrowserError> {
+ cdp.call("Page.enable", json!({}), Duration::from_secs(10)).await?;
+ // A Chrome window behind other apps on a Mac doesn't have the OS's focus, so its page
+ // can act unfocused and drop typed keys. While anyone watches or controls it, the page
+ // behaves as focused (as Playwright does for every page). It ends with this connection.
+ let _ = cdp.call("Emulation.setFocusEmulationEnabled", json!({"enabled": true}), PROBE_WAIT).await;
+ guard_app_links(cdp).await;
+ let (w, h) = shared.view();
+ cdp.call("Page.startScreencast", screencast_params(w as u32, h as u32), Duration::from_secs(10)).await?;
+ Ok(())
+}
+
+/// Moves the view to the page in front when that changed: a popup the page opened ("Continue
+/// with Google"), or the opener once the popup closed. The new page's events, or `None` when
+/// it is the page already shown or can't be reached.
+async fn follow_page(ctrl: &BrowserController, cdp: &Cdp, page: &mut Page, shared: &Shared) -> Option<mpsc::Receiver<Value>> {
+ let ws_url = ctrl.get_ws_url().await.ok()?;
+ if ws_url == page.ws_url {
+ return None;
+ }
+ let ws = crate::sandbox::browser::connect_cdp(&ws_url).await.ok()?;
+ cdp.fire("Page.stopScreencast", json!({}));
+ let events = cdp.attach(ws);
+ tracing::info!("the live view follows the page in front");
+ page.ws_url = ws_url;
+ if let Err(e) = watch_page(cdp, shared).await {
+ // a popup that closed at once: its socket ends and the view comes back from it
+ tracing::debug!("the live view couldn't watch the page in front: {}", e);
+ }
+ Some(events)
+}
+
+/// The shown page's socket closed. When that page was a popup, its close reaches the controller
+/// a moment later and the view goes back to the page that opened it; `None` when no other page
+/// comes to the front within a few seconds (the browser itself went away).
+async fn back_from_closed_page(ctrl: &BrowserController, cdp: &Cdp, page: &mut Page, shared: &Shared) -> Option<mpsc::Receiver<Value>> {
+ let back = async {
+ loop {
+ if let Some(events) = follow_page(ctrl, cdp, page, shared).await {
+ return events;
+ }
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ };
+ timeout(Duration::from_secs(4), back).await.ok()
+}
+
async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(), BrowserError> {
let ctrl = match get_or_create_browser_controller(&state, &id).await {
Some(ctrl) => ctrl,
@@ -1159,8 +1266,12 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
return Ok(());
}
};
- let ws = crate::sandbox::browser::connect_cdp(&ctrl.get_ws_url().await?).await?;
- let (cdp, mut events, tasks) = Cdp::open(ws);
+ // subscribed first, so a popup opening while this connects is still followed
+ let changes = ctrl.page_changes();
+ let ws_url = ctrl.get_ws_url().await?;
+ let ws = crate::sandbox::browser::connect_cdp(&ws_url).await?;
+ let (cdp, mut events) = Cdp::open(ws);
+ let mut page = Page { ws_url, changes };
let (w, h) = ctrl.fixed_viewport().unwrap_or(DEFAULT_VIEW);
let shared = Arc::new(Shared {
socket: NEXT_SOCKET.fetch_add(1, Ordering::Relaxed),
@@ -1179,7 +1290,7 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
let worker = tokio::spawn(worker.run(jobs_rx));
let mut rec = StageRecorder::new(state.clone(), id.clone(), shared.socket);
let pointer = Pointer::new(state.clone(), cdp.clone(), client_tx.clone());
- let result = stream(&mut socket, &ctrl, &cdp, &mut events, &shared, &client_tx, &mut client_rx, &jobs, &mut rec, &pointer).await;
+ let result = stream(&mut socket, &ctrl, &cdp, &mut events, &mut page, &shared, &client_tx, &mut client_rx, &jobs, &mut rec, &pointer).await;
// a recording live on this socket stops here (Show it once: `closed`), its steps kept, after
// the edit still pending in the page, if the page can still be reached
if rec.is_live() {
@@ -1194,7 +1305,7 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
release_on(&cdp, held).await;
restore_viewport(&ctrl, &cdp, &shared).await;
drop(result.1);
- for task in tasks { task.abort(); }
+ cdp.close();
result.0
}
@@ -1204,6 +1315,7 @@ async fn stream(
ctrl: &BrowserController,
cdp: &Cdp,
events: &mut mpsc::Receiver<Value>,
+ page: &mut Page,
shared: &Arc<Shared>,
client_tx: &mpsc::UnboundedSender<Value>,
client_rx: &mut mpsc::UnboundedReceiver<Value>,
@@ -1215,14 +1327,7 @@ async fn stream(
// the Show it once recorder's script on new documents, while a recording is live
let mut recorder_script: Option<String> = None;
let result = async {
- cdp.call("Page.enable", json!({}), Duration::from_secs(10)).await?;
- // A Chrome window behind other apps on a Mac doesn't have the OS's focus, so its page
- // can act unfocused and drop typed keys. While anyone watches or controls it, the page
- // behaves as focused (as Playwright does for every page). It ends with this connection.
- let _ = cdp.call("Emulation.setFocusEmulationEnabled", json!({"enabled": true}), PROBE_WAIT).await;
- guard_app_links(cdp).await;
- let (w, h) = shared.view();
- cdp.call("Page.startScreencast", screencast_params(w as u32, h as u32), Duration::from_secs(10)).await?;
+ watch_page(cdp, shared).await?;
// a link to another app may have fired before the view opened, with nobody to close
// Chrome's prompt: check the page still gets input, off the loop. Not while a button is
// held, where a move would be part of someone's drag.
@@ -1235,9 +1340,35 @@ async fn stream(
let mut moves = RateLimit::new(bi::MOVES_PER_SECOND, 10.0, std::time::Instant::now());
let mut dialog_open = false;
let mut app_links = AppLinkWatch::default();
+ // the events of the page the view moved to: a popup the page opened, or back from it
+ let mut moved: Option<mpsc::Receiver<Value>> = None;
loop {
+ if let Some(next) = moved.take() {
+ *events = next;
+ frames = FrameGate::default();
+ app_links = AppLinkWatch::default();
+ dialog_open = false;
+ pointer.forget_world();
+ // Show it once records on the page in front too
+ if rec.is_live() {
+ recorder_script = None;
+ recorder_acts(socket, ctrl, cdp, shared, rec, vec![Act::Install], &mut recorder_script).await?;
+ }
+ // the address bar moves before the new page's first picture is shown: a still
+ // page (the opener once its popup closed) draws that picture once, and a client
+ // must know whose it is. Its frames wait in `events` until the loop reads them.
+ match read_location(cdp, ctrl).await {
+ Some(location) => send(socket, location).await?,
+ // a dialog open on the new page: the address follows when it answers
+ None => refresh_location(cdp, ctrl, shared, client_tx),
+ }
+ }
let app_link_due = app_links.deadline();
tokio::select! {
+ // a popup the page opened came to the front, or closed
+ _ = async { if page.changes.changed().await.is_err() { std::future::pending::<()>().await } } => {
+ moved = follow_page(ctrl, cdp, page, shared).await;
+ }
_ = async { match app_link_due { Some(at) => tokio::time::sleep_until(at).await, None => std::future::pending().await } } => {
if let Some(verdict) = app_links.due(Instant::now()) { act_on_app_link(cdp, client_tx, verdict); }
}
@@ -1277,7 +1408,12 @@ async fn stream(
}
Some(value) = client_rx.recv() => send(socket, value).await?,
event = events.recv() => {
- let Some(event) = event else { break };
+ let Some(event) = event else {
+ // the page's socket closed: a popup that closed, with its opener in front again
+ moved = back_from_closed_page(ctrl, cdp, page, shared).await;
+ if moved.is_none() { break }
+ continue;
+ };
let params = &event["params"];
let method = event["method"].as_str().unwrap_or_default();
// the person's own clicks, back/forward/reload and a bot's navigate all land
diff --git a/tests/browser_popups_test.rs b/tests/browser_popups_test.rs
new file mode 100644
index 00000000..7a07f79b
--- /dev/null
+++ b/tests/browser_popups_test.rs
@@ -0,0 +1,172 @@
+//! Sign-in popups in a real Chrome, the way "Continue with Google" opens one: the page calls
+//! `window.open`, the popup posts its answer back to the page that opened it and closes. The bot's
+//! browser tools and the live view both move to the popup while it is open and come back to the
+//! opener when it closes. Skipped when no Chrome is installed.
+#[path = "support/chrome_guard.rs"]
+mod chrome_guard;
+use chrome_guard::ChromeGuard;
+use futures::{SinkExt, StreamExt};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::Kwant, spaces::SpaceId, Database},
+ router::LayaRouter,
+ sandbox::{computer, BrowserController},
+ server::{create_router, routes::get_or_create_browser_controller, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::time::Duration;
+use tempfile::{tempdir, TempDir};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio_tungstenite::{connect_async, tungstenite::{client::IntoClientRequest, Message as WsMessage}};
+
+/// A page with a sign-in button over all of it that opens the sign-in in a popup window, and
+/// shows the popup's answer in its title a little later, as a real sign-in page does after its
+/// own requests: the view is back on the opener, and has its picture, before the answer shows.
+const OPENER: &str = "<!doctype html><html><head><title>opener</title></head><body style=margin:0>\
+<button onclick=\"window.open('/popup','signin','width=480,height=600')\" style='position:fixed;inset:0'>Continue with Google</button>\
+<script>addEventListener('message',function(e){setTimeout(function(){document.title='signed in: '+e.data},700)})</script></body></html>";
+/// The sign-in: a button over all of it posts the answer to the opener and closes the popup.
+const POPUP: &str = "<!doctype html><html><head><title>popup</title></head><body style=margin:0>\
+<button onclick=\"opener.postMessage('ok','*');window.close()\" style='position:fixed;inset:0'>Choose account</button></body></html>";
+
+async fn serve() -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut buf = [0u8; 4096];
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let req = String::from_utf8_lossy(&buf[..n]).to_string();
+ let page = match req.split_whitespace().nth(1).unwrap_or("/") {
+ "/opener" => OPENER,
+ "/popup" => POPUP,
+ _ => "<!doctype html><title>plain</title>",
+ };
+ let reply = format!("HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{page}", page.len());
+ let _ = stream.write_all(reply.as_bytes()).await;
+ });
+ }
+ });
+ format!("http://127.0.0.1:{port}")
+}
+
+struct Env {
+ state: AppState,
+ bot: Kwant,
+ tmp: TempDir,
+}
+
+/// kwnt in Local mode, so the bot's browser is a real Chrome on this machine.
+async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ db.set_setting(computer::SETTING_KEY, "local").await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(config.clone(), db, ToolRunner::new(tmp.path().join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();
+ Env { state, bot, tmp }
+}
+
+/// A DevTools command; `None` when it failed or took too long (the page it went to may be closing).
+async fn cdp(ctrl: &BrowserController, method: &str, params: Value) -> Option<Value> {
+ tokio::time::timeout(Duration::from_secs(10), ctrl.send_cdp_command(method, params)).await.ok()?.ok()
+}
+
+/// The title of the page the bot's tools act on, once it is `want` (or after 5 s).
+async fn title_becomes(ctrl: &BrowserController, want: &str) -> String {
+ let mut title = String::new();
+ for _ in 0..50 {
+ let value = cdp(ctrl, "Runtime.evaluate", json!({"expression": "document.title", "returnByValue": true})).await;
+ title = value.and_then(|v| v["result"]["value"].as_str().map(str::to_string)).unwrap_or_default();
+ if title == want { break; }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ title
+}
+
+async fn click(ctrl: &BrowserController) {
+ for kind in ["mousePressed", "mouseReleased"] {
+ cdp(ctrl, "Input.dispatchMouseEvent", json!({"type": kind, "x": 40, "y": 40, "button": "left", "buttons": if kind == "mousePressed" { 1 } else { 0 }, "clickCount": 1})).await;
+ }
+}
+
+#[tokio::test]
+async fn a_popup_the_page_opens_is_where_the_bots_tools_act_until_it_closes() {
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let e = setup().await;
+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));
+ let base = serve().await;
+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");
+ ctrl.navigate(&format!("{base}/opener")).await.unwrap();
+ assert_eq!(title_becomes(&ctrl, "opener").await, "opener");
+ click(&ctrl).await;
+ assert_eq!(title_becomes(&ctrl, "popup").await, "popup", "the bot's tools act on the popup the page opened");
+ click(&ctrl).await;
+ assert_eq!(title_becomes(&ctrl, "signed in: ok").await, "signed in: ok", "back on the opener once the popup closed, with its answer");
+ ctrl.navigate(&format!("{base}/plain")).await.expect("the bot's tools still work on the opener");
+ assert_eq!(title_becomes(&ctrl, "plain").await, "plain");
+}
+
+type Ws = tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
+
+/// The next live-view message of `kind` that `matches`, answering pings meanwhile; `None` after 10 s.
+async fn next_message(ws: &mut Ws, kind: &str, matches: impl Fn(&Value) -> bool) -> Option<Value> {
+ tokio::time::timeout(Duration::from_secs(10), async {
+ loop {
+ let message = ws.next().await?.ok()?;
+ let WsMessage::Text(text) = message else { continue };
+ let value: Value = serde_json::from_str(&text).unwrap_or_default();
+ // the person sees every error: opening a popup or closing it by a click is none
+ assert_ne!(value["type"], "error", "the live view reported an error: {value}");
+ if value["type"] == "ping" { ws.send(WsMessage::Text(json!({"action": "pong"}).to_string())).await.ok()?; }
+ if value["type"] == "frame" { ws.send(WsMessage::Text(json!({"action": "frame_ack", "id": value["id"]}).to_string())).await.ok()?; }
+ if value["type"] == kind && matches(&value) { return Some(value); }
+ }
+ }).await.ok().flatten()
+}
+
+#[tokio::test]
+async fn the_live_view_shows_a_popup_the_page_opens_and_comes_back_when_it_closes() {
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let e = setup().await;
+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));
+ let base = serve().await;
+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");
+ ctrl.navigate(&format!("{base}/opener")).await.unwrap();
+ assert_eq!(title_becomes(&ctrl, "opener").await, "opener");
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let app = create_router(e.state.clone());
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let mut request = format!("ws://127.0.0.1:{port}/api/sandbox/{}/stream", e.bot.id).into_client_request().unwrap();
+ request.headers_mut().insert("Origin", format!("http://127.0.0.1:{port}").parse().unwrap());
+ let (mut ws, _) = connect_async(request).await.unwrap();
+ assert!(next_message(&mut ws, "frame", |_| true).await.is_some(), "the opener is shown");
+ ws.send(WsMessage::Text(json!({"action": "take_control"}).to_string())).await.unwrap();
+ assert!(next_message(&mut ws, "control", |c| c["active"] == true).await.is_some());
+
+ ws.send(WsMessage::Text(json!({"action": "click", "x": 40, "y": 40, "id": 1}).to_string())).await.unwrap();
+ let shown = next_message(&mut ws, "location", |l| l["url"].as_str().is_some_and(|u| u.ends_with("/popup"))).await;
+ assert!(shown.is_some(), "the live view moves to the popup the person's click opened");
+ assert!(next_message(&mut ws, "frame", |_| true).await.is_some(), "and shows it");
+
+ ws.send(WsMessage::Text(json!({"action": "click", "x": 40, "y": 40, "id": 2}).to_string())).await.unwrap();
+ let on_opener = |l: &Value| l["url"].as_str().is_some_and(|u| u.ends_with("/opener"));
+ assert!(next_message(&mut ws, "location", on_opener).await.is_some(), "once the popup closed, the live view is back on the opener");
+ // the stream sends the address before the new page's pictures, so this frame is the opener's
+ assert!(next_message(&mut ws, "frame", |_| true).await.is_some(), "and shows it again");
+ let answered = next_message(&mut ws, "location", |l| on_opener(l) && l["title"] == "signed in: ok").await;
+ assert!(answered.is_some(), "with the popup's answer once the opener has it");
+ ws.close(None).await.unwrap();
+ server.abort();
+}