Skip to main content

agentmux_srv/server/
browser_attention.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's browser pane asking the human for something: a hand-off
5//! (sign in, a CAPTCHA, anything the agent mustn't do) or approval of a
6//! committing action (submit, send, pay, delete)
7//! (docs/specs/SPEC_AGENT_DRIVEN_BROWSER_PANES_2026_10_07.md §5.2, §5.4).
8//!
9//! The request is shown as a banner in the pane through the block's
10//! `browser:attention` meta key. The human's answer comes back only through
11//! the CEF host (`/api/v1/host/browser_attention`, authenticated with the
12//! host's IPC token, which agents never see): an agent can't answer its own
13//! request, even though it holds the instance auth key every other route
14//! trusts.
15//!
16//! A pane's slot has two levels (REPORT_BROWSER_PANE_BLANK_AFTER_BLOCKED_SIGN_IN_REDIRECT_RCA_2026_10_16.md
17//! §6.1): below, one hand-off, approval, auto-approve question or page
18//! dialog; above it, one question or notice about a navigation the pane
19//! stopped. A sign-in redirect during a hand-off is asked about over the
20//! hand-off, whose banner returns when it's answered.
21
22use std::collections::HashMap;
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::sync::{Mutex, OnceLock};
25use std::time::Duration;
26
27use serde_json::{json, Value};
28use tokio::sync::oneshot;
29
30use crate::server::AppState;
31
32/// Block meta key the browser pane's banner reads.
33pub(crate) const ATTENTION_META_KEY: &str = "browser:attention";
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub(crate) enum Kind {
37    Handoff,
38    Approval,
39    /// The page tried to leave the sites the pane is limited to
40    /// (SPEC_BROWSER_PANE_ALLOWED_ORIGINS_2026_10_09.md §4).
41    Navigation,
42    /// The agent asks to act without asking for a while
43    /// (SPEC_BROWSER_PANE_BYPASS_2026_10_16.md §6).
44    Bypass,
45    /// The page's own confirm or "Leave site?" box
46    /// (SPEC_BROWSER_PANE_NATIVE_DIALOGS_2026_10_17.md §5).
47    Dialog,
48    /// The agent typed a line in a web terminal and the person's grant says to
49    /// ask before Enter (SPEC_BROWSER_WEB_TERMINAL_TYPING_2026_10_23.md §4.4).
50    Line,
51    /// An agent that did not open the pane asks to drive it
52    /// (SPEC_BROWSER_RETAKE_AND_COMMANDEER_2026_11_04.md §2.3).
53    Take,
54    /// Why a navigation the pane stopped didn't load. Nothing waits on it:
55    /// it doesn't pause the agent's tools or time out.
56    Notice,
57}
58
59impl Kind {
60    fn as_str(self) -> &'static str {
61        match self {
62            Kind::Handoff => "handoff",
63            Kind::Approval => "approval",
64            Kind::Navigation => "navigation",
65            Kind::Bypass => "bypass",
66            Kind::Dialog => "dialog",
67            Kind::Line => "line",
68            Kind::Take => "take",
69            Kind::Notice => "notice",
70        }
71    }
72
73    /// The slot's upper level: about a navigation the pane stopped, shown
74    /// over whatever the pane already waits on.
75    fn on_top(self) -> bool {
76        matches!(self, Kind::Navigation | Kind::Notice)
77    }
78
79    /// Why the agent's tools on `pane` are refused while a request of this
80    /// kind is up.
81    pub(crate) fn tools_paused(self, pane: &str) -> String {
82        let why = match self {
83            Kind::Handoff => format!("the user is working in pane {pane:?} (your Browser handoff)"),
84            Kind::Approval => format!("pane {pane:?} is waiting for the user to approve your click"),
85            Kind::Navigation => format!(
86                "the page in pane {pane:?} tried to leave its allowed_origins and the user is being asked whether to allow it"
87            ),
88            Kind::Bypass => format!("pane {pane:?} is asking the user whether to auto-approve your clicks"),
89            Kind::Dialog => format!(
90                "the page in pane {pane:?} is showing its own question (a confirm or \"Leave site?\" box) and the user is being asked to answer it"
91            ),
92            Kind::Line => format!("pane {pane:?} is showing the user the terminal line you typed and waiting for Run it or Don't run"),
93            Kind::Take => format!("pane {pane:?} is asking the user whether another agent may drive it"),
94            // Never pauses anything (`waiting_on_user`); named for completeness.
95            Kind::Notice => format!("pane {pane:?} is showing the user why a navigation stopped"),
96        };
97        let until = if self == Kind::Handoff { "they click Done or Cancel" } else { "they answer" };
98        format!("{why}; your tools on it are paused until {until}")
99    }
100}
101
102/// The human's answer, or the lack of one.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub(crate) enum Answer {
105    /// Done (hand-off) or Approve (approval).
106    Yes,
107    /// Approve, and keep it: the person answered an auto-approve request with
108    /// "Always for this agent on this site", which writes a standing row
109    /// (`browser_standing`). Only that request takes it ([`resolve`]).
110    YesAlways,
111    /// Allow, but ask about each terminal line: the person answered an
112    /// auto-approve request that asked for the terminal with its stricter form.
113    /// Only that request takes it ([`resolve`]).
114    YesAsking,
115    Cancelled,
116    TimedOut,
117}
118
119impl Answer {
120    pub(crate) fn parse(decision: &str) -> Option<Answer> {
121        match decision {
122            "done" | "approve" => Some(Answer::Yes),
123            "approve_always" => Some(Answer::YesAlways),
124            "approve_ask" => Some(Answer::YesAsking),
125            "cancel" => Some(Answer::Cancelled),
126            _ => None,
127        }
128    }
129}
130
131/// How a request ended: the human's answer, or the lack of one, and whether the agent that asked took the
132/// request back itself ([`withdraw`]). Both are written in the one step that settles the request, so whoever
133/// waits on it reads who ended it from the answer, not from a table kept somewhere else.
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub(crate) struct Settled {
136    pub(crate) answer: Answer,
137    pub(crate) by_agent: bool,
138}
139
140impl From<Answer> for Settled {
141    fn from(answer: Answer) -> Settled {
142        Settled { answer, by_agent: false }
143    }
144}
145
146/// Why a request couldn't be put up. Callers handle each: a busy slot must
147/// never turn into silence (RCA §7.2).
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub(crate) enum AskError {
150    /// The pane's slot for this kind is taken, by a request of `kind`.
151    Busy { kind: Kind },
152    /// The banner couldn't be written to the pane.
153    NotShown(String),
154}
155
156impl std::fmt::Display for AskError {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        match self {
159            AskError::Busy { kind } => write!(f, "this pane is already waiting for the user (its pending request: {})", kind.as_str()),
160            AskError::NotShown(e) => write!(f, "couldn't show the request in the pane: {e}"),
161        }
162    }
163}
164
165impl AskError {
166    /// What a route answers the agent with: wait and retry, or a fault.
167    pub(crate) fn status(&self) -> axum::http::StatusCode {
168        match self {
169            AskError::Busy { .. } => axum::http::StatusCode::CONFLICT,
170            AskError::NotShown(_) => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
171        }
172    }
173}
174
175struct Pending {
176    block_id: String,
177    kind: Kind,
178    /// Taken by the first answer. The entry itself stays until the asker's
179    /// [`Waiting`] is dropped, so the pane stays locked until it's done.
180    tx: Option<oneshot::Sender<Settled>>,
181    /// The banner it shows, kept so it can come back when a question shown
182    /// over it is answered.
183    banner: Value,
184    /// Arrival order: on one level, the newest request shows.
185    seq: u64,
186}
187
188fn pending() -> &'static Mutex<HashMap<String, Pending>> {
189    static P: OnceLock<Mutex<HashMap<String, Pending>>> = OnceLock::new();
190    P.get_or_init(Default::default)
191}
192
193fn next_seq() -> u64 {
194    static SEQ: AtomicU64 = AtomicU64::new(0);
195    SEQ.fetch_add(1, Ordering::Relaxed)
196}
197
198/// What `block_id` is waiting on the human for, if anything. While it
199/// waits, the agent's tools on that pane are refused: during a hand-off so
200/// it can't watch what the human types (§5.2), during an approval so it
201/// can't change the form the human is reading (§5.4). A notice holds
202/// nothing. With a question over another request, the one under it is named:
203/// it holds the pane longest.
204pub(crate) fn waiting_on_user(block_id: &str) -> Option<Kind> {
205    pending()
206        .lock()
207        .unwrap_or_else(|p| p.into_inner())
208        .values()
209        .filter(|p| p.block_id == block_id && p.kind != Kind::Notice)
210        .min_by_key(|p| p.kind.on_top())
211        .map(|p| p.kind)
212}
213
214/// The panes with a request of `kind` up.
215pub(crate) fn asking(kind: Kind) -> Vec<String> {
216    pending()
217        .lock()
218        .unwrap_or_else(|p| p.into_inner())
219        .values()
220        .filter(|p| p.kind == kind)
221        .map(|p| p.block_id.clone())
222        .collect()
223}
224
225/// Resolve request `id` on `block_id` with the human's answer. Called only
226/// by the host-authenticated route.
227pub(crate) fn resolve(id: &str, block_id: &str, answer: Answer) -> Result<(), String> {
228    settle(id, block_id, answer.into())
229}
230
231/// The agent that asked takes request `id` on `block_id` back: it ends as Cancelled, marked as the agent's own
232/// doing ([`Settled::by_agent`]) in the same step that takes the answer, so a person's Cancel that got there
233/// first is never read as the agent's, and the other way round. Fails like [`resolve`] when the request is
234/// already answered.
235pub(crate) fn withdraw(id: &str, block_id: &str) -> Result<(), String> {
236    settle(id, block_id, Settled { answer: Answer::Cancelled, by_agent: true })
237}
238
239fn settle(id: &str, block_id: &str, settled: Settled) -> Result<(), String> {
240    let answer = settled.answer;
241    let mut map = pending().lock().unwrap_or_else(|p| p.into_inner());
242    let tx = match map.get_mut(id) {
243        Some(p) if p.block_id == block_id && answer == Answer::YesAlways && p.kind != Kind::Bypass => {
244            return Err("only an auto-approve request can be answered with Always".to_string());
245        }
246        Some(p) if p.block_id == block_id && answer == Answer::YesAsking && p.kind != Kind::Bypass => {
247            return Err("only an auto-approve request can be answered with Allow, asking for each line".to_string());
248        }
249        Some(p) if p.block_id == block_id => p.tx.take(),
250        Some(_) => return Err("that request belongs to another pane".to_string()),
251        None => return Err("no such request (it may have timed out)".to_string()),
252    };
253    let Some(tx) = tx else {
254        return Err("that request was already answered".to_string());
255    };
256    let _ = tx.send(settled);
257    Ok(())
258}
259
260/// Answer every request waiting on `block_id` with Cancelled: the user took
261/// the pane over, which ends whatever the agent was waiting for there.
262pub(crate) fn cancel_for(block_id: &str) {
263    let mut map = pending().lock().unwrap_or_else(|p| p.into_inner());
264    for p in map.values_mut().filter(|p| p.block_id == block_id) {
265        if let Some(tx) = p.tx.take() {
266            let _ = tx.send(Answer::Cancelled.into());
267        }
268    }
269}
270
271/// Answer `block_id`'s unanswered request of `kind`, if any, with Cancelled:
272/// what it asked about ended on its own (a page dialog whose page navigated).
273pub(crate) fn cancel_kind_for(block_id: &str, kind: Kind) {
274    let mut map = pending().lock().unwrap_or_else(|p| p.into_inner());
275    for p in map.values_mut().filter(|p| p.block_id == block_id && p.kind == kind) {
276        if let Some(tx) = p.tx.take() {
277            let _ = tx.send(Answer::Cancelled.into());
278        }
279    }
280}
281
282/// A request that is still up. Dropping it takes the request down: it
283/// leaves the pending map, which unlocks the pane, and the banner shows what
284/// is left (the request under it, or nothing). That happens on every path,
285/// including when the waiting HTTP handler is cancelled because its caller
286/// went away.
287pub(crate) struct Waiting {
288    state: AppState,
289    id: String,
290    block_id: String,
291    kind: Kind,
292}
293
294impl Drop for Waiting {
295    fn drop(&mut self) {
296        // Removing the entry and showing what's left happen under one hold
297        // of the lock, so a new request on the pane can't publish its banner
298        // in between and lose it.
299        let mut map = pending().lock().unwrap_or_else(|p| p.into_inner());
300        map.remove(&self.id);
301        if let Err(e) = show(&self.state, &map, &self.block_id) {
302            tracing::debug!(pane = %self.block_id, error = %e, "[browser-attention] banner not updated");
303        }
304        drop(map);
305        if self.kind == Kind::Handoff {
306            crate::server::browser_owner::changed().notify_one();
307        }
308    }
309}
310
311/// Show `block_id`'s banner from its requests: the newest unanswered one,
312/// the upper level first. With none unanswered, the banner already shown
313/// stays while its request is still being acted on (an approved click being
314/// made), so an answered banner never comes back. Called with the map
315/// locked, so two changes can't publish out of order.
316fn show(state: &AppState, map: &HashMap<String, Pending>, block_id: &str) -> Result<(), String> {
317    let shown = state
318        .mstore
319        .get::<crate::backend::obj::Block>(block_id)
320        .ok()
321        .flatten()
322        .and_then(|b| b.meta.get(ATTENTION_META_KEY).and_then(|v| v.get("id")).and_then(|v| v.as_str()).map(str::to_string));
323    let top = map
324        .iter()
325        .filter(|(_, p)| p.block_id == block_id && p.tx.is_some())
326        .max_by_key(|(_, p)| (p.kind.on_top(), p.seq));
327    let want = match top {
328        Some((id, p)) => Some((id.as_str(), p.banner.clone())),
329        None if shown.as_deref().is_some_and(|s| map.get(s).is_some_and(|p| p.block_id == block_id)) => return Ok(()),
330        None => None,
331    };
332    if want.as_ref().map(|(id, _)| *id) == shown.as_deref() {
333        return Ok(());
334    }
335    let mut meta = crate::backend::obj::MetaMapType::new();
336    meta.insert(ATTENTION_META_KEY.to_string(), want.map(|(_, b)| b).unwrap_or(Value::Null));
337    crate::server::http_shell::broadcast_meta_update(state, block_id, &meta).map(|_| ())
338}
339
340/// The human answered a banner srv has no request for (srv restarted, so its
341/// requests are gone but the block meta persisted): take that banner down,
342/// so its buttons don't sit there doing nothing. Host-authenticated callers only.
343pub(crate) fn clear_stale(state: &AppState, block_id: &str, id: &str) {
344    let map = pending().lock().unwrap_or_else(|p| p.into_inner());
345    if map.contains_key(id) {
346        return;
347    }
348    let _ = show(state, &map, block_id);
349}
350
351/// Whether a new request of `kind` on `block_id` must wait, and on which
352/// kind. Each level holds one request at a time, except that a page dialog
353/// may follow one already answered (the approved click opened it). A notice
354/// holds nothing and is replaced by anything new, but doesn't cover a
355/// navigation question still unanswered.
356fn slot_taken(map: &HashMap<String, Pending>, block_id: &str, kind: Kind) -> Option<Kind> {
357    map.values()
358        .filter(|p| p.block_id == block_id && p.kind != Kind::Notice)
359        .find(|p| match kind {
360            Kind::Notice => p.kind == Kind::Navigation && p.tx.is_some(),
361            Kind::Dialog => !p.kind.on_top() && p.tx.is_some(),
362            _ => p.kind.on_top() == kind.on_top(),
363        })
364        .map(|p| p.kind)
365}
366
367/// A request put up in its pane's banner, not yet answered.
368pub(crate) struct Raised {
369    rx: oneshot::Receiver<Settled>,
370    waiting: Waiting,
371    _asking: Option<crate::backend::user_attention::Asking>,
372}
373
374impl Raised {
375    /// The request's id: what its banner carries, and what `Browser handoff_status` asks about.
376    pub(crate) fn id(&self) -> &str {
377        &self.waiting.id
378    }
379
380    /// The human's answer if it comes within `grace`; else the request itself, still up and unanswered, to
381    /// wait on further ([`Raised::answer`]) from a task of its own: the caller's call ends, the banner stays.
382    pub(crate) async fn answer_within(self, grace: Duration) -> Result<(Answer, Waiting), Raised> {
383        self.settled_within(grace).await.map(|(settled, waiting)| (settled.answer, waiting))
384    }
385
386    /// [`Raised::answer_within`], with who ended the request too.
387    pub(crate) async fn settled_within(mut self, grace: Duration) -> Result<(Settled, Waiting), Raised> {
388        match tokio::time::timeout(grace, &mut self.rx).await {
389            Ok(Ok(settled)) => Ok((settled, self.waiting)),
390            Ok(Err(_)) => Ok((Answer::Cancelled.into(), self.waiting)),
391            Err(_) => Err(self),
392        }
393    }
394
395    /// The human's answer, after up to `timeout` (`None`: no limit). A
396    /// request taken down without one (replaced, or its pane closed) reads
397    /// as Cancelled. The pane stays as it is until the returned [`Waiting`]
398    /// is dropped.
399    pub(crate) async fn answer(self, timeout: Option<Duration>) -> (Answer, Waiting) {
400        let (settled, waiting) = self.settled(timeout).await;
401        (settled.answer, waiting)
402    }
403
404    /// [`Raised::answer`], with who ended the request too: `by_agent` only for a request its agent took
405    /// back ([`withdraw`]).
406    pub(crate) async fn settled(self, timeout: Option<Duration>) -> (Settled, Waiting) {
407        let Raised { rx, waiting, _asking } = self;
408        let settled = match timeout {
409            Some(t) => match tokio::time::timeout(t, rx).await {
410                Ok(Ok(a)) => a,
411                Ok(Err(_)) => Answer::Cancelled.into(),
412                Err(_) => {
413                    // Settled as answered, like any other answer: a late click
414                    // finds it over, and the slot is free for what follows
415                    // (a notice saying nobody answered) while `waiting` lives.
416                    let mut map = pending().lock().unwrap_or_else(|p| p.into_inner());
417                    if let Some(p) = map.get_mut(&waiting.id) {
418                        p.tx = None;
419                    }
420                    Answer::TimedOut.into()
421                }
422            },
423            None => rx.await.unwrap_or(Answer::Cancelled.into()),
424        };
425        (settled, waiting)
426    }
427}
428
429/// Put `payload` up in `block_id`'s banner as a request of `kind`, without
430/// waiting for the answer: the caller learns at once whether the slot was
431/// free. A notice on the pane is replaced.
432pub(crate) fn raise(state: &AppState, block_id: &str, agent_id: &str, kind: Kind, payload: Value) -> Result<Raised, AskError> {
433    let id = uuid::Uuid::new_v4().to_string();
434    let (tx, rx) = oneshot::channel();
435    let mut banner = json!({ "id": id, "kind": kind.as_str(), "agent": agent_id });
436    if let (Some(b), Some(p)) = (banner.as_object_mut(), payload.as_object()) {
437        for (k, v) in p {
438            b.insert(k.clone(), v.clone());
439        }
440    }
441    let mut map = pending().lock().unwrap_or_else(|p| p.into_inner());
442    if let Some(busy) = slot_taken(&map, block_id, kind) {
443        return Err(AskError::Busy { kind: busy });
444    }
445    // Its sender goes with it: the notice's own wait ends as dismissed.
446    map.retain(|_, p| !(p.block_id == block_id && p.kind == Kind::Notice));
447    let pending = Pending { block_id: block_id.to_string(), kind, tx: Some(tx), banner: banner.clone(), seq: next_seq() };
448    map.insert(id.clone(), pending);
449    let waiting = Waiting { state: state.clone(), id, block_id: block_id.to_string(), kind };
450    let shown = show(state, &map, block_id);
451    // Unlocked before `waiting` can drop, which locks it again.
452    drop(map);
453    shown.map_err(AskError::NotShown)?;
454    if kind != Kind::Notice {
455        crate::server::browser_sessions::reveal_for_prompt(state, block_id);
456    }
457    // The host leaves a page's dialogs to the person during a hand-off
458    // (dialogs spec §4.3): it learns of one from the next push.
459    if kind == Kind::Handoff {
460        crate::server::browser_owner::changed().notify_one();
461    }
462    // The pane waits on the user until they answer or it times out: the
463    // waiting tone and notification for it
464    // (REPORT_AGENT_ATTENTION_CTA_CONTRAST_AND_TONE_2026_10_10.md §2). A
465    // notice waits on nobody.
466    let _asking = (kind != Kind::Notice).then(|| {
467        let what = ["reason", "what", "origin"]
468            .iter()
469            .find_map(|k| banner.get(*k).and_then(|v| v.as_str()))
470            .unwrap_or("")
471            .to_string();
472        let who = if agent_id.is_empty() { "An agent" } else { agent_id };
473        let text = if what.is_empty() { format!("{who} needs you") } else { format!("{who} needs you: {what}") };
474        crate::backend::user_attention::Asking::start(&state.broker, &state.mstore, block_id, "browser", &text)
475    });
476    Ok(Raised { rx, waiting, _asking })
477}
478
479/// Show `payload` in `block_id`'s banner and wait for the human, up to
480/// `timeout`. The pane stays locked until the returned [`Waiting`] is
481/// dropped, so a caller that acts on a Yes holds it until that action is
482/// done. See [`slot_taken`] for what may be up at the same time.
483pub(crate) async fn ask(
484    state: &AppState,
485    block_id: &str,
486    agent_id: &str,
487    kind: Kind,
488    payload: Value,
489    timeout: Duration,
490) -> Result<(Answer, Waiting), AskError> {
491    Ok(raise(state, block_id, agent_id, kind, payload)?.answer(Some(timeout)).await)
492}
493
494#[cfg(test)]
495pub(crate) mod tests {
496    use super::*;
497
498    fn park(id: &str, block: &str, kind: Kind) -> oneshot::Receiver<Settled> {
499        let (tx, rx) = oneshot::channel();
500        let p = Pending { block_id: block.to_string(), kind, tx: Some(tx), banner: json!({ "id": id }), seq: next_seq() };
501        pending().lock().unwrap().insert(id.to_string(), p);
502        rx
503    }
504
505    /// A browser pane in `state`'s store, for the banner to be written to.
506    pub(crate) fn browser_block(state: &AppState, id: &str) {
507        let mut meta = crate::backend::obj::MetaMapType::new();
508        meta.insert("view".to_string(), json!("browser"));
509        let mut block = crate::backend::obj::Block {
510            oid: id.to_string(),
511            parentoref: String::new(),
512            version: 1,
513            runtimeopts: None,
514            stickers: None,
515            meta,
516            subblockids: None,
517        };
518        state.mstore.insert(&mut block).unwrap();
519    }
520
521    pub(crate) fn banner(state: &AppState, id: &str) -> Value {
522        let block = state.mstore.must_get::<crate::backend::obj::Block>(id).unwrap();
523        block.meta.get(ATTENTION_META_KEY).cloned().unwrap_or(Value::Null)
524    }
525
526    #[test]
527    fn a_navigation_question_may_come_over_a_handoff_but_not_over_another() {
528        let _h = park("attn-test-10", "pane-k", Kind::Handoff);
529        let taken = |kind: Kind| slot_taken(&pending().lock().unwrap(), "pane-k", kind);
530        assert_eq!(taken(Kind::Navigation), None, "the upper level is free");
531        assert_eq!(taken(Kind::Approval), Some(Kind::Handoff), "the lower one isn't");
532        let _n = park("attn-test-11", "pane-k", Kind::Navigation);
533        assert_eq!(taken(Kind::Navigation), Some(Kind::Navigation), "one question about a navigation at a time");
534        assert_eq!(taken(Kind::Notice), Some(Kind::Navigation), "a notice doesn't cover an unanswered question");
535        // The hand-off is what the pane is locked for.
536        assert_eq!(waiting_on_user("pane-k"), Some(Kind::Handoff));
537        pending().lock().unwrap().remove("attn-test-10");
538        assert_eq!(waiting_on_user("pane-k"), Some(Kind::Navigation));
539        pending().lock().unwrap().remove("attn-test-11");
540    }
541
542    #[test]
543    fn a_notice_locks_nothing_and_holds_no_slot() {
544        let _rx = park("attn-test-12", "pane-l", Kind::Notice);
545        assert_eq!(waiting_on_user("pane-l"), None, "the agent's tools aren't paused");
546        let taken = |kind: Kind| slot_taken(&pending().lock().unwrap(), "pane-l", kind);
547        for kind in [Kind::Handoff, Kind::Approval, Kind::Navigation, Kind::Dialog, Kind::Notice] {
548            assert_eq!(taken(kind), None, "{kind:?}");
549        }
550        pending().lock().unwrap().remove("attn-test-12");
551    }
552
553    #[test]
554    fn a_busy_slot_names_what_holds_it() {
555        let e = AskError::Busy { kind: Kind::Handoff };
556        assert!(e.to_string().contains("already waiting") && e.to_string().contains("handoff"), "{e}");
557    }
558
559    // The RCA's headline (§6.4), at this level: a question over a hand-off
560    // shows, and when it's answered the hand-off's banner returns while the
561    // hand-off itself still waits.
562    #[tokio::test]
563    async fn the_handoff_banner_returns_after_a_question_over_it() {
564        let state = crate::server::tests::test_state();
565        let pane = uuid::Uuid::new_v4().to_string();
566        browser_block(&state, &pane);
567        let handoff = raise(&state, &pane, "agent-m", Kind::Handoff, json!({ "reason": "sign in" })).unwrap();
568        let h_id = banner(&state, &pane)["id"].as_str().unwrap().to_string();
569        let handoff_wait = tokio::spawn(handoff.answer(Some(Duration::from_secs(30))));
570        let question = raise(&state, &pane, "agent-m", Kind::Navigation, json!({ "origin": "https://b.example" })).unwrap();
571        let shown = banner(&state, &pane);
572        assert_eq!(shown["kind"], "navigation");
573        assert!(matches!(
574            raise(&state, &pane, "agent-m", Kind::Navigation, json!({})),
575            Err(AskError::Busy { kind: Kind::Navigation })
576        ));
577        resolve(shown["id"].as_str().unwrap(), &pane, Answer::Yes).unwrap();
578        let (answer, waiting) = question.answer(Some(Duration::from_secs(5))).await;
579        assert_eq!(answer, Answer::Yes);
580        drop(waiting);
581        let back = banner(&state, &pane);
582        assert_eq!((back["kind"].as_str(), back["id"].as_str()), (Some("handoff"), Some(h_id.as_str())));
583        assert_eq!(back["reason"], "sign in");
584        assert!(!handoff_wait.is_finished(), "the hand-off still waits");
585        assert_eq!(waiting_on_user(&pane), Some(Kind::Handoff));
586        resolve(&h_id, &pane, Answer::Yes).unwrap();
587        let (answer, waiting) = handoff_wait.await.unwrap();
588        assert_eq!(answer, Answer::Yes);
589        drop(waiting);
590        assert!(banner(&state, &pane).is_null());
591    }
592
593    // A request nobody answers in time is settled like an answered one: a
594    // late click finds it over, and the notice saying so can go up while its
595    // asker still holds the pane.
596    #[tokio::test]
597    async fn a_request_that_times_out_is_settled_as_answered() {
598        let state = crate::server::tests::test_state();
599        let pane = uuid::Uuid::new_v4().to_string();
600        browser_block(&state, &pane);
601        let question = raise(&state, &pane, "", Kind::Navigation, json!({ "origin": "https://b.example" })).unwrap();
602        let id = banner(&state, &pane)["id"].as_str().unwrap().to_string();
603        let (answer, waiting) = question.answer(Some(Duration::from_millis(50))).await;
604        assert_eq!(answer, Answer::TimedOut);
605        assert_eq!(resolve(&id, &pane, Answer::Yes), Err("that request was already answered".to_string()));
606        assert_eq!(slot_taken(&pending().lock().unwrap(), &pane, Kind::Notice), None);
607        let notice = raise(&state, &pane, "", Kind::Notice, json!({ "why": "Nobody answered." })).unwrap();
608        assert_eq!(banner(&state, &pane)["kind"], "notice");
609        drop(waiting);
610        assert_eq!(banner(&state, &pane)["kind"], "notice", "the question going away leaves the notice up");
611        drop(notice);
612        assert!(banner(&state, &pane).is_null());
613    }
614
615    #[tokio::test]
616    async fn a_new_request_replaces_a_notice() {
617        let state = crate::server::tests::test_state();
618        let pane = uuid::Uuid::new_v4().to_string();
619        browser_block(&state, &pane);
620        let notice = raise(&state, &pane, "", Kind::Notice, json!({ "why": "You blocked it." })).unwrap();
621        assert_eq!(banner(&state, &pane)["kind"], "notice");
622        let notice_wait = tokio::spawn(notice.answer(None));
623        let approval = raise(&state, &pane, "agent-n", Kind::Approval, json!({ "what": "Click \"Send\"" })).unwrap();
624        assert_eq!(banner(&state, &pane)["kind"], "approval");
625        // The notice's own wait ends, as dismissed, without taking the approval down.
626        let (answer, waiting) = notice_wait.await.unwrap();
627        assert_eq!(answer, Answer::Cancelled);
628        drop(waiting);
629        assert_eq!(banner(&state, &pane)["kind"], "approval");
630        drop(approval);
631        assert!(banner(&state, &pane).is_null());
632    }
633
634    #[test]
635    fn decisions_parse() {
636        assert_eq!(Answer::parse("done"), Some(Answer::Yes));
637        assert_eq!(Answer::parse("approve"), Some(Answer::Yes));
638        assert_eq!(Answer::parse("cancel"), Some(Answer::Cancelled));
639        assert_eq!(Answer::parse("yes please"), None);
640    }
641
642    #[tokio::test]
643    async fn resolve_answers_the_waiting_request_once() {
644        let rx = park("attn-test-1", "pane-a", Kind::Approval);
645        resolve("attn-test-1", "pane-a", Answer::Yes).unwrap();
646        assert_eq!(rx.await.unwrap().answer, Answer::Yes);
647        assert!(resolve("attn-test-1", "pane-a", Answer::Yes).is_err(), "single use");
648        // Answered, but the asker hasn't finished acting on it: still locked.
649        assert_eq!(waiting_on_user("pane-a"), Some(Kind::Approval));
650        pending().lock().unwrap().remove("attn-test-1");
651    }
652
653    #[tokio::test]
654    async fn take_over_cancels_what_the_pane_waits_for() {
655        let rx = park("attn-test-5", "pane-f", Kind::Approval);
656        let _other = park("attn-test-6", "pane-g", Kind::Approval);
657        cancel_for("pane-f");
658        assert_eq!(rx.await.unwrap().answer, Answer::Cancelled);
659        // A late Approve finds the request already answered.
660        assert!(resolve("attn-test-5", "pane-f", Answer::Yes).is_err());
661        // Another pane's request is untouched.
662        assert!(resolve("attn-test-6", "pane-g", Answer::Yes).is_ok());
663        pending().lock().unwrap().remove("attn-test-5");
664        pending().lock().unwrap().remove("attn-test-6");
665    }
666
667    #[test]
668    fn only_an_auto_approve_request_takes_allow_but_ask_for_each_line() {
669        let _a = park("attn-test-ask-1", "pane-ask", Kind::Approval);
670        let e = resolve("attn-test-ask-1", "pane-ask", Answer::YesAsking).unwrap_err();
671        assert!(e.contains("auto-approve"), "{e}");
672        pending().lock().unwrap().remove("attn-test-ask-1");
673        let _b = park("attn-test-ask-2", "pane-ask", Kind::Bypass);
674        assert!(resolve("attn-test-ask-2", "pane-ask", Answer::YesAsking).is_ok());
675        pending().lock().unwrap().remove("attn-test-ask-2");
676        assert_eq!(Answer::parse("approve_ask"), Some(Answer::YesAsking));
677    }
678
679    #[test]
680    fn a_request_is_answered_only_for_its_own_pane() {
681        let _rx = park("attn-test-2", "pane-b", Kind::Approval);
682        assert!(resolve("attn-test-2", "pane-other", Answer::Yes).is_err());
683        pending().lock().unwrap().remove("attn-test-2");
684    }
685
686    #[test]
687    fn a_page_dialog_may_follow_an_answered_request_only() {
688        let _rx = park("attn-test-7", "pane-h", Kind::Approval);
689        let busy = |kind: Kind| slot_taken(&pending().lock().unwrap(), "pane-h", kind).is_some();
690        assert!(busy(Kind::Dialog), "the approval is still up");
691        resolve("attn-test-7", "pane-h", Answer::Yes).unwrap();
692        assert!(!busy(Kind::Dialog), "approved, and the click it allowed opened the dialog");
693        assert!(busy(Kind::Handoff), "anything else still waits its turn");
694        pending().lock().unwrap().remove("attn-test-7");
695    }
696
697    #[tokio::test]
698    async fn a_dialog_that_ended_is_cancelled() {
699        let rx = park("attn-test-8", "pane-i", Kind::Dialog);
700        let _other = park("attn-test-9", "pane-j", Kind::Dialog);
701        cancel_kind_for("pane-i", Kind::Approval);
702        cancel_kind_for("pane-i", Kind::Dialog);
703        assert_eq!(rx.await.unwrap().answer, Answer::Cancelled);
704        assert!(resolve("attn-test-9", "pane-j", Answer::Yes).is_ok());
705        pending().lock().unwrap().remove("attn-test-8");
706        pending().lock().unwrap().remove("attn-test-9");
707    }
708
709    #[test]
710    fn a_pending_request_of_either_kind_locks_the_pane() {
711        let _rx = park("attn-test-3", "pane-c", Kind::Handoff);
712        assert_eq!(waiting_on_user("pane-c"), Some(Kind::Handoff));
713        assert_eq!(waiting_on_user("pane-d"), None);
714        pending().lock().unwrap().remove("attn-test-3");
715        assert_eq!(waiting_on_user("pane-c"), None);
716        let _rx = park("attn-test-4", "pane-e", Kind::Approval);
717        assert_eq!(waiting_on_user("pane-e"), Some(Kind::Approval));
718        pending().lock().unwrap().remove("attn-test-4");
719    }
720
721    #[tokio::test]
722    async fn a_cancelled_hand_off_leaves_the_agent_its_pane() {
723        // Naki-2's Cloud Shell run (2026-10-23): the person cancelled a hand-off. Only Take over ends ownership.
724        let pane = uuid::Uuid::new_v4().to_string();
725        crate::server::browser_owner::record(&pane, "lark");
726        let rx = park("attn-test-handoff-cancel", &pane, Kind::Handoff);
727        resolve("attn-test-handoff-cancel", &pane, Answer::Cancelled).unwrap();
728        assert_eq!(rx.await.unwrap().answer, Answer::Cancelled);
729        assert_eq!(crate::server::browser_owner::owner_of(&pane).as_deref(), Some("lark"));
730        pending().lock().unwrap().remove("attn-test-handoff-cancel");
731        crate::server::browser_owner::forget(&pane);
732    }
733
734    #[tokio::test]
735    async fn a_request_the_agent_takes_back_says_so_in_its_answer_and_a_person_who_answered_first_stands() {
736        let rx = park("attn-test-withdraw-1", "pane-w1", Kind::Approval);
737        withdraw("attn-test-withdraw-1", "pane-w1").unwrap();
738        assert_eq!(rx.await.unwrap(), Settled { answer: Answer::Cancelled, by_agent: true });
739        assert!(withdraw("attn-test-withdraw-1", "pane-w1").is_err(), "single use");
740
741        let rx = park("attn-test-withdraw-2", "pane-w2", Kind::Approval);
742        resolve("attn-test-withdraw-2", "pane-w2", Answer::Cancelled).unwrap();
743        assert!(withdraw("attn-test-withdraw-2", "pane-w2").is_err(), "the person got there first");
744        assert_eq!(rx.await.unwrap(), Settled { answer: Answer::Cancelled, by_agent: false });
745
746        let rx = park("attn-test-withdraw-3", "pane-w3", Kind::Approval);
747        withdraw("attn-test-withdraw-3", "pane-w3").unwrap();
748        assert!(resolve("attn-test-withdraw-3", "pane-w3", Answer::Cancelled).is_err(), "the agent's cancel settled it");
749        assert_eq!(rx.await.unwrap().by_agent, true);
750        assert!(withdraw("attn-test-withdraw-4", "pane-w3").is_err(), "no such request");
751        let _rx = park("attn-test-withdraw-5", "pane-w5", Kind::Approval);
752        assert!(withdraw("attn-test-withdraw-5", "pane-other").is_err(), "another pane's request");
753    }
754}