Skip to main content

agentmux_srv/server/
browser_sessions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's background browser sessions: which browser panes it holds, and `show`, which turns a background
5//! session into a floating pane the person sees (docs/specs/SPEC_BACKGROUND_BROWSER_SESSIONS_2026_11_28.md §4, §6).
6//!
7//! A background session is a browser pane in a floating window kept above every display (`app_api::floater_place`,
8//! `pane_openers`). It is the agent's, as any pane it opened is: the opener record decides who may list and show it.
9
10use axum::extract::State;
11use axum::http::StatusCode;
12use axum::response::IntoResponse;
13use axum::Json;
14use serde_json::{json, Value};
15
16use crate::backend::obj::Block;
17use crate::backend::rpc::action_record::{ActionRecord, Target};
18use crate::backend::rpc::actor::Actor;
19use crate::backend::rpc_types::CommandPaneOpenData;
20use crate::server::app_api::floater_place;
21use crate::server::ui_handlers::{err_response, verified_block_id};
22use crate::server::AppState;
23
24/// The agent a request is from: its token's uid, else the signed id (as `floater_place::for_browser` reads it).
25fn agent_of(caller: Option<&crate::server::caller::Caller>, auth: &agentmux_common::api_types::UiAutomationAuth) -> String {
26    caller.and_then(|c| c.uid()).map_or_else(|| auth.agent_id.clone(), str::to_string)
27}
28
29/// One pane of `list`: where it is and what it shows.
30fn row(block_id: &str, block: &Block, floating: bool, background: bool) -> Value {
31    let text = |key: &str| block.meta.get(key).and_then(Value::as_str).unwrap_or("").to_string();
32    json!({ "pane": block_id, "url": text("url"), "title": text("frame:title"), "floating": floating, "background": background })
33}
34
35/// `POST /api/v1/ui/browser/list` — the browser panes the caller opened and still has: each pane's id, address and
36/// title, whether it floats and whether it is a background session.
37pub(crate) async fn handle_ui_browser_list(
38    State(state): State<AppState>,
39    caller: Option<axum::Extension<crate::server::caller::Caller>>,
40    Json(req): Json<agentmux_common::browser_control_types::UiBrowserListRequest>,
41) -> impl IntoResponse {
42    if let Err(e) = verified_block_id(&state, caller.as_deref(), &req.auth) {
43        return err_response(StatusCode::UNAUTHORIZED, e);
44    }
45    let agent = agent_of(caller.as_deref(), &req.auth);
46    let mut panes = Vec::new();
47    for (block_id, floating, background) in crate::server::pane_openers::opened_by_agent(&agent) {
48        let Some(block) = state.mstore.get::<Block>(&block_id).ok().flatten() else { continue };
49        if block.meta.get("view").and_then(Value::as_str) == Some("browser") {
50            panes.push(row(&block_id, &block, floating, background));
51        }
52    }
53    let background = panes.iter().filter(|p| p["background"] == json!(true)).count();
54    let data = json!({ "panes": panes, "background": background, "background_limit": floater_place::MAX_BACKGROUND_PER_AGENT });
55    (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
56}
57
58/// The refusal for a pane that is not the caller's background session, or none.
59fn not_background(agent: &str, pane: &str) -> Option<(StatusCode, String)> {
60    if !crate::server::pane_openers::opened_by(pane, agent) {
61        return Some((StatusCode::FORBIDDEN, crate::server::pane_place::NOT_YOURS.to_string()));
62    }
63    (!crate::server::pane_openers::is_background(pane))
64        .then(|| (StatusCode::CONFLICT, format!("NOT_BACKGROUND: {pane} is not a background session: it is already a pane the person sees")))
65}
66
67/// Make the caller's background session `pane` a floating pane the person sees, on the right of the work area, at the size
68/// it has. It counts as a floating pane from then on, so it is refused when the caller already has the most of those.
69pub(crate) async fn show(state: &AppState, agent: &str, pane: &str) -> Result<Value, (StatusCode, String)> {
70    if let Some(refusal) = not_background(agent, pane) {
71        return Err(refusal);
72    }
73    let open = floater_place::live_floaters(state, agent).await;
74    if open.len() >= floater_place::MAX_FLOATERS {
75        return Err((StatusCode::TOO_MANY_REQUESTS, floater_place::limit_text(&open)));
76    }
77    crate::server::deeplink_guard::check_place_rate(agent).map_err(|text| (StatusCode::TOO_MANY_REQUESTS, text))?;
78    let shown = bring_into_view(state, pane).await?;
79    audit(state, agent, "show", pane);
80    Ok(shown)
81}
82
83/// Move the window of background session `pane` into the work area, on the right, keeping the size it has.
84async fn bring_into_view(state: &AppState, pane: &str) -> Result<Value, (StatusCode, String)> {
85    let Some(win) = crate::server::pane_place::window_of(state, pane).await else {
86        return Err((StatusCode::CONFLICT, format!("NOT_FLOATING: the window of {pane} is not open (the person may have closed it)")));
87    };
88    let cmd = CommandPaneOpenData { floating: Some(true), spot: Some("right".to_string()), ..Default::default() };
89    match crate::server::pane_place::ask(state, win, pane, Some("size"), Some(&cmd), floater_place::WAIT).await {
90        Ok(placed) => {
91            crate::server::pane_openers::clear_background(pane);
92            Ok(json!({ "pane": pane, "placed": placed }))
93        }
94        Err(crate::server::pane_place::Asked::Failed(why)) => Err((StatusCode::BAD_GATEWAY, format!("the window could not show it: {why}"))),
95        Err(crate::server::pane_place::Asked::NoAnswer) => {
96            Err((StatusCode::GATEWAY_TIMEOUT, "NO_ANSWER: the session's window did not answer (it may still be starting): try again".to_string()))
97        }
98    }
99}
100
101/// The refusal for a pane that is not a browser pane the caller opened and can put back in the background, or none.
102fn not_hideable(agent: &str, pane: &str, is_browser: bool) -> Option<(StatusCode, String)> {
103    if !crate::server::pane_openers::opened_by(pane, agent) {
104        return Some((StatusCode::FORBIDDEN, crate::server::pane_place::NOT_YOURS.to_string()));
105    }
106    if crate::server::pane_openers::is_background(pane) {
107        return Some((StatusCode::CONFLICT, format!("ALREADY_BACKGROUND: {pane} is already a background session")));
108    }
109    if !is_browser {
110        return Some((StatusCode::CONFLICT, format!("NOT_BROWSER: {pane} is not a browser pane: only a browser pane can be a background session")));
111    }
112    (!crate::server::pane_openers::is_floating(pane))
113        .then(|| (StatusCode::CONFLICT, format!("NOT_FLOATING: {pane} is not a floating pane: Pane float it first, then hide it")))
114}
115
116/// Put the caller's floating browser pane `pane` back in the background: its window goes above every display, at the
117/// size it has, and it counts against the background caps again.
118pub(crate) async fn hide(state: &AppState, agent: &str, from: &str, pane: &str) -> Result<Value, (StatusCode, String)> {
119    if let Some(why) = floater_place::background_refusal(floater_place::BACKGROUND_PLATFORM) {
120        return Err((StatusCode::CONFLICT, why));
121    }
122    let is_browser = state.mstore.get::<Block>(pane).ok().flatten().is_some_and(|b| b.meta.get("view").and_then(Value::as_str) == Some("browser"));
123    if let Some(refusal) = not_hideable(agent, pane, is_browser) {
124        return Err(refusal);
125    }
126    let (mine, all) = (floater_place::live_background(state, Some(agent)).await, floater_place::live_background(state, None).await.len());
127    if let Some(why) = floater_place::background_limit(&mine, all) {
128        return Err((StatusCode::TOO_MANY_REQUESTS, why));
129    }
130    crate::server::deeplink_guard::check_place_rate(agent).map_err(|text| (StatusCode::TOO_MANY_REQUESTS, text))?;
131    let Some(win) = crate::server::pane_place::window_of(state, pane).await else {
132        return Err((StatusCode::CONFLICT, format!("NOT_FLOATING: the window of {pane} is not open (the person may have closed it)")));
133    };
134    let cmd = CommandPaneOpenData { floating: Some(true), background: true, ..Default::default() };
135    match crate::server::pane_place::ask(state, win, pane, Some("size"), Some(&cmd), floater_place::WAIT).await {
136        Ok(placed) => {
137            crate::server::pane_openers::set_background(pane, from);
138            audit(state, agent, "hide", pane);
139            Ok(json!({ "pane": pane, "placed": placed }))
140        }
141        Err(crate::server::pane_place::Asked::Failed(why)) => Err((StatusCode::BAD_GATEWAY, format!("the window could not hide it: {why}"))),
142        Err(crate::server::pane_place::Asked::NoAnswer) => Err((StatusCode::GATEWAY_TIMEOUT, "NO_ANSWER: the pane's window did not answer: try again".to_string())),
143    }
144}
145
146/// `POST /api/v1/ui/browser/hide` — put a floating browser pane back in the background.
147pub(crate) async fn handle_ui_browser_hide(
148    State(state): State<AppState>,
149    caller: Option<axum::Extension<crate::server::caller::Caller>>,
150    Json(req): Json<agentmux_common::browser_control_types::UiBrowserHideRequest>,
151) -> impl IntoResponse {
152    let from = match verified_block_id(&state, caller.as_deref(), &req.auth) {
153        Ok(block) => block,
154        Err(e) => return err_response(StatusCode::UNAUTHORIZED, e),
155    };
156    let agent = agent_of(caller.as_deref(), &req.auth);
157    tracing::info!(agent_id = %agent, pane = %req.pane, "[ui-automation] browser hide (back to a background session)");
158    match hide(&state, &agent, &from, &req.pane).await {
159        Ok(data) => (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response(),
160        Err((code, e)) => err_response(code, e),
161    }
162}
163
164/// The Audit row for something done to a background session: `what` (open, show, hide), by `agent`, naming the pane and the
165/// site it is on (the host and no more: never a path, a query or anything typed).
166pub(crate) fn audit(state: &AppState, agent: &str, what: &str, pane: &str) {
167    audit_by(state, Some(agent), what, pane);
168}
169
170/// The same row, by `agent`, or by the person when there is none (their own Show from the strip).
171fn audit_by(state: &AppState, agent: Option<&str>, what: &str, pane: &str) {
172    write_audit(state, agent, what, pane, site_of(state, pane));
173}
174
175/// The site `pane` is on now (the host, as the Audit names it), or nothing when it is not a pane with an address.
176pub(crate) fn site_of(state: &AppState, pane: &str) -> String {
177    state.mstore.get::<Block>(pane).ok().flatten().and_then(|b| b.meta.get("url").and_then(Value::as_str).map(shown_site)).unwrap_or_default()
178}
179
180/// The row for a step in a session (a navigation, a click, a fill): the site is the page the step is about when it has an
181/// address, else the one the pane is on.
182pub(crate) fn audit_step(state: &AppState, agent: Option<&str>, what: &str, pane: &str, url: Option<&str>) {
183    let site = url.map(shown_site).filter(|s| !s.is_empty()).unwrap_or_else(|| site_of(state, pane));
184    write_audit(state, agent, what, pane, site);
185}
186
187/// The row for a pane that is already closed: its site was read before it went.
188pub(crate) fn audit_closed(state: &AppState, agent: &str, what: &str, pane: &str, site: &str) {
189    write_audit(state, Some(agent), what, pane, site.to_string());
190}
191
192fn write_audit(state: &AppState, agent: Option<&str>, what: &str, pane: &str, site: String) {
193    let store = state.mstore.clone();
194    let (agent, what, pane) = (agent.map(str::to_string), what.to_string(), pane.to_string());
195    // Off the caller's path: naming the agent reads the store.
196    tokio::task::spawn_blocking(move || {
197        let actor = match agent {
198            Some(agent) => Actor::Agent(store.agent_names_by_id(&agent).ok().flatten().map(|row| row.slug).unwrap_or(agent)),
199            None => Actor::Operator,
200        };
201        let subject = Some(format!("pane={pane} site={site}"));
202        let record = ActionRecord { actor, command: format!("browser session {what}"), target: Target { agent: None, block_id: Some(pane), subject }, request_id: String::new(), error: None };
203        crate::backend::reactive::get_global_handler().audit_action(&record);
204    });
205}
206
207/// The host of `url` (no scheme, sign-in, path or query). An address with no host (`data:`, `about:`, `javascript:`) shows
208/// its scheme only, since the rest of it can be anything the page or the agent wrote; text that is not an address shows
209/// nothing.
210fn shown_site(url: &str) -> String {
211    let Some((_, rest)) = url.split_once("://") else {
212        let scheme = url.split_once(':').map(|(s, _)| s).filter(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c)));
213        return scheme.map(|s| format!("{}:", s.chars().take(20).collect::<String>())).unwrap_or_default();
214    };
215    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
216    authority.rsplit('@').next().unwrap_or("").chars().take(120).collect()
217}
218
219/// Record `agent` as the opener of the floating pane `pane` (a background session when `cmd` says so, opened from the
220/// agent's pane `cmd.split_reference_block_id`), and, for a session, write its Audit row.
221pub(crate) fn note_opened(state: &AppState, pane: &str, agent: &str, cmd: &CommandPaneOpenData) {
222    crate::server::pane_openers::record_floating(pane, agent, cmd.background, cmd.split_reference_block_id.as_deref());
223    if cmd.background {
224        audit(state, agent, "open", pane);
225    }
226}
227
228/// The agent pane's meta key that lists its background sessions (pane ids), which the strip in the pane shows.
229pub(crate) const META_SESSIONS: &str = "agent:bgsessions";
230
231type Lists = std::collections::BTreeMap<String, Value>;
232
233/// What `agent:bgsessions` was last set to on each agent pane, so a change is written once.
234fn written() -> std::sync::MutexGuard<'static, Lists> {
235    static WRITTEN: std::sync::OnceLock<std::sync::Mutex<Lists>> = std::sync::OnceLock::new();
236    WRITTEN.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner())
237}
238
239/// What each agent pane's `agent:bgsessions` should be: the sessions it opened that are still background ones and still
240/// there. A pane with none has no list.
241fn wanted(by_block: std::collections::BTreeMap<String, Vec<String>>, exists: impl Fn(&str) -> bool) -> Lists {
242    let lists = by_block.into_iter().map(|(from, panes)| (from, panes.into_iter().filter(|p| exists(p)).collect::<Vec<_>>()));
243    lists.filter(|(_, live)| !live.is_empty()).map(|(from, live)| (from, json!(live))).collect()
244}
245
246/// Make each agent pane's `agent:bgsessions` say which background sessions it holds, writing only what changed. The first
247/// call also clears a list a previous run left on a pane. Run whenever the sessions may have changed
248/// (`browser_owner::changed`).
249pub(crate) fn sync_strips(state: &AppState) {
250    let mut written = written();
251    if written.is_empty() {
252        for b in state.mstore.get_all::<Block>().unwrap_or_default() {
253            if let Some(v) = b.meta.get(META_SESSIONS).filter(|v| !v.is_null()) {
254                written.insert(b.oid.clone(), v.clone());
255            }
256        }
257    }
258    let exists = |pane: &str| state.mstore.get::<Block>(pane).ok().flatten().is_some();
259    let wanted = wanted(crate::server::pane_openers::background_by_block(), exists);
260    let panes: std::collections::BTreeSet<String> = wanted.keys().chain(written.keys()).cloned().collect();
261    for from in panes {
262        let value = wanted.get(&from).cloned().unwrap_or(Value::Null);
263        if written.get(&from).unwrap_or(&Value::Null) == &value {
264            continue;
265        }
266        crate::server::prep::set_block_meta(state, &[from.as_str()], &[(META_SESSIONS, value.clone())]);
267        match value.is_null() {
268            true => written.remove(&from),
269            false => written.insert(from, value),
270        };
271    }
272}
273
274/// `browser.session.show`: the person shows an agent's background session, from the strip in the agent's pane.
275pub const COMMAND_BROWSER_SESSION_SHOW: &str = "browser.session.show";
276
277/// Data for `browser.session.show`: the session's pane.
278#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default, ts_rs::TS)]
279#[ts(export, export_to = "../../../frontend/types/rpc/")]
280pub struct CommandBrowserSessionShowData {
281    pub pane: String,
282}
283
284/// The answer to `browser.session.show`.
285#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default, ts_rs::TS)]
286#[ts(export, export_to = "../../../frontend/types/rpc/")]
287pub struct BrowserSessionShowResult {
288    pub shown: bool,
289}
290
291/// Register `browser.session.show`, accepted only from the proven AgentMux window: the person's own choice to see the
292/// page, never an agent's.
293pub fn register(engine: &std::sync::Arc<crate::backend::rpc::engine::WshRpcEngine>, state: &AppState) {
294    let state = state.clone();
295    engine.register_typed(COMMAND_BROWSER_SESSION_SHOW, move |cmd: CommandBrowserSessionShowData, ctx| {
296        let state = state.clone();
297        async move {
298            ctx.operator_only("only the person can show an agent's background session")?;
299            if !crate::server::pane_openers::is_background(&cmd.pane) {
300                return Err(format!("NOT_BACKGROUND: {} is not a background session", cmd.pane));
301            }
302            bring_into_view(&state, &cmd.pane).await.map_err(|(_, why)| why)?;
303            audit_by(&state, None, "show (by the person)", &cmd.pane);
304            Ok(BrowserSessionShowResult { shown: true })
305        }
306    });
307}
308
309/// What a hand-off does about where its pane is: a background session is shown first (the person is asked to work in a
310/// page they can see, whoever the caller is: it is the caller's hand-off to make), and the hand-off is refused when it
311/// cannot be, since its banner would wait on a window above every display. Any other pane is as `float_for_handoff` says.
312pub(crate) async fn handoff_float(state: &AppState, asked: Option<bool>, agent: Option<&str>, pane: &str, popup: bool) -> Result<Option<Value>, String> {
313    if !crate::server::pane_openers::is_background(pane) {
314        return Ok(crate::server::pane_dock::float_for_handoff(state, asked, agent, pane, popup).await);
315    }
316    match bring_into_view(state, pane).await {
317        Ok(_) => {
318            audit(state, &crate::server::pane_openers::opener_of(pane).unwrap_or_default(), "show for a hand-off", pane);
319            Ok(Some(json!({ "floated": true, "shown": true })))
320        }
321        Err((_, why)) => Err(format!("this pane is a background session no screen shows, and it could not be shown for the hand-off: {why}")),
322    }
323}
324
325/// A prompt for the person (an approval, a sign-in, a request for a value, a navigation to ask about) was raised in
326/// `pane`: when it is a background session its window is above every display, so it is shown, and the prompt is where
327/// the person can see it. Nothing else changes for a pane the person already sees.
328pub(crate) fn reveal_for_prompt(state: &AppState, pane: &str) {
329    if !crate::server::pane_openers::is_background(pane) {
330        return;
331    }
332    let (state, pane) = (state.clone(), pane.to_string());
333    tokio::spawn(async move {
334        match bring_into_view(&state, &pane).await {
335            Ok(_) => audit(&state, &crate::server::pane_openers::opener_of(&pane).unwrap_or_default(), "show for a request to the person", &pane),
336            Err((_, why)) => tracing::warn!(pane = %pane, "[browser-sessions] a prompt waits in a background session that could not be shown: {why}"),
337        }
338    });
339}
340
341/// Before a committing click asks the person: a background session is shown first, so the question is on a screen, and
342/// the click is refused at once when it cannot be (a question in a window above every display would wait unseen for its
343/// ten minutes). Any other pane is as it is.
344pub(crate) async fn show_to_ask(state: &AppState, pane: &str) -> Result<(), String> {
345    if !crate::server::pane_openers::is_background(pane) {
346        return Ok(());
347    }
348    match bring_into_view(state, pane).await {
349        Ok(_) => {
350            audit(state, &crate::server::pane_openers::opener_of(pane).unwrap_or_default(), "show for a request to the person", pane);
351            Ok(())
352        }
353        Err((_, why)) => Err(format!("this pane is a background session no screen shows, and it could not be shown to ask the person, so nothing was asked and the click was not made: {why}")),
354    }
355}
356
357/// `POST /api/v1/ui/browser/show` — show a background session.
358pub(crate) async fn handle_ui_browser_show(
359    State(state): State<AppState>,
360    caller: Option<axum::Extension<crate::server::caller::Caller>>,
361    Json(req): Json<agentmux_common::browser_control_types::UiBrowserShowRequest>,
362) -> impl IntoResponse {
363    if let Err(e) = verified_block_id(&state, caller.as_deref(), &req.auth) {
364        return err_response(StatusCode::UNAUTHORIZED, e);
365    }
366    let agent = agent_of(caller.as_deref(), &req.auth);
367    tracing::info!(agent_id = %agent, pane = %req.pane, "[ui-automation] browser show (background session)");
368    match show(&state, &agent, &req.pane).await {
369        Ok(data) => (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response(),
370        Err((code, e)) => err_response(code, e),
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377
378    #[test]
379    fn a_pane_that_is_not_the_callers_background_session_is_refused_with_its_reason() {
380        crate::server::pane_openers::record_background("bs-1", "alice");
381        crate::server::pane_openers::record("bs-2", "alice", true);
382        assert!(not_background("alice", "bs-1").is_none());
383        assert_eq!(not_background("bob", "bs-1").map(|r| r.0), Some(StatusCode::FORBIDDEN));
384        let shown = not_background("alice", "bs-2").expect("a pane the person sees is not a session");
385        assert_eq!(shown.0, StatusCode::CONFLICT);
386        assert!(shown.1.starts_with("NOT_BACKGROUND"), "{}", shown.1);
387        crate::server::pane_openers::forget("bs-1");
388        crate::server::pane_openers::forget("bs-2");
389    }
390
391    #[test]
392    fn the_caps_name_who_holds_the_sessions() {
393        let two = vec!["a".to_string(), "b".to_string()];
394        assert!(floater_place::background_limit(&two, 2).expect("two is the most").starts_with("BACKGROUND_LIMIT: you hold 2"));
395        assert!(floater_place::background_limit(&two[..1], 6).expect("six is the most").contains("on this machine"));
396        assert!(floater_place::background_limit(&two[..1], 5).is_none());
397    }
398
399    #[test]
400    fn only_a_floating_browser_pane_the_caller_opened_can_be_hidden() {
401        crate::server::pane_openers::record("hp-1", "alice", true);
402        crate::server::pane_openers::record("hp-2", "alice", false);
403        crate::server::pane_openers::record_background("hp-3", "alice");
404        assert!(not_hideable("alice", "hp-1", true).is_none());
405        assert_eq!(not_hideable("bob", "hp-1", true).map(|r| r.0), Some(StatusCode::FORBIDDEN));
406        assert!(not_hideable("alice", "hp-1", false).expect("not a browser").1.starts_with("NOT_BROWSER"));
407        assert!(not_hideable("alice", "hp-2", true).expect("docked").1.starts_with("NOT_FLOATING"));
408        assert!(not_hideable("alice", "hp-3", true).expect("already hidden").1.starts_with("ALREADY_BACKGROUND"));
409        for pane in ["hp-1", "hp-2", "hp-3"] {
410            crate::server::pane_openers::forget(pane);
411        }
412    }
413
414    #[test]
415    fn a_pane_hidden_is_held_by_the_agent_pane_that_hid_it() {
416        crate::server::pane_openers::record("sb-1", "alice", true);
417        assert!(!crate::server::pane_openers::background_by_block().values().any(|v| v.contains(&"sb-1".to_string())));
418        crate::server::pane_openers::set_background("sb-1", "agent-pane-1");
419        assert_eq!(crate::server::pane_openers::background_by_block().get("agent-pane-1"), Some(&vec!["sb-1".to_string()]));
420        // A session opened from one pane keeps it, whoever hides it again.
421        crate::server::pane_openers::set_background("sb-1", "agent-pane-2");
422        assert!(crate::server::pane_openers::background_by_block().get("agent-pane-2").is_none());
423        crate::server::pane_openers::forget("sb-1");
424    }
425
426    #[test]
427    fn the_audit_names_the_site_and_nothing_after_it() {
428        assert_eq!(shown_site("https://example.com/pay?card=4111#x"), "example.com");
429        assert_eq!(shown_site("http://user:secret@host.test:8080/a"), "host.test:8080");
430        // No host: the scheme at most, never what follows it.
431        assert_eq!(shown_site("data:,private-credential"), "data:");
432        assert_eq!(shown_site("javascript:alert(document.cookie)"), "javascript:");
433        assert_eq!(shown_site("no address"), "");
434    }
435
436    #[test]
437    fn a_background_session_is_refused_where_its_window_cannot_be_kept_off_every_screen() {
438        assert!(floater_place::background_refusal(true).is_none());
439        let why = floater_place::background_refusal(false).expect("refused");
440        assert!(why.starts_with("BACKGROUND_UNAVAILABLE") && why.contains("floating: true"), "{why}");
441    }
442
443    #[test]
444    fn a_pane_lists_the_sessions_it_opened_that_still_exist() {
445        let by_block = [("agent-1".to_string(), vec!["s1".to_string(), "gone".to_string()]), ("agent-2".to_string(), vec!["gone".to_string()])].into();
446        let wanted = wanted(by_block, |pane| pane != "gone");
447        assert_eq!(wanted.get("agent-1"), Some(&json!(["s1"])));
448        assert!(!wanted.contains_key("agent-2"), "a pane with no session left has no list");
449    }
450}