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.

29d picked-tab-list-follows: a picked page's tab-list entry follows its own view's reads (#824)

Oleksandr Ivanchenko556b7aa7bc3c
diff --git a/src/sandbox/service.rs b/src/sandbox/service.rs
index 87896635..d2b59c9d 100644
--- a/src/sandbox/service.rs
+++ b/src/sandbox/service.rs
@@ -76,6 +76,48 @@ async fn previous_entry(endpoint: &str, target: &str) -> Option<String> {
history["entries"].as_array()?.get(index.checked_sub(1)?)?["url"].as_str().map(str::to_string)
}
+/// 29d: what a live view on a page the person picked last read there (its own `location`
+/// message), kept per page key for the tab list. Such a view never writes the controller's
+/// address (29a), so without this the page's tab-list entry would stay on its old address while
+/// the person clicks links or goes Back/Forward in it.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct SeenLocation {
+ pub url: String,
+ pub title: String,
+ /// The controller's `(current_url, current_title)` when this was read. While the controller
+ /// still holds exactly these, nothing wrote it since, so this read is the newer one; once it
+ /// holds anything else, browser.rs wrote it after this read and the controller is newer.
+ pub over: (Option<String>, Option<String>),
+}
+
+/// Each page's [`SeenLocation`], by page key. Cloned handles share one map.
+#[derive(Clone, Default)]
+pub struct PagesSeen(std::sync::Arc<std::sync::Mutex<HashMap<String, SeenLocation>>>);
+
+impl PagesSeen {
+ fn map(&self) -> std::sync::MutexGuard<'_, HashMap<String, SeenLocation>> {
+ self.0.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ pub fn record(&self, key: &str, seen: SeenLocation) {
+ self.map().insert(key.to_string(), seen);
+ }
+
+ pub fn get(&self, key: &str) -> Option<SeenLocation> {
+ self.map().get(key).cloned()
+ }
+
+ pub fn forget(&self, key: &str) {
+ self.map().remove(key);
+ }
+
+ /// Forgets the team page `team` and all its job pages.
+ pub fn forget_team(&self, team: &str) {
+ let prefix = format!("{team}{PAGE_SEP}");
+ self.map().retain(|k, _| k != team && !k.starts_with(&prefix));
+ }
+}
+
pub struct BrowserService {
root: PathBuf,
endpoint: Option<String>,
@@ -101,6 +143,8 @@ pub struct BrowserService {
last_outage: std::sync::Mutex<Option<Outage>>,
/// Pages the idle sweep put to rest, until they are used again (see [`Self::touch_page`]).
rested: std::sync::Mutex<HashMap<String, Rest>>,
+ /// 29d: what a view on a picked page last read there, for the tab list ([`PagesSeen`]).
+ pages_seen: PagesSeen,
}
struct ServiceState {
@@ -126,6 +170,7 @@ impl BrowserService {
page_use: Default::default(),
last_outage: Default::default(),
rested: Default::default(),
+ pages_seen: Default::default(),
}
}
@@ -713,9 +758,15 @@ impl BrowserService {
pub fn forget_page(&self, key: &str) {
if is_job_page(key) {
self.page_use.lock().unwrap_or_else(|e| e.into_inner()).remove(key);
+ self.pages_seen.forget(key);
}
}
+ /// 29d: each picked page's last seen address, shared with the live views that record it.
+ pub fn pages_seen(&self) -> PagesSeen {
+ self.pages_seen.clone()
+ }
+
/// When a page was last used in this run, if it was.
pub fn page_used_at(&self, key: &str) -> Option<std::time::Instant> {
self.page_use.lock().unwrap_or_else(|e| e.into_inner()).get(key).copied()
@@ -751,6 +802,7 @@ impl BrowserService {
if !is_job_page(key) { return Ok(()); }
self.page_use.lock().unwrap_or_else(|e| e.into_inner()).remove(key);
self.rested.lock().unwrap_or_else(|e| e.into_inner()).remove(key);
+ self.pages_seen.forget(key);
let mut lock = self.state.lock().await;
if let Some(state) = lock.as_mut() {
// Drop this page's own cached controller too (#753): otherwise its downloads/site
@@ -790,6 +842,7 @@ impl BrowserService {
let prefix = format!("{id}{PAGE_SEP}");
self.page_use.lock().unwrap_or_else(|e| e.into_inner()).retain(|k, _| !k.starts_with(&prefix));
self.rested.lock().unwrap_or_else(|e| e.into_inner()).retain(|k, _| k != id && !k.starts_with(&prefix));
+ self.pages_seen.forget_team(id);
let mut lock = self.state.lock().await;
if lock.is_none() && self.sessions_file().exists() {
*lock = Some(self.connect().await?);
diff --git a/src/server/browser_pages.rs b/src/server/browser_pages.rs
index dc89b0b9..b824e3fc 100644
--- a/src/server/browser_pages.rs
+++ b/src/server/browser_pages.rs
@@ -35,7 +35,7 @@
use super::continuity::SelfScope;
use super::AppState;
-use crate::sandbox::service::Rest;
+use crate::sandbox::service::{Rest, SeenLocation};
use axum::{extract::{Path, State}, Json};
use serde_json::{json, Value};
use std::{
@@ -460,6 +460,17 @@ pub async fn live_page(state: &AppState, team: &str) -> String {
.unwrap_or_else(|| team.to_string())
}
+/// 29d: the address and title the tab list shows for a page: the newer of what the controller
+/// holds (written by browser.rs, or by a view on the bot's page) and what a view on the page the
+/// person picked last read there. The picked read is newer while the controller still holds
+/// exactly what it held at that read ([`SeenLocation::over`]), or holds nothing yet.
+pub(crate) fn shown_location(written: (Option<String>, Option<String>), seen: Option<SeenLocation>) -> (Option<String>, Option<String>) {
+ match seen {
+ Some(seen) if written.0.is_none() || seen.over == written => (Some(seen.url), Some(seen.title)),
+ _ => written,
+ }
+}
+
/// `GET /api/sandbox/:team_id/pages`: the team's pages for a tab strip, newest first. Each has
/// its `page` key (pass it to the live view as `?page=`), the bot and chat of a job page, its
/// address and title, whether a step holds it (`held`), and seconds since its last use. `live`
@@ -473,10 +484,11 @@ pub async fn list_pages(State(state): State<AppState>, Path(team_id): Path<Strin
let mut out = Vec::new();
for (key, at) in pages {
let ctrl = state.browser_controllers.lock().await.get(&key).cloned();
- let (url, title) = match &ctrl {
+ let written = match &ctrl {
Some(c) => (c.current_url.lock().await.clone(), c.current_title.lock().await.clone()),
None => (None, None),
};
+ let (url, title) = shown_location(written, state.browser_service.pages_seen().get(&key));
let mut parts = key.splitn(3, PAGE_SEP).skip(1);
out.push(json!({
"page": key,
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index ccb39686..28a7e24e 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -13,6 +13,7 @@ use crate::db::attachments::Attachment;
use crate::sandbox::app_links::{self, AppLinkWatch, Verdict};
use crate::sandbox::browser::{web_address, BrowserController, BrowserError, HeldPointer, PersonLease, ViewClaim, ViewRelease, FOCUSED_EDITABLE_JS, MOUSE_BUTTON_BITS};
use crate::sandbox::browser_history::HistoryDirection;
+use crate::sandbox::service::{PagesSeen, SeenLocation};
use axum::{extract::{Path, State, WebSocketUpgrade, ws::{Message, WebSocket}}, http::{HeaderMap, StatusCode}, response::Response};
use futures::{SinkExt, StreamExt};
use serde::Deserialize;
@@ -434,6 +435,10 @@ struct Shared {
/// page the person picked never writes it: the bot's own status and a resumed run would
/// otherwise report the person's tab as the bot's page.
bots_page: bool,
+ /// 29d: on a view of a page the person picked, where its reads are kept as that page's own
+ /// last seen address for the tab list, under the page key the view was opened with. `None`
+ /// on the bot's page, whose reads go to the controller instead.
+ seen: Option<(PagesSeen, String)>,
}
/// How long after a Point picture a frame at exactly its size is taken for that picture's.
@@ -535,6 +540,7 @@ fn refresh_location(cdp: &Cdp, ctrl: &BrowserController, shared: &Arc<Shared>, c
while shared.location.next().is_some() {
// blocks while a dialog is open, so never on the stream loop
let Some(location) = read_location(&cdp, shared.bots_page.then_some(&ctrl)).await else { continue };
+ keep_seen(&shared, &ctrl, &location).await;
let _ = client.send(location);
}
});
@@ -560,6 +566,17 @@ async fn read_location(cdp: &Cdp, bot: Option<&BrowserController>) -> Option<Val
Some(json!({"type":"location","url":url,"title":title.unwrap_or_default()}))
}
+/// 29d: on a view of a page the person picked, keeps the `location` it just read as that page's
+/// last seen address, with what the controller held at the time (see [`SeenLocation::over`]).
+/// The controller itself stays untouched (29a). Nothing on the bot's page.
+async fn keep_seen(shared: &Shared, ctrl: &BrowserController, location: &Value) {
+ let Some((seen, key)) = &shared.seen else { return };
+ let Some(url) = location["url"].as_str() else { return };
+ let over = (ctrl.current_url.lock().await.clone(), ctrl.current_title.lock().await.clone());
+ let title = location["title"].as_str().unwrap_or_default().to_string();
+ seen.record(key, SeenLocation { url: url.to_string(), title, over });
+}
+
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());
@@ -1379,6 +1396,7 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String, bots_page: bo
recording: AtomicBool::new(false),
shot: std::sync::Mutex::new(None),
bots_page,
+ seen: (!bots_page).then(|| (state.browser_service.pages_seen(), id.clone())),
});
let (client_tx, mut client_rx) = mpsc::unbounded_channel::<Value>();
let (jobs, jobs_rx) = mpsc::unbounded_channel::<Job>();
@@ -1476,6 +1494,7 @@ async fn stream(
// must know whose it is. Its frames wait in `events` until the loop reads them.
match read_location(cdp, shared.bots_page.then_some(ctrl)).await {
Some(location) => {
+ keep_seen(shared, ctrl, &location).await;
// a "Continue with Google" popup in front
let url = location["url"].as_str().unwrap_or_default().to_string();
send(socket, location).await?;
@@ -2357,6 +2376,15 @@ mod tests {
/// A live view's shared state as `serve` makes it, for tests.
fn test_shared(bots_page: bool) -> Arc<Shared> {
+ test_view(bots_page, (!bots_page).then(|| (PagesSeen::default(), "t".to_string())))
+ }
+
+ /// A view on the page `key` the person picked, keeping its reads in `seen`, as `serve` makes it.
+ fn test_picked(seen: &PagesSeen, key: &str) -> Arc<Shared> {
+ test_view(false, Some((seen.clone(), key.to_string())))
+ }
+
+ fn test_view(bots_page: bool, seen: Option<(PagesSeen, String)>) -> Arc<Shared> {
Arc::new(Shared {
socket: NEXT_SOCKET.fetch_add(1, Ordering::Relaxed),
view: std::sync::Mutex::new((DEFAULT_VIEW.0 as f64, DEFAULT_VIEW.1 as f64)),
@@ -2368,6 +2396,7 @@ mod tests {
recording: AtomicBool::new(false),
shot: std::sync::Mutex::new(None),
bots_page,
+ seen,
})
}
@@ -2418,6 +2447,73 @@ mod tests {
assert_eq!(bots_address().await, bots("https://bot.example/done", "Signed in"));
}
+ /// 29d: a view on a page the person picked keeps what it reads as that page's own last seen
+ /// address, so the page's tab-list entry follows the person's clicks and Back/Forward in it,
+ /// while the bot's address on the controller stays the bot's (29a). The tab list shows the
+ /// newer of the two: a later write from browser.rs wins until the picked view reads again.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn a_picked_pages_tab_list_entry_follows_its_own_reads_and_the_bots_address_stays() {
+ use crate::server::browser_pages::shown_location;
+ let ctrl = BrowserController::new(0);
+ *ctrl.current_url.lock().await = Some("https://bot.example/start".into());
+ *ctrl.current_title.lock().await = Some("Bot start".into());
+ let picked = Arc::new(std::sync::Mutex::new(json!({"url": "https://shared.example/doc", "title": "Shared doc"})));
+ let picked_tab = fake_page(picked.clone()).await;
+ let seen = PagesSeen::default();
+ let view = test_picked(&seen, "t");
+ let location = |url: &str, title: &str| json!({"type": "location", "url": url, "title": title});
+ let pair = |url: &str, title: &str| (Some(url.to_string()), Some(title.to_string()));
+ let bots_address = || async { (ctrl.current_url.lock().await.clone(), ctrl.current_title.lock().await.clone()) };
+ let tab_list = || async { shown_location(bots_address().await, seen.get("t")) };
+ let (tx, mut rx) = mpsc::unbounded_channel::<Value>();
+ // the view as `stream` runs it: a refresh, and what reached the person
+ macro_rules! refresh {
+ ($shared:expr) => {{
+ refresh_location(&picked_tab, &ctrl, &$shared, &tx);
+ timeout(Duration::from_secs(5), rx.recv()).await.expect("the location reached the person")
+ }};
+ }
+
+ // the view opens on the picked page: the tab list shows it, the bot's address stays
+ assert_eq!(refresh!(view.clone()), Some(location("https://shared.example/doc", "Shared doc")));
+ assert_eq!(tab_list().await, pair("https://shared.example/doc", "Shared doc"));
+ assert_eq!(bots_address().await, pair("https://bot.example/start", "Bot start"));
+
+ // the person clicks a link in it (or goes Back): the tab list follows, the bot's address stays
+ *picked.lock().unwrap() = json!({"url": "https://shared.example/other", "title": "Other"});
+ assert_eq!(refresh!(view.clone()), Some(location("https://shared.example/other", "Other")));
+ assert_eq!(tab_list().await, pair("https://shared.example/other", "Other"));
+ assert_eq!(bots_address().await, pair("https://bot.example/start", "Bot start"));
+
+ // the page switch in `stream` keeps its read the same way
+ *picked.lock().unwrap() = json!({"url": "https://accounts.google.com/signin", "title": "Sign in"});
+ let read = read_location(&picked_tab, None).await.expect("the page answered");
+ keep_seen(&view, &ctrl, &read).await;
+ assert_eq!(tab_list().await, pair("https://accounts.google.com/signin", "Sign in"));
+ assert_eq!(bots_address().await, pair("https://bot.example/start", "Bot start"));
+
+ // browser.rs writes the controller after that read: it is the newer one now
+ *ctrl.current_url.lock().await = Some("https://bot.example/next".into());
+ *ctrl.current_title.lock().await = Some("Bot next".into());
+ assert_eq!(tab_list().await, pair("https://bot.example/next", "Bot next"));
+ // until the picked view reads again
+ *picked.lock().unwrap() = json!({"url": "https://shared.example/doc", "title": "Shared doc"});
+ assert_eq!(refresh!(view.clone()), Some(location("https://shared.example/doc", "Shared doc")));
+ assert_eq!(tab_list().await, pair("https://shared.example/doc", "Shared doc"));
+ assert_eq!(bots_address().await, pair("https://bot.example/next", "Bot next"));
+
+ // a view on the bot's page keeps nothing here: it writes the controller, which then wins
+ *picked.lock().unwrap() = json!({"url": "https://bot.example/done", "title": "Done"});
+ assert_eq!(refresh!(test_shared(true)), Some(location("https://bot.example/done", "Done")));
+ assert_eq!(seen.get("t").map(|s| s.url), Some("https://shared.example/doc".to_string()));
+ assert_eq!(tab_list().await, pair("https://bot.example/done", "Done"));
+
+ // a closed page's last seen is forgotten
+ seen.forget("t");
+ assert_eq!(tab_list().await, pair("https://bot.example/done", "Done"));
+ assert_eq!(seen.get("t"), None);
+ }
+
/// 28v: the Shared tab's stream and the bot's own page share one controller, and the bot's
/// navigation writes the controller's address. Opening the view and taking control judge the
/// sign-in notice by the address of the page this stream shows: a notice only when its own page