1use std::collections::HashMap;
23use std::sync::{Arc, LazyLock, Mutex};
24use std::time::Duration;
25
26use serde::{Deserialize, Serialize};
27
28pub use crate::backend::prompt_events::{PaneConfirmView, EVENT_PANE_CONFIRM};
29use crate::backend::rpc::engine::WshRpcEngine;
30use crate::server::AppState;
31use agentmux_common::time::now_ms;
32
33pub const COMMAND_PANE_CONFIRM_DECIDE: &str = "pane.confirm.decide";
35pub const ASK_FOR: Duration = Duration::from_secs(120);
37const KEEP_FINISHED_MS: i64 = 60_000;
39const REPLAY_EVENTS: usize = 32;
41
42#[derive(Debug, Clone, Default, PartialEq, Eq)]
44pub struct Question {
45 pub title: String,
46 pub message: String,
48 pub ok_label: String,
49 pub cancel_label: String,
50 pub destructive: bool,
52 pub checkbox: String,
54}
55
56impl Question {
57 pub fn from_json(q: &serde_json::Value) -> Self {
60 let text = |k: &str, d: &str| q.get(k).and_then(|v| v.as_str()).filter(|s| !s.is_empty()).unwrap_or(d).to_string();
61 Self {
62 title: text("title", "AgentMux needs your answer"),
63 message: text("message", ""),
64 ok_label: text("ok_label", "OK"),
65 cancel_label: text("cancel_label", "Cancel"),
66 destructive: q.get("destructive").and_then(|v| v.as_bool()).unwrap_or(false),
67 checkbox: text("checkbox", ""),
68 }
69 }
70}
71
72#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
75pub struct Answer {
76 pub answered: bool,
77 pub approve: bool,
78 pub checkbox: bool,
79}
80
81#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
83#[ts(export, export_to = "../../../frontend/types/rpc/")]
84pub struct CommandPaneConfirmDecideData {
85 pub request_id: String,
86 pub approve: bool,
87 #[serde(default)]
89 pub checkbox: bool,
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
94#[ts(export, export_to = "../../../frontend/types/rpc/")]
95pub struct PaneConfirmDecideResult {
96 #[ts(type = r#""answered" | "too_late""#)]
97 pub outcome: String,
98}
99
100struct Entry {
101 view: PaneConfirmView,
102 answer: Option<Answer>,
103 wake: Arc<tokio::sync::Notify>,
104 finished_at_ms: Option<i64>,
105}
106
107static ENTRIES: LazyLock<Mutex<HashMap<String, Entry>>> = LazyLock::new(Default::default);
108
109fn entries() -> std::sync::MutexGuard<'static, HashMap<String, Entry>> {
110 ENTRIES.lock().unwrap_or_else(|e| e.into_inner())
111}
112
113pub fn pending() -> Vec<PaneConfirmView> {
115 entries().values().filter(|e| e.view.status == "pending").map(|e| e.view.clone()).collect()
116}
117
118pub async fn ask(state: &AppState, block_id: &str, question: Question) -> Result<Answer, String> {
121 ask_for(state, block_id, question, ASK_FOR).await
122}
123
124pub async fn ask_for(state: &AppState, block_id: &str, question: Question, window: Duration) -> Result<Answer, String> {
126 if block_id.is_empty() {
127 return Err("no pane was named to ask the user in".to_string());
128 }
129 crate::server::app_api::connections::host_to_ask_user(state).await?;
130 let id = uuid::Uuid::new_v4().to_string();
131 let opened = now_ms();
132 let view = PaneConfirmView {
133 id: id.clone(),
134 block_id: block_id.to_string(),
135 title: question.title,
136 message: question.message,
137 ok_label: question.ok_label,
138 cancel_label: question.cancel_label,
139 destructive: question.destructive,
140 checkbox: question.checkbox,
141 deadline_ms: opened + window.as_millis() as i64,
142 status: "pending",
143 };
144 let wake = Arc::new(tokio::sync::Notify::new());
145 {
146 let mut map = entries();
147 map.retain(|_, e| e.finished_at_ms.is_none_or(|t| opened - t < KEEP_FINISHED_MS));
148 map.insert(id.clone(), Entry { view: view.clone(), answer: None, wake: wake.clone(), finished_at_ms: None });
149 }
150 state.broker.publish_event::<crate::backend::mps_events::PaneConfirm>(&view, vec![], REPLAY_EVENTS);
151 let _asking = crate::backend::user_attention::Asking::start(&state.broker, &state.mstore, block_id, "confirm", &view.title);
153 tracing::info!(request_id = %id, block_id, title = %view.title, "pane confirm: asked");
154
155 let mut ending = Ending { broker: state.broker.clone(), id: id.clone(), view, done: false };
158 let _ = tokio::time::timeout(window, wake.notified()).await;
159 Ok(ending.finish())
160}
161
162struct Ending {
163 broker: Arc<crate::backend::mps::Broker>,
164 id: String,
165 view: PaneConfirmView,
166 done: bool,
167}
168
169impl Ending {
170 fn finish(&mut self) -> Answer {
171 let answer = settle(&self.id);
172 self.done = true;
173 let mut done = self.view.clone();
174 done.status = "cleared";
175 self.broker.publish_event::<crate::backend::mps_events::PaneConfirm>(&done, vec![], REPLAY_EVENTS);
176 tracing::info!(request_id = %self.id, answered = answer.answered, approve = answer.approve, "pane confirm: ended");
177 answer
178 }
179}
180
181impl Drop for Ending {
182 fn drop(&mut self) {
183 if !self.done {
184 self.finish();
185 }
186 }
187}
188
189fn settle(id: &str) -> Answer {
192 let mut map = entries();
193 let Some(e) = map.get_mut(id) else { return Answer::default() };
194 e.view.status = "cleared";
195 e.finished_at_ms = Some(now_ms());
196 e.answer.unwrap_or_default()
197}
198
199pub fn decide(id: &str, approve: bool, checkbox: bool) -> &'static str {
201 let mut map = entries();
202 let Some(e) = map.get_mut(id).filter(|e| e.view.status == "pending" && e.answer.is_none()) else {
203 return "too_late";
204 };
205 e.answer = Some(Answer { answered: true, approve, checkbox: checkbox && !e.view.checkbox.is_empty() });
206 e.wake.notify_one();
207 "answered"
208}
209
210pub fn register(engine: &Arc<WshRpcEngine>) {
213 engine.register_typed(COMMAND_PANE_CONFIRM_DECIDE, move |cmd: CommandPaneConfirmDecideData, ctx| async move {
214 ctx.operator_only("only the person can answer a question AgentMux asks them")?;
215 Ok(PaneConfirmDecideResult { outcome: decide(&cmd.request_id, cmd.approve, cmd.checkbox).to_string() })
216 });
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use crate::server::tests::test_state;
223 use crate::server::HostIpc;
224
225 fn question() -> Question {
226 Question {
227 title: "End a session on db1".to_string(),
228 message: "End the durable session s1 on db1?".to_string(),
229 ok_label: "End Session".to_string(),
230 cancel_label: "Keep It".to_string(),
231 destructive: true,
232 checkbox: String::new(),
233 }
234 }
235
236 fn block() -> String {
237 format!("block-{}", uuid::Uuid::new_v4().simple())
238 }
239
240 async fn with_window() -> AppState {
241 let state = test_state();
242 *state.host_ipc.lock().await = Some(HostIpc { port: 1, token: "t".to_string() });
243 state
244 }
245
246 async fn asked_in(block_id: &str) -> PaneConfirmView {
247 for _ in 0..400 {
248 if let Some(v) = pending().into_iter().find(|v| v.block_id == block_id) {
249 return v;
250 }
251 tokio::time::sleep(Duration::from_millis(5)).await;
252 }
253 panic!("nothing asked in {block_id}");
254 }
255
256 fn spawn_ask(state: &AppState, block_id: &str, q: Question, window: Duration) -> tokio::task::JoinHandle<Result<Answer, String>> {
257 let (state, block_id) = (state.clone(), block_id.to_string());
258 tokio::spawn(async move { ask_for(&state, &block_id, q, window).await })
259 }
260
261 #[tokio::test]
262 async fn with_no_window_connected_nothing_is_asked_and_nothing_is_approved() {
263 let state = test_state();
264 let b = block();
265 let err = ask_for(&state, &b, question(), Duration::from_secs(60)).await.unwrap_err();
266 assert!(err.contains("no AgentMux window is connected"), "{err}");
267 assert!(pending().iter().all(|v| v.block_id != b));
268 }
269
270 #[tokio::test]
271 async fn a_question_with_no_pane_is_refused() {
272 let state = with_window().await;
273 assert!(ask_for(&state, "", question(), Duration::from_secs(60)).await.unwrap_err().contains("no pane"));
274 }
275
276 #[tokio::test]
277 async fn the_persons_yes_is_the_answer_and_the_question_goes() {
278 let state = with_window().await;
279 let b = block();
280 let task = spawn_ask(&state, &b, question(), Duration::from_secs(60));
281 let v = asked_in(&b).await;
282 assert_eq!((v.title.as_str(), v.ok_label.as_str(), v.cancel_label.as_str(), v.destructive), ("End a session on db1", "End Session", "Keep It", true));
283 assert_eq!(decide(&v.id, true, false), "answered");
284 assert_eq!(task.await.unwrap().unwrap(), Answer { answered: true, approve: true, checkbox: false });
285 assert!(pending().iter().all(|p| p.block_id != b), "the question goes with its answer");
286 assert_eq!(decide(&v.id, true, false), "too_late");
287 }
288
289 #[tokio::test]
292 async fn the_attention_it_raises_is_a_panes_question_not_an_agents_consent() {
293 let state = with_window().await;
294 let b = block();
295 let task = spawn_ask(&state, &b, question(), Duration::from_secs(60));
296 let v = asked_in(&b).await;
297 let raised = crate::backend::user_attention::open_requests().into_iter().find(|a| a.block_id == b);
298 assert_eq!(raised.map(|a| a.kind).as_deref(), Some("confirm"));
299 decide(&v.id, false, false);
300 task.await.unwrap().unwrap();
301 assert!(crate::backend::user_attention::open_requests().iter().all(|a| a.block_id != b));
302 }
303
304 #[tokio::test]
305 async fn a_no_is_answered_and_not_approved() {
306 let state = with_window().await;
307 let b = block();
308 let task = spawn_ask(&state, &b, question(), Duration::from_secs(60));
309 let v = asked_in(&b).await;
310 assert_eq!(decide(&v.id, false, false), "answered");
311 assert_eq!(task.await.unwrap().unwrap(), Answer { answered: true, approve: false, checkbox: false });
312 }
313
314 #[tokio::test]
315 async fn nobody_answering_leaves_it_unanswered_never_approved() {
316 let state = with_window().await;
317 let b = block();
318 let answer = ask_for(&state, &b, question(), Duration::from_millis(60)).await.unwrap();
319 assert_eq!(answer, Answer::default());
320 assert!(pending().iter().all(|p| p.block_id != b));
321 }
322
323 #[tokio::test]
324 async fn the_tick_box_counts_only_when_the_question_has_one() {
325 let state = with_window().await;
326 let b = block();
327 let mut q = question();
328 q.checkbox = "Don't ask again for db1".to_string();
329 let task = spawn_ask(&state, &b, q, Duration::from_secs(60));
330 let v = asked_in(&b).await;
331 assert_eq!(v.checkbox, "Don't ask again for db1");
332 decide(&v.id, true, true);
333 assert!(task.await.unwrap().unwrap().checkbox);
334
335 let b2 = block();
336 let task = spawn_ask(&state, &b2, question(), Duration::from_secs(60));
337 let v = asked_in(&b2).await;
338 decide(&v.id, true, true);
339 assert!(!task.await.unwrap().unwrap().checkbox, "no box was shown, so none was ticked");
340 }
341
342 #[tokio::test]
343 async fn a_caller_dropped_while_it_waits_takes_its_question_with_it() {
344 let state = with_window().await;
345 let b = block();
346 let task = spawn_ask(&state, &b, question(), Duration::from_secs(60));
347 let v = asked_in(&b).await;
348 task.abort();
349 let _ = task.await;
350 assert!(pending().iter().all(|p| p.block_id != b));
351 assert_eq!(decide(&v.id, true, false), "too_late");
352 }
353
354 #[test]
355 fn a_question_reads_the_approval_windows_json() {
356 let q = Question::from_json(&serde_json::json!({
357 "kind": "consent", "title": "Install git", "message": "Run:\n\nwinget install git", "ok_label": "Install",
358 "cancel_label": "Cancel", "destructive": true, "checkbox": "Don't ask again",
359 }));
360 assert_eq!(q.title, "Install git");
361 assert!(q.message.contains('\n'));
362 assert_eq!((q.ok_label.as_str(), q.cancel_label.as_str(), q.destructive, q.checkbox.as_str()), ("Install", "Cancel", true, "Don't ask again"));
363 let bare = Question::from_json(&serde_json::json!({}));
364 assert_eq!((bare.ok_label.as_str(), bare.cancel_label.as_str(), bare.destructive), ("OK", "Cancel", false));
365 assert!(!bare.title.is_empty());
366 }
367}