Skip to main content

agentmux_srv/server/
browser_owner.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which agent owns which agent-opened browser pane
5//! (docs/specs/SPEC_AGENT_DRIVEN_BROWSER_PANES_2026_10_07.md §3).
6//!
7//! An agent may drive a browser pane only if it opened that pane with
8//! `OpenBrowser`. The authority is this in-memory map, written only by
9//! `ui_handlers::handle_ui_browser_open` after verifying the caller's
10//! signed identity. The block's `browser:owner_agent` meta key mirrors it
11//! for the "Driven by" badge, and both must agree:
12//!
13//! - a client that writes the meta key itself gains nothing, since the map
14//!   has no entry for it;
15//! - a duplicated pane copies the meta key but gets a new block id, which
16//!   the map doesn't know;
17//! - the human's Take over clears the meta key; the client-write guard
18//!   (`guard_client_meta_write`) then drops the map entry, so ownership ends
19//!   for good, and no client can set the key at all;
20//! - deleting the block drops its entry (`wcore::delete_block`);
21//! - after srv restarts the map is filled again from `browser_pane_records`, for the panes whose block
22//!   still names the same owner (a Take over cleared the key; a copy has no record).
23//! - a Take over is remembered for a day, so the agent that lost the pane is told
24//!   what happened instead of guessing (`lost_message`); a pane that closed is only logged,
25//!   since a deleted block is already answered as "no such pane".
26//! - the agent gets such a pane back with `retake` once the person pressed Give back in the pane
27//!   header (relayed by the host, like every answer to a pane's banner, so no agent can give itself
28//!   the pane) or took the pane over during the agent's own hand-off; otherwise the person is still
29//!   using it and the agent is told to wait.
30
31use std::collections::HashMap;
32use std::sync::{Mutex, OnceLock};
33
34use crate::backend::obj::{Block, MetaMapType};
35
36/// Block meta key mirroring the owner, for the frontend.
37pub(crate) const OWNER_META_KEY: &str = "browser:owner_agent";
38
39/// Block meta key naming the agent that drove the pane last, written by srv whenever an agent becomes
40/// its driver and kept through the person's Take over, so the pane header can offer "Give back to X".
41pub(crate) const LAST_DRIVER_META_KEY: &str = "browser:last_driver";
42
43/// Block meta key naming the agent the person gave the pane back to (their Give back click, relayed by the
44/// host), so the retake still works after an srv restart. Cleared when an agent drives the pane again.
45pub(crate) const GIVEN_BACK_META_KEY: &str = "browser:given_back";
46
47/// Block meta key set to true while the agent that drives the pane did not open it (`take_control`), so the header
48/// says "took control". Cleared when the agent lets the pane go.
49pub(crate) const TOOK_CONTROL_META_KEY: &str = "browser:took_control";
50
51fn owners() -> &'static Mutex<HashMap<String, String>> {
52    static OWNERS: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
53    OWNERS.get_or_init(Default::default)
54}
55
56/// Record `agent_id` as the owner of `block_id`. Only `OpenBrowser` calls this.
57pub(crate) fn record(block_id: &str, agent_id: &str) {
58    lost().lock().unwrap_or_else(|p| p.into_inner()).remove(block_id);
59    // A bypass belongs to the owner it was granted to.
60    crate::server::browser_bypass::forget(block_id, "the pane got a new owner");
61    owners()
62        .lock()
63        .unwrap_or_else(|p| p.into_inner())
64        .insert(block_id.to_string(), agent_id.to_string());
65    changed().notify_one();
66}
67
68/// Put back the owner `browser_pane_records` kept across a restart, for a pane whose block still
69/// names that agent. Only the owner is restored; the take-over record and a pane's grants keep their own rules.
70pub(crate) fn restore(block_id: &str, agent_id: &str) {
71    owners().lock().unwrap_or_else(|p| p.into_inner()).insert(block_id.to_string(), agent_id.to_string());
72    changed().notify_one();
73}
74
75/// Every pane an agent owns and the agent, for `browser_pane_records`.
76pub(crate) fn all_owners() -> std::collections::BTreeMap<String, String> {
77    owners().lock().unwrap_or_else(|p| p.into_inner()).iter().map(|(k, v)| (k.clone(), v.clone())).collect()
78}
79
80/// Drop `block_id`'s owner: the pane was deleted or taken over. Its bypass,
81/// if any, ends with the ownership.
82pub(crate) fn forget(block_id: &str) {
83    forget_because(block_id, Lost::Closed);
84}
85
86/// Why an agent no longer drives a pane.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub(crate) enum Lost {
89    /// The person's Take over.
90    TookOver,
91    /// The pane was closed, or no longer exists.
92    Closed,
93}
94
95/// What srv remembers about a pane an agent lost to a Take over.
96struct LostEntry {
97    at: std::time::Instant,
98    /// Who drove it.
99    agent: String,
100    /// The person pressed Give back in the pane header.
101    given_back: bool,
102    /// A hand-off of this agent's was up when the person took the pane over: the person was
103    /// working in the pane at the agent's own request, and that request ended with the Take over.
104    during_handoff: bool,
105}
106
107/// Panes the person took over, newest few hundred. In memory like the
108/// owner map, so after an srv restart there is nothing here and the plain
109/// refusal is the right answer.
110fn lost() -> &'static Mutex<HashMap<String, LostEntry>> {
111    static LOST: OnceLock<Mutex<HashMap<String, LostEntry>>> = OnceLock::new();
112    LOST.get_or_init(Default::default)
113}
114
115const LOST_KEPT: usize = 256;
116
117/// How long a lost pane is remembered, so an agent that comes back the next day is still told what happened.
118const LOST_KEPT_FOR: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
119
120/// Drop `block_id`'s owner and remember why. Its bypass, if any, ends with the
121/// ownership, and so does a pause (the action log stays, for the person to
122/// read). Logged, so a refusal an agent reports can be traced to its cause.
123pub(crate) fn forget_because(block_id: &str, why: Lost) {
124    crate::server::browser_bypass::forget(block_id, "the agent no longer drives the pane");
125    crate::server::browser_actions::forget_pause(block_id);
126    crate::server::browser_agent_calls::forget(block_id);
127    let removed = owners()
128        .lock()
129        .unwrap_or_else(|p| p.into_inner())
130        .remove(block_id);
131    // The person's Take over ends the agent's say over where the pane is, as it does over what the page does.
132    if why == Lost::TookOver {
133        crate::server::pane_openers::forget(block_id);
134    }
135    if let Some(agent) = removed {
136        tracing::info!(pane = %block_id, agent_id = %agent, why = ?why, "[browser-owner] agent no longer drives the pane");
137        // Only a Take over is worth telling the agent about: a closed pane's block is
138        // already gone, so its next call is answered "no such pane" before this is read.
139        if why == Lost::TookOver {
140            let during_handoff = crate::server::browser_attention::waiting_on_user(block_id) == Some(crate::server::browser_attention::Kind::Handoff);
141            let mut map = lost().lock().unwrap_or_else(|p| p.into_inner());
142            map.retain(|_, e| e.at.elapsed() < LOST_KEPT_FOR);
143            if map.len() >= LOST_KEPT {
144                if let Some(oldest) = map.iter().min_by_key(|(_, e)| e.at).map(|(k, _)| k.clone()) {
145                    map.remove(&oldest);
146                }
147            }
148            map.insert(block_id.to_string(), LostEntry { at: std::time::Instant::now(), agent, given_back: false, during_handoff });
149        }
150        changed().notify_one();
151    }
152}
153
154/// How long ago, in words an agent can read.
155fn ago(d: std::time::Duration) -> String {
156    let m = d.as_secs() / 60;
157    match m {
158        0 => "just now".to_string(),
159        1..=89 => format!("{m} min ago"),
160        _ => format!("{} h ago", m / 60),
161    }
162}
163
164/// What to tell the agent that lost a pane to the person's Take over. Another
165/// agent asking about the same pane gets the plain refusal, and never learns who
166/// drove it. None after an srv restart (nothing is remembered) or for a pane the
167/// agent never opened.
168pub(crate) fn lost_message(pane: &str, agent_id: &str) -> Option<String> {
169    let map = lost().lock().unwrap_or_else(|p| p.into_inner());
170    let e = map.get(pane).filter(|e| e.agent.eq_ignore_ascii_case(agent_id) && e.at.elapsed() < LOST_KEPT_FOR)?;
171    let how = if e.given_back || e.during_handoff {
172        "The user is done with it: take it back with Browser's retake action"
173    } else {
174        "When the user presses Give back, or has left the pane alone for a minute, take it back with Browser's retake action"
175    };
176    Some(format!(
177        "the user took over pane {pane:?} ({}). {how} (same page: snapshot it first), or open a new pane with Browser's open action",
178        ago(e.at.elapsed())
179    ))
180}
181
182/// How long ago the person took `block_id` over from an agent, if srv remembers it (not after a restart).
183pub(crate) fn taken_over_ago(block_id: &str) -> Option<std::time::Duration> {
184    lost().lock().unwrap_or_else(|p| p.into_inner()).get(block_id).map(|e| e.at.elapsed())
185}
186
187/// Make the person's takeover of `block_id` `by` older, for a test of the idle rule.
188#[cfg(test)]
189pub(crate) fn age_lost(block_id: &str, by: std::time::Duration) {
190    if let Some(e) = lost().lock().unwrap_or_else(|p| p.into_inner()).get_mut(block_id) {
191        e.at = e.at.checked_sub(by).unwrap_or(e.at);
192    }
193}
194
195/// The person pressed Give back on `block_id`: the agent that lost it may retake it.
196pub(crate) fn mark_given_back(block_id: &str) {
197    if let Some(e) = lost().lock().unwrap_or_else(|p| p.into_inner()).get_mut(block_id) {
198        e.given_back = true;
199    }
200}
201
202/// How long the person must have left a pane they took over alone before the agent that lost it may drive it again.
203pub(crate) const IDLE_BEFORE_RETAKE: std::time::Duration = std::time::Duration::from_secs(60);
204
205/// The person took `block_id` over from `agent_id` and has neither given it back nor taken it over at the agent's own
206/// request: only their idleness can return it. Some(how long ago they took it over) then, so the caller knows to ask the
207/// host when they last used the pane.
208pub(crate) fn takeover_in_use(block: &Block, block_id: &str, agent_id: &str) -> Option<std::time::Duration> {
209    let given_back_to = block.meta.get(GIVEN_BACK_META_KEY).and_then(|v| v.as_str());
210    if given_back_to.is_some_and(|a| a.eq_ignore_ascii_case(agent_id)) {
211        return None;
212    }
213    let map = lost().lock().unwrap_or_else(|p| p.into_inner());
214    let e = map.get(block_id).filter(|e| e.agent.eq_ignore_ascii_case(agent_id) && e.at.elapsed() < LOST_KEPT_FOR)?;
215    (!e.given_back && !e.during_handoff).then(|| e.at.elapsed())
216}
217
218/// May `agent_id` drive `block` (`block_id`) again, the pane it lost to the person's Take over? Yes once the person
219/// gave the pane back (remembered in memory and in the block's meta, which outlives an srv restart), or took it over
220/// during the agent's own hand-off, or has not used the pane for [`IDLE_BEFORE_RETAKE`]; a pane the person is still
221/// using is refused with what to do. `since_input` is how long ago the host last saw the person use the pane's page:
222/// `Duration::MAX` when it never has, None when the host could not say (then only Give back counts). The caller then
223/// writes the owner meta (`retaken_meta`) and records the agent (`record`).
224pub(crate) fn may_retake(
225    block: &Block,
226    block_id: &str,
227    agent_id: &str,
228    since_input: Option<std::time::Duration>,
229) -> Result<(), String> {
230    let given_back_to = block.meta.get(GIVEN_BACK_META_KEY).and_then(|v| v.as_str());
231    if given_back_to.is_some_and(|a| a.eq_ignore_ascii_case(agent_id)) {
232        return Ok(());
233    }
234    let map = lost().lock().unwrap_or_else(|p| p.into_inner());
235    let Some(e) = map.get(block_id).filter(|e| e.agent.eq_ignore_ascii_case(agent_id) && e.at.elapsed() < LOST_KEPT_FOR) else {
236        return Err(format!(
237            "pane {block_id:?} is not one you lost to the user in the last 24 hours: retake gets back a pane you drove and the \
238             user took over. Open a new one with Browser's open action"
239        ));
240    };
241    if e.given_back || e.during_handoff {
242        return Ok(());
243    }
244    if person_has_left(since_input, e.at.elapsed()) {
245        return Ok(());
246    }
247    let used = since_input.map(|d| format!(", last touched {}", ago_exact(d.min(e.at.elapsed())))).unwrap_or_default();
248    Err(format!(
249        "the user took over pane {block_id:?} ({}{used}) and is using it. Wait until they press Give back or leave it alone for {} s, \
250         or ask them in chat",
251        ago(e.at.elapsed()),
252        IDLE_BEFORE_RETAKE.as_secs()
253    ))
254}
255
256/// Has the person left a pane they took over alone for [`IDLE_BEFORE_RETAKE`]? Their Take over click is their last touch
257/// if they never used the page itself. Unknown (the host could not say) is not left.
258fn person_has_left(since_input: Option<std::time::Duration>, since_takeover: std::time::Duration) -> bool {
259    since_input.is_some_and(|d| d.min(since_takeover) >= IDLE_BEFORE_RETAKE)
260}
261
262/// How long ago, to the second under a minute.
263fn ago_exact(d: std::time::Duration) -> String {
264    match d.as_secs() {
265        s @ 0..=59 => format!("{s} s ago"),
266        _ => ago(d),
267    }
268}
269
270/// The meta that shows `agent` driving a pane: the owner the header reads, and the last driver Give back names.
271pub(crate) fn driver_meta(agent: &str) -> MetaMapType {
272    let mut m = MetaMapType::new();
273    m.insert(OWNER_META_KEY.to_string(), serde_json::json!(agent));
274    m.insert(LAST_DRIVER_META_KEY.to_string(), serde_json::json!(agent));
275    m
276}
277
278/// [`driver_meta`] for an agent that drives a pane again: the Give back it used is spent.
279pub(crate) fn retaken_meta(agent: &str) -> MetaMapType {
280    let mut m = driver_meta(agent);
281    m.insert(GIVEN_BACK_META_KEY.to_string(), serde_json::Value::Null);
282    m
283}
284
285/// The meta that shows `agent` driving a pane it did not open.
286pub(crate) fn took_control_meta(agent: &str) -> MetaMapType {
287    let mut m = retaken_meta(agent);
288    m.insert(TOOK_CONTROL_META_KEY.to_string(), serde_json::json!(true));
289    m
290}
291
292/// The meta of a pane nobody drives and the person did not take over: an agent let it go (`release`).
293pub(crate) fn released_meta() -> MetaMapType {
294    [OWNER_META_KEY, LAST_DRIVER_META_KEY, GIVEN_BACK_META_KEY, TOOK_CONTROL_META_KEY]
295        .into_iter()
296        .map(|k| (k.to_string(), serde_json::Value::Null))
297        .collect()
298}
299
300/// Who drives a browser pane, for `Pane layout`: the agent's id, `person` after they took it over from an agent that
301/// has not got it back, or None for a pane no agent has driven.
302pub(crate) fn driver_of(meta: &MetaMapType) -> Option<String> {
303    let text = |k: &str| meta.get(k).and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty());
304    let gave_back = text(GIVEN_BACK_META_KEY).is_some();
305    text(OWNER_META_KEY).map(str::to_string).or_else(|| text(LAST_DRIVER_META_KEY).filter(|_| !gave_back).map(|_| "person".to_string()))
306}
307
308/// Every pane an agent owns. The host keeps a copy, to decide inside
309/// `on_before_popup` which of a pane's popups open in-app
310/// (SPEC_BROWSER_PANE_NATIVE_POPUPS_AGENT_DRIVEN_2026_10_08.md §3); it is
311/// only a hint there, since who may drive what is always checked here.
312pub(crate) fn owned_panes() -> Vec<String> {
313    let mut v: Vec<String> = owners()
314        .lock()
315        .unwrap_or_else(|p| p.into_inner())
316        .keys()
317        .cloned()
318        .collect();
319    v.sort();
320    v
321}
322
323/// Woken whenever the set of owned panes changes, or the host needs the
324/// whole set again (it registered). See `browser_host_sync`.
325pub(crate) fn changed() -> &'static tokio::sync::Notify {
326    static CHANGED: OnceLock<tokio::sync::Notify> = OnceLock::new();
327    CHANGED.get_or_init(tokio::sync::Notify::new)
328}
329
330pub(crate) fn owner_of(block_id: &str) -> Option<String> {
331    owners()
332        .lock()
333        .unwrap_or_else(|p| p.into_inner())
334        .get(block_id)
335        .cloned()
336}
337
338/// Why a caller may not drive a pane. Not an authentication failure: the
339/// caller's identity was already verified.
340#[derive(Debug, PartialEq, Eq)]
341pub(crate) enum Denied {
342    /// No such block (closed, or never existed).
343    NotFound(String),
344    /// The block exists, but this caller may not drive it.
345    Forbidden(String),
346}
347
348/// May `agent_id` drive `pane`? `block` is the pane's block as stored (None if
349/// it no longer exists) and `recorded` its entry in the owner map.
350pub(crate) fn check(
351    block: Option<&Block>,
352    recorded: Option<&str>,
353    agent_id: &str,
354    pane: &str,
355) -> Result<(), Denied> {
356    let block = block
357        .ok_or_else(|| Denied::NotFound(format!("no pane {pane:?} (it may have been closed)")))?;
358    let view = block
359        .meta
360        .get("view")
361        .and_then(|v| v.as_str())
362        .unwrap_or("");
363    if view != "browser" {
364        return Err(Denied::Forbidden(format!(
365            "pane {pane:?} is not a browser pane"
366        )));
367    }
368    if !recorded.is_some_and(|r| r.eq_ignore_ascii_case(agent_id)) {
369        if recorded.is_none() {
370            if let Some(why) = lost_message(pane, agent_id) {
371                return Err(Denied::Forbidden(why));
372            }
373        }
374        return Err(Denied::Forbidden(format!(
375            "pane {pane:?} is not a browser pane you own: an agent can drive only browser \
376             panes it opened itself with Browser's open action, and loses one the user takes over"
377        )));
378    }
379    let mirrored = block
380        .meta
381        .get(OWNER_META_KEY)
382        .and_then(|v| v.as_str())
383        .unwrap_or("");
384    if !mirrored.eq_ignore_ascii_case(agent_id) {
385        return Err(Denied::Forbidden(format!(
386            "the user took over pane {pane:?}; open a new one with Browser's open action if you still need a browser"
387        )));
388    }
389    Ok(())
390}
391
392/// Meta keys only srv writes, from its own records: who drives a pane, the
393/// banner that asks the person something, the bypass the person granted,
394/// what the agent did and whether the person paused it, what opened a
395/// popup, the sites a pane is limited to, and which agent coaches a worker.
396pub(crate) fn srv_only_keys() -> [&'static str; 13] {
397    [
398        OWNER_META_KEY,
399        LAST_DRIVER_META_KEY,
400        GIVEN_BACK_META_KEY,
401        TOOK_CONTROL_META_KEY,
402        crate::server::browser_allowlist::ALLOWED_META_KEY,
403        crate::server::browser_attention::ATTENTION_META_KEY,
404        crate::server::browser_bypass::BYPASS_META_KEY,
405        crate::server::browser_actions::ACTIONS_META_KEY,
406        crate::server::browser_actions::PAUSED_META_KEY,
407        crate::server::browser_popup::POPUP_OF_META_KEY,
408        crate::server::browser_popup::POPUP_FROM_META_KEY,
409        crate::server::browser_popup::POPUP_WINDOWS_META_KEY,
410        crate::server::app_api::agent_spawn::COACHED_BY_META_KEY,
411    ]
412}
413
414/// Remove srv-only keys from the meta a client gives a NEW block
415/// (`pane.open` over RPC or HTTP, `object.CreateBlock`). Removed rather than
416/// refused, so duplicating a pane still works: the copy is an ordinary pane,
417/// without an owner, a banner, or a claim to be a popup. srv's own callers
418/// (`OpenBrowser`, the popup route) set these keys after this check, through
419/// `open_pane` directly. Returns the keys it removed.
420pub(crate) fn strip_srv_only_keys(meta: &mut MetaMapType) -> Vec<&'static str> {
421    srv_only_keys().into_iter().filter(|k| meta.remove(*k).is_some()).collect()
422}
423
424/// Guard for meta updates that come from a client (the `setmeta` WebSocket
425/// command and the `UpdateObjectMeta` service call), not from srv itself.
426/// `browser:owner_agent` is srv's to write: a client may only clear it, which
427/// is the human's Take over and ends that pane's ownership for good. Setting
428/// or changing it is refused, so a taken-over agent can't write itself back.
429/// `browser:attention` (the hand-off and approval banner) is srv's alone:
430/// a client that could write it could keep a real request's id and change
431/// what the banner tells the human they're approving.
432pub(crate) fn guard_client_meta_write(oref: &str, meta: &MetaMapType) -> Result<(), String> {
433    // The popup keys name the pane that opened this one and its site, shown
434    // to the person as "Popup from …": a client that could write them could
435    // make any pane claim to come from a site it doesn't.
436    // The site list is the agent's limit on its pane: a client that could
437    // write it could widen it.
438    // A tab's identity is fixed when it is opened: changing it would move a
439    // live tab to another jar under the person's feet.
440    // Who coaches a worker is what the limits on forking count: a client that
441    // could write it could free a leader's slots or let a worker fork.
442    // The bypass strip shows what the person granted: a client that could
443    // write it could show a grant that doesn't exist, or hide one that does.
444    // The action log is the person's record of what the agent did, and the
445    // pause flag what they decided: a client could rewrite or hide either.
446    // Who drove the pane last and who it was given back to are what Give back and a retake rest on: a client that
447    // could write them could give a pane to an agent the person never gave it to.
448    for key in [
449        LAST_DRIVER_META_KEY,
450        GIVEN_BACK_META_KEY,
451        TOOK_CONTROL_META_KEY,
452        crate::server::browser_attention::ATTENTION_META_KEY,
453        crate::server::browser_bypass::BYPASS_META_KEY,
454        crate::server::browser_actions::ACTIONS_META_KEY,
455        crate::server::browser_actions::PAUSED_META_KEY,
456        crate::server::browser_allowlist::ALLOWED_META_KEY,
457        crate::server::browser_identity::IDENTITY_META_KEY,
458        crate::server::browser_popup::POPUP_OF_META_KEY,
459        crate::server::browser_popup::POPUP_FROM_META_KEY,
460        crate::server::browser_popup::POPUP_WINDOWS_META_KEY,
461        crate::server::app_api::agent_spawn::COACHED_BY_META_KEY,
462        // The folder a container agent's Files pane is confined to: a client that could clear it would lift the limit.
463        crate::server::files_root::FILES_ROOT_META_KEY,
464    ] {
465        if meta.contains_key(key) {
466            return Err(format!("{key} is written only by AgentMux itself"));
467        }
468    }
469    let Some(value) = meta.get(OWNER_META_KEY) else {
470        return Ok(());
471    };
472    if !value.is_null() {
473        return Err(format!(
474            "{OWNER_META_KEY} is written by AgentMux itself when an agent opens a browser pane; \
475             a client can only clear it (Take over)"
476        ));
477    }
478    if let Some(block_id) = oref.strip_prefix("block:") {
479        forget_because(block_id, Lost::TookOver);
480        // Take over also answers any hand-off or approval still up on the
481        // pane: an Approve clicked after it must not go through.
482        crate::server::browser_attention::cancel_for(block_id);
483        // And ends the site limit: the person browses freely. The header
484        // shows the limit only while an agent drives the pane, so the meta
485        // key left behind shows nothing.
486        crate::server::browser_allowlist::drop_pane(block_id);
487    }
488    Ok(())
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494    use serde_json::json;
495
496    fn block(view: &str, owner: Option<&str>) -> Block {
497        let mut b = Block::default();
498        b.meta.insert("view".to_string(), json!(view));
499        if let Some(o) = owner {
500            b.meta.insert(OWNER_META_KEY.to_string(), json!(o));
501        }
502        b
503    }
504
505    #[test]
506    fn the_opener_may_drive_its_pane() {
507        let b = block("browser", Some("lark"));
508        assert!(check(Some(&b), Some("lark"), "lark", "p1").is_ok());
509        // Agent ids compare case-insensitively, as elsewhere.
510        assert!(check(Some(&b), Some("Lark"), "lark", "p1").is_ok());
511    }
512
513    #[test]
514    fn another_agent_may_not() {
515        let b = block("browser", Some("lark"));
516        let e = check(Some(&b), Some("lark"), "korp", "p1").unwrap_err();
517        assert!(
518            matches!(&e, Denied::Forbidden(m) if m.contains("not a browser pane you own")),
519            "{e:?}"
520        );
521    }
522
523    #[test]
524    fn a_forged_meta_key_without_a_recorded_owner_is_refused() {
525        // A client wrote the meta key, or the pane was duplicated: no map entry.
526        let b = block("browser", Some("lark"));
527        assert!(check(Some(&b), None, "lark", "p1").is_err());
528    }
529
530    #[test]
531    fn take_over_clears_the_meta_key_and_ends_ownership() {
532        let b = block("browser", None);
533        let e = check(Some(&b), Some("lark"), "lark", "p1").unwrap_err();
534        assert!(
535            matches!(&e, Denied::Forbidden(m) if m.contains("took over")),
536            "{e:?}"
537        );
538    }
539
540    #[test]
541    fn only_browser_panes_and_only_existing_ones() {
542        let b = block("term", Some("lark"));
543        assert!(matches!(
544            check(Some(&b), Some("lark"), "lark", "p1"),
545            Err(Denied::Forbidden(_))
546        ));
547        assert!(matches!(
548            check(None, Some("lark"), "lark", "p1"),
549            Err(Denied::NotFound(_))
550        ));
551    }
552
553    #[test]
554    fn record_owner_of_and_forget() {
555        record("test-block-browser-owner-rt", "lark");
556        assert_eq!(
557            owner_of("test-block-browser-owner-rt").as_deref(),
558            Some("lark")
559        );
560        assert_eq!(owner_of("test-block-browser-owner-unknown"), None);
561        forget("test-block-browser-owner-rt");
562        assert_eq!(owner_of("test-block-browser-owner-rt"), None);
563    }
564
565    fn meta(key: &str, v: serde_json::Value) -> MetaMapType {
566        let mut m = MetaMapType::new();
567        m.insert(key.to_string(), v);
568        m
569    }
570
571    #[test]
572    fn a_client_cannot_set_the_owner_key() {
573        // The taken-over agent writing itself back, or any client faking an owner.
574        let e =
575            guard_client_meta_write("block:test-guard-set", &meta(OWNER_META_KEY, json!("lark")))
576                .unwrap_err();
577        assert!(e.contains("only clear it"), "{e}");
578    }
579
580    #[test]
581    fn a_client_clearing_the_owner_key_ends_ownership_for_good() {
582        record("test-guard-clear", "lark");
583        guard_client_meta_write(
584            "block:test-guard-clear",
585            &meta(OWNER_META_KEY, serde_json::Value::Null),
586        )
587        .unwrap();
588        assert_eq!(owner_of("test-guard-clear"), None);
589        // Even if the key were somehow written back, the map no longer agrees.
590        let b = block("browser", Some("lark"));
591        assert!(check(
592            Some(&b),
593            owner_of("test-guard-clear").as_deref(),
594            "lark",
595            "test-guard-clear"
596        )
597        .is_err());
598    }
599
600    #[test]
601    fn a_client_cannot_write_the_banner_at_all() {
602        // Rewriting a real request's banner (same id, harmless-looking text)
603        // would make the human approve something they weren't shown.
604        let key = crate::server::browser_attention::ATTENTION_META_KEY;
605        let forged = json!({ "id": "real-id", "kind": "approval", "what": "Click \"Cancel\"" });
606        assert!(guard_client_meta_write("block:test-guard-attn", &meta(key, forged)).is_err());
607        assert!(guard_client_meta_write("block:test-guard-attn", &meta(key, serde_json::Value::Null)).is_err());
608    }
609
610    #[test]
611    fn a_client_cannot_write_the_bypass_strip() {
612        let key = crate::server::browser_bypass::BYPASS_META_KEY;
613        let forged = json!({ "agent": "lark", "origins": ["https://github.com"], "expires_at": 0 });
614        assert!(guard_client_meta_write("block:test-guard-bypass", &meta(key, forged)).is_err());
615        assert!(guard_client_meta_write("block:test-guard-bypass", &meta(key, serde_json::Value::Null)).is_err());
616        let mut m = MetaMapType::new();
617        m.insert(key.into(), json!({ "agent": "lark" }));
618        assert_eq!(strip_srv_only_keys(&mut m), vec![key]);
619    }
620
621    #[test]
622    fn a_client_cannot_write_the_action_log_or_the_pause() {
623        use crate::server::browser_actions::{ACTIONS_META_KEY, PAUSED_META_KEY};
624        for key in [ACTIONS_META_KEY, PAUSED_META_KEY] {
625            assert!(guard_client_meta_write("block:test-guard-log", &meta(key, json!({ "count": 0, "entries": [] }))).is_err());
626            assert!(guard_client_meta_write("block:test-guard-log", &meta(key, serde_json::Value::Null)).is_err());
627            let mut m = MetaMapType::new();
628            m.insert(key.into(), json!(true));
629            assert_eq!(strip_srv_only_keys(&mut m), vec![key]);
630        }
631    }
632
633    #[test]
634    fn take_over_ends_a_bypass() {
635        record("test-guard-bypass-end", "lark");
636        crate::server::browser_bypass::tests_put("test-guard-bypass-end", "lark");
637        assert!(crate::server::browser_bypass::active_for("test-guard-bypass-end", "lark").is_some());
638        guard_client_meta_write("block:test-guard-bypass-end", &meta(OWNER_META_KEY, serde_json::Value::Null)).unwrap();
639        assert!(crate::server::browser_bypass::active_for("test-guard-bypass-end", "lark").is_none());
640    }
641
642    #[test]
643    fn a_client_cannot_write_the_popup_keys() {
644        use crate::server::browser_popup::{POPUP_FROM_META_KEY, POPUP_OF_META_KEY, POPUP_WINDOWS_META_KEY};
645        for key in [POPUP_OF_META_KEY, POPUP_FROM_META_KEY, POPUP_WINDOWS_META_KEY] {
646            assert!(guard_client_meta_write("block:test-guard-popup", &meta(key, json!("x"))).is_err());
647            assert!(guard_client_meta_write("block:test-guard-popup", &meta(key, serde_json::Value::Null)).is_err());
648        }
649    }
650
651    #[test]
652    fn a_new_block_from_a_client_starts_without_srv_only_keys() {
653        let mut m = MetaMapType::new();
654        m.insert("view".into(), json!("browser"));
655        m.insert("url".into(), json!("https://example.com"));
656        m.insert(OWNER_META_KEY.into(), json!("lark"));
657        m.insert(crate::server::browser_popup::POPUP_FROM_META_KEY.into(), json!("https://bank.example"));
658        m.insert(crate::server::browser_popup::POPUP_OF_META_KEY.into(), json!("some-pane"));
659        let mut removed = strip_srv_only_keys(&mut m);
660        removed.sort();
661        assert_eq!(removed, vec!["browser:owner_agent", "browser:popup_from", "browser:popup_of"]);
662        assert_eq!(m.len(), 2);
663        assert!(strip_srv_only_keys(&mut m).is_empty());
664    }
665
666    #[test]
667    fn other_meta_writes_pass_untouched() {
668        record("test-guard-other", "lark");
669        guard_client_meta_write(
670            "block:test-guard-other",
671            &meta("url", json!("https://example.com")),
672        )
673        .unwrap();
674        assert_eq!(owner_of("test-guard-other").as_deref(), Some("lark"));
675        forget("test-guard-other");
676    }
677
678    fn null_owner() -> MetaMapType {
679        let mut m = MetaMapType::new();
680        m.insert(OWNER_META_KEY.to_string(), serde_json::Value::Null);
681        m
682    }
683
684    #[test]
685    fn a_take_over_is_named_in_the_agents_next_refusal() {
686        let pane = uuid::Uuid::new_v4().to_string();
687        record(&pane, "lark");
688        guard_client_meta_write(&format!("block:{pane}"), &null_owner()).unwrap();
689        assert!(owner_of(&pane).is_none());
690        let e = check(Some(&block("browser", None)), None, "lark", &pane).unwrap_err();
691        assert!(
692            matches!(&e, Denied::Forbidden(m) if m.contains("the user took over pane") && m.contains("just now")),
693            "{e:?}"
694        );
695    }
696
697    #[test]
698    fn another_agent_is_not_told_who_lost_the_pane() {
699        let pane = uuid::Uuid::new_v4().to_string();
700        record(&pane, "lark");
701        guard_client_meta_write(&format!("block:{pane}"), &null_owner()).unwrap();
702        let e = check(Some(&block("browser", None)), None, "korp", &pane).unwrap_err();
703        assert!(
704            matches!(&e, Denied::Forbidden(m) if m.contains("not a browser pane you own") && !m.contains("lark") && !m.contains("took over")),
705            "{e:?}"
706        );
707    }
708
709    #[test]
710    fn a_pane_that_closed_leaves_no_take_over_note() {
711        let pane = uuid::Uuid::new_v4().to_string();
712        record(&pane, "lark");
713        forget(&pane);
714        assert!(owner_of(&pane).is_none());
715        assert!(lost_message(&pane, "lark").is_none());
716    }
717
718    #[test]
719    fn a_pane_never_owned_gets_the_plain_refusal() {
720        let pane = uuid::Uuid::new_v4().to_string();
721        let e = check(Some(&block("browser", None)), None, "lark", &pane).unwrap_err();
722        assert!(matches!(&e, Denied::Forbidden(m) if m.contains("not a browser pane you own")), "{e:?}");
723    }
724
725    #[test]
726    fn a_new_owner_forgets_the_old_reason() {
727        let pane = uuid::Uuid::new_v4().to_string();
728        record(&pane, "lark");
729        guard_client_meta_write(&format!("block:{pane}"), &null_owner()).unwrap();
730        assert!(lost_message(&pane, "lark").is_some());
731        record(&pane, "korp");
732        assert!(lost_message(&pane, "lark").is_none());
733        forget(&pane);
734    }
735
736    #[test]
737    fn a_taken_over_pane_is_retaken_only_after_give_back() {
738        let pane = uuid::Uuid::new_v4().to_string();
739        let oref = format!("block:{pane}");
740        let b = block("browser", None);
741        assert!(may_retake(&b, &pane, "lark", None).is_err(), "a pane never driven");
742        record(&pane, "lark");
743        guard_client_meta_write(&oref, &null_owner()).unwrap();
744        let e = may_retake(&b, &pane, "lark", None).unwrap_err();
745        assert!(e.contains("is using it") && e.contains("Give back"), "{e}");
746        assert!(may_retake(&b, &pane, "korp", None).is_err(), "another agent never lost it");
747        mark_given_back(&pane);
748        assert!(may_retake(&b, &pane, "lark", None).is_ok());
749        assert!(may_retake(&b, &pane, "LARK", None).is_ok(), "agent ids compare without case");
750        assert!(may_retake(&b, &pane, "korp", None).is_err(), "given back to lark, not to korp");
751        record(&pane, "lark");
752        assert!(may_retake(&b, &pane, "lark", None).is_err(), "retaken: nothing left to retake");
753        forget(&pane);
754    }
755
756    /// The person's Give back is in the block's meta, so an srv restart (which forgets the lost record) does not undo it.
757    #[test]
758    fn a_give_back_in_the_blocks_meta_survives_a_restart() {
759        let pane = uuid::Uuid::new_v4().to_string();
760        let mut b = block("browser", None);
761        b.meta.insert(GIVEN_BACK_META_KEY.to_string(), json!("lark"));
762        assert!(may_retake(&b, &pane, "lark", None).is_ok());
763        assert!(may_retake(&b, &pane, "korp", None).is_err(), "given back to lark only");
764        assert!(retaken_meta("lark").get(GIVEN_BACK_META_KEY).is_some_and(|v| v.is_null()), "driving again spends it");
765    }
766
767    #[test]
768    fn the_person_has_left_after_a_minute_of_no_input_and_no_takeover_click() {
769        use std::time::Duration as D;
770        assert!(person_has_left(Some(D::from_secs(61)), D::from_secs(300)), "idle 61 s");
771        assert!(!person_has_left(Some(D::from_secs(5)), D::from_secs(300)), "typed 5 s ago");
772        assert!(!person_has_left(Some(D::from_secs(600)), D::from_secs(10)), "took over 10 s ago");
773        assert!(person_has_left(Some(D::MAX), D::from_secs(61)), "never used the page; took over 61 s ago");
774        assert!(!person_has_left(Some(D::MAX), D::from_secs(59)), "never used the page; took over 59 s ago");
775        assert!(!person_has_left(None, D::from_secs(3600)), "the host could not say");
776    }
777
778    #[test]
779    fn a_takeover_in_use_is_told_from_one_given_back_or_made_at_a_hand_off() {
780        let pane = uuid::Uuid::new_v4().to_string();
781        let b = block("browser", None);
782        assert!(takeover_in_use(&b, &pane, "lark").is_none(), "never lost");
783        record(&pane, "lark");
784        guard_client_meta_write(&format!("block:{pane}"), &null_owner()).unwrap();
785        assert!(takeover_in_use(&b, &pane, "lark").is_some());
786        assert!(takeover_in_use(&b, &pane, "korp").is_none(), "another agent");
787        let err = may_retake(&b, &pane, "lark", Some(std::time::Duration::from_secs(4))).unwrap_err();
788        assert!(err.contains("last touched 0 s ago") && err.contains("60 s"), "{err}");  // took over just now
789        mark_given_back(&pane);
790        assert!(takeover_in_use(&b, &pane, "lark").is_none(), "given back");
791        record(&pane, "lark");
792        forget(&pane);
793    }
794
795    #[test]
796    fn the_agent_is_told_how_to_get_the_pane_back() {
797        let pane = uuid::Uuid::new_v4().to_string();
798        record(&pane, "lark");
799        guard_client_meta_write(&format!("block:{pane}"), &null_owner()).unwrap();
800        let waiting = lost_message(&pane, "lark").unwrap();
801        assert!(waiting.contains("When the user presses Give back") && waiting.contains("retake"), "{waiting}");
802        mark_given_back(&pane);
803        let given = lost_message(&pane, "lark").unwrap();
804        assert!(given.contains("The user is done with it") && given.contains("retake"), "{given}");
805        record(&pane, "lark");
806        forget(&pane);
807    }
808
809    #[test]
810    fn a_client_cannot_write_the_last_driver_or_the_give_back() {
811        for key in [LAST_DRIVER_META_KEY, GIVEN_BACK_META_KEY, TOOK_CONTROL_META_KEY] {
812            assert!(guard_client_meta_write("block:test-guard-last", &meta(key, json!("lark"))).is_err(), "{key}");
813            assert!(guard_client_meta_write("block:test-guard-last", &meta(key, serde_json::Value::Null)).is_err(), "{key}");
814            let mut m = MetaMapType::new();
815            m.insert(key.into(), json!("lark"));
816            assert_eq!(strip_srv_only_keys(&mut m), vec![key], "a new pane from a client has neither");
817        }
818    }
819
820    #[test]
821    fn who_drives_a_pane_is_the_agent_the_person_or_nobody() {
822        let mut m = MetaMapType::new();
823        assert_eq!(driver_of(&m), None, "never driven");
824        m.insert(OWNER_META_KEY.into(), json!("lark"));
825        m.insert(LAST_DRIVER_META_KEY.into(), json!("lark"));
826        assert_eq!(driver_of(&m).as_deref(), Some("lark"));
827        m.insert(OWNER_META_KEY.into(), serde_json::Value::Null);
828        assert_eq!(driver_of(&m).as_deref(), Some("person"), "taken over from lark");
829        m.insert(GIVEN_BACK_META_KEY.into(), json!("lark"));
830        assert_eq!(driver_of(&m), None, "given back: nobody drives it");
831        m.remove(GIVEN_BACK_META_KEY);
832        for (k, v) in released_meta() {
833            assert!(v.is_null(), "{k}");
834            m.insert(k, v);
835        }
836        assert_eq!(driver_of(&m), None, "released");
837        let took = took_control_meta("lark");
838        assert_eq!(took.get(TOOK_CONTROL_META_KEY), Some(&json!(true)));
839        assert_eq!(took.get(OWNER_META_KEY), Some(&json!("lark")));
840        assert!(took.get(GIVEN_BACK_META_KEY).is_some_and(|v| v.is_null()));
841    }
842
843    #[test]
844    fn an_agent_driving_shows_as_owner_and_last_driver() {
845        let m = driver_meta("lark");
846        assert_eq!(m.get(OWNER_META_KEY), Some(&json!("lark")));
847        assert_eq!(m.get(LAST_DRIVER_META_KEY), Some(&json!("lark")));
848    }
849
850    #[test]
851    fn how_long_ago_reads_in_words() {
852        use std::time::Duration;
853        assert_eq!(ago(Duration::from_secs(5)), "just now");
854        assert_eq!(ago(Duration::from_secs(61 * 60)), "61 min ago");
855        assert_eq!(ago(Duration::from_secs(5 * 3600)), "5 h ago");
856    }
857}