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 takeover polish: prompt address, trailing cursor look, history text, title follows navigation (#275)

Oleksandr Ivanchenkoc8132cb8165e
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index 535f8b55..354075f4 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -161,6 +161,8 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
// Once the stream reports where the tab is, trust it; before that, the last URL the app heard of.
const pageUrl = stream.location ? stream.location.url : activeUrl;
+ // The same for the title: a new page's empty title must not fall back to the previous page's.
+ const shownTitle = stream.location ? stream.location.title : pageTitle;
const currentScreenshot = isBlankPage(pageUrl) ? null : stream.frame?.image || screenshotBase64;
const frameSrc = currentScreenshot ? (currentScreenshot.startsWith('data:') ? currentScreenshot : `data:image/jpeg;base64,${currentScreenshot}`) : null;
// A hidden frame never loads, so acknowledge it here or the stream stalls waiting for the ack.
@@ -489,9 +491,9 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
)}
</div>
- {(stream.location?.title || pageTitle) && (
+ {shownTitle && (
<div className="text-[11px] text-zinc-400 truncate px-1 font-medium">
- {stream.location?.title || pageTitle}
+ {shownTitle}
</div>
)}
@@ -715,7 +717,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
<BrowserTakeoverStage
botName={teamName}
pageUrl={pageUrl}
- pageTitle={stream.location?.title || pageTitle}
+ pageTitle={shownTitle}
stream={stream}
image={frameSrc}
step={stepForStage}
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index 550339a3..26246cc9 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -335,6 +335,9 @@ pub enum BrowserError {
Timeout,
#[error("Browser is controlled by a person. Retry after control is returned.")]
HumanControl,
+ /// The person's live view sent input without taking control, and nobody else has it.
+ #[error("Take control of the browser first.")]
+ NotInControl,
/// The browser works, but the page itself could not be loaded (DNS, TLS, refused, ...).
#[error("Page could not be loaded: {0}")]
Navigation(String),
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index 1cdc99b4..888ca8ea 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -26,6 +26,9 @@ const ACTION_WAIT: Duration = Duration::from_secs(30);
/// dialog is open.
const PROBE_WAIT: Duration = Duration::from_secs(2);
const SELECT_GROUP: &str = "kwnt-select";
+/// A frame the client has not acked for this long is let go, so a lost ack costs one stale
+/// picture instead of the stream (and the person's control).
+const FRAME_STALL: Duration = Duration::from_secs(4);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -289,8 +292,94 @@ struct Shared {
/// A `resize` is applied and must be put back on hand back.
resized: AtomicBool,
cursor: std::sync::Mutex<String>,
- cursor_busy: AtomicBool,
+ /// The newest point a move asked to look the cursor up at.
+ cursor_moves: Latest<(f64, f64)>,
cursor_at: std::sync::Mutex<Option<Instant>>,
+ /// Asks to read the page's address and title again.
+ location: Latest<()>,
+}
+
+/// Keeps only the newest value offered and makes sure exactly one runner drains it, so a value
+/// offered while the runner is busy is never lost (the trailing probe) and never doubled.
+struct Latest<T> {
+ slot: std::sync::Mutex<Option<T>>,
+ busy: AtomicBool,
+}
+
+impl<T> Latest<T> {
+ fn new() -> Self {
+ Self { slot: std::sync::Mutex::new(None), busy: AtomicBool::new(false) }
+ }
+
+ fn lock(&self) -> std::sync::MutexGuard<'_, Option<T>> {
+ self.slot.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ /// Stores `value`; true when the caller must start the runner.
+ fn offer(&self, value: T) -> bool {
+ *self.lock() = Some(value);
+ !self.busy.swap(true, Ordering::SeqCst)
+ }
+
+ /// The runner's next value, or `None` when it should stop.
+ fn next(&self) -> Option<T> {
+ loop {
+ if let Some(value) = self.lock().take() { return Some(value); }
+ self.busy.store(false, Ordering::SeqCst);
+ // an offer that landed after the take: keep going unless its own runner started
+ if self.lock().is_none() || self.busy.swap(true, Ordering::SeqCst) { return None; }
+ }
+ }
+}
+
+/// How long to wait before the next cursor lookup, so lookups stay `CURSOR_EVERY` apart.
+fn cursor_wait(last: Option<Instant>, now: Instant) -> Duration {
+ last.map(|t| bi::CURSOR_EVERY.saturating_sub(now.saturating_duration_since(t))).unwrap_or_default()
+}
+
+/// Whether a page event can change the address or title the person sees.
+fn moves_location(method: &str, params: &Value) -> bool {
+ match method {
+ // the top document only; a subframe navigating changes nothing in the address bar
+ "Page.frameNavigated" => params["frame"]["parentId"].is_null(),
+ // pushState, replaceState and #fragment changes
+ "Page.navigatedWithinDocument" => true,
+ // the new page's title is parsed by now
+ "Page.domContentEventFired" => true,
+ _ => false,
+ }
+}
+
+/// The address a top-level page navigation lands on. A new document has no title yet, so the
+/// person sees the new address with an empty title at once instead of the last page's title until
+/// the new one is parsed.
+fn navigated_to(method: &str, params: &Value) -> Option<String> {
+ if method != "Page.frameNavigated" || !params["frame"]["parentId"].is_null() { return None; }
+ let url = params["frame"]["url"].as_str()?;
+ Some(format!("{url}{}", params["frame"]["urlFragment"].as_str().unwrap_or_default()))
+}
+
+/// The error for input from a live view that has not taken control.
+fn not_in_control(someone_has_control: bool) -> BrowserError {
+ if someone_has_control { BrowserError::HumanControl } else { BrowserError::NotInControl }
+}
+
+/// Reads the page's address and title on the stream's socket, off the caller, and sends them
+/// to the person. Requests while a read is running are folded into one more read. A read that
+/// fails (the page is between documents) sends nothing: the next page event or tick reads again,
+/// and resending what kwant last knew would put the previous page's title back on screen.
+fn refresh_location(cdp: &Cdp, ctrl: &BrowserController, shared: &Arc<Shared>, client: &mpsc::UnboundedSender<Value>) {
+ if !shared.location.offer(()) { return; }
+ let (cdp, ctrl, shared, client) = (cdp.clone(), ctrl.clone(), shared.clone(), client.clone());
+ 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()}));
+ }
+ });
}
impl Shared {
@@ -438,11 +527,13 @@ impl Worker {
let parsed = reqwest::Url::parse(&url).map_err(|e| BrowserError::Protocol(e.to_string()))?;
if !matches!(parsed.scheme(), "http"|"https") { return Err(protocol("Use an HTTP or HTTPS URL")); }
self.ctrl.navigate_unlocked(&url).await?;
+ refresh_location(&self.cdp, &self.ctrl, &self.shared, &self.client);
let _ = self.client.send(ack(id, json!({})));
}
BrowserInput::History { direction } => {
self.close_select();
self.ctrl.navigate_history(direction).await?;
+ refresh_location(&self.cdp, &self.ctrl, &self.shared, &self.client);
let _ = self.client.send(ack(id, json!({})));
}
BrowserInput::PointerDown { x, y } => {
@@ -589,27 +680,29 @@ impl Worker {
}
/// After a move, looks up the cursor at most every 125 ms and tells the person when it
- /// changes.
+ /// changes. The first move is looked up at once; moves inside the window end in one
+ /// trailing lookup at the newest point, so where the pointer comes to rest always counts.
fn check_cursor(&self, x: f64, y: f64) {
- {
- let mut at = self.shared.cursor_at.lock().unwrap_or_else(|e| e.into_inner());
- if at.is_some_and(|t| t.elapsed() < bi::CURSOR_EVERY) { return; }
- if self.shared.cursor_busy.swap(true, Ordering::SeqCst) { return; }
- *at = Some(Instant::now());
- }
+ if !self.shared.cursor_moves.offer((x, y)) { return; }
let (cdp, shared, client) = (self.cdp.clone(), self.shared.clone(), self.client.clone());
tokio::spawn(async move {
- if let Ok(result) = cdp.call("Runtime.evaluate", json!({"expression": bi::cursor_js(x, y), "returnByValue": true}), PROBE_WAIT).await {
- let cursor = bi::sanitize_cursor(result["result"]["value"].as_str().unwrap_or("auto"));
- let changed = {
- let mut last = shared.cursor.lock().unwrap_or_else(|e| e.into_inner());
- let changed = *last != cursor;
- *last = cursor.clone();
- changed
- };
- if changed { let _ = client.send(json!({"type":"cursor","cursor":cursor})); }
+ loop {
+ // wait out the window first, so the lookup takes the newest point in it
+ let wait = cursor_wait(*shared.cursor_at.lock().unwrap_or_else(|e| e.into_inner()), Instant::now());
+ if !wait.is_zero() { tokio::time::sleep(wait).await; }
+ let Some((x, y)) = shared.cursor_moves.next() else { break };
+ *shared.cursor_at.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now());
+ if let Ok(result) = cdp.call("Runtime.evaluate", json!({"expression": bi::cursor_js(x, y), "returnByValue": true}), PROBE_WAIT).await {
+ let cursor = bi::sanitize_cursor(result["result"]["value"].as_str().unwrap_or("auto"));
+ let changed = {
+ let mut last = shared.cursor.lock().unwrap_or_else(|e| e.into_inner());
+ let changed = *last != cursor;
+ *last = cursor.clone();
+ changed
+ };
+ if changed { let _ = client.send(json!({"type":"cursor","cursor":cursor})); }
+ }
}
- shared.cursor_busy.store(false, Ordering::SeqCst);
});
}
@@ -683,8 +776,9 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
view: std::sync::Mutex::new((w as f64, h as f64)),
resized: AtomicBool::new(false),
cursor: std::sync::Mutex::new("auto".into()),
- cursor_busy: AtomicBool::new(false),
+ cursor_moves: Latest::new(),
cursor_at: std::sync::Mutex::new(None),
+ location: Latest::new(),
});
let (client_tx, mut client_rx) = mpsc::unbounded_channel::<Value>();
let (jobs, jobs_rx) = mpsc::unbounded_channel::<Job>();
@@ -725,14 +819,12 @@ async fn stream(
let mut next_frame = 0u64;
let mut pending_token = 0u64;
let mut location_tick = tokio::time::interval(Duration::from_secs(2));
- let location_busy = Arc::new(AtomicBool::new(false));
let mut moves = RateLimit::new(bi::MOVES_PER_SECOND, 10.0, std::time::Instant::now());
let mut dialog_open = false;
loop {
tokio::select! {
_ = heartbeat.tick() => {
if last_client.elapsed() > Duration::from_secs(35) { break; }
- if pending_frame.is_some() && frame_sent.elapsed() > Duration::from_secs(15) { break; }
send(socket, json!({"type":"ping"})).await?;
}
_ = location_tick.tick() => {
@@ -740,24 +832,29 @@ async fn stream(
if lease.is_none() && !ctrl.is_held_for_person() && shared.resized.load(Ordering::SeqCst) {
let _ = jobs.send(Job::HandBack(None));
}
- // read on the stream's socket, off the loop: it blocks while a dialog is open
- if !location_busy.swap(true, Ordering::SeqCst) {
- let (cdp, ctrl, client, busy) = (cdp.clone(), ctrl.clone(), client_tx.clone(), location_busy.clone());
- tokio::spawn(async move {
- if let Ok(result) = cdp.call("Runtime.evaluate", json!({"expression": "({url: location.href, title: document.title})", "returnByValue": true}), PROBE_WAIT).await {
- 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()}));
- busy.store(false, Ordering::SeqCst);
- });
+ // a client that never acks the last frame (an identical picture fires no
+ // load) gets the next one anyway instead of a frozen view and a dropped stream
+ if pending_frame.is_some() && frame_sent.elapsed() > FRAME_STALL {
+ if let Some(session) = pending_frame.take() {
+ cdp.fire("Page.screencastFrameAck", json!({"sessionId":session}));
+ }
}
+ // a fallback for title changes no page event announces
+ refresh_location(cdp, ctrl, shared, client_tx);
}
Some(value) = client_rx.recv() => send(socket, value).await?,
event = events.recv() => {
let Some(event) = event else { break };
let params = &event["params"];
- match event["method"].as_str().unwrap_or_default() {
+ let method = event["method"].as_str().unwrap_or_default();
+ // the person's own clicks, back/forward/reload and a bot's navigate all land
+ // here: the address follows at once instead of on the next tick
+ // a new document: the old title goes now, the new one follows on DOMContentLoaded
+ if let Some(url) = navigated_to(method, params) {
+ let _ = client_tx.send(json!({"type":"location","url":url,"title":""}));
+ }
+ if moves_location(method, params) { refresh_location(cdp, ctrl, shared, client_tx); }
+ match method {
"Page.screencastFrame" => {
let session = params["sessionId"].as_i64().unwrap_or_default();
let (dw, dh) = (params["metadata"]["deviceWidth"].as_f64().unwrap_or(0.0), params["metadata"]["deviceHeight"].as_f64().unwrap_or(0.0));
@@ -826,7 +923,7 @@ async fn stream(
}
_ => {
if lease.is_none() && !ctrl.is_held_for_person() {
- send(socket, error(&id, BrowserError::HumanControl)).await?;
+ send(socket, error(&id, not_in_control(ctrl.control.try_read().is_err()))).await?;
continue;
}
let input = match BrowserInput::parse(&value) {
@@ -945,6 +1042,89 @@ mod tests {
}
}
+ #[test]
+ fn latest_keeps_only_the_newest_value_for_one_runner() {
+ let latest = Latest::new();
+ assert!(latest.offer(1), "the first offer starts the runner");
+ assert!(!latest.offer(2), "a busy runner is not started twice");
+ assert!(!latest.offer(3));
+ assert_eq!(latest.next(), Some(3), "moves inside the window collapse to the newest");
+ // an offer while the runner works is its trailing value, not a second runner
+ assert!(!latest.offer(4));
+ assert_eq!(latest.next(), Some(4));
+ assert_eq!(latest.next(), None, "nothing left: the runner stops");
+ assert!(latest.offer(5), "after it stopped the next offer starts a new runner");
+ assert_eq!(latest.next(), Some(5));
+ assert_eq!(latest.next(), None);
+ }
+
+ #[test]
+ fn latest_never_loses_an_offer_or_runs_twice_under_contention() {
+ use std::sync::atomic::AtomicUsize;
+ let latest = Arc::new(Latest::new());
+ let (running, most, drained) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
+ let mut runners = vec![];
+ let offerers: Vec<_> = (0..4).map(|t| {
+ let (latest, running, most, drained) = (latest.clone(), running.clone(), most.clone(), drained.clone());
+ std::thread::spawn(move || {
+ let mut started = vec![];
+ for i in 0..2000 {
+ if latest.offer(t * 10_000 + i) {
+ let (latest, running, most, drained) = (latest.clone(), running.clone(), most.clone(), drained.clone());
+ started.push(std::thread::spawn(move || {
+ let now = running.fetch_add(1, Ordering::SeqCst) + 1;
+ most.fetch_max(now, Ordering::SeqCst);
+ while latest.next().is_some() { drained.fetch_add(1, Ordering::SeqCst); }
+ running.fetch_sub(1, Ordering::SeqCst);
+ }));
+ }
+ }
+ started
+ })
+ }).collect();
+ for offerer in offerers { runners.extend(offerer.join().unwrap()); }
+ for runner in runners { runner.join().unwrap(); }
+ assert_eq!(most.load(Ordering::SeqCst), 1, "never two runners at once");
+ assert!(drained.load(Ordering::SeqCst) >= 1);
+ assert!(latest.lock().is_none(), "the last offer was taken by a runner");
+ assert!(!latest.busy.load(Ordering::SeqCst), "and the runner stopped");
+ }
+
+ #[test]
+ fn cursor_lookups_wait_out_the_window_after_the_last_one() {
+ let t0 = Instant::now();
+ assert_eq!(cursor_wait(None, t0), Duration::ZERO, "the first move is looked up at once");
+ assert_eq!(cursor_wait(Some(t0), t0 + Duration::from_millis(40)), Duration::from_millis(85));
+ assert_eq!(cursor_wait(Some(t0), t0 + bi::CURSOR_EVERY), Duration::ZERO);
+ assert_eq!(cursor_wait(Some(t0), t0 + Duration::from_secs(5)), Duration::ZERO);
+ }
+
+ #[test]
+ fn the_address_follows_top_level_navigation_and_title() {
+ assert!(moves_location("Page.frameNavigated", &json!({"frame":{"id":"A","url":"https://b.test/"}})));
+ assert!(!moves_location("Page.frameNavigated", &json!({"frame":{"id":"B","parentId":"A","url":"https://ads.test/"}})), "an iframe moving is not the page moving");
+ assert!(moves_location("Page.navigatedWithinDocument", &json!({"frameId":"A","url":"https://b.test/#x"})));
+ assert!(moves_location("Page.domContentEventFired", &json!({"timestamp":1.0})));
+ for other in ["Page.screencastFrame", "Page.javascriptDialogOpening", "Page.loadEventFired", ""] {
+ assert!(!moves_location(other, &json!({})), "{other}");
+ }
+ }
+
+ #[test]
+ fn a_new_top_level_document_clears_the_title_and_keeps_the_fragment() {
+ assert_eq!(navigated_to("Page.frameNavigated", &json!({"frame":{"id":"A","url":"https://b.test/"}})).as_deref(), Some("https://b.test/"));
+ assert_eq!(navigated_to("Page.frameNavigated", &json!({"frame":{"id":"A","url":"https://b.test/","urlFragment":"#top"}})).as_deref(), Some("https://b.test/#top"));
+ assert_eq!(navigated_to("Page.frameNavigated", &json!({"frame":{"id":"B","parentId":"A","url":"https://ads.test/"}})), None, "an iframe keeps the page's title");
+ assert_eq!(navigated_to("Page.navigatedWithinDocument", &json!({"frameId":"A","url":"https://b.test/#x"})), None, "same document, same title");
+ assert_eq!(navigated_to("Page.domContentEventFired", &json!({"timestamp":1.0})), None);
+ }
+
+ #[test]
+ fn input_without_control_says_to_take_control_unless_someone_has_it() {
+ assert_eq!(not_in_control(false).to_string(), "Take control of the browser first.");
+ assert!(matches!(not_in_control(true), BrowserError::HumanControl));
+ }
+
#[test]
fn letting_go_releases_every_held_button_in_order() {
let events = release_events(HeldPointer { x: 3.0, y: 4.0, buttons: 1 | 2 | 4 });
diff --git a/tests/browser_stream_test.rs b/tests/browser_stream_test.rs
index 0a1f9d9a..69d49570 100644
--- a/tests/browser_stream_test.rs
+++ b/tests/browser_stream_test.rs
@@ -12,14 +12,38 @@ struct Mock {
targets: Arc<Mutex<Vec<Value>>>,
commands: Arc<Mutex<Vec<Value>>>,
contexts: Arc<AtomicUsize>,
+ /// What the page answers for `location.href`; empty means https://example.com.
+ page_url: Arc<Mutex<String>>,
+ /// Reading the page's address fails, the way Chromium answers between two documents.
+ between_documents: Arc<std::sync::atomic::AtomicBool>,
+ /// Every open DevTools socket, to push page events the way Chromium does.
+ sockets: Arc<Mutex<Vec<tokio::sync::mpsc::UnboundedSender<String>>>>,
+}
+
+/// Sends a page event on every open DevTools socket.
+async fn push_event(mock: &Mock, method: &str, params: Value) {
+ let event = json!({"method":method,"params":params}).to_string();
+ for socket in mock.sockets.lock().await.iter() { let _ = socket.send(event.clone()); }
}
async fn cdp(State(mock): State<Mock>, Path(_id): Path<String>, ws: WebSocketUpgrade) -> impl axum::response::IntoResponse {
ws.on_upgrade(move |mut socket| async move {
- while let Some(Ok(Message::Text(text))) = socket.next().await {
+ let (push, mut pushed) = tokio::sync::mpsc::unbounded_channel::<String>();
+ mock.sockets.lock().await.push(push);
+ loop {
+ let text = tokio::select! {
+ Some(event) = pushed.recv() => { if socket.send(Message::Text(event)).await.is_err() { break; } continue; }
+ message = socket.next() => match message { Some(Ok(Message::Text(text))) => text, _ => break },
+ };
let cmd: Value = serde_json::from_str(&text).unwrap();
mock.commands.lock().await.push(cmd.clone());
let method = cmd["method"].as_str().unwrap();
+ if method == "Runtime.evaluate" && mock.between_documents.load(Ordering::SeqCst)
+ && cmd["params"]["expression"].as_str().unwrap_or_default().contains("location.href") {
+ let error = json!({"id":cmd["id"],"error":{"code":-32000,"message":"Cannot find context with specified id"}});
+ if socket.send(Message::Text(error.to_string())).await.is_err() { break; }
+ continue;
+ }
let result = match method {
"Target.createBrowserContext" => json!({"browserContextId":format!("context-{}",mock.contexts.fetch_add(1,Ordering::SeqCst))}),
"Target.createTarget" => {
@@ -35,7 +59,16 @@ async fn cdp(State(mock): State<Mock>, Path(_id): Path<String>, ws: WebSocketUpg
mock.targets.lock().await.retain(|target| target["browserContextId"] != cmd["params"]["browserContextId"]);
json!({})
}
- "Runtime.evaluate" => json!({"result":{"value":{"url":"https://example.com","title":"Example"}}}),
+ // the page has a link at (300, 300); everything else has the default cursor
+ "Runtime.evaluate" if cmd["params"]["expression"].as_str().unwrap_or_default().contains("getComputedStyle") => {
+ let link = cmd["params"]["expression"].as_str().unwrap().contains("elementFromPoint(300, 300)");
+ json!({"result":{"value": if link {"pointer"} else {"auto"}}})
+ }
+ "Runtime.evaluate" => {
+ let url = mock.page_url.lock().await.clone();
+ let url = if url.is_empty() { "https://example.com".to_string() } else { url };
+ json!({"result":{"value":{"url":url,"title":"Example"}}})
+ }
"Page.captureScreenshot" => json!({"data":"fresh-frame"}),
_ => json!({}),
};
@@ -283,7 +316,7 @@ async fn protocol_v2_mouse_keys_wheel_and_resize_reach_the_page_in_order_and_res
// input needs control first
ws.send(send(json!({"action":"mouse","type":"down","x":5,"y":5,"button":"left","id":"early"}))).await.unwrap();
- assert!(until_reply(&mut ws,"early").await.last().unwrap()["error"].as_str().unwrap().contains("controlled"));
+ assert_eq!(until_reply(&mut ws,"early").await.last().unwrap()["error"], "Take control of the browser first.");
ws.send(send(json!({"action":"take_control"}))).await.unwrap();
let control = receive(&mut ws,"control").await;
assert_eq!((control["active"].clone(), control["viewport"]["width"].as_f64()), (json!(true), Some(1280.0)));
@@ -377,6 +410,118 @@ async fn protocol_v2_mouse_keys_wheel_and_resize_reach_the_page_in_order_and_res
app_task.abort(); cdp_task.abort();
}
+type Client = tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
+
+/// A kwant server on a mock browser with one live view open on it.
+async fn open_stream(mock: &Mock, tmp: &std::path::Path) -> (Client, kwnt::sandbox::BrowserController, tokio::task::JoinHandle<()>) {
+ let config = Config {data_dir:tmp.into(),browser_cdp_url:Some(format!("http://127.0.0.1:{}",mock.port)),..Config::default()};
+ let db = Database::init(tmp).await.unwrap();
+ let id=db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap()[0].id.clone();
+ let state=AppState::new(config.clone(),db,ToolRunner::new(tmp.join("workspace")),PermissionBroker::new(),LayaRouter::new(config.laya_url));
+ let ctrl=kwnt::server::routes::get_or_create_browser_controller(&state,&id).await.unwrap();
+ let listener=TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port=listener.local_addr().unwrap().port();
+ let app_task=tokio::spawn(async move {axum::serve(listener,create_router(state)).await.unwrap();});
+ let mut request=format!("ws://127.0.0.1:{port}/api/sandbox/{id}/stream").into_client_request().unwrap();
+ request.headers_mut().insert("Origin",format!("http://127.0.0.1:{port}").parse().unwrap());
+ let (ws,_)=connect_async(request).await.unwrap();
+ (ws, ctrl, app_task)
+}
+
+/// The next `location` whose url is `url`, acking frames on the way.
+async fn location_for(ws: &mut Client, url: &str, within: Duration) -> Option<Value> {
+ timeout(within, async {
+ loop {
+ if let WsMessage::Text(text) = ws.next().await.unwrap().unwrap() {
+ let value: Value = serde_json::from_str(&text).unwrap();
+ match value["type"].as_str().unwrap_or_default() {
+ "ping" => ws.send(WsMessage::Text(json!({"action":"pong"}).to_string())).await.unwrap(),
+ "frame" => ws.send(WsMessage::Text(json!({"action":"frame_ack","id":value["id"]}).to_string())).await.unwrap(),
+ "location" if value["url"] == url => return value,
+ _ => {}
+ }
+ }
+ }
+ }).await.ok()
+}
+
+#[tokio::test]
+async fn the_address_follows_navigation_at_once_and_the_cursor_follows_where_the_pointer_rests() {
+ let (mock, cdp_task) = mock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let (mut ws, _ctrl, app_task) = open_stream(&mock, tmp.path()).await;
+ // the first location comes from the 2 s tick, which fires at once; the next tick is 2 s away
+ location_for(&mut ws, "https://example.com", Duration::from_secs(5)).await.expect("first location");
+ let tick = tokio::time::Instant::now();
+
+ // a top-level navigation (a link, back/forward/reload or a bot's navigate) is sent at once
+ *mock.page_url.lock().await = "https://example.org/next".into();
+ push_event(&mock, "Page.frameNavigated", json!({"frame":{"id":"main","url":"https://example.org/next"},"type":"Navigation"})).await;
+ let next = location_for(&mut ws, "https://example.org/next", Duration::from_millis(1500)).await;
+ assert!(next.is_some() && tick.elapsed() < Duration::from_millis(1900), "the address must not wait for the 2 s tick");
+ // pushState and #fragment changes too
+ *mock.page_url.lock().await = "https://example.org/next#b".into();
+ push_event(&mock, "Page.navigatedWithinDocument", json!({"frameId":"main","url":"https://example.org/next#b"})).await;
+ assert!(location_for(&mut ws, "https://example.org/next#b", Duration::from_millis(1500)).await.is_some());
+
+ // the title: a new document clears the old one at once, even while the page can't be read
+ // yet, and a failed read never puts the previous page's address or title back
+ mock.between_documents.store(true, Ordering::SeqCst);
+ *mock.page_url.lock().await = "https://example.net/".into();
+ push_event(&mock, "Page.frameNavigated", json!({"frame":{"id":"main","url":"https://example.net/"},"type":"Navigation"})).await;
+ let cleared = location_for(&mut ws, "https://example.net/", Duration::from_millis(1500)).await.expect("the new address at once");
+ assert_eq!(cleared["title"], "", "the previous page's title must not linger");
+ assert!(location_for(&mut ws, "https://example.org/next#b", Duration::from_millis(2500)).await.is_none(), "a failed read resent the previous page");
+ // once the document is parsed its title arrives
+ mock.between_documents.store(false, Ordering::SeqCst);
+ push_event(&mock, "Page.domContentEventFired", json!({"timestamp":1.0})).await;
+ let titled = location_for(&mut ws, "https://example.net/", Duration::from_millis(1500)).await.expect("the new title");
+ assert_eq!(titled["title"], "Example");
+
+ // D3: a move onto a link right after one that was looked up still gets its cursor
+ ws.send(WsMessage::Text(json!({"action":"take_control"}).to_string())).await.unwrap();
+ receive(&mut ws,"control").await;
+ ws.send(WsMessage::Text(json!({"action":"mouse","type":"move","x":10,"y":10}).to_string())).await.unwrap();
+ ws.send(WsMessage::Text(json!({"action":"mouse","type":"move","x":300,"y":300}).to_string())).await.unwrap();
+ let cursor = timeout(Duration::from_secs(2), receive(&mut ws,"cursor")).await.expect("a trailing lookup at the resting point");
+ assert_eq!(cursor["cursor"], "pointer");
+ let probes: Vec<_> = mock.commands.lock().await.iter()
+ .filter(|c| c["params"]["expression"].as_str().is_some_and(|e| e.contains("getComputedStyle")))
+ .map(|c| c["params"]["expression"].as_str().unwrap().contains("elementFromPoint(300, 300)")).collect();
+ assert_eq!(probes, vec![false, true], "one lookup at once, one trailing at the newest point");
+ app_task.abort(); cdp_task.abort();
+}
+
+#[tokio::test]
+async fn a_watcher_is_told_to_take_control_and_a_lost_frame_ack_does_not_drop_the_stream() {
+ let (mock, cdp_task) = mock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let (mut ws, ctrl, app_task) = open_stream(&mock, tmp.path()).await;
+ // the frame is never acked, like an identical picture that fires no load event
+ receive(&mut ws,"frame").await;
+
+ // D4: history without control gets the same refusal as any other input
+ for (id, payload) in [("h", json!({"action":"history","direction":"back"})), ("c", json!({"action":"click","x":5,"y":5}))] {
+ let mut payload = payload; payload["id"] = json!(id);
+ ws.send(WsMessage::Text(payload.to_string())).await.unwrap();
+ assert_eq!(receive(&mut ws,"error").await, json!({"type":"error","id":id,"error":"Take control of the browser first."}));
+ }
+ // another viewer holds control: then it is theirs
+ let other = ctrl.take_control().await.unwrap();
+ ws.send(WsMessage::Text(json!({"action":"history","direction":"reload","id":"o"}).to_string())).await.unwrap();
+ assert!(receive(&mut ws,"error").await["error"].as_str().unwrap().contains("controlled by a person"));
+ drop(other);
+
+ // the server stops waiting for the lost ack and keeps the stream (and control) alive
+ timeout(Duration::from_secs(9), async { loop {
+ if mock.commands.lock().await.iter().any(|c| c["method"]=="Page.screencastFrameAck") { break; }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }}).await.expect("the stalled frame is let go");
+ ws.send(WsMessage::Text(json!({"action":"take_control"}).to_string())).await.unwrap();
+ assert_eq!(receive(&mut ws,"control").await["active"], true, "the stream is still up");
+ app_task.abort(); cdp_task.abort();
+}
+
/// Opt in after building docker/browser.Dockerfile. Uses disposable data and a local HTML page.
#[tokio::test]
#[ignore = "requires Docker and the kwnt-browser:v2 image"]