1use std::sync::Arc;
23
24use crate::backend::notify::policy::{Family, FocusReport};
25use crate::backend::notify::router;
26use crate::backend::rpc::engine::WshRpcEngine;
27use crate::backend::rpc_types::{AgentShutdownNowResult, CommandAgentShutdownNowData, RpcContext, COMMAND_AGENT_SHUTDOWN_NOW};
28
29use super::AppState;
30
31#[derive(serde::Deserialize, ts_rs::TS)]
34#[serde(rename_all = "snake_case")]
35#[ts(export, export_to = "../../../frontend/types/rpc/")]
36pub enum NotifyPaneEvent {
37 TurnStarted,
41 TurnCompleted,
43 TurnErrored,
45 TurnStopped,
47 InputWaiting,
48 InputResolved,
49}
50
51#[derive(serde::Deserialize, ts_rs::TS)]
52#[ts(export, export_to = "../../../frontend/types/rpc/")]
53pub struct NotifyEmitParams {
54 pub block_id: String,
55 pub event: NotifyPaneEvent,
56 #[ts(optional)]
57 pub question: Option<String>,
58 #[ts(optional)]
60 pub question_count: Option<u32>,
61}
62
63#[derive(serde::Deserialize, ts_rs::TS)]
64#[ts(export, export_to = "../../../frontend/types/rpc/")]
65pub struct NotifyFocusParams {
66 pub window_focused: bool,
67 #[ts(optional)]
68 pub block_id: Option<String>,
69 #[ts(optional)]
71 pub window_id: Option<String>,
72}
73
74#[derive(serde::Deserialize, ts_rs::TS)]
75#[ts(export, export_to = "../../../frontend/types/rpc/")]
76pub struct NotifyAckParams {
77 pub id: String,
78 pub clicked: bool,
79 #[serde(default)]
83 #[ts(optional)]
84 pub action: Option<String>,
85 #[serde(default)]
88 #[ts(optional)]
89 pub proof: Option<String>,
90}
91
92#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
95#[ts(export, export_to = "../../../frontend/types/rpc/")]
96pub struct NotifyAttentionResult {
97 pub attention: Vec<crate::backend::user_attention::UserAttentionEvent>,
98}
99
100#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
101#[ts(export, export_to = "../../../frontend/types/rpc/")]
102pub struct NotifyAckResult {
103 pub has_window: bool,
106 #[serde(default)]
108 pub known: bool,
109 #[serde(default, skip_serializing_if = "Option::is_none")]
111 #[ts(optional)]
112 pub window_id: Option<String>,
113 #[serde(default, skip_serializing_if = "Option::is_none")]
115 #[ts(optional)]
116 pub workspace_id: Option<String>,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
120 #[ts(optional)]
121 pub kept: Option<String>,
122}
123
124#[derive(serde::Deserialize, ts_rs::TS)]
125#[ts(export, export_to = "../../../frontend/types/rpc/")]
126pub struct NotifyTakeActivationParams {
127 #[serde(default)]
130 #[ts(optional)]
131 pub workspace_id: Option<String>,
132}
133
134#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
135#[ts(export, export_to = "../../../frontend/types/rpc/")]
136pub struct NotifyTakeActivationResult {
137 #[ts(optional)]
138 pub block_id: Option<String>,
139 #[ts(optional)]
140 pub tab_id: Option<String>,
141}
142
143#[derive(serde::Deserialize, ts_rs::TS)]
144#[ts(export, export_to = "../../../frontend/types/rpc/")]
145pub struct NotifyNoArgs {}
146
147#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
148#[ts(export, export_to = "../../../frontend/types/rpc/")]
149pub struct NotifyOk {
150 pub ok: bool,
151}
152
153#[derive(serde::Deserialize, ts_rs::TS)]
154#[ts(export, export_to = "../../../frontend/types/rpc/")]
155pub struct BlockRevealParams {
156 pub block_id: String,
157 #[serde(default)]
161 #[ts(optional)]
162 pub await_ack: Option<bool>,
163 #[serde(default)]
167 #[ts(optional)]
168 pub open_if_closed: Option<bool>,
169}
170
171#[derive(serde::Deserialize, ts_rs::TS)]
173#[ts(export, export_to = "../../../frontend/types/rpc/")]
174pub struct BlockRevealedParams {
175 pub request_id: String,
177 pub ok: bool,
178 #[serde(default)]
180 #[ts(optional)]
181 pub reason: Option<String>,
182}
183
184#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
185#[ts(export, export_to = "../../../frontend/types/rpc/")]
186pub struct BlockRevealedResult {
187 pub delivered: bool,
189}
190
191const REVEAL_ACK_WAIT: std::time::Duration = std::time::Duration::from_millis(2000);
194
195#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
196#[ts(export, export_to = "../../../frontend/types/rpc/")]
197pub struct BlockRevealResult {
198 pub found: bool,
201 #[serde(default, skip_serializing_if = "Option::is_none")]
203 #[ts(optional)]
204 pub window_id: Option<String>,
205 #[serde(default, skip_serializing_if = "Option::is_none")]
208 #[ts(optional)]
209 pub revealed: Option<bool>,
210 #[serde(default, skip_serializing_if = "Option::is_none")]
212 #[ts(optional)]
213 pub reason: Option<String>,
214 #[serde(default, skip_serializing_if = "Option::is_none")]
217 #[ts(optional)]
218 pub workspace_id: Option<String>,
219}
220
221pub(crate) fn router_for(state: &AppState) -> Arc<router::Router> {
222 router::init(state.broker.clone(), state.config_watcher.clone(), state.mstore.clone(), state.reactive_handler)
223}
224
225pub(crate) async fn reveal_block(
231 state: &AppState,
232 r: &Arc<router::Router>,
233 block_id: String,
234 await_ack: bool,
235) -> Result<BlockRevealResult, String> {
236 if block_id.is_empty() {
237 return Err("block.reveal: block_id required".to_string());
238 }
239 let rr = r.clone();
240 let target = tokio::task::spawn_blocking(move || rr.reveal_target(&block_id))
241 .await
242 .map_err(|e| format!("block.reveal: {e}"))?;
243 let Some(target) = target else {
244 return Ok(BlockRevealResult { found: false, window_id: None, revealed: None, reason: None, workspace_id: None });
245 };
246 activate_in_stored_layout(state, &target.tab_id, &target.block_id).await;
247 let mut target = target;
248 let waiting = await_ack.then(|| {
250 let id = uuid::Uuid::new_v4().to_string();
251 let rx = r.expect_reveal_ack(&id);
252 target.request_id = Some(id.clone());
253 (id, rx)
254 });
255 r.publish_block_reveal(&target);
256 let (mut revealed, mut reason) = (None, None);
257 if let Some((id, rx)) = waiting {
258 match tokio::time::timeout(REVEAL_ACK_WAIT, rx).await {
259 Ok(Ok(ack)) => (revealed, reason) = (Some(ack.ok), ack.reason),
260 _ => r.forget_reveal_ack(&id),
261 }
262 }
263 Ok(BlockRevealResult { found: true, window_id: Some(target.window_id), revealed, reason, workspace_id: None })
264}
265
266async fn block_reveal(state: &AppState, r: &Arc<router::Router>, p: BlockRevealParams) -> Result<BlockRevealResult, String> {
269 let mut res = reveal_block(state, r, p.block_id.clone(), p.await_ack == Some(true)).await?;
270 if !res.found && p.open_if_closed == Some(true) {
271 let (rr, block_id) = (r.clone(), p.block_id);
272 res.workspace_id = tokio::task::spawn_blocking(move || rr.park_activation_for_closed_workspace(&block_id))
273 .await
274 .map_err(|e| format!("block.reveal: {e}"))?;
275 }
276 Ok(res)
277}
278
279async fn activate_in_stored_layout(state: &AppState, tab_id: &str, block_id: &str) {
284 let events = crate::server::service::dispatch_to_reducer(
285 state,
286 agentmux_common::ipc::Command::LayoutStackActivate {
287 tab_id: tab_id.to_string(),
288 block_id: block_id.to_string(),
289 correlation_id: String::new(),
290 },
291 )
292 .await;
293 if let Some(msg) = events.iter().find_map(|e| match e {
294 agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
295 _ => None,
296 }) {
297 tracing::debug!(block_id, "block.reveal: stored layout not updated: {msg}");
298 return;
299 }
300 for ev in &events {
301 if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore) {
302 tracing::warn!(block_id, "block.reveal: mstore apply failed: {e}");
303 }
304 }
305 crate::server::service::publish_events(state, &events);
306}
307
308fn press_from_toast(state: &AppState, r: &Arc<router::Router>, notification_id: &str, action: &str, proof: Option<&str>) -> Option<String> {
315 let (kind, block_id, request_id) = r.live_by_id(notification_id)?;
316 press_for(state, kind, &block_id, &request_id?, action, proof)
317}
318
319fn launcher_proven(state: &AppState, proof: Option<&str>) -> bool {
322 crate::server::service::host_caller_allowed(state.host_reg_secret.as_deref(), proof.unwrap_or(""))
323}
324
325fn press_for(
332 state: &AppState,
333 kind: crate::backend::notify::policy::NotifyKind,
334 block_id: &str,
335 request_id: &str,
336 action: &str,
337 proof: Option<&str>,
338) -> Option<String> {
339 if kind != crate::backend::notify::policy::NotifyKind::ShutdownPending {
340 return None;
341 }
342 let sensitive = block_id.starts_with(crate::sagas::sensitive_window::TOAST_GROUP_PREFIX);
343 if action == "keep" && !sensitive {
344 return Some(crate::sagas::pending_shutdown::keep(state, block_id, request_id).to_string());
345 }
346 if !launcher_proven(state, proof) {
347 tracing::warn!(block_id, action, "notify.ack: a press that decides a countdown came without the launcher's proof; ignored");
348 return Some("refused".to_string());
349 }
350 let outcome = match (action, sensitive) {
351 ("keep", true) => crate::sagas::sensitive_window::veto(state, request_id),
352 ("now", true) => crate::sagas::sensitive_window::approve_now(request_id),
353 ("now", false) => crate::sagas::pending_shutdown::close_now(state, block_id, request_id),
354 _ => return None,
355 };
356 Some(outcome.to_string())
357}
358
359pub fn register_notify_handlers(engine: &Arc<WshRpcEngine>, state: &AppState, conn_id: String) {
360 let state_now = state.clone();
361 engine.register_typed(COMMAND_AGENT_SHUTDOWN_NOW, move |cmd: CommandAgentShutdownNowData, ctx| {
362 let state = state_now.clone();
363 async move { shutdown_now(&state, &ctx, cmd) }
364 });
365 let r = router_for(state);
366
367 let rr = r.clone();
368 engine.register_typed("notify.emit", move |p: NotifyEmitParams, _ctx| {
369 let r = rr.clone();
370 async move { notify_emit(&r, p) }
371 });
372
373 let rr = r.clone();
374 let conn = conn_id.clone();
375 engine.register_typed("notify.focus", move |p: NotifyFocusParams, _ctx| {
376 let r = rr.clone();
377 let conn = conn.clone();
378 async move { notify_focus(&r, &conn, p) }
379 });
380
381 let rr = r.clone();
382 let ack_state = state.clone();
383 engine.register_typed("notify.ack", move |p: NotifyAckParams, _ctx| {
384 let r = rr.clone();
385 let state = ack_state.clone();
386 async move { notify_ack(&state, &r, p).await }
387 });
388
389 engine.register_typed("notify.attention", |_p: NotifyNoArgs, _ctx| async move { Ok(notify_attention()) });
390
391 let rr = r.clone();
392 engine.register_typed("notify.test", move |_p: NotifyNoArgs, _ctx| {
393 let r = rr.clone();
394 async move { notify_test(&r) }
395 });
396
397 let rr = r.clone();
398 engine.register_typed("notify.takeactivation", move |p: NotifyTakeActivationParams, _ctx| {
399 let r = rr.clone();
400 async move { notify_take_activation(&r, p) }
401 });
402
403 let rr = r.clone();
404 let st = state.clone();
405 engine.register_typed("block.reveal", move |p: BlockRevealParams, _ctx| {
406 let r = rr.clone();
407 let st = st.clone();
408 async move { block_reveal(&st, &r, p).await }
409 });
410 let rr = r;
411 engine.register_typed("block.revealed", move |p: BlockRevealedParams, _ctx| {
412 let r = rr.clone();
413 async move { block_revealed(&r, p) }
414 });
415}
416
417pub(crate) fn shutdown_now(
420 state: &AppState,
421 ctx: &RpcContext,
422 cmd: CommandAgentShutdownNowData,
423) -> Result<AgentShutdownNowResult, String> {
424 ctx.operator_only("only the person can close an agent before its countdown ends")?;
425 let outcome = crate::sagas::pending_shutdown::close_now(state, &cmd.blockid, &cmd.request_id);
426 Ok(AgentShutdownNowResult { outcome: outcome.to_string() })
427}
428
429pub(crate) fn notify_emit(r: &Arc<router::Router>, p: NotifyEmitParams) -> Result<NotifyOk, String> {
431 if p.block_id.is_empty() {
432 return Err("notify.emit: block_id required".to_string());
433 }
434 match p.event {
439 NotifyPaneEvent::TurnStarted | NotifyPaneEvent::TurnCompleted | NotifyPaneEvent::TurnErrored => {}
442 NotifyPaneEvent::TurnStopped => {
443 crate::backend::user_stop::note_user_stop(&p.block_id);
447 r.turn_stopped_nonblocking(&p.block_id)
448 }
449 NotifyPaneEvent::InputResolved => r.resolve_nonblocking(&p.block_id, Family::Input),
450 NotifyPaneEvent::InputWaiting => {
451 r.input_waiting_nonblocking(&p.block_id, p.question, p.question_count.unwrap_or(0) as usize)
452 }
453 }
454 Ok(NotifyOk { ok: true })
455}
456
457pub(crate) fn notify_focus(r: &Arc<router::Router>, conn_id: &str, p: NotifyFocusParams) -> Result<NotifyOk, String> {
459 r.focus(
460 conn_id,
461 FocusReport {
462 window_focused: p.window_focused,
463 block_id: p.block_id.filter(|b| !b.is_empty()),
464 window_id: p.window_id.filter(|w| !w.is_empty()),
465 },
466 );
467 Ok(NotifyOk { ok: true })
468}
469
470pub(crate) async fn notify_ack(
472 state: &AppState,
473 r: &Arc<router::Router>,
474 p: NotifyAckParams,
475) -> Result<NotifyAckResult, String> {
476 let kept = match p.action.as_deref() {
477 Some(action @ ("keep" | "now")) => press_from_toast(state, r, &p.id, action, p.proof.as_deref()),
478 _ => None,
479 };
480 let clicked = p.clicked && p.action.is_none();
482 let r = r.clone();
484 let o = tokio::task::spawn_blocking(move || r.ack(&p.id, clicked))
485 .await
486 .map_err(|e| format!("notify.ack: {e}"))?;
487 Ok(NotifyAckResult { has_window: o.has_window, known: o.known, window_id: o.window_id, workspace_id: o.workspace_id, kept })
488}
489
490pub(crate) fn notify_attention() -> NotifyAttentionResult {
493 NotifyAttentionResult { attention: crate::backend::user_attention::open_requests() }
494}
495
496pub(crate) fn notify_test(r: &Arc<router::Router>) -> Result<NotifyOk, String> {
498 r.test();
499 Ok(NotifyOk { ok: true })
500}
501
502pub(crate) fn notify_take_activation(
504 r: &Arc<router::Router>,
505 p: NotifyTakeActivationParams,
506) -> Result<NotifyTakeActivationResult, String> {
507 let taken = r.take_pending_activation(p.workspace_id.as_deref().filter(|w| !w.is_empty()));
508 Ok(NotifyTakeActivationResult {
509 block_id: taken.as_ref().map(|t| t.block_id.clone()),
510 tab_id: taken.map(|t| t.tab_id),
511 })
512}
513
514pub(crate) fn block_revealed(r: &Arc<router::Router>, p: BlockRevealedParams) -> Result<BlockRevealedResult, String> {
516 let ack = router::RevealAck { ok: p.ok, reason: p.reason.filter(|s| !s.is_empty()) };
517 Ok(BlockRevealedResult { delivered: r.reveal_acked(&p.request_id, ack) })
518}
519
520#[cfg(test)]
521mod block_reveal_tests {
522 use std::sync::{Arc, Mutex};
523
524 use agentmux_common::ipc::{Command, Event};
525
526 use crate::backend::mps::MuxEvent;
527 use crate::backend::notify::policy::FocusReport;
528 use crate::backend::notify::router::{self, BlockRevealEvent, EVENT_BLOCK_REVEAL};
529 use crate::backend::obj::Window;
530 use crate::server::AppState;
531 use crate::server::tests::dispatch_apply;
532
533 struct Fixture {
534 state: AppState,
535 router: Arc<router::Router>,
536 tab_id: String,
537 a: String,
539 b: String,
540 window_id: String,
541 workspace_id: String,
542 reveals: Arc<Mutex<Vec<serde_json::Value>>>,
543 }
544
545 async fn fixture(open: bool) -> Fixture {
549 let state = crate::server::tests::test_state();
550 let ws_id = dispatch_apply(&state, Command::CreateWorkspace { name: "w".into() })
551 .await
552 .iter()
553 .find_map(|e| match e {
554 Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
555 _ => None,
556 })
557 .unwrap();
558 let tab_id = dispatch_apply(&state, Command::CreateTab { workspace_id: ws_id.clone(), name: "t".into() })
559 .await
560 .iter()
561 .find_map(|e| match e {
562 Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
563 _ => None,
564 })
565 .unwrap();
566 let mut ids = Vec::new();
567 for _ in 0..2 {
568 let id = dispatch_apply(&state, Command::CreateBlock { tab_id: tab_id.clone(), meta: serde_json::Value::Null })
569 .await
570 .iter()
571 .find_map(|e| match e {
572 Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
573 _ => None,
574 })
575 .unwrap();
576 ids.push(id);
577 }
578 let (a, b) = (ids[0].clone(), ids[1].clone());
579 dispatch_apply(
580 &state,
581 Command::LayoutSetTree {
582 tab_id: tab_id.clone(),
583 new_tree: Some(agentmux_common::LayoutNode {
584 id: "pane".into(),
585 data: Some(agentmux_common::LayoutNodeData {
586 block_id: a.clone(),
587 block_stack: vec![a.clone(), b.clone()],
588 active_block_id: a.clone(),
589 ..Default::default()
590 }),
591 ..Default::default()
592 }),
593 correlation_id: String::new(),
594 slices: None,
595 },
596 )
597 .await;
598 let mut window = state.mstore.get_all::<Window>().unwrap().into_iter().next().expect("seeded window");
600 window.oid = uuid::Uuid::new_v4().to_string();
601 window.workspaceid = ws_id.clone();
602 state.mstore.insert(&mut window).unwrap();
603
604 let reveals = Arc::new(Mutex::new(Vec::new()));
605 let rec = reveals.clone();
606 state.broker.add_observer(Arc::new(move |ev: &MuxEvent| {
607 if ev.event == EVENT_BLOCK_REVEAL {
608 rec.lock().unwrap().push(ev.data.clone().unwrap_or_default());
609 }
610 }));
611 let r = super::router_for(&state);
612 if open {
613 r.focus("conn-1", FocusReport { window_focused: false, block_id: None, window_id: Some(window.oid.clone()) });
614 }
615 Fixture { state, router: r, tab_id, a, b, window_id: window.oid, workspace_id: ws_id, reveals }
616 }
617
618 #[tokio::test]
619 async fn reveals_a_background_pane_tab_in_the_window_showing_it() {
620 let f = fixture(true).await;
621 let res = super::reveal_block(&f.state, &f.router, f.b.clone(), false).await.unwrap();
622 assert!(res.found);
623 assert_eq!(res.window_id.as_deref(), Some(f.window_id.as_str()));
624
625 let tree = f.state.srv_state.lock().await.tabs[&f.tab_id].rootnode.clone().unwrap();
627 let data = tree.data.as_ref().unwrap();
628 assert_eq!((data.block_id.as_str(), data.active_block_id.as_str()), (f.b.as_str(), f.b.as_str()));
629 let tab = f.state.mstore.must_get::<crate::backend::obj::Tab>(&f.tab_id).unwrap();
630 let layout = f.state.mstore.must_get::<crate::backend::obj::LayoutState>(&tab.layoutstate).unwrap();
631 assert_eq!(layout.rootnode.as_ref(), Some(&tree), "db_layout has b active");
632
633 let reveals = f.reveals.lock().unwrap().clone();
635 assert_eq!(reveals.len(), 1, "{reveals:?}");
636 let ev: BlockRevealEvent = serde_json::from_value(reveals[0].clone()).unwrap();
637 assert_eq!(ev, BlockRevealEvent { block_id: f.b.clone(), tab_id: f.tab_id.clone(), window_id: f.window_id.clone(), request_id: None });
638 }
639
640 async fn told_request_id(f: &Fixture) -> String {
642 loop {
643 if let Some(v) = f.reveals.lock().unwrap().first().cloned() {
644 let ev: BlockRevealEvent = serde_json::from_value(v).unwrap();
645 return ev.request_id.expect("the event names the request the caller waits on");
646 }
647 tokio::task::yield_now().await;
648 }
649 }
650
651 #[tokio::test]
652 async fn a_caller_that_waits_hears_the_window_say_it_showed_the_block() {
653 let f = fixture(true).await;
654 let (res, delivered) = tokio::join!(
655 super::reveal_block(&f.state, &f.router, f.b.clone(), true),
656 async {
657 let id = told_request_id(&f).await;
658 f.router.reveal_acked(&id, router::RevealAck { ok: true, reason: None })
659 }
660 );
661 let res = res.unwrap();
662 assert!(delivered);
663 assert!(res.found);
664 assert_eq!((res.revealed, res.reason), (Some(true), None));
665 }
666
667 #[tokio::test]
668 async fn a_window_that_could_not_show_the_block_says_why() {
669 let f = fixture(true).await;
670 let (res, _) = tokio::join!(
671 super::reveal_block(&f.state, &f.router, f.b.clone(), true),
672 async {
673 let id = told_request_id(&f).await;
674 f.router.reveal_acked(&id, router::RevealAck { ok: false, reason: Some("layout-timeout".into()) })
675 }
676 );
677 let res = res.unwrap();
678 assert_eq!((res.revealed, res.reason.as_deref()), (Some(false), Some("layout-timeout")));
679 }
680
681 #[tokio::test]
682 async fn a_caller_that_does_not_wait_sends_no_request_id_and_an_answer_to_nobody_is_dropped() {
683 let f = fixture(true).await;
684 let res = super::reveal_block(&f.state, &f.router, f.b.clone(), false).await.unwrap();
685 assert_eq!(res.revealed, None);
686 let ev: BlockRevealEvent = serde_json::from_value(f.reveals.lock().unwrap()[0].clone()).unwrap();
687 assert_eq!(ev.request_id, None);
688 assert!(!f.router.reveal_acked("nobody-asked", router::RevealAck { ok: true, reason: None }));
689 }
690
691 #[tokio::test]
692 async fn unknown_block_is_not_found_and_publishes_nothing() {
693 let f = fixture(true).await;
694 let res = super::reveal_block(&f.state, &f.router, "no-such-block".into(), false).await.unwrap();
695 assert!(!res.found);
696 assert_eq!(res.window_id, None);
697 assert!(f.reveals.lock().unwrap().is_empty());
698 }
699
700 #[tokio::test]
701 async fn workspace_open_in_no_window_is_not_found_and_changes_nothing() {
702 let f = fixture(false).await;
703 let res = super::reveal_block(&f.state, &f.router, f.b.clone(), false).await.unwrap();
704 assert!(!res.found);
705 assert!(f.reveals.lock().unwrap().is_empty());
706 let tree = f.state.srv_state.lock().await.tabs[&f.tab_id].rootnode.clone().unwrap();
707 assert_eq!(tree.data.as_ref().unwrap().active_block_id, f.a, "stored tree untouched");
708 }
709
710 fn reveal_params(block_id: &str, open_if_closed: bool) -> super::BlockRevealParams {
711 super::BlockRevealParams { block_id: block_id.to_string(), await_ack: None, open_if_closed: Some(open_if_closed) }
712 }
713
714 #[tokio::test]
716 async fn a_pane_in_a_workspace_no_window_shows_names_the_workspace_and_is_parked_for_a_new_window() {
717 let f = fixture(false).await;
718 let ws_id = f.workspace_id.clone();
719 let res = super::block_reveal(&f.state, &f.router, reveal_params(&f.b, true)).await.unwrap();
720 assert!(!res.found);
721 assert_eq!(res.workspace_id.as_deref(), Some(ws_id.as_str()));
722 assert!(f.reveals.lock().unwrap().is_empty(), "no open window is told");
723
724 assert!(f.router.take_pending_activation(Some("some-other-workspace")).is_none());
726 let taken = f.router.take_pending_activation(Some(&ws_id)).expect("parked for the workspace's window");
727 assert_eq!((taken.block_id.as_str(), taken.tab_id.as_str()), (f.b.as_str(), f.tab_id.as_str()));
728 assert!(f.router.take_pending_activation(Some(&ws_id)).is_none(), "taken once");
729 }
730
731 #[tokio::test]
733 async fn reveals_for_two_closed_workspaces_are_both_kept() {
734 let f = fixture(false).await;
735 let other = f.router.park_activation_for_closed_workspace(&f.a).expect("workspace of a");
736 assert_eq!(other, f.workspace_id, "the fixture's panes share one workspace");
737 f.router.park_activation(router::PendingActivation {
739 block_id: "elsewhere".into(),
740 tab_id: "t2".into(),
741 workspace_id: Some("ws-2".into()),
742 at_ms: agentmux_common::time::now_ms(),
743 });
744 assert_eq!(f.router.take_pending_activation(Some("ws-2")).unwrap().block_id, "elsewhere");
745 assert_eq!(f.router.take_pending_activation(Some(&f.workspace_id)).unwrap().block_id, f.a);
746 f.router.park_activation_for_closed_workspace(&f.a);
748 f.router.park_activation_for_closed_workspace(&f.b);
749 assert_eq!(f.router.take_pending_activation(Some(&f.workspace_id)).unwrap().block_id, f.b);
750 assert!(f.router.take_pending_activation(None).is_none());
751 }
752
753 #[tokio::test]
754 async fn nothing_is_parked_unless_the_caller_asked_to_open_the_workspace() {
755 let f = fixture(false).await;
756 let res = super::block_reveal(&f.state, &f.router, reveal_params(&f.b, false)).await.unwrap();
757 assert!(!res.found);
758 assert_eq!(res.workspace_id, None);
759 assert!(f.router.take_pending_activation(None).is_none());
760 }
761
762 #[tokio::test]
763 async fn a_pane_shown_in_an_open_window_names_no_workspace_and_parks_nothing() {
764 let f = fixture(true).await;
765 let res = super::block_reveal(&f.state, &f.router, reveal_params(&f.b, true)).await.unwrap();
766 assert!(res.found);
767 assert_eq!(res.workspace_id, None);
768 assert!(f.router.take_pending_activation(None).is_none());
769 }
770
771 #[tokio::test]
772 async fn a_block_that_is_gone_names_no_workspace() {
773 let f = fixture(true).await;
774 let res = super::block_reveal(&f.state, &f.router, reveal_params("no-such-block", true)).await.unwrap();
775 assert_eq!((res.found, res.workspace_id), (false, None));
776 }
777
778 #[tokio::test]
779 async fn empty_block_id_is_an_error() {
780 let f = fixture(true).await;
781 assert!(super::reveal_block(&f.state, &f.router, String::new(), false).await.is_err());
782 }
783}
784
785#[cfg(test)]
786mod live_tests {
787 use futures_util::{SinkExt, StreamExt};
788 use tokio_tungstenite::tungstenite::{ClientRequestBuilder, Message};
789
790 async fn next_event<S>(rx: &mut S, want: &str) -> serde_json::Value
791 where
792 S: futures_util::Stream<Item = Result<Message, tokio_tungstenite::tungstenite::Error>> + Unpin,
793 {
794 loop {
795 let msg = tokio::time::timeout(std::time::Duration::from_secs(5), rx.next())
796 .await
797 .unwrap_or_else(|_| panic!("timed out waiting for {want}"))
798 .unwrap()
799 .unwrap();
800 let Ok(text) = msg.to_text() else { continue };
801 let Ok(v) = serde_json::from_str::<serde_json::Value>(text) else { continue };
802 if v["data"]["command"] == "eventrecv" && v["data"]["data"]["event"] == want {
803 return v["data"]["data"]["data"].clone();
804 }
805 }
806 }
807
808 #[tokio::test]
813 async fn header_authed_client_receives_router_events_over_ws() {
814 let state = crate::server::tests::test_state();
815 state
819 .broker
820 .set_client(Box::new(crate::backend::eventbus::EventBusBridge::new(state.event_bus.clone())));
821 let auth = state.auth_key.clone();
822 let app = crate::server::build_router(state);
823 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
824 let addr = listener.local_addr().unwrap();
825 tokio::spawn(async move {
826 axum::serve(listener, app.into_make_service_with_connect_info::<std::net::SocketAddr>())
827 .await
828 .unwrap();
829 });
830
831 let uri: tokio_tungstenite::tungstenite::http::Uri = format!("ws://{addr}/ws").parse().unwrap();
832 let req = ClientRequestBuilder::new(uri).with_header("X-AuthKey", auth);
833 let (ws, _) = tokio_tungstenite::connect_async(req).await.expect("header auth accepted on /ws");
834 let (mut tx, mut rx) = ws.split();
835
836 let send = |cmd: &str, reqid: &str, data: serde_json::Value| {
837 serde_json::json!({"wscommand":"rpc","message":{"command":cmd,"reqid":reqid,"data":data}}).to_string()
838 };
839 for (i, ev) in ["notification", "notification:retract"].iter().enumerate() {
840 tx.send(Message::Text(send("eventsub", &format!("s{i}"), serde_json::json!({"event":ev,"scopes":[],"allscopes":true})).into()))
841 .await
842 .unwrap();
843 }
844 tx.send(Message::Text(send("notify.test", "t1", serde_json::json!({})).into())).await.unwrap();
845
846 let n = next_event(&mut rx, "notification").await;
847 assert_eq!(n["kind"], "test");
848 assert_eq!(n["title"], "AgentMux notifications are working");
849 let id = n["id"].as_str().unwrap().to_string();
850 let tag = n["tag"].as_str().unwrap().to_string();
851
852 tx.send(Message::Text(send("notify.ack", "a1", serde_json::json!({"id": id, "clicked": false})).into()))
853 .await
854 .unwrap();
855 let r = next_event(&mut rx, "notification:retract").await;
856 assert_eq!(r["tag"], tag);
857 }
858
859 #[tokio::test]
863 async fn clicking_a_pane_toast_names_its_open_window_and_tab() {
864 use crate::backend::obj::{Block, Window};
865 let state = crate::server::tests::test_state();
866 state
867 .broker
868 .set_client(Box::new(crate::backend::eventbus::EventBusBridge::new(state.event_bus.clone())));
869 let (broker, store) = (state.broker.clone(), state.mstore.clone());
870 crate::backend::wcore::ensure_initial_data(&store).unwrap();
871 let block = store.get_all::<Block>().unwrap().into_iter().next().expect("seeded block");
872 let window = store.get_all::<Window>().unwrap().into_iter().next().expect("seeded window");
873 let auth = state.auth_key.clone();
874 let app = crate::server::build_router(state);
875 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
876 let addr = listener.local_addr().unwrap();
877 tokio::spawn(async move {
878 axum::serve(listener, app.into_make_service_with_connect_info::<std::net::SocketAddr>())
879 .await
880 .unwrap();
881 });
882 let uri: tokio_tungstenite::tungstenite::http::Uri = format!("ws://{addr}/ws").parse().unwrap();
883 let (ws, _) = tokio_tungstenite::connect_async(ClientRequestBuilder::new(uri).with_header("X-AuthKey", auth))
884 .await
885 .unwrap();
886 let (mut tx, mut rx) = ws.split();
887 let send = |cmd: &str, reqid: &str, data: serde_json::Value| {
888 serde_json::json!({"wscommand":"rpc","message":{"command":cmd,"reqid":reqid,"data":data}}).to_string()
889 };
890 for (i, ev) in ["notification", "notification:activate"].iter().enumerate() {
891 tx.send(Message::Text(send("eventsub", &format!("s{i}"), serde_json::json!({"event":ev,"scopes":[],"allscopes":true})).into()))
892 .await
893 .unwrap();
894 }
895 tx.send(Message::Text(send("notify.focus", "f1", serde_json::json!({"window_focused": false, "window_id": window.oid})).into()))
897 .await
898 .unwrap();
899 let r = crate::backend::notify::router::get(&broker).expect("router created by the connection");
900 let b = block.oid.clone();
901 tokio::task::spawn_blocking(move || {
902 r.emit_fixed(crate::backend::notify::policy::NotifyKind::MessageNeedsReview, &b, Some("x".into()))
903 })
904 .await
905 .unwrap();
906 let n = next_event(&mut rx, "notification").await;
907 let id = n["id"].as_str().unwrap().to_string();
908
909 tx.send(Message::Text(send("notify.ack", "a1", serde_json::json!({"id": id, "clicked": true})).into()))
910 .await
911 .unwrap();
912 let (mut activate, mut response) = (None, None);
913 while activate.is_none() || response.is_none() {
914 let msg = tokio::time::timeout(std::time::Duration::from_secs(5), rx.next()).await.expect("ack answered").unwrap().unwrap();
915 let Ok(v) = serde_json::from_str::<serde_json::Value>(msg.to_text().unwrap_or("")) else { continue };
916 if v["data"]["resid"] == "a1" {
917 response = Some(v["data"]["data"].clone());
918 } else if v["data"]["command"] == "eventrecv" && v["data"]["data"]["event"] == "notification:activate" {
919 activate = Some(v["data"]["data"]["data"].clone());
920 }
921 }
922 let (a, resp) = (activate.unwrap(), response.unwrap());
923 let tab_id = block.parentoref.strip_prefix("tab:").unwrap();
924 assert_eq!(a["block_id"], block.oid.as_str());
925 assert_eq!(a["tab_id"], tab_id);
926 assert_eq!(a["window_id"], window.oid.as_str());
927 assert_eq!(a["workspace_id"], window.workspaceid.as_str());
928 assert_eq!(resp["window_id"], window.oid.as_str(), "the launcher raises that window: {resp}");
929 assert_eq!(resp["known"], true);
930 assert_eq!(resp["has_window"], true);
931 }
932
933 #[tokio::test]
939 async fn keep_running_on_the_toast_cancels_the_shutdown_over_ws() {
940 use crate::backend::obj::Block;
941 let state = crate::server::tests::test_state();
942 state
943 .broker
944 .set_client(Box::new(crate::backend::eventbus::EventBusBridge::new(state.event_bus.clone())));
945 crate::backend::wcore::ensure_initial_data(&state.mstore).unwrap();
946 let block = state.mstore.get_all::<Block>().unwrap().into_iter().next().expect("seeded block");
947 let (broker, auth) = (state.broker.clone(), state.auth_key.clone());
948 let st = state.clone();
949 let app = crate::server::build_router(state);
950 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
951 let addr = listener.local_addr().unwrap();
952 tokio::spawn(async move {
953 axum::serve(listener, app.into_make_service_with_connect_info::<std::net::SocketAddr>())
954 .await
955 .unwrap();
956 });
957 let uri: tokio_tungstenite::tungstenite::http::Uri = format!("ws://{addr}/ws").parse().unwrap();
958 let (ws, _) = tokio_tungstenite::connect_async(ClientRequestBuilder::new(uri).with_header("X-AuthKey", auth))
959 .await
960 .unwrap();
961 let (mut tx, mut rx) = ws.split();
962 let send = |cmd: &str, reqid: &str, data: serde_json::Value| {
963 serde_json::json!({"wscommand":"rpc","message":{"command":cmd,"reqid":reqid,"data":data}}).to_string()
964 };
965 for (i, ev) in ["notification", "notification:retract"].iter().enumerate() {
966 tx.send(Message::Text(send("eventsub", &format!("s{i}"), serde_json::json!({"event":ev,"scopes":[],"allscopes":true})).into()))
967 .await
968 .unwrap();
969 }
970 tx.send(Message::Text(send("notify.focus", "f1", serde_json::json!({"window_focused": false})).into()))
972 .await
973 .unwrap();
974 loop {
975 let msg = tokio::time::timeout(std::time::Duration::from_secs(5), rx.next()).await.expect("focus answered").unwrap().unwrap();
976 let Ok(v) = serde_json::from_str::<serde_json::Value>(msg.to_text().unwrap_or("")) else { continue };
977 if v["data"]["resid"] == "f1" {
978 break;
979 }
980 }
981 assert!(crate::backend::notify::router::get(&broker).is_some(), "router created by the connection");
982
983 let v = crate::sagas::pending_shutdown::request(
984 &st,
985 &block.oid,
986 "AgentY",
987 "FleetBulkStop",
988 "tidying up, the token is abc123",
989 crate::sagas::pending_shutdown::Action::CloseTab { detail: "test".into() },
990 );
991 let n = next_event(&mut rx, "notification").await;
992 assert_eq!(n["kind"], "shutdown_pending");
993 assert_eq!(n["title"], "Closing agent pane in 30 s");
994 assert_eq!(n["body"], "AgentY asked to close it. It stays in My Agents, with its conversation.");
995 assert_eq!(n["actions"], serde_json::json!([{ "id": "keep", "label": "Keep open" }, { "id": "now", "label": "Close now" }]), "no session runs here");
996 assert_eq!(n["countdown"]["title_template"], "Closing agent pane in {n} s");
997 let left = n["countdown"]["remaining_ms"].as_i64().unwrap();
998 assert!((28_000..=30_000).contains(&left), "{left}");
999 assert!(!n.to_string().contains("abc123") && !n.to_string().contains("tidying"), "the reason is not in the toast: {n}");
1000 let (id, tag) = (n["id"].as_str().unwrap().to_string(), n["tag"].as_str().unwrap().to_string());
1001
1002 tx.send(Message::Text(send("notify.ack", "a1", serde_json::json!({"id": id, "clicked": false, "action": "keep"})).into()))
1003 .await
1004 .unwrap();
1005 let (mut answer, mut retracted) = (None, None);
1008 while answer.is_none() || retracted.is_none() {
1009 let msg = tokio::time::timeout(std::time::Duration::from_secs(5), rx.next()).await.expect("ack answered and toast retracted").unwrap().unwrap();
1010 let Ok(v) = serde_json::from_str::<serde_json::Value>(msg.to_text().unwrap_or("")) else { continue };
1011 if v["data"]["resid"] == "a1" {
1012 answer = Some(v["data"]["data"].clone());
1013 } else if v["data"]["command"] == "eventrecv" && v["data"]["data"]["event"] == "notification:retract" {
1014 retracted = Some(v["data"]["data"]["data"].clone());
1015 }
1016 }
1017 assert_eq!(answer.unwrap()["kept"], "kept_by_user");
1018 assert_eq!(crate::sagas::pending_shutdown::status(&v.request_id).unwrap().status, "kept_by_user");
1019 assert_eq!(retracted.unwrap()["tag"], tag, "the toast goes");
1020
1021 tx.send(Message::Text(send("notify.ack", "a2", serde_json::json!({"id": id, "clicked": false, "action": "keep"})).into()))
1023 .await
1024 .unwrap();
1025 let mut again = None;
1026 while again.is_none() {
1027 let msg = tokio::time::timeout(std::time::Duration::from_secs(5), rx.next()).await.expect("ack answered").unwrap().unwrap();
1028 let Ok(v) = serde_json::from_str::<serde_json::Value>(msg.to_text().unwrap_or("")) else { continue };
1029 if v["data"]["resid"] == "a2" {
1030 again = Some(v["data"]["data"].clone());
1031 }
1032 }
1033 assert!(again.unwrap().get("kept").is_none());
1034 }
1035
1036 #[tokio::test]
1040 async fn a_stale_toast_button_does_not_cancel_a_newer_shutdown_of_the_same_block() {
1041 use crate::backend::obj::Block;
1042 let state = crate::server::tests::test_state();
1043 state
1044 .broker
1045 .set_client(Box::new(crate::backend::eventbus::EventBusBridge::new(state.event_bus.clone())));
1046 crate::backend::wcore::ensure_initial_data(&state.mstore).unwrap();
1047 let block = state.mstore.get_all::<Block>().unwrap().into_iter().next().expect("seeded block");
1048 let (broker, auth) = (state.broker.clone(), state.auth_key.clone());
1049 let st = state.clone();
1050 let app = crate::server::build_router(state);
1051 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1052 let addr = listener.local_addr().unwrap();
1053 tokio::spawn(async move {
1054 axum::serve(listener, app.into_make_service_with_connect_info::<std::net::SocketAddr>())
1055 .await
1056 .unwrap();
1057 });
1058 let uri: tokio_tungstenite::tungstenite::http::Uri = format!("ws://{addr}/ws").parse().unwrap();
1059 let (ws, _) = tokio_tungstenite::connect_async(ClientRequestBuilder::new(uri).with_header("X-AuthKey", auth))
1060 .await
1061 .unwrap();
1062 let (mut tx, mut rx) = ws.split();
1063 let send = |cmd: &str, reqid: &str, data: serde_json::Value| {
1064 serde_json::json!({"wscommand":"rpc","message":{"command":cmd,"reqid":reqid,"data":data}}).to_string()
1065 };
1066 tx.send(Message::Text(send("eventsub", "s0", serde_json::json!({"event":"notification","scopes":[],"allscopes":true})).into()))
1067 .await
1068 .unwrap();
1069 tx.send(Message::Text(send("notify.focus", "f1", serde_json::json!({"window_focused": false})).into()))
1070 .await
1071 .unwrap();
1072 loop {
1073 let msg = tokio::time::timeout(std::time::Duration::from_secs(5), rx.next()).await.expect("focus answered").unwrap().unwrap();
1074 let Ok(v) = serde_json::from_str::<serde_json::Value>(msg.to_text().unwrap_or("")) else { continue };
1075 if v["data"]["resid"] == "f1" {
1076 break;
1077 }
1078 }
1079 assert!(crate::backend::notify::router::get(&broker).is_some(), "router created by the connection");
1080
1081 let close = || crate::sagas::pending_shutdown::Action::CloseTab { detail: "test".into() };
1083 let a = crate::sagas::pending_shutdown::request(&st, &block.oid, "AgentY", "FleetBulkStop", "", close());
1084 let toast_a = next_event(&mut rx, "notification").await["id"].as_str().unwrap().to_string();
1085 assert_eq!(crate::sagas::pending_shutdown::keep(&st, &block.oid, &a.request_id), "kept_by_user");
1086
1087 let b = crate::sagas::pending_shutdown::request(&st, &block.oid, "AgentY", "FleetBulkStop", "", close());
1089 assert_ne!(a.request_id, b.request_id);
1090
1091 tx.send(Message::Text(send("notify.ack", "a1", serde_json::json!({"id": toast_a, "clicked": false, "action": "keep"})).into()))
1093 .await
1094 .unwrap();
1095 let mut answer = None;
1096 while answer.is_none() {
1097 let msg = tokio::time::timeout(std::time::Duration::from_secs(5), rx.next()).await.expect("ack answered").unwrap().unwrap();
1098 let Ok(v) = serde_json::from_str::<serde_json::Value>(msg.to_text().unwrap_or("")) else { continue };
1099 if v["data"]["resid"] == "a1" {
1100 answer = Some(v["data"]["data"].clone());
1101 }
1102 }
1103 let kept = answer.unwrap().get("kept").and_then(|k| k.as_str().map(str::to_string));
1104 assert_ne!(kept.as_deref(), Some("kept_by_user"), "the stale button cancelled nothing");
1105 assert_eq!(crate::sagas::pending_shutdown::status(&b.request_id).unwrap().status, "pending", "B still counts down");
1106 crate::sagas::pending_shutdown::keep(&st, &block.oid, &b.request_id);
1107 }
1108
1109 #[tokio::test]
1113 async fn the_toast_follows_a_stop_that_is_upgraded_to_a_close() {
1114 use crate::backend::obj::Block;
1115 let state = crate::server::tests::test_state();
1116 state
1117 .broker
1118 .set_client(Box::new(crate::backend::eventbus::EventBusBridge::new(state.event_bus.clone())));
1119 crate::backend::wcore::ensure_initial_data(&state.mstore).unwrap();
1120 let block = state.mstore.get_all::<Block>().unwrap().into_iter().next().expect("seeded block");
1121 let (broker, auth) = (state.broker.clone(), state.auth_key.clone());
1122 let st = state.clone();
1123 let app = crate::server::build_router(state);
1124 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1125 let addr = listener.local_addr().unwrap();
1126 tokio::spawn(async move {
1127 axum::serve(listener, app.into_make_service_with_connect_info::<std::net::SocketAddr>())
1128 .await
1129 .unwrap();
1130 });
1131 let uri: tokio_tungstenite::tungstenite::http::Uri = format!("ws://{addr}/ws").parse().unwrap();
1132 let (ws, _) = tokio_tungstenite::connect_async(ClientRequestBuilder::new(uri).with_header("X-AuthKey", auth))
1133 .await
1134 .unwrap();
1135 let (mut tx, mut rx) = ws.split();
1136 let send = |cmd: &str, reqid: &str, data: serde_json::Value| {
1137 serde_json::json!({"wscommand":"rpc","message":{"command":cmd,"reqid":reqid,"data":data}}).to_string()
1138 };
1139 tx.send(Message::Text(send("eventsub", "s0", serde_json::json!({"event":"notification","scopes":[],"allscopes":true})).into()))
1140 .await
1141 .unwrap();
1142 tx.send(Message::Text(send("notify.focus", "f1", serde_json::json!({"window_focused": false})).into()))
1143 .await
1144 .unwrap();
1145 loop {
1146 let msg = tokio::time::timeout(std::time::Duration::from_secs(5), rx.next()).await.expect("focus answered").unwrap().unwrap();
1147 let Ok(v) = serde_json::from_str::<serde_json::Value>(msg.to_text().unwrap_or("")) else { continue };
1148 if v["data"]["resid"] == "f1" {
1149 break;
1150 }
1151 }
1152 assert!(crate::backend::notify::router::get(&broker).is_some(), "router created by the connection");
1153
1154 let stop = crate::sagas::pending_shutdown::request(
1155 &st,
1156 &block.oid,
1157 "Settings",
1158 "FleetBulkStop",
1159 "",
1160 crate::sagas::pending_shutdown::Action::Stop { signal: None, stop_background: None },
1161 );
1162 let first = next_event(&mut rx, "notification").await;
1163 assert_eq!(first["title"], "Stopping agent pane in 30 s");
1164
1165 let close = crate::sagas::pending_shutdown::request(
1166 &st,
1167 &block.oid,
1168 "AgentY",
1169 "FleetBulkStop",
1170 "",
1171 crate::sagas::pending_shutdown::Action::CloseTab { detail: "test".into() },
1172 );
1173 assert_eq!(close.request_id, stop.request_id, "the same request and deadline");
1174 let second = next_event(&mut rx, "notification").await;
1175 assert!(second["title"].as_str().unwrap().starts_with("Closing agent pane in "), "{second}");
1176 assert!(second["body"].as_str().unwrap().contains("asked to close it"), "{second}");
1177 assert_eq!(second["tag"], first["tag"], "replaces the toast in place");
1178 assert!(second["countdown"]["remaining_ms"].as_i64().unwrap() <= first["countdown"]["remaining_ms"].as_i64().unwrap(), "the deadline did not restart");
1179 crate::sagas::pending_shutdown::keep(&st, &block.oid, &stop.request_id);
1180 }
1181
1182 #[tokio::test]
1186 async fn the_close_toast_names_the_pane_and_the_asker() {
1187 use crate::backend::obj::{Block, MetaMapType};
1188 use crate::sagas::pending_shutdown::{keep, request, Action};
1189 let state = crate::server::tests::test_state();
1190 state
1191 .broker
1192 .set_client(Box::new(crate::backend::eventbus::EventBusBridge::new(state.event_bus.clone())));
1193 crate::backend::wcore::ensure_initial_data(&state.mstore).unwrap();
1194 let add = |id: &str, pairs: &[(&str, &str)]| {
1195 let meta: MetaMapType = pairs.iter().map(|(k, v)| (k.to_string(), serde_json::json!(v))).collect();
1196 let mut block = Block { oid: id.to_string(), parentoref: String::new(), version: 1, runtimeopts: None, stickers: None, meta, subblockids: None };
1197 state.mstore.insert(&mut block).unwrap();
1198 };
1199 add("toast-browser", &[("view", "browser"), ("url", "https://portal.azure.com/x"), ("frame:title", "Azure: subscriptions")]);
1200 add("toast-editor", &[("view", "editor"), ("file", "C:\\work\\private\\notes.md")]);
1201 add("toast-bare-browser", &[("view", "browser"), ("url", "https://example.com:8443/a?token=x")]);
1202 add("toast-agent", &[("view", "agent"), ("agentName", "Lark"), ("agentId", "lark")]);
1203 add("toast-asker", &[("view", "agent"), ("agentName", "QTest"), ("agentId", "qtest")]);
1204 state.reactive_handler.register_agent("qtest", "toast-asker", None).unwrap();
1205 let (broker, auth) = (state.broker.clone(), state.auth_key.clone());
1206 let st = state.clone();
1207 let app = crate::server::build_router(state);
1208 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1209 let addr = listener.local_addr().unwrap();
1210 tokio::spawn(async move {
1211 axum::serve(listener, app.into_make_service_with_connect_info::<std::net::SocketAddr>())
1212 .await
1213 .unwrap();
1214 });
1215 let uri: tokio_tungstenite::tungstenite::http::Uri = format!("ws://{addr}/ws").parse().unwrap();
1216 let (ws, _) = tokio_tungstenite::connect_async(ClientRequestBuilder::new(uri).with_header("X-AuthKey", auth))
1217 .await
1218 .unwrap();
1219 let (mut tx, mut rx) = ws.split();
1220 let send = |cmd: &str, reqid: &str, data: serde_json::Value| {
1221 serde_json::json!({"wscommand":"rpc","message":{"command":cmd,"reqid":reqid,"data":data}}).to_string()
1222 };
1223 tx.send(Message::Text(send("eventsub", "s0", serde_json::json!({"event":"notification","scopes":[],"allscopes":true})).into()))
1224 .await
1225 .unwrap();
1226 tx.send(Message::Text(send("notify.focus", "f1", serde_json::json!({"window_focused": false})).into()))
1227 .await
1228 .unwrap();
1229 loop {
1230 let msg = tokio::time::timeout(std::time::Duration::from_secs(5), rx.next()).await.expect("focus answered").unwrap().unwrap();
1231 let Ok(v) = serde_json::from_str::<serde_json::Value>(msg.to_text().unwrap_or("")) else { continue };
1232 if v["data"]["resid"] == "f1" {
1233 break;
1234 }
1235 }
1236 assert!(crate::backend::notify::router::get(&broker).is_some(), "router created by the connection");
1237
1238 let close_pane = |id: &str| Action::ClosePane { block_ids: vec![id.to_string()] };
1239 let cases: [(&str, Action, &str, &str, &str); 4] = [
1240 ("toast-browser", close_pane("toast-browser"), "Closing browser pane: Azure: subscriptions in 30 s", "qtest", "QTest asked to close it."),
1241 ("toast-editor", close_pane("toast-editor"), "Closing editor: notes.md in 30 s", "qtest", "QTest asked to close it."),
1242 ("toast-bare-browser", close_pane("toast-bare-browser"), "Closing browser pane: example.com in 30 s", "Settings", "Settings asked to close it."),
1243 (
1244 "toast-agent",
1245 Action::CloseTab { detail: "test".into() },
1246 "Closing Lark in 30 s",
1247 "qtest",
1248 "QTest asked to close it. It stays in My Agents, with its conversation.",
1249 ),
1250 ];
1251 for (block, action, title, by, body) in cases {
1252 let v = request(&st, block, by, "ClosePane", "", action);
1253 let n = next_event(&mut rx, "notification").await;
1254 assert_eq!(n["title"], title, "{n}");
1255 assert_eq!(n["body"], body, "{n}");
1256 assert!(!n["title"].as_str().unwrap().contains("An agent"), "{n}");
1257 assert_eq!(v.by, by.replace("qtest", "QTest"), "the banner and status name the asker the same way");
1258 keep(&st, block, &v.request_id);
1259 }
1260 }
1261}
1262
1263#[cfg(test)]
1264mod toast_press_tests {
1265 use super::*;
1266 use crate::backend::notify::policy::NotifyKind;
1267 use crate::backend::sensitive_requests as requests;
1268 use crate::sagas::sensitive_window as window;
1269 use crate::server::tests::test_state;
1270 use crate::server::AppState;
1271 use agentmux_common::time::now_ms;
1272
1273 fn countdown(state: &AppState) -> (String, String) {
1275 let facts: std::collections::BTreeMap<String, String> =
1276 [("template".to_string(), format!("t-{}", uuid::Uuid::new_v4().simple())), ("publisher".to_string(), "p".to_string())].into_iter().collect();
1277 let id = requests::registry().request(&format!("u-{}", uuid::Uuid::new_v4().simple()), "asker", "job_template_approve", &facts, "", now_ms()).unwrap().id;
1278 requests::registry().approve(&id, "boss", now_ms()).unwrap();
1279 window::open(state, &id, std::time::Duration::from_secs(60)).unwrap();
1280 let group = format!("{}{id}", window::TOAST_GROUP_PREFIX);
1281 (id, group)
1282 }
1283
1284 fn proven_state() -> AppState {
1285 let mut state = test_state();
1286 state.host_reg_secret = Some("launcher-secret".into());
1287 state
1288 }
1289
1290 #[tokio::test]
1291 async fn a_press_on_a_sensitive_toast_decides_nothing_without_the_launchers_proof() {
1292 let state = proven_state();
1293 let (id, group) = countdown(&state);
1294 for action in ["keep", "now"] {
1297 assert_eq!(press_for(&state, NotifyKind::ShutdownPending, &group, &id, action, None).as_deref(), Some("refused"), "{action}");
1298 assert_eq!(press_for(&state, NotifyKind::ShutdownPending, &group, &id, action, Some("not-the-secret")).as_deref(), Some("refused"), "{action}");
1299 }
1300 assert_eq!(window::status(&id).unwrap().status, "pending", "the countdown goes on");
1301 let mut open = test_state();
1303 open.host_reg_secret = None;
1304 assert_eq!(press_for(&open, NotifyKind::ShutdownPending, &group, &id, "now", Some("")).as_deref(), Some("refused"));
1305 assert_eq!(window::veto(&state, &id), "vetoed");
1306 }
1307
1308 #[tokio::test]
1309 async fn the_launchers_proof_lets_a_sensitive_toast_veto_or_approve_now() {
1310 let state = proven_state();
1311 let (veto_id, veto_group) = countdown(&state);
1312 assert_eq!(press_for(&state, NotifyKind::ShutdownPending, &veto_group, &veto_id, "keep", Some("launcher-secret")).as_deref(), Some("vetoed"));
1313 assert_eq!(window::status(&veto_id).unwrap().status, "vetoed");
1314
1315 let (now_id, now_group) = countdown(&state);
1316 assert_eq!(press_for(&state, NotifyKind::ShutdownPending, &now_group, &now_id, "now", Some("launcher-secret")).as_deref(), Some("approved_now"));
1317 let _ = window::veto(&state, &now_id);
1318 }
1319
1320 #[tokio::test]
1322 async fn keep_needs_no_proof_on_an_agent_close_and_close_now_needs_it() {
1323 use crate::sagas::pending_shutdown as shutdown;
1324 let state = proven_state();
1325 let block = format!("blk-{}", uuid::Uuid::new_v4().simple());
1326 let a = shutdown::request(&state, &block, "Korp", "FleetBulkStop", "", shutdown::Action::CloseTab { detail: String::new() });
1327 assert_eq!(press_for(&state, NotifyKind::ShutdownPending, &block, &a.request_id, "now", None).as_deref(), Some("refused"));
1328 assert_eq!(shutdown::status(&a.request_id).unwrap().status, "pending");
1329 assert_eq!(press_for(&state, NotifyKind::ShutdownPending, &block, &a.request_id, "keep", None).as_deref(), Some("kept_by_user"));
1330
1331 let block = format!("blk-{}", uuid::Uuid::new_v4().simple());
1332 let b = shutdown::request(&state, &block, "Korp", "FleetBulkStop", "", shutdown::Action::CloseTab { detail: String::new() });
1333 assert_eq!(press_for(&state, NotifyKind::ShutdownPending, &block, &b.request_id, "now", Some("launcher-secret")).as_deref(), Some("closed_now"));
1334 assert_eq!(press_for(&state, NotifyKind::ShutdownPending, &block, &b.request_id, "now", Some("launcher-secret")).as_deref(), Some("too_late"), "once");
1335 }
1336}
1337
1338#[cfg(test)]
1339mod handler_tests {
1340 use super::*;
1341 use crate::server::tests::test_state;
1342
1343 fn emit(block_id: &str, event: NotifyPaneEvent) -> NotifyEmitParams {
1344 NotifyEmitParams { block_id: block_id.into(), event, question: None, question_count: None }
1345 }
1346
1347 #[tokio::test]
1348 async fn an_emit_without_a_block_is_refused_and_one_with_a_block_is_taken() {
1349 let state = test_state();
1350 let r = router_for(&state);
1351 let err = notify_emit(&r, emit("", NotifyPaneEvent::InputResolved)).err().unwrap();
1352 assert_eq!(err, "notify.emit: block_id required");
1353 assert!(notify_emit(&r, emit("emit-block", NotifyPaneEvent::InputResolved)).unwrap().ok);
1354 assert!(notify_emit(&r, emit("emit-block", NotifyPaneEvent::TurnStarted)).unwrap().ok, "an ignored event is still answered ok");
1355 }
1356
1357 #[tokio::test]
1358 async fn closing_an_agent_early_is_the_windows_alone() {
1359 let state = test_state();
1360 let cmd = || CommandAgentShutdownNowData { blockid: "b".into(), request_id: "r".into() };
1361 let agent = RpcContext { agent_id: "some-agent".into(), ..Default::default() };
1362 assert!(shutdown_now(&state, &agent, cmd()).err().unwrap().starts_with("FORBIDDEN"));
1363 assert!(shutdown_now(&state, &RpcContext::default(), cmd()).err().unwrap().starts_with("FORBIDDEN"));
1364 }
1365
1366 #[tokio::test]
1367 async fn a_reveal_answer_for_a_request_nobody_is_waiting_on_is_not_delivered() {
1368 let state = test_state();
1369 let r = router_for(&state);
1370 let answer = BlockRevealedParams { request_id: "no-such-request".into(), ok: true, reason: None };
1371 assert!(!block_revealed(&r, answer).unwrap().delivered);
1372 }
1373
1374 #[tokio::test]
1375 async fn with_no_click_waiting_nothing_is_taken_for_activation() {
1376 let state = test_state();
1377 let r = router_for(&state);
1378 let taken = notify_take_activation(&r, NotifyTakeActivationParams { workspace_id: Some(String::new()) }).unwrap();
1379 assert!(taken.block_id.is_none() && taken.tab_id.is_none());
1380 }
1381
1382 #[tokio::test]
1383 async fn an_ack_for_a_toast_nobody_knows_says_so() {
1384 let state = test_state();
1385 let r = router_for(&state);
1386 let ack = NotifyAckParams { id: "no-such-toast".into(), clicked: true, action: None, proof: None };
1387 let result = notify_ack(&state, &r, ack).await.unwrap();
1388 assert!(!result.known);
1389 assert!(result.kept.is_none());
1390 }
1391}