1use std::collections::{HashMap, VecDeque};
33use std::ffi::c_void;
34use std::sync::atomic::{AtomicBool, Ordering};
35use std::sync::{mpsc, Arc, Mutex, OnceLock, Weak};
36
37struct RegistryEntry {
40 bridge: Weak<ActionBridge>,
41 active: Weak<AtomicBool>,
42}
43static BRIDGES: OnceLock<Mutex<HashMap<usize, RegistryEntry>>> = OnceLock::new();
44fn bridges() -> &'static Mutex<HashMap<usize, RegistryEntry>> {
45 BRIDGES.get_or_init(Mutex::default)
46}
47thread_local! {
48 static CURRENT_INVOCATION: std::cell::RefCell<Option<Arc<ActionBridge>>> = const { std::cell::RefCell::new(None) };
49}
50pub(crate) struct InvocationGuard {
51 previous: Option<Arc<ActionBridge>>,
52 _thread_bound: std::marker::PhantomData<std::rc::Rc<()>>,
53}
54impl Drop for InvocationGuard {
55 fn drop(&mut self) {
56 CURRENT_INVOCATION.with(|slot| *slot.borrow_mut() = self.previous.take());
57 }
58}
59
60use rpi_plugin_sdk::{RuntimeActionId, StbString, StbStringRef};
61use tokio::runtime::Handle;
62
63pub const PLUGIN_RESERVED_PREFIX: &str = "pidingo:";
73
74#[derive(Clone, Debug, PartialEq)]
81pub struct UiDialogRequest {
82 pub request_id: String,
83 pub tool_call_id: Option<String>,
84 pub ui: serde_json::Value,
85 pub raw: serde_json::Value,
86}
87
88struct UiDialogEntry {
89 request: UiDialogRequest,
90 answer: Option<serde_json::Value>,
91 cancelled: bool,
92}
93
94#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
96#[serde(rename_all = "lowercase")]
97pub enum UiNotificationLevel {
98 Info,
99 Warning,
100 Error,
101}
102
103#[derive(Debug, serde::Deserialize)]
105#[serde(rename_all = "camelCase", deny_unknown_fields)]
106pub struct UiNotification {
107 pub message: String,
108 pub notify_type: Option<UiNotificationLevel>,
109}
110
111const MAX_UI_NOTIFICATIONS: usize = 32;
112const MAX_UI_NOTIFICATION_BYTES: usize = 4096;
113
114struct UiDialogState {
115 attached: bool,
116 attachment_generation: u64,
119 external_takeover: bool,
126 pending: VecDeque<String>,
127 notifications: VecDeque<UiNotification>,
128 active: HashMap<String, UiDialogEntry>,
129 cancelled_tool_calls: std::collections::HashSet<String>,
130}
131
132#[derive(Clone)]
136pub struct UiDialogMailbox {
137 state: Arc<Mutex<UiDialogState>>,
138}
139
140impl Default for UiDialogMailbox {
141 fn default() -> Self {
142 Self::new()
143 }
144}
145
146impl UiDialogMailbox {
147 pub fn new() -> Self {
148 Self {
149 state: Arc::new(Mutex::new(UiDialogState {
150 attached: false,
151 attachment_generation: 0,
152 external_takeover: false,
153 pending: VecDeque::new(),
154 notifications: VecDeque::new(),
155 active: HashMap::new(),
156 cancelled_tool_calls: std::collections::HashSet::new(),
157 })),
158 }
159 }
160
161 pub fn notify(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
163 let notification: UiNotification = serde_json::from_value(args)
164 .map_err(|error| format!("invalid UI notification: {error}"))?;
165 if notification.message.trim().is_empty()
166 || notification.message.len() > MAX_UI_NOTIFICATION_BYTES
167 {
168 return Err("notification message must contain 1–4096 bytes".into());
169 }
170 let mut state = self.state.lock().map_err(|_| "UI mailbox unavailable")?;
171 if state.notifications.len() >= MAX_UI_NOTIFICATIONS {
172 return Err("UI notification queue is full".into());
173 }
174 state.notifications.push_back(notification);
175 Ok(serde_json::json!({"queued":true}))
176 }
177
178 pub fn take_notifications(&self) -> VecDeque<UiNotification> {
180 self.state
181 .lock()
182 .map(|mut state| std::mem::take(&mut state.notifications))
183 .unwrap_or_default()
184 }
185
186 pub fn attach(&self) {
189 let _ = self.try_attach_with_generation();
190 }
191
192 pub fn try_attach_with_generation(&self) -> Option<u64> {
198 let mut state = self.state.lock().ok()?;
202 let generation = state.attachment_generation.checked_add(1)?;
203 state.attachment_generation = generation;
204 state.attached = true;
205 Some(generation)
206 }
207
208 pub fn attachment_generation(&self) -> Option<u64> {
211 self.state
212 .lock()
213 .ok()
214 .map(|state| state.attachment_generation)
215 }
216
217 pub fn set_external_takeover(&self, takeover: bool) {
228 self.state
229 .lock()
230 .expect("ui dialog mailbox poisoned")
231 .external_takeover = takeover;
232 }
233
234 pub fn external_takeover(&self) -> bool {
236 self.state
237 .lock()
238 .expect("ui dialog mailbox poisoned")
239 .external_takeover
240 }
241
242 pub fn detach(&self) {
245 let Ok(mut state) = self.state.lock() else {
248 return;
249 };
250 Self::detach_locked(&mut state);
251 }
252
253 pub fn detach_if_generation(&self, generation: u64) -> bool {
256 let Ok(mut state) = self.state.lock() else {
260 return false;
261 };
262 if state.attachment_generation != generation {
263 return false;
264 }
265 Self::detach_locked(&mut state);
266 true
267 }
268
269 fn detach_locked(state: &mut UiDialogState) {
270 state.attached = false;
271 state.external_takeover = false;
275 state.pending.clear();
276 for entry in state.active.values_mut() {
277 entry.cancelled = true;
278 entry.answer = None;
279 }
280 }
281
282 pub fn release_takeover(&self) -> usize {
291 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
292 state.external_takeover = false;
293 let mut requeued: Vec<String> = state
294 .active
295 .iter()
296 .filter(|(_, entry)| !entry.cancelled && entry.answer.is_none())
297 .map(|(request_id, _)| request_id.clone())
298 .filter(|request_id| !state.pending.contains(request_id))
299 .collect();
300 if requeued.is_empty() {
301 return 0;
302 }
303 let count = requeued.len();
304 requeued.sort();
306 for request_id in requeued.into_iter().rev() {
307 state.pending.push_front(request_id);
308 }
309 count
310 }
311
312 pub fn is_attached(&self) -> bool {
313 self.state.lock().ok().is_some_and(|state| state.attached)
314 }
315
316 pub fn take_pending(&self) -> Option<UiDialogRequest> {
320 self.take_pending_filtered(|_| true)
321 }
322
323 pub fn take_pending_unless_external<F>(&self, keep: F) -> Option<UiDialogRequest>
332 where
333 F: Fn(&UiDialogRequest) -> bool,
334 {
335 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
336 if state.external_takeover {
337 return None;
338 }
339 Self::take_pending_locked(&mut state, keep)
340 }
341
342 pub fn take_pending_filtered<F>(&self, keep: F) -> Option<UiDialogRequest>
357 where
358 F: Fn(&UiDialogRequest) -> bool,
359 {
360 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
361 Self::take_pending_locked(&mut state, keep)
362 }
363
364 fn take_pending_locked<F>(
365 state: &mut std::sync::MutexGuard<'_, UiDialogState>,
366 keep: F,
367 ) -> Option<UiDialogRequest>
368 where
369 F: Fn(&UiDialogRequest) -> bool,
370 {
371 let mut scanned = 0usize;
372 let total = state.pending.len();
373 while scanned < total {
374 scanned += 1;
375 let Some(request_id) = state.pending.pop_front() else {
376 break;
377 };
378 let Some(entry) = state.active.get(&request_id) else {
379 continue;
380 };
381 if entry.cancelled || entry.answer.is_some() {
382 continue;
383 }
384 let request = entry.request.clone();
385 if keep(&request) {
386 return Some(request);
387 }
388 state.pending.push_back(request_id);
390 }
391 None
392 }
393
394 pub fn take_all_unreserved(&self) -> Vec<UiDialogRequest> {
403 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
404 let mut out: Vec<UiDialogRequest> = Vec::new();
405 let drained = std::mem::take(&mut state.pending);
407 for request_id in drained {
408 let Some(entry) = state.active.get(&request_id) else {
409 continue;
410 };
411 if entry.cancelled || entry.answer.is_some() {
412 continue;
413 }
414 if request_id.starts_with(PLUGIN_RESERVED_PREFIX) {
415 state.pending.push_back(request_id);
416 } else {
417 out.push(entry.request.clone());
418 }
419 }
420 out
421 }
422
423 pub fn is_reserved(&self, request_id: &str) -> bool {
425 request_id.starts_with(PLUGIN_RESERVED_PREFIX)
426 }
427
428 pub fn pending_len(&self) -> usize {
429 self.state
430 .lock()
431 .expect("ui dialog mailbox poisoned")
432 .pending
433 .len()
434 }
435
436 pub fn is_pending(&self, request_id: &str) -> bool {
438 self.state
439 .lock()
440 .expect("ui dialog mailbox poisoned")
441 .active
442 .get(request_id)
443 .is_some_and(|entry| !entry.cancelled && entry.answer.is_none())
444 }
445
446 pub fn respond(&self, request_id: &str, answer: serde_json::Value) -> Result<(), String> {
449 let mut state = self
450 .state
451 .lock()
452 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
453 let entry = state
454 .active
455 .get_mut(request_id)
456 .ok_or_else(|| format!("unknown UI request `{request_id}`"))?;
457 if entry.cancelled {
458 return Err(format!("UI request `{request_id}` was cancelled"));
459 }
460 if entry.answer.is_none() {
461 entry.answer = Some(answer);
462 }
463 Ok(())
464 }
465
466 pub fn cancel(&self, request_id: &str) -> Result<(), String> {
469 let mut state = self
470 .state
471 .lock()
472 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
473 let entry = state
474 .active
475 .get_mut(request_id)
476 .ok_or_else(|| format!("unknown UI request `{request_id}`"))?;
477 entry.cancelled = true;
478 entry.answer = None;
479 state.pending.retain(|id| id != request_id);
480 Ok(())
481 }
482
483 pub fn cancel_all(&self) {
485 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
486 state.pending.clear();
487 for entry in state.active.values_mut() {
488 entry.cancelled = true;
489 entry.answer = None;
490 }
491 }
492
493 pub fn cancel_tool_call(&self, tool_call_id: &str) {
496 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
497 state.cancelled_tool_calls.insert(tool_call_id.to_string());
500 for entry in state.active.values_mut() {
501 if entry.request.tool_call_id.as_deref() == Some(tool_call_id) {
502 entry.cancelled = true;
503 entry.answer = None;
504 }
505 }
506 let cancelled: std::collections::HashSet<String> = state
507 .active
508 .iter()
509 .filter(|(_, entry)| entry.cancelled)
510 .map(|(id, _)| id.clone())
511 .collect();
512 state.pending.retain(|id| !cancelled.contains(id));
513 }
514
515 pub fn poll(&self, request_id: &str) -> Result<serde_json::Value, String> {
518 let mut state = self
519 .state
520 .lock()
521 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
522 let terminal = match state.active.get(request_id) {
523 Some(entry) if entry.cancelled => Some(serde_json::json!({
524 "status": "cancelled",
525 "requestId": request_id,
526 "toolCallId": entry.request.tool_call_id,
527 })),
528 Some(entry) if entry.answer.is_some() => Some(serde_json::json!({
529 "status": "answered",
530 "requestId": request_id,
531 "toolCallId": entry.request.tool_call_id,
532 "answer": entry.answer.clone().unwrap_or(serde_json::Value::Null),
533 })),
534 Some(entry) => Some(serde_json::json!({
535 "status": "pending",
536 "requestId": request_id,
537 "toolCallId": entry.request.tool_call_id,
538 })),
539 None => None,
540 };
541 let Some(result) = terminal else {
542 return Err(format!("unknown UI request `{request_id}`"));
543 };
544 if result.get("status").and_then(serde_json::Value::as_str) != Some("pending") {
545 state.active.remove(request_id);
546 }
547 Ok(result)
548 }
549
550 pub fn forget(&self, request_id: &str) -> Result<bool, String> {
562 let mut state = self
563 .state
564 .lock()
565 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
566 let Some(entry) = state.active.get(request_id) else {
567 return Ok(false);
568 };
569 if !entry.cancelled && entry.answer.is_none() {
570 return Err(format!("UI request `{request_id}` is still pending"));
571 }
572 state.active.remove(request_id);
573 state.pending.retain(|id| id != request_id);
574 Ok(true)
575 }
576
577 pub fn handle(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
582 let op = args
583 .get("op")
584 .and_then(serde_json::Value::as_str)
585 .unwrap_or("open");
586 let request_id = || {
587 args.get("requestId")
588 .or_else(|| args.get("request_id"))
589 .and_then(serde_json::Value::as_str)
590 .map(str::to_owned)
591 .filter(|id| !id.trim().is_empty())
592 .ok_or_else(|| "missing non-empty `requestId`".to_string())
593 };
594 match op {
595 "open" => {
596 let id = request_id()?;
597 let mut state = self
598 .state
599 .lock()
600 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
601 if !state.attached {
602 return Err("ask_user requires an interactive UI".to_string());
603 }
604 if let Some(entry) = state.active.get(&id) {
605 return Ok(if entry.cancelled {
606 serde_json::json!({"status":"cancelled","requestId":id})
607 } else if let Some(answer) = &entry.answer {
608 serde_json::json!({"status":"answered","requestId":id,"answer":answer})
609 } else {
610 serde_json::json!({"status":"pending","requestId":id})
611 });
612 }
613 let tool_call_id = args
614 .get("toolCallId")
615 .or_else(|| args.get("tool_call_id"))
616 .and_then(serde_json::Value::as_str)
617 .map(str::to_owned);
618 if tool_call_id
619 .as_ref()
620 .is_some_and(|id| state.cancelled_tool_calls.contains(id))
621 {
622 return Ok(serde_json::json!({
623 "status": "cancelled", "requestId": id, "toolCallId": tool_call_id,
624 }));
625 }
626 let ui = args.get("ui").cloned().unwrap_or_else(|| args.clone());
627 rpi_plugin_sdk::dialogs::validate(&ui, tool_call_id.as_deref())?;
628 state.active.insert(
629 id.clone(),
630 UiDialogEntry {
631 request: UiDialogRequest {
632 request_id: id.clone(),
633 tool_call_id: tool_call_id.clone(),
634 ui,
635 raw: args,
636 },
637 answer: None,
638 cancelled: false,
639 },
640 );
641 state.pending.push_back(id.clone());
642 Ok(serde_json::json!({"status":"pending","requestId":id,"toolCallId":tool_call_id}))
643 }
644 "poll" => self.poll(&request_id()?),
645 "cancel" => {
646 let id = request_id()?;
647 self.cancel(&id)?;
648 Ok(serde_json::json!({"status":"cancelled","requestId":id}))
649 }
650 "forget" => {
651 let id = request_id()?;
652 let removed = self.forget(&id)?;
653 Ok(serde_json::json!({"status":"forgotten","requestId":id,"removed":removed}))
654 }
655 "response" | "respond" => {
656 let id = request_id()?;
657 let answer = args
658 .get("answer")
659 .or_else(|| args.get("value"))
660 .cloned()
661 .unwrap_or(serde_json::Value::Null);
662 self.respond(&id, answer)?;
663 Ok(serde_json::json!({"status":"answered","requestId":id}))
664 }
665 other => Err(format!("unknown UI dialog operation `{other}`")),
666 }
667 }
668}
669
670pub type SideQuestionSink =
672 Arc<dyn Fn(serde_json::Value) -> Result<serde_json::Value, String> + Send + Sync>;
673
674#[async_trait::async_trait]
689pub trait RuntimeActionHost: Send + Sync {
690 async fn tool_program(
692 &self,
693 capability: Arc<rpi_agent::tool_program::ToolProgram>,
694 args: serde_json::Value,
695 ) -> Result<serde_json::Value, String> {
696 capability.handle(args).await
697 }
698 fn cancel_side_questions(&self, _owner: u64) {}
700 fn side_question_revision(&self) -> u64 {
702 0
703 }
704 fn side_question_views(&self) -> Vec<serde_json::Value> {
705 Vec::new()
706 }
707 async fn side_question_ui(
708 &self,
709 _owner: u64,
710 _thread_id: String,
711 _args: serde_json::Value,
712 ) -> Result<serde_json::Value, String> {
713 Err("SideQuestion UI is not supported by this host".into())
714 }
715 async fn side_question(
717 &self,
718 _owner: u64,
719 _args: serde_json::Value,
720 _sink: SideQuestionSink,
721 ) -> Result<serde_json::Value, String> {
722 Err("SideQuestion is not supported by this host; upgrade rpi".into())
723 }
724
725 fn replace_model_catalog(&self, _models: Vec<rpi_ai::Model>) {}
727 fn cancel_child_agents(&self, _owner: u64) {}
729 fn child_agent_roster(&self) -> Vec<serde_json::Value> {
739 Vec::new()
740 }
741 fn stop_child_agent(&self, _child_id: &str) -> Result<serde_json::Value, String> {
750 Err("child agent control is not supported by this host; upgrade rpi".into())
751 }
752 async fn send_message(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
757 async fn send_user_message(&self, args: serde_json::Value)
759 -> Result<serde_json::Value, String>;
760 async fn append_entry(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
770 async fn set_session_name(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
772 async fn get_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
774 async fn set_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
776 async fn set_model(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
778 async fn get_thinking_level(
780 &self,
781 args: serde_json::Value,
782 ) -> Result<serde_json::Value, String>;
783 async fn set_thinking_level(
785 &self,
786 args: serde_json::Value,
787 ) -> Result<serde_json::Value, String>;
788 async fn compact(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
790 async fn get_system_prompt(&self, args: serde_json::Value)
792 -> Result<serde_json::Value, String>;
793 async fn new_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
795 async fn fork(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
797 async fn navigate_tree(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
799 async fn switch_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
801 async fn reload(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
805
806 async fn reload_models(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
816 Err("reload_models is not supported by this host".to_string())
817 }
818
819 async fn get_cli_flag(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
822 Err("CLI flag lookup is not configured".to_string())
823 }
824
825 async fn ui_dialog(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
829 Err("ask_user requires an interactive UI".to_string())
830 }
831
832 async fn list_commands(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
843 Ok(serde_json::json!({ "commands": [] }))
844 }
845
846 fn publish_registry(&self, _snapshot: std::sync::Arc<crate::registry::RegistrySnapshot>) {}
857
858 fn publish_registry_opt(
864 &self,
865 snapshot: Option<std::sync::Arc<crate::registry::RegistrySnapshot>>,
866 ) {
867 if let Some(snapshot) = snapshot {
868 self.publish_registry(snapshot);
869 }
870 }
871
872 async fn abort(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
880 Ok(serde_json::json!({
881 "aborted": false,
882 "steer": [],
883 "followUp": [],
884 }))
885 }
886
887 fn stop_round(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
897 Ok(serde_json::json!({ "requested": true }))
898 }
899
900 async fn get_execution_context(
902 &self,
903 _args: serde_json::Value,
904 ) -> Result<serde_json::Value, String> {
905 Err("execution context is not supported by this host".into())
906 }
907
908 async fn independent_run(
910 &self,
911 _owner: u64,
912 _args: serde_json::Value,
913 ) -> Result<serde_json::Value, String> {
914 Err("IndependentRun is not supported by this host".into())
915 }
916
917 async fn independent_run_for_tool(
919 &self,
920 owner: u64,
921 args: serde_json::Value,
922 _tool_call_id: Option<String>,
923 ) -> Result<serde_json::Value, String> {
924 self.independent_run(owner, args).await
925 }
926
927 fn supports_child_observations(&self) -> bool {
929 false
930 }
931
932 fn child_observations(
934 &self,
935 _parent: &str,
936 _request: serde_json::Value,
937 ) -> Result<serde_json::Value, String> {
938 Err("child observations are not supported by this host".into())
939 }
940
941 async fn get_session_branch(
951 &self,
952 _args: serde_json::Value,
953 ) -> Result<serde_json::Value, String> {
954 Err("session branch lookup is not configured".to_string())
955 }
956}
957
958pub struct ActionBridge {
985 invocation: Option<ToolInvocation>,
987 execution_context: Option<serde_json::Value>,
988 tool_program: Option<Arc<rpi_agent::tool_program::ToolProgram>>,
989 stdio: crate::StdioLifecycle,
990 plugin_identity: Option<(u64, String)>,
991 component_owners: Arc<std::sync::Mutex<Vec<u64>>>,
992 pub(crate) runtime: Handle,
994 pub(crate) host: Arc<dyn RuntimeActionHost>,
996 pub(crate) reload:
998 Option<Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>>,
999 ui_dialog: UiDialogMailbox,
1002 ext_status: crate::status::ExtensionStatusMailbox,
1006 editor_text: crate::editor_text::EditorTextMailbox,
1010 active: Arc<AtomicBool>,
1013}
1014
1015struct ToolInvocation {
1016 child: bool,
1017 key: String,
1018 signal: tokio_util::sync::CancellationToken,
1019 tool_call_id: Option<String>,
1020}
1021
1022impl ActionBridge {
1023 pub fn user_data(self: &Arc<Self>) -> *mut c_void {
1025 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1);
1026 let mut registry = bridges().lock().unwrap_or_else(|e| e.into_inner());
1027 if let Some((&id, _)) = registry
1028 .iter()
1029 .find(|(_, entry)| entry.bridge.as_ptr() == Arc::as_ptr(self))
1030 {
1031 return id as *mut c_void;
1032 }
1033 let mut id = NEXT.load(Ordering::Relaxed);
1034 loop {
1035 let next = id.checked_add(1).expect("runtime handle space exhausted");
1036 match NEXT.compare_exchange_weak(id, next, Ordering::Relaxed, Ordering::Relaxed) {
1037 Ok(_) => break,
1038 Err(current) => id = current,
1039 }
1040 }
1041 registry.insert(
1042 id,
1043 RegistryEntry {
1044 bridge: Arc::downgrade(self),
1045 active: Arc::downgrade(&self.active),
1046 },
1047 );
1048 id as *mut c_void
1049 }
1050 pub(crate) fn resolve_handle(id: usize) -> Option<Arc<Self>> {
1051 bridges()
1052 .lock()
1053 .unwrap_or_else(|e| e.into_inner())
1054 .get(&id)
1055 .and_then(|entry| entry.bridge.upgrade())
1056 }
1057 #[cfg(test)]
1058 pub(crate) fn for_invocation(
1059 &self,
1060 child: bool,
1061 signal: tokio_util::sync::CancellationToken,
1062 ) -> Arc<Self> {
1063 self.for_tool_invocation(child, signal, None)
1064 }
1065
1066 pub(crate) fn for_tool_invocation(
1067 &self,
1068 child: bool,
1069 signal: tokio_util::sync::CancellationToken,
1070 tool_call_id: Option<String>,
1071 ) -> Arc<Self> {
1072 let tool_program = rpi_agent::tool_program::current();
1073 if let Some(program) = &tool_program {
1074 program.bind_signal(signal.clone());
1075 }
1076 let mut execution_context = rpi_agent::tool_execution_scope::public_execution_context();
1077 if child
1081 && self
1082 .plugin_identity
1083 .as_ref()
1084 .is_some_and(|(_, name)| name == "librpi_goal" || name.starts_with("librpi_goal-v"))
1085 {
1086 execution_context.get_or_insert_with(|| serde_json::json!({}))["childAgent"] =
1087 serde_json::Value::Bool(false);
1088 }
1089 Arc::new(Self {
1090 invocation: Some(ToolInvocation {
1091 child,
1092 key: uuid::Uuid::new_v4().to_string(),
1093 signal,
1094 tool_call_id,
1095 }),
1096 execution_context,
1097 tool_program,
1098 stdio: self.stdio.clone(),
1099 plugin_identity: self.plugin_identity.clone(),
1100 component_owners: self.component_owners.clone(),
1101 runtime: self.runtime.clone(),
1102 host: self.host.clone(),
1103 reload: self.reload.clone(),
1104 ui_dialog: self.ui_dialog.clone(),
1105 ext_status: self.ext_status.clone(),
1106 editor_text: self.editor_text.clone(),
1107 active: self.active.clone(),
1108 })
1109 }
1110 pub(crate) fn resolve_result_reference(
1113 &self,
1114 id: &str,
1115 ) -> Result<(rpi_agent::AgentToolResult, bool), String> {
1116 if !self.is_active()
1117 || !self
1118 .invocation
1119 .as_ref()
1120 .is_some_and(|invocation| !invocation.signal.is_cancelled())
1121 {
1122 return Err("result reference requires a live invocation bridge".into());
1123 }
1124 self.tool_program
1125 .as_ref()
1126 .ok_or("result reference requires an effective ToolProgram")?
1127 .resolve_result_reference(id)
1128 }
1129 pub(crate) fn resolve_content_parts(
1131 &self,
1132 parts: Vec<rpi_agent::tool_program::ToolProgramContentPart>,
1133 ) -> Result<Vec<rpi_agent::TextContentOrImage>, String> {
1134 if !self.is_active()
1135 || !self
1136 .invocation
1137 .as_ref()
1138 .is_some_and(|invocation| !invocation.signal.is_cancelled())
1139 {
1140 return Err("content parts require a live invocation bridge".into());
1141 }
1142 self.tool_program
1143 .as_ref()
1144 .ok_or("content parts require an effective ToolProgram")?
1145 .resolve_content_parts(parts)
1146 }
1147 pub(crate) fn invocation_key(&self) -> Option<&str> {
1148 self.invocation
1149 .as_ref()
1150 .map(|invocation| invocation.key.as_str())
1151 }
1152 pub(crate) fn is_independent_invocation(&self) -> bool {
1153 self.invocation
1154 .as_ref()
1155 .is_some_and(|invocation| invocation.child)
1156 }
1157 pub(crate) fn enter_invocation(self: &Arc<Self>) -> InvocationGuard {
1158 InvocationGuard {
1159 previous: CURRENT_INVOCATION.with(|slot| slot.replace(Some(self.clone()))),
1160 _thread_bound: std::marker::PhantomData,
1161 }
1162 }
1163 pub fn new(runtime: Handle, host: Arc<dyn RuntimeActionHost>) -> Arc<Self> {
1166 Arc::new(Self {
1167 invocation: None,
1168 tool_program: None,
1169 execution_context: None,
1170 stdio: crate::StdioLifecycle::default(),
1171 plugin_identity: None,
1172 component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1173 runtime,
1174 host,
1175 reload: None,
1176 ui_dialog: UiDialogMailbox::new(),
1177 ext_status: crate::status::ExtensionStatusMailbox::new(),
1178 editor_text: crate::editor_text::EditorTextMailbox::new(),
1179 active: Arc::new(AtomicBool::new(true)),
1180 })
1181 }
1182
1183 pub fn with_reload(
1186 runtime: Handle,
1187 host: Arc<dyn RuntimeActionHost>,
1188 reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>,
1189 ) -> Arc<Self> {
1190 Self::with_reload_and_ui(
1191 runtime,
1192 host,
1193 reload,
1194 UiDialogMailbox::new(),
1195 crate::status::ExtensionStatusMailbox::new(),
1196 crate::editor_text::EditorTextMailbox::new(),
1197 )
1198 }
1199
1200 pub fn with_ui_dialog(
1202 runtime: Handle,
1203 host: Arc<dyn RuntimeActionHost>,
1204 ui_dialog: UiDialogMailbox,
1205 ) -> Arc<Self> {
1206 Arc::new(Self {
1207 invocation: None,
1208 tool_program: None,
1209 execution_context: None,
1210 stdio: crate::StdioLifecycle::default(),
1211 plugin_identity: None,
1212 component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1213 runtime,
1214 host,
1215 reload: None,
1216 ui_dialog,
1217 ext_status: crate::status::ExtensionStatusMailbox::new(),
1218 editor_text: crate::editor_text::EditorTextMailbox::new(),
1219 active: Arc::new(AtomicBool::new(true)),
1220 })
1221 }
1222
1223 pub fn with_reload_and_ui(
1225 runtime: Handle,
1226 host: Arc<dyn RuntimeActionHost>,
1227 reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>,
1228 ui_dialog: UiDialogMailbox,
1229 ext_status: crate::status::ExtensionStatusMailbox,
1230 editor_text: crate::editor_text::EditorTextMailbox,
1231 ) -> Arc<Self> {
1232 Arc::new(Self {
1233 invocation: None,
1234 tool_program: None,
1235 execution_context: None,
1236 stdio: crate::StdioLifecycle::default(),
1237 plugin_identity: None,
1238 component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1239 runtime,
1240 host,
1241 reload: Some(reload),
1242 ui_dialog,
1243 ext_status,
1244 editor_text,
1245 active: Arc::new(AtomicBool::new(true)),
1246 })
1247 }
1248
1249 pub(crate) fn for_plugin(&self, name: &str) -> Arc<Self> {
1250 static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1251 let owner = NEXT_ID.fetch_add(1, Ordering::Relaxed);
1252 self.component_owners
1253 .lock()
1254 .unwrap_or_else(|e| e.into_inner())
1255 .push(owner);
1256 Arc::new(Self {
1257 invocation: None,
1258 tool_program: None,
1259 execution_context: None,
1260 component_owners: self.component_owners.clone(),
1261 stdio: self.stdio.clone(),
1262 plugin_identity: Some((owner, name.to_owned())),
1263 runtime: self.runtime.clone(),
1264 host: self.host.clone(),
1265 reload: self.reload.clone(),
1266 ui_dialog: self.ui_dialog.clone(),
1267 ext_status: self.ext_status.clone(),
1268 editor_text: self.editor_text.clone(),
1269 active: self.active.clone(),
1270 })
1271 }
1272
1273 pub fn stdio_lifecycle(&self) -> crate::StdioLifecycle {
1274 self.stdio.clone()
1275 }
1276
1277 pub fn disable_stdio_claims(&self) {
1279 self.stdio.disable_claims();
1280 }
1281
1282 pub(crate) fn claim_stdio(&self) -> Result<(), String> {
1283 let (id, name) = self
1284 .plugin_identity
1285 .as_ref()
1286 .ok_or("missing plugin identity")?;
1287 self.stdio.claim(*id, name)
1288 }
1289
1290 pub(crate) fn release_stdio_claim(&self) {
1291 if let Some((id, _)) = &self.plugin_identity {
1292 self.stdio.release_failed_registration(*id);
1293 self.ext_status.remove_owner(*id);
1294 }
1295 }
1296
1297 pub fn ui_dialog_mailbox(&self) -> UiDialogMailbox {
1299 self.ui_dialog.clone()
1300 }
1301
1302 pub fn extension_status_mailbox(&self) -> crate::status::ExtensionStatusMailbox {
1304 self.ext_status.clone()
1305 }
1306
1307 pub fn editor_text_mailbox(&self) -> crate::editor_text::EditorTextMailbox {
1309 self.editor_text.clone()
1310 }
1311
1312 pub fn invalidate(&self) {
1317 let owners = {
1318 let owners = self
1319 .component_owners
1320 .lock()
1321 .unwrap_or_else(|e| e.into_inner());
1322 self.active.store(false, Ordering::SeqCst);
1323 for owner in owners.iter() {
1324 self.ext_status.remove_owner(*owner);
1325 }
1326 owners.clone()
1327 };
1328 let live = self.bridges_for_owner();
1330 for bridge in live {
1331 if let Some(program) = &bridge.tool_program {
1332 program.cancel_all();
1333 }
1334 }
1335 for owner in owners {
1338 self.host.cancel_child_agents(owner);
1339 self.host.cancel_side_questions(owner);
1340 }
1341 }
1342
1343 fn bridges_for_owner(&self) -> Vec<Arc<Self>> {
1344 let active = Arc::downgrade(&self.active);
1345 bridges()
1351 .lock()
1352 .unwrap_or_else(|e| e.into_inner())
1353 .values()
1354 .filter(|entry| entry.active.ptr_eq(&active))
1355 .filter_map(|entry| entry.bridge.upgrade())
1356 .collect()
1357 }
1358
1359 pub fn is_active(&self) -> bool {
1361 self.active.load(Ordering::SeqCst)
1362 }
1363
1364 pub fn clone_host(&self) -> Arc<dyn RuntimeActionHost> {
1371 Arc::clone(&self.host)
1372 }
1373}
1374
1375#[derive(Clone)]
1388pub struct ReloadMailbox {
1389 tx: Arc<std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<()>>>>,
1390}
1391
1392impl Default for ReloadMailbox {
1393 fn default() -> Self {
1394 Self {
1395 tx: Arc::new(std::sync::Mutex::new(None)),
1396 }
1397 }
1398}
1399
1400impl ReloadMailbox {
1401 pub fn new() -> Self {
1403 Self::default()
1404 }
1405
1406 pub fn install(&self, tx: tokio::sync::mpsc::UnboundedSender<()>) {
1410 *self.tx.lock().unwrap() = Some(tx);
1411 }
1412
1413 pub fn signal(&self) -> Result<(), ()> {
1418 let g = self.tx.lock().unwrap();
1419 match &*g {
1420 Some(tx) => {
1421 let _ = tx.send(());
1422 Ok(())
1423 }
1424 None => Err(()),
1425 }
1426 }
1427
1428 pub fn clear(&self) {
1430 *self.tx.lock().unwrap() = None;
1431 }
1432}
1433
1434pub struct ReloadModelsMailbox {
1445 tx: Arc<std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<ReloadModelsRequest>>>>,
1446}
1447
1448impl Default for ReloadModelsMailbox {
1449 fn default() -> Self {
1450 Self {
1451 tx: Arc::new(std::sync::Mutex::new(None)),
1452 }
1453 }
1454}
1455
1456pub struct ReloadModelsRequest {
1458 pub reply: tokio::sync::oneshot::Sender<Result<usize, String>>,
1460}
1461
1462impl Clone for ReloadModelsMailbox {
1463 fn clone(&self) -> Self {
1464 Self {
1465 tx: Arc::clone(&self.tx),
1466 }
1467 }
1468}
1469
1470impl ReloadModelsMailbox {
1471 pub fn new() -> Self {
1472 Self::default()
1473 }
1474
1475 pub fn install(&self, tx: tokio::sync::mpsc::UnboundedSender<ReloadModelsRequest>) {
1477 *self.tx.lock().unwrap() = Some(tx);
1478 }
1479
1480 pub async fn request(&self) -> Result<usize, String> {
1485 let (reply, wait) = tokio::sync::oneshot::channel();
1486 let tx = self.tx.lock().unwrap().clone();
1487 let Some(tx) = tx else {
1488 return Err("reload_models is not available (no TUI attached)".to_string());
1489 };
1490 tx.send(ReloadModelsRequest { reply })
1491 .map_err(|_| "reload_models request dropped (TUI gone)".to_string())?;
1492 wait.await
1493 .map_err(|_| "reload_models request dropped (TUI gone)".to_string())?
1494 }
1495
1496 pub fn clear(&self) {
1498 *self.tx.lock().unwrap() = None;
1499 }
1500}
1501
1502pub fn reload_callback_from_mailbox(
1509 mailbox: ReloadMailbox,
1510) -> Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync> {
1511 Arc::new(move || {
1512 let m = mailbox.clone();
1513 Box::pin(async move {
1514 let _ = m.signal();
1515 })
1516 })
1517}
1518
1519fn dispatch_relay_ui_dialog(
1534 ui_dialog: &UiDialogMailbox,
1535 args: serde_json::Value,
1536) -> Result<serde_json::Value, String> {
1537 let op = args
1538 .get("op")
1539 .and_then(serde_json::Value::as_str)
1540 .unwrap_or("take");
1541 match op {
1542 "take" => {
1543 ui_dialog.set_external_takeover(true);
1547 let requests: Vec<serde_json::Value> = ui_dialog
1548 .take_all_unreserved()
1549 .into_iter()
1550 .map(|request| {
1551 serde_json::json!({
1552 "requestId": request.request_id,
1553 "toolCallId": request.tool_call_id,
1554 "ui": request.ui,
1555 })
1556 })
1557 .collect();
1558 Ok(serde_json::json!({ "requests": requests }))
1559 }
1560 "release" => {
1563 let requeued = ui_dialog.release_takeover();
1564 Ok(serde_json::json!({ "requeued": requeued }))
1565 }
1566 "respond" | "cancel" | "forget" => ui_dialog.handle(args),
1568 other => Err(format!("RelayUiDialog does not support op `{other}`")),
1569 }
1570}
1571
1572async fn dispatch(
1573 host: &Arc<dyn RuntimeActionHost>,
1574 ui_dialog: &UiDialogMailbox,
1575 ext_status: &crate::status::ExtensionStatusMailbox,
1576 editor_text: &crate::editor_text::EditorTextMailbox,
1577 action: RuntimeActionId,
1578 args: serde_json::Value,
1579) -> Result<serde_json::Value, String> {
1580 match action {
1581 RuntimeActionId::SendMessage => host.send_message(args).await,
1582 RuntimeActionId::SendUserMessage => host.send_user_message(args).await,
1583 RuntimeActionId::AppendEntry => host.append_entry(args).await,
1584 RuntimeActionId::SetSessionName => host.set_session_name(args).await,
1585 RuntimeActionId::GetActiveTools => host.get_active_tools(args).await,
1586 RuntimeActionId::SetActiveTools => host.set_active_tools(args).await,
1587 RuntimeActionId::SetModel => host.set_model(args).await,
1588 RuntimeActionId::GetThinkingLevel => host.get_thinking_level(args).await,
1589 RuntimeActionId::SetThinkingLevel => host.set_thinking_level(args).await,
1590 RuntimeActionId::Compact => host.compact(args).await,
1591 RuntimeActionId::GetSystemPrompt => host.get_system_prompt(args).await,
1592 RuntimeActionId::NewSession => host.new_session(args).await,
1593 RuntimeActionId::Fork => host.fork(args).await,
1594 RuntimeActionId::NavigateTree => host.navigate_tree(args).await,
1595 RuntimeActionId::SwitchSession => host.switch_session(args).await,
1596 RuntimeActionId::Reload => host.reload(args).await,
1597 RuntimeActionId::ReloadModels => host.reload_models(args).await,
1598 RuntimeActionId::GetCliFlag => host.get_cli_flag(args).await,
1599 RuntimeActionId::UiDialog => ui_dialog.handle(args),
1600 RuntimeActionId::UiNotify => ui_dialog.notify(args),
1601 RuntimeActionId::SetStatus => ext_status.handle(args),
1604 RuntimeActionId::UiComponent => Err("UiComponent requires a plugin bridge".into()),
1605 RuntimeActionId::SetEditorText => editor_text.handle(args),
1608 RuntimeActionId::GetEditorText => editor_text.handle_get(args),
1611 RuntimeActionId::GetSessionBranch => host.get_session_branch(args).await,
1612 RuntimeActionId::GetExecutionContext => host.get_execution_context(args).await,
1613 RuntimeActionId::ToolProgram => Err("ToolProgram requires a live invocation bridge".into()),
1614 RuntimeActionId::IndependentRun => Err("IndependentRun requires a plugin bridge".into()),
1615 RuntimeActionId::SideQuestion => Err("SideQuestion requires a plugin bridge".into()),
1616 RuntimeActionId::ListCommands => host.list_commands(args).await,
1617 RuntimeActionId::Abort => host.abort(args).await,
1618 RuntimeActionId::RelayUiDialog => dispatch_relay_ui_dialog(ui_dialog, args),
1622 RuntimeActionId::StopRound => host.stop_round(args),
1623 RuntimeActionId::StdioLifecycle => {
1624 Err("stdio lifecycle requires a plugin context".to_owned())
1625 }
1626 }
1627}
1628
1629pub extern "C" fn trampoline_runtime_action(
1653 action_id: u32,
1654 args_json: StbStringRef,
1655 out: *mut StbString,
1656 user_data: *mut c_void,
1657) -> i32 {
1658 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1659 run_action(
1660 action_id,
1661 rpi_plugin_sdk::RuntimeActionId::MAX,
1663 args_json,
1664 out,
1665 user_data,
1666 )
1667 }));
1668 match outcome {
1669 Ok(rc) => rc,
1670 Err(_) => {
1671 tracing::error!("runtime_action trampoline panicked — reporting host error");
1675 if !out.is_null() {
1676 unsafe {
1677 *out = StbString::from_string(
1678 r#"{"error":"runtime_action panicked"}"#.to_string(),
1679 );
1680 }
1681 }
1682 1
1683 }
1684 }
1685}
1686
1687fn run_action(
1689 action_id: u32,
1690 max_action_id: u32,
1691 args_json: StbStringRef,
1692 out: *mut StbString,
1693 user_data: *mut c_void,
1694) -> i32 {
1695 let action = match RuntimeActionId::try_from(action_id) {
1699 Ok(action) if action_id <= max_action_id => action,
1700 Ok(_) | Err(_) => {
1701 if !out.is_null() {
1702 let json = serde_json::json!({
1703 "error": format!("unknown runtime action id {action_id}")
1704 })
1705 .to_string();
1706 unsafe {
1710 *out = StbString::from_string(json);
1711 }
1712 }
1713 return 2;
1714 }
1715 };
1716
1717 if user_data.is_null() {
1718 return -1;
1719 }
1720 let invocation = CURRENT_INVOCATION.with(|slot| slot.borrow().clone());
1723 let invocation_thread = invocation.is_some();
1724 let bridge = invocation.or_else(|| ActionBridge::resolve_handle(user_data as usize));
1725 let Some(bridge) = bridge else {
1726 if !out.is_null() {
1727 unsafe {
1729 *out = StbString::from_string("{\"error\":\"expired runtime handle\"}".into());
1730 }
1731 }
1732 return 1;
1733 };
1734
1735 if !bridge.is_active() {
1743 if out.is_null() {
1744 return 1;
1745 }
1746 let json = serde_json::json!({
1747 "error": "runtime_action on a stale ActionBridge (session reloaded/swapped)"
1748 })
1749 .to_string();
1750 unsafe {
1751 *out = StbString::from_string(json);
1752 }
1753 return 1;
1754 }
1755
1756 let args_str = unsafe { args_json.as_str() };
1759 let mut args: serde_json::Value = if args_str.is_empty() {
1760 serde_json::Value::Object(serde_json::Map::new())
1761 } else {
1762 serde_json::from_str(args_str)
1763 .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new()))
1764 };
1765
1766 let runtime_key = args
1767 .as_object_mut()
1768 .and_then(|args| args.remove("__rpiRuntimeKey"));
1769
1770 let (tx, rx) = mpsc::sync_channel::<Result<serde_json::Value, String>>(1);
1775 let host = Arc::clone(&bridge.host);
1779 let ui_dialog = bridge.ui_dialog.clone();
1780 let ext_status = bridge.ext_status.clone();
1781 let editor_text = bridge.editor_text.clone();
1782 let reload_cb = bridge.reload.clone();
1783 let execution_context = bridge.execution_context.clone();
1784 if action == RuntimeActionId::StdioLifecycle {
1785 let result = bridge.stdio.handle(
1786 bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id),
1787 args,
1788 );
1789 let _ = tx.send(result);
1790 } else if action == RuntimeActionId::UiComponent {
1791 let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1792 let _owners = bridge
1793 .component_owners
1794 .lock()
1795 .unwrap_or_else(|e| e.into_inner());
1796 let result = if bridge.is_active() {
1797 ext_status.component(owner, args)
1798 } else {
1799 Err("stale plugin bridge".into())
1800 };
1801 let _ = tx.send(result);
1802 } else if action == RuntimeActionId::SideQuestion {
1803 let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1804 if owner == 0 || bridge.invocation.is_some() {
1805 let _ = tx.send(Err(
1806 "SideQuestion requires a plugin command, not a tool invocation".into(),
1807 ));
1808 } else {
1809 let weak = Arc::downgrade(&bridge);
1812 let sink: SideQuestionSink = Arc::new(move |args| {
1813 let bridge = weak.upgrade().ok_or("expired side question bridge")?;
1814 let _owners = bridge
1815 .component_owners
1816 .lock()
1817 .unwrap_or_else(|e| e.into_inner());
1818 if !bridge.is_active() {
1819 return Err("stale side question bridge".into());
1820 }
1821 if args["op"] == "check" {
1822 return Ok(serde_json::json!({"ok":true}));
1823 }
1824 bridge.ext_status.component(owner, args)
1825 });
1826 bridge.runtime.spawn(async move {
1827 let _ = tx.send(host.side_question(owner, args, sink).await);
1828 });
1829 }
1830 } else if action == RuntimeActionId::GetActiveTools && bridge.tool_program.is_some() {
1831 let tools = bridge
1832 .tool_program
1833 .as_ref()
1834 .expect("checked")
1835 .active_tool_names();
1836 let _ = tx.send(Ok(serde_json::json!({"tools":tools})));
1837 } else if action == RuntimeActionId::SetActiveTools && bridge.execution_context.is_some() {
1838 let _ = tx.send(Err(
1839 "cannot replace active tools from a narrowed execution".into()
1840 ));
1841 } else if action == RuntimeActionId::ToolProgram {
1842 let cleanup = matches!(
1843 args.get("op").and_then(serde_json::Value::as_str),
1844 Some("poll" | "cancel" | "dispose" | "release_result")
1845 );
1846 let authenticated = bridge.invocation.as_ref().is_some_and(|invocation| {
1847 (cleanup || !invocation.signal.is_cancelled())
1848 && (invocation_thread
1849 || runtime_key.as_ref().and_then(serde_json::Value::as_str)
1850 == Some(invocation.key.as_str()))
1851 });
1852 if let Some(capability) = bridge.tool_program.clone().filter(|_| authenticated) {
1853 let signal = bridge
1854 .invocation
1855 .as_ref()
1856 .expect("authenticated")
1857 .signal
1858 .clone();
1859 bridge.runtime.spawn(async move {
1860 if signal.is_cancelled() {
1861 capability.cancel_all();
1862 if !cleanup {
1863 let _ = tx.send(Err("parent invocation is no longer active".into()));
1864 return;
1865 }
1866 }
1867 let _ = tx.send(host.tool_program(capability, args).await);
1868 });
1869 } else {
1870 let _ = tx.send(Err(
1871 "ToolProgram requires an authenticated executing invocation".into(),
1872 ));
1873 }
1874 } else if action == RuntimeActionId::IndependentRun {
1875 let cleanup = matches!(
1880 args.get("op").and_then(serde_json::Value::as_str),
1881 Some("poll" | "cancel" | "dispose")
1882 );
1883 let allowed = bridge.invocation.as_ref().is_some_and(|invocation| {
1884 !invocation.child
1885 && (cleanup || !invocation.signal.is_cancelled())
1886 && (invocation_thread
1887 || runtime_key.as_ref().and_then(serde_json::Value::as_str)
1888 == Some(invocation.key.as_str()))
1889 });
1890 if !allowed {
1891 let _ = tx.send(Err(
1892 "IndependentRun requires a live top-level tool invocation".into(),
1893 ));
1894 } else {
1895 let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1896 let invocation = bridge.invocation.as_ref().expect("authorized invocation");
1897 let signal = invocation.signal.clone();
1898 let tool_call_id = invocation.tool_call_id.clone();
1899 bridge.runtime.spawn(async move {
1900 let result = rpi_agent::tool_execution_scope::with_invocation_signal(
1901 signal,
1902 host.independent_run_for_tool(owner, args, tool_call_id),
1903 )
1904 .await;
1905 let _ = tx.send(result);
1906 });
1907 }
1908 } else if action == RuntimeActionId::UiNotify {
1909 let _ = tx.send(ui_dialog.notify(args));
1911 } else if action == RuntimeActionId::SetStatus {
1912 std::thread::spawn(move || {
1917 let _ = tx.send(ext_status.handle(args));
1918 });
1919 } else if action == RuntimeActionId::SetEditorText {
1920 std::thread::spawn(move || {
1923 let _ = tx.send(editor_text.handle(args));
1924 });
1925 } else if action == RuntimeActionId::RelayUiDialog {
1926 std::thread::spawn(move || {
1932 let _ = tx.send(dispatch_relay_ui_dialog(&ui_dialog, args));
1933 });
1934 } else if action == RuntimeActionId::UiDialog {
1935 std::thread::spawn(move || {
1941 let _ = tx.send(ui_dialog.handle(args));
1942 });
1943 } else {
1944 bridge.runtime.spawn(async move {
1945 let mut r = if action == RuntimeActionId::Reload {
1946 if let Some(cb) = reload_cb {
1947 cb().await;
1948 Ok(serde_json::Value::Null)
1949 } else {
1950 host.reload(args).await
1951 }
1952 } else {
1953 dispatch(&host, &ui_dialog, &ext_status, &editor_text, action, args).await
1954 };
1955 if action == RuntimeActionId::GetExecutionContext {
1956 if let (Ok(context), Some(serde_json::Value::Object(fields))) =
1957 (&mut r, execution_context)
1958 {
1959 if let Some(object) = context.as_object_mut() {
1960 object.extend(fields);
1961 }
1962 }
1963 }
1964 let _ = tx.send(r);
1967 });
1968 }
1969
1970 let received = if Handle::try_current()
1976 .is_ok_and(|handle| handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread)
1977 {
1978 tokio::task::block_in_place(|| rx.recv())
1979 } else {
1980 rx.recv()
1981 };
1982 let result = match received {
1983 Ok(r) => r,
1984 Err(_) => {
1985 return -2;
1990 }
1991 };
1992
1993 if out.is_null() {
1996 return match result {
1998 Ok(_) => 0,
1999 Err(_) => 1,
2000 };
2001 }
2002
2003 let (rc, payload) = match result {
2004 Ok(value) => {
2005 let json = serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string());
2006 (0, json)
2007 }
2008 Err(msg) => {
2009 let json = serde_json::json!({ "error": msg }).to_string();
2010 (1, json)
2011 }
2012 };
2013 unsafe {
2019 *out = StbString::from_string(payload);
2020 }
2021 rc
2022}
2023
2024#[cfg(test)]
2033mod tests {
2034 use super::*;
2035 use std::sync::Mutex;
2036
2037 #[test]
2046 fn host_child_agent_control_has_no_plugin_action_id() {
2047 assert!(
2048 RuntimeActionId::try_from(31).is_ok(),
2049 "ReloadModels must remain a valid runtime action id"
2050 );
2051 assert!(
2056 RuntimeActionId::try_from(32).is_ok(),
2057 "GetEditorText must remain a valid runtime action id"
2058 );
2059 assert_eq!(
2062 RuntimeActionId::try_from(33),
2063 Ok(RuntimeActionId::IndependentRun)
2064 );
2065 assert_eq!(RuntimeActionId::try_from(34), Ok(RuntimeActionId::UiNotify));
2067 assert!(
2068 RuntimeActionId::try_from(35).is_err(),
2069 "a new RuntimeActionId was added: re-verify that host-only child-agent control \
2070 (un-owner-scoped roster/stop) is still unreachable from the plugin ABI"
2071 );
2072 }
2073
2074 #[tokio::test(flavor = "current_thread")]
2075 async fn shared_host_refuses_stdio_during_registration() {
2076 let master = ActionBridge::new(
2077 Handle::current(),
2078 Arc::new(MockHost {
2079 prompt: String::new(),
2080 saw: Mutex::new(Vec::new()),
2081 }),
2082 );
2083 master.disable_stdio_claims();
2084 let plugin = crate::HostApi::with_action_bridge(
2085 "stdio-plugin",
2086 crate::ExtensionRegistry::new(),
2087 Arc::new(crate::NullDiagnostics),
2088 master.clone(),
2089 );
2090 let vtable = plugin.build_vtable();
2091 let _registration = crate::enter_current_api(&plugin);
2092 let declare = vtable.declare.unwrap();
2093 assert_ne!(declare(StbStringRef::from_str(r#"{"ownsStdio":true}"#)), 0);
2094 assert!(plugin.take_registry().unwrap().declared_owns_stdio());
2095 assert!(master.stdio_lifecycle().validate().is_ok());
2096 }
2097
2098 #[tokio::test(flavor = "current_thread")]
2099 async fn stdio_claim_is_exclusive_and_only_its_scoped_context_can_finish() {
2100 let master = ActionBridge::new(
2101 Handle::current(),
2102 Arc::new(MockHost {
2103 prompt: String::new(),
2104 saw: Mutex::new(Vec::new()),
2105 }),
2106 );
2107 let diag: Arc<dyn crate::PluginDiagnostics> = Arc::new(crate::NullDiagnostics);
2108 let owner = crate::HostApi::with_action_bridge(
2109 "owner",
2110 crate::ExtensionRegistry::new(),
2111 diag.clone(),
2112 master.clone(),
2113 );
2114 let other = crate::HostApi::with_action_bridge(
2115 "other",
2116 crate::ExtensionRegistry::new(),
2117 diag,
2118 master.clone(),
2119 );
2120 let vtable = owner.build_vtable();
2121 let claim = r#"{"ownsStdio":true}"#;
2122 {
2123 let _registration = crate::enter_current_api(&owner);
2124 assert_eq!(vtable.declare.unwrap()(StbStringRef::from_str(claim)), 0);
2125 }
2126 let other_vtable = other.build_vtable();
2127 let finish = StbStringRef::from_str(r#"{"op":"finish","exitCode":7}"#);
2128 let mut out = StbString::empty();
2129 assert_eq!(
2131 (other_vtable.runtime_action)(
2132 RuntimeActionId::StdioLifecycle as u32,
2133 finish,
2134 &mut out,
2135 other_vtable.user_data
2136 ),
2137 1
2138 );
2139 unsafe { (other_vtable.free_string)(out) };
2141 assert_eq!(
2142 (vtable.runtime_action)(
2143 RuntimeActionId::StdioLifecycle as u32,
2144 finish,
2145 &mut out,
2146 vtable.user_data
2147 ),
2148 0
2149 );
2150 unsafe { (vtable.free_string)(out) };
2152 assert_eq!(master.stdio_lifecycle().wait().await, 7);
2153 {
2154 let _registration = crate::enter_current_api(&other);
2155 assert_ne!(
2156 other_vtable.declare.unwrap()(StbStringRef::from_str(claim)),
2157 0
2158 );
2159 }
2160 assert!(master
2161 .stdio_lifecycle()
2162 .validate()
2163 .unwrap_err()
2164 .contains("owner"));
2165 }
2166
2167 struct MockHost {
2172 prompt: String,
2173 saw: Mutex<Vec<RuntimeActionId>>,
2174 }
2175
2176 #[test]
2177 fn runtime_action_from_a_tokio_worker_does_not_block_its_dispatch() {
2178 const CHILD: &str = "RPI_RUNTIME_ACTION_WORKER_REGRESSION_CHILD";
2179 if std::env::var_os(CHILD).is_some() {
2180 let runtime = tokio::runtime::Builder::new_multi_thread()
2181 .worker_threads(1)
2182 .enable_all()
2183 .build()
2184 .unwrap();
2185 runtime.block_on(async {
2186 tokio::spawn(async {
2189 let host = Arc::new(MockHost {
2190 prompt: "worker callback".into(),
2191 saw: Mutex::new(Vec::new()),
2192 });
2193 let bridge = ActionBridge::new(Handle::current(), host);
2194 let mut out = StbString::empty();
2195 assert_eq!(
2196 trampoline_runtime_action(
2197 RuntimeActionId::GetSystemPrompt.into(),
2198 StbStringRef::from_str("{}"),
2199 &mut out,
2200 bridge.user_data(),
2201 ),
2202 0
2203 );
2204 let text = unsafe {
2206 rpi_plugin_sdk::callbacks::OwnedString::from_raw(
2207 out,
2208 Some(crate::host_free_string),
2209 )
2210 }
2211 .to_string_lossy();
2212 assert_eq!(
2213 serde_json::from_str::<serde_json::Value>(&text).unwrap()["prompt"],
2214 "worker callback"
2215 );
2216 })
2217 .await
2218 .unwrap();
2219 });
2220 return;
2221 }
2222 let mut child = std::process::Command::new(std::env::current_exe().unwrap())
2225 .args([
2226 "--exact",
2227 "actions::tests::runtime_action_from_a_tokio_worker_does_not_block_its_dispatch",
2228 "--nocapture",
2229 ])
2230 .env(CHILD, "1")
2231 .stdout(std::process::Stdio::piped())
2232 .stderr(std::process::Stdio::piped())
2233 .spawn()
2234 .unwrap();
2235 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2236 while child.try_wait().unwrap().is_none() {
2237 if std::time::Instant::now() >= deadline {
2238 let _ = child.kill();
2239 let _ = child.wait();
2240 panic!("runtime action blocked the worker needed by its own dispatch");
2241 }
2242 std::thread::sleep(std::time::Duration::from_millis(10));
2243 }
2244 let output = child.wait_with_output().unwrap();
2245 assert!(
2246 output.status.success(),
2247 "{}\n{}",
2248 String::from_utf8_lossy(&output.stdout),
2249 String::from_utf8_lossy(&output.stderr)
2250 );
2251 }
2252
2253 #[async_trait::async_trait]
2254 impl RuntimeActionHost for MockHost {
2255 async fn send_message(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2256 unreachable!("not under test")
2257 }
2258 async fn send_user_message(
2259 &self,
2260 _: serde_json::Value,
2261 ) -> Result<serde_json::Value, String> {
2262 unreachable!("not under test")
2263 }
2264 async fn append_entry(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2265 unreachable!("not under test")
2266 }
2267 async fn set_session_name(
2268 &self,
2269 _: serde_json::Value,
2270 ) -> Result<serde_json::Value, String> {
2271 unreachable!("not under test")
2272 }
2273 async fn get_active_tools(
2274 &self,
2275 _: serde_json::Value,
2276 ) -> Result<serde_json::Value, String> {
2277 unreachable!("not under test")
2278 }
2279 async fn set_active_tools(
2280 &self,
2281 _: serde_json::Value,
2282 ) -> Result<serde_json::Value, String> {
2283 unreachable!("not under test")
2284 }
2285 async fn set_model(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2286 unreachable!("not under test")
2287 }
2288 async fn get_thinking_level(
2289 &self,
2290 _: serde_json::Value,
2291 ) -> Result<serde_json::Value, String> {
2292 unreachable!("not under test")
2293 }
2294 async fn set_thinking_level(
2295 &self,
2296 _: serde_json::Value,
2297 ) -> Result<serde_json::Value, String> {
2298 unreachable!("not under test")
2299 }
2300 async fn compact(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2301 unreachable!("not under test")
2302 }
2303 async fn get_system_prompt(
2304 &self,
2305 _: serde_json::Value,
2306 ) -> Result<serde_json::Value, String> {
2307 self.saw
2308 .lock()
2309 .unwrap()
2310 .push(RuntimeActionId::GetSystemPrompt);
2311 Ok(serde_json::json!({ "prompt": self.prompt }))
2312 }
2313 async fn new_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2314 unreachable!("not under test")
2315 }
2316 async fn fork(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2317 unreachable!("not under test")
2318 }
2319 async fn navigate_tree(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2320 unreachable!("not under test")
2321 }
2322 async fn switch_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2323 unreachable!("not under test")
2324 }
2325 async fn reload(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2326 self.saw.lock().unwrap().push(RuntimeActionId::Reload);
2327 Ok(serde_json::Value::Null)
2328 }
2329 async fn get_cli_flag(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2330 self.saw.lock().unwrap().push(RuntimeActionId::GetCliFlag);
2331 Ok(serde_json::json!({ "value": true }))
2332 }
2333 }
2334
2335 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2339 async fn trampoline_round_trips_get_system_prompt() {
2340 let host = Arc::new(MockHost {
2341 prompt: "hello from host".to_string(),
2342 saw: Mutex::new(Vec::new()),
2343 });
2344 let host_for_assert = Arc::clone(&host);
2345 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2346 let runtime = tokio::runtime::Handle::current();
2347 let bridge = ActionBridge::new(runtime, host_dyn);
2348 let user_data = bridge.user_data();
2349
2350 let args_str = "{}";
2352 let args_ref = StbStringRef::from_str(args_str);
2353
2354 let mut out = StbString::empty();
2355 let rc = trampoline_runtime_action(
2356 RuntimeActionId::GetSystemPrompt.into(),
2357 args_ref,
2358 &mut out as *mut StbString,
2359 user_data,
2360 );
2361 assert_eq!(rc, 0, "success return code");
2362
2363 let json_text = unsafe {
2366 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2367 }
2368 .to_string_lossy();
2369 let parsed: serde_json::Value = serde_json::from_str(&json_text).expect("valid json");
2370 assert_eq!(parsed["prompt"], "hello from host");
2371
2372 let saw = host_for_assert.saw.lock().unwrap().clone();
2375 assert_eq!(saw, vec![RuntimeActionId::GetSystemPrompt]);
2376 }
2377
2378 #[tokio::test]
2384 async fn trampoline_routes_set_editor_text_into_the_mailbox() {
2385 let host = Arc::new(MockHost {
2386 prompt: String::new(),
2387 saw: Mutex::new(Vec::new()),
2388 });
2389 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2390 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2391 let mailbox = bridge.editor_text_mailbox();
2392 let user_data = bridge.user_data();
2393
2394 let args_ref =
2395 StbStringRef::from_str(r#"{"text":"from voice","mode":"append","autoSendMs":2000}"#);
2396 let mut out = StbString::empty();
2397 let rc = trampoline_runtime_action(
2398 RuntimeActionId::SetEditorText.into(),
2399 args_ref,
2400 &mut out as *mut StbString,
2401 user_data,
2402 );
2403 assert_eq!(rc, 0, "success return code");
2404
2405 let parsed: serde_json::Value = serde_json::from_str(
2407 &unsafe {
2408 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2409 }
2410 .to_string_lossy(),
2411 )
2412 .expect("valid json");
2413 assert_eq!(parsed["ok"], serde_json::json!(true));
2414 assert_eq!(parsed["chars"], serde_json::json!(10));
2415
2416 let edit = mailbox.take_pending().expect("queued edit");
2418 assert_eq!(edit.text, "from voice");
2419 assert_eq!(edit.mode, crate::EditorTextMode::Append);
2420 assert_eq!(edit.auto_send_ms, Some(2000));
2421 assert!(mailbox.take_pending().is_none());
2422 }
2423
2424 #[tokio::test]
2425 async fn trampoline_null_user_data_returns_minus_one() {
2426 let args_ref = StbStringRef::from_str("{}");
2427 let mut out = StbString::empty();
2428 let rc = trampoline_runtime_action(
2429 RuntimeActionId::GetSystemPrompt.into(),
2430 args_ref,
2431 &mut out as *mut StbString,
2432 std::ptr::null_mut(),
2433 );
2434 assert_eq!(rc, -1, "null user_data ⇒ no bridge");
2435 }
2436
2437 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2438 async fn trampoline_intercepts_reload_when_bridge_has_callback() {
2439 use std::sync::atomic::{AtomicUsize, Ordering};
2443 let reload_calls = Arc::new(AtomicUsize::new(0));
2444 let reload_calls_for_cb = Arc::clone(&reload_calls);
2445 let reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync> =
2446 Arc::new(move || {
2447 let c = Arc::clone(&reload_calls_for_cb);
2448 Box::pin(async move {
2449 c.fetch_add(1, Ordering::SeqCst);
2450 })
2451 });
2452 let host = Arc::new(MockHost {
2453 prompt: String::new(),
2454 saw: Mutex::new(Vec::new()),
2455 });
2456 let host_for_assert = Arc::clone(&host);
2457 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2458 let runtime = tokio::runtime::Handle::current();
2459 let bridge = ActionBridge::with_reload(runtime, host_dyn, reload);
2460 let user_data = bridge.user_data();
2461
2462 let args_ref = StbStringRef::from_str("{}");
2463 let mut out = StbString::empty();
2464 let rc = trampoline_runtime_action(
2465 RuntimeActionId::Reload.into(),
2466 args_ref,
2467 &mut out as *mut StbString,
2468 user_data,
2469 );
2470 assert_eq!(rc, 0);
2471 assert_eq!(reload_calls.load(Ordering::SeqCst), 1);
2473 assert!(host_for_assert.saw.lock().unwrap().is_empty());
2474 drop(unsafe {
2476 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2477 });
2478 }
2479
2480 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2485 async fn trampoline_rejects_stale_bridge_with_invalidate() {
2486 let host = Arc::new(MockHost {
2487 prompt: String::new(),
2488 saw: Mutex::new(Vec::new()),
2489 });
2490 let host_for_assert = Arc::clone(&host);
2491 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2492 let runtime = tokio::runtime::Handle::current();
2493 let bridge = ActionBridge::new(runtime, host_dyn);
2494 let user_data = bridge.user_data();
2495
2496 bridge.invalidate();
2498 assert!(!bridge.is_active());
2499
2500 let args_ref = StbStringRef::from_str("{}");
2501 let mut out = StbString::empty();
2502 let rc = trampoline_runtime_action(
2503 RuntimeActionId::GetSystemPrompt.into(),
2504 args_ref,
2505 &mut out as *mut StbString,
2506 user_data,
2507 );
2508 assert_eq!(rc, 1, "stale bridge ⇒ error return code");
2510 let json_text = unsafe {
2512 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2513 }
2514 .to_string_lossy();
2515 assert!(
2516 json_text.contains("stale"),
2517 "stale-bridge error payload: {json_text}"
2518 );
2519
2520 assert!(
2521 host_for_assert.saw.lock().unwrap().is_empty(),
2522 "host dispatch must NOT run on a stale bridge"
2523 );
2524 }
2525
2526 #[tokio::test]
2527 async fn trampoline_rejects_unknown_numeric_id_without_dispatch() {
2528 let host = Arc::new(MockHost {
2529 prompt: String::new(),
2530 saw: Mutex::new(Vec::new()),
2531 });
2532 let host_for_assert = Arc::clone(&host);
2533 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2534 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2535 let user_data = bridge.user_data();
2536
2537 let mut out = StbString::empty();
2538 let rc = trampoline_runtime_action(
2539 0xFFFF_FFFE,
2540 StbStringRef::from_str("{}"),
2541 &mut out,
2542 user_data,
2543 );
2544
2545 assert_eq!(rc, 2, "unknown action id must be a protocol error");
2546 let payload: serde_json::Value = serde_json::from_str(
2547 &unsafe {
2548 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2549 }
2550 .to_string_lossy(),
2551 )
2552 .expect("structured error JSON");
2553 assert_eq!(payload["error"], "unknown runtime action id 4294967294");
2554
2555 assert!(
2556 host_for_assert.saw.lock().unwrap().is_empty(),
2557 "unknown action id must not reach host dispatch"
2558 );
2559 }
2560
2561 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2562 async fn v2_trampoline_accepts_new_action() {
2563 let host = Arc::new(MockHost {
2564 prompt: "v2".to_string(),
2565 saw: Mutex::new(Vec::new()),
2566 });
2567 let host_for_assert = Arc::clone(&host);
2568 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2569 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2570 let user_data = bridge.user_data();
2571
2572 let mut v2_out = StbString::empty();
2573 assert_eq!(
2574 trampoline_runtime_action(
2575 RuntimeActionId::GetCliFlag.into(),
2576 StbStringRef::from_str(r#"{"name":"flag"}"#),
2577 &mut v2_out,
2578 user_data,
2579 ),
2580 0
2581 );
2582 drop(unsafe {
2584 rpi_plugin_sdk::callbacks::OwnedString::from_raw(v2_out, Some(crate::host_free_string))
2585 });
2586
2587 assert_eq!(
2588 *host_for_assert.saw.lock().unwrap(),
2589 vec![RuntimeActionId::GetCliFlag]
2590 );
2591 }
2592
2593 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2598 async fn reload_mailbox_signals_installed_receiver() {
2599 let mailbox = ReloadMailbox::new();
2600 assert!(matches!(mailbox.signal(), Err(())));
2602
2603 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2604 mailbox.install(tx);
2605 let cb = reload_callback_from_mailbox(mailbox.clone());
2606 cb().await;
2607 assert_eq!(
2608 rx.recv().await,
2609 Some(()),
2610 "installed receiver saw the signal"
2611 );
2612 mailbox.clear();
2613 }
2614
2615 fn open_args(id: &str, tool_call: &str) -> serde_json::Value {
2618 serde_json::json!({
2619 "op": "open",
2620 "requestId": id,
2621 "toolCallId": tool_call,
2622 "ui": {"kind": "selector", "questions": [
2623 {"id": "q1", "question": "Which target?", "options": ["Linux"]}
2624 ]},
2625 })
2626 }
2627
2628 #[test]
2631 fn ui_dialog_open_requires_an_attached_ui() {
2632 let mailbox = UiDialogMailbox::new();
2633 let error = mailbox.handle(open_args("r1", "c1")).unwrap_err();
2634 assert!(error.contains("interactive UI"), "got: {error}");
2635 }
2636
2637 #[test]
2638 fn ui_dialog_attachment_generation_exhaustion_fails_closed() {
2639 let mailbox = UiDialogMailbox::new();
2640 mailbox
2641 .state
2642 .lock()
2643 .expect("ui dialog mailbox poisoned")
2644 .attachment_generation = u64::MAX;
2645
2646 assert_eq!(mailbox.try_attach_with_generation(), None);
2647 assert_eq!(mailbox.attachment_generation(), Some(u64::MAX));
2648 assert!(!mailbox.is_attached());
2649
2650 mailbox.attach();
2653 assert!(!mailbox.is_attached());
2654 }
2655
2656 #[test]
2657 fn ui_dialog_attachment_lock_poison_fails_closed_without_panicking() {
2658 let mailbox = UiDialogMailbox::new();
2659 let state = mailbox.state.clone();
2660 assert!(std::thread::spawn(move || {
2661 let _guard = state.lock().unwrap();
2662 panic!("poison synthetic dialog mailbox state");
2663 })
2664 .join()
2665 .is_err());
2666
2667 assert_eq!(mailbox.try_attach_with_generation(), None);
2668 assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2669 mailbox.attach();
2671 }))
2672 .is_ok());
2673 }
2674
2675 #[test]
2676 fn ui_dialog_observation_lock_poison_fails_closed_without_panicking() {
2677 let mailbox = UiDialogMailbox::new();
2678 let state = mailbox.state.clone();
2679 assert!(std::thread::spawn(move || {
2680 let _guard = state.lock().unwrap();
2681 panic!("poison synthetic dialog observation state");
2682 })
2683 .join()
2684 .is_err());
2685
2686 assert_eq!(mailbox.attachment_generation(), None);
2687 assert!(!mailbox.is_attached());
2688 }
2689
2690 #[test]
2691 fn ui_dialog_detach_generation_lock_poison_fails_closed_without_panicking() {
2692 let mailbox = UiDialogMailbox::new();
2693 let state = mailbox.state.clone();
2694 assert!(std::thread::spawn(move || {
2695 let _guard = state.lock().unwrap();
2696 panic!("poison synthetic dialog retirement state");
2697 })
2698 .join()
2699 .is_err());
2700
2701 assert!(!mailbox.detach_if_generation(1));
2702 }
2703
2704 #[test]
2705 fn ui_dialog_compat_detach_lock_poison_fails_closed_without_panicking() {
2706 let mailbox = UiDialogMailbox::new();
2707 let state = mailbox.state.clone();
2708 assert!(std::thread::spawn(move || {
2709 let _guard = state.lock().unwrap();
2710 panic!("poison synthetic dialog compatibility retirement state");
2711 })
2712 .join()
2713 .is_err());
2714
2715 assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2716 mailbox.detach();
2717 }))
2718 .is_ok());
2719 assert_eq!(mailbox.try_attach_with_generation(), None);
2720 }
2721
2722 #[test]
2723 fn ui_dialog_open_poll_answer_round_trip() {
2724 let mailbox = UiDialogMailbox::new();
2725 mailbox.attach();
2726
2727 let opened = mailbox.handle(open_args("r1", "c1")).unwrap();
2728 assert_eq!(opened["status"], "pending");
2729 assert_eq!(opened["toolCallId"], "c1");
2730
2731 let request = mailbox.take_pending().expect("request visible to TUI");
2732 assert_eq!(request.request_id, "r1");
2733 assert_eq!(request.tool_call_id.as_deref(), Some("c1"));
2734 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2736 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2737
2738 mailbox
2739 .respond("r1", serde_json::json!("7890"))
2740 .expect("respond");
2741 let answered = mailbox.poll("r1").unwrap();
2742 assert_eq!(answered["status"], "answered");
2743 assert_eq!(answered["answer"], "7890");
2744 assert!(mailbox.poll("r1").is_err());
2746 }
2747
2748 #[test]
2749 fn ui_dialog_forget_reclaims_terminal_entries_without_stranding_pending_ones() {
2750 let mailbox = UiDialogMailbox::new();
2751 mailbox.attach();
2752
2753 mailbox.handle(open_args("r1", "c1")).unwrap();
2756 assert_eq!(
2757 mailbox.forget("r1"),
2758 Err("UI request `r1` is still pending".to_string())
2759 );
2760 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2761
2762 mailbox.cancel("r1").unwrap();
2765 assert_eq!(mailbox.forget("r1"), Ok(true));
2766 assert_eq!(mailbox.forget("r1"), Ok(false)); assert!(mailbox.poll("r1").is_err());
2768
2769 mailbox.handle(open_args("r2", "c2")).unwrap();
2772 mailbox
2773 .respond("r2", serde_json::json!({"values": ["Linux"]}))
2774 .unwrap();
2775 let forgotten = mailbox
2776 .handle(serde_json::json!({"op": "forget", "requestId": "r2"}))
2777 .unwrap();
2778 assert_eq!(forgotten["status"], "forgotten");
2779 assert_eq!(forgotten["removed"], true);
2780 assert!(mailbox.poll("r2").is_err());
2781
2782 assert_eq!(mailbox.forget("missing"), Ok(false));
2785 let reopened = mailbox.handle(open_args("r1", "c1")).unwrap();
2786 assert_eq!(reopened["status"], "pending");
2787 }
2788
2789 #[test]
2790 fn ui_dialog_cancel_is_reported_once() {
2791 let mailbox = UiDialogMailbox::new();
2792 mailbox.attach();
2793 mailbox.handle(open_args("r1", "c1")).unwrap();
2794 mailbox.cancel("r1").unwrap();
2795 let cancelled = mailbox.poll("r1").unwrap();
2796 assert_eq!(cancelled["status"], "cancelled");
2797 assert!(mailbox.poll("r1").is_err());
2798 }
2799
2800 #[test]
2801 fn ui_dialog_tool_cancel_preserves_other_calls_and_rejects_late_questions() {
2802 let mailbox = UiDialogMailbox::new();
2803 mailbox.attach();
2804 mailbox.handle(open_args("r1", "c1")).unwrap();
2805 mailbox.handle(open_args("r2", "c2")).unwrap();
2806 mailbox.cancel_tool_call("c1");
2807 assert_eq!(mailbox.poll("r1").unwrap()["status"], "cancelled");
2808 assert_eq!(mailbox.take_pending().unwrap().request_id, "r2");
2809 assert_eq!(mailbox.poll("r2").unwrap()["status"], "pending");
2810 assert_eq!(
2811 mailbox.handle(open_args("late", "c1")).unwrap()["status"],
2812 "cancelled"
2813 );
2814 assert!(mailbox.take_pending().is_none());
2815 }
2816
2817 #[test]
2818 fn ui_dialog_concurrent_requests_do_not_cross_answers() {
2819 let mailbox = UiDialogMailbox::new();
2820 mailbox.attach();
2821 mailbox.handle(open_args("r1", "c1")).unwrap();
2822 mailbox.handle(open_args("r2", "c2")).unwrap();
2823
2824 let first = mailbox.take_pending().unwrap().request_id;
2825 let second = mailbox.take_pending().unwrap().request_id;
2826 assert_ne!(first, second);
2827
2828 mailbox
2830 .respond(&second, serde_json::json!("second"))
2831 .unwrap();
2832 assert_eq!(mailbox.poll(&first).unwrap()["status"], "pending");
2833 let second_answer = mailbox.poll(&second).unwrap();
2834 assert_eq!(second_answer["answer"], "second");
2835
2836 mailbox.respond(&first, serde_json::json!("first")).unwrap();
2837 assert_eq!(mailbox.poll(&first).unwrap()["answer"], "first");
2838 }
2839
2840 #[test]
2841 fn ui_dialog_detach_cancels_outstanding() {
2842 let mailbox = UiDialogMailbox::new();
2843 mailbox.attach();
2844 mailbox.handle(open_args("r1", "c1")).unwrap();
2845 mailbox.detach();
2846 assert!(!mailbox.is_attached());
2847 assert_eq!(mailbox.pending_len(), 0);
2848 assert!(mailbox.handle(open_args("r2", "c2")).is_err());
2850 assert_eq!(mailbox.poll("r1").unwrap()["status"], "cancelled");
2851 }
2852
2853 #[test]
2854 fn ui_dialog_duplicate_open_does_not_reenqueue() {
2855 let mailbox = UiDialogMailbox::new();
2856 mailbox.attach();
2857 mailbox.handle(open_args("r1", "c1")).unwrap();
2858 let again = mailbox.handle(open_args("r1", "c1")).unwrap();
2859 assert_eq!(again["status"], "pending");
2860 assert_eq!(mailbox.pending_len(), 1);
2861 mailbox.take_pending().unwrap();
2862 assert!(mailbox.take_pending().is_none());
2863 }
2864
2865 #[tokio::test(flavor = "current_thread")]
2866 async fn ui_notify_routes_synchronously_and_never_opens_a_dialog() {
2867 let mailbox = UiDialogMailbox::new();
2868 let bridge = ActionBridge::with_ui_dialog(
2869 Handle::current(),
2870 Arc::new(MockHost {
2871 prompt: String::new(),
2872 saw: Mutex::new(Vec::new()),
2873 }),
2874 mailbox.clone(),
2875 );
2876 let mut out = StbString::empty();
2877 assert_eq!(
2878 trampoline_runtime_action(
2879 u32::from(RuntimeActionId::UiNotify),
2880 StbStringRef::from_str(r#"{"message":"loaded","notifyType":"warning"}"#),
2881 &mut out,
2882 bridge.user_data(),
2883 ),
2884 0
2885 );
2886 let _reply = unsafe {
2887 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2888 };
2889 let mut batch = mailbox.take_notifications();
2890 let notice = batch.pop_front().unwrap();
2891 assert_eq!(notice.message, "loaded");
2892 assert_eq!(notice.notify_type, Some(UiNotificationLevel::Warning));
2893 assert!(batch.is_empty());
2894 assert_eq!(mailbox.pending_len(), 0);
2895 }
2896
2897 #[test]
2898 fn ui_notification_queue_rejects_invalid_and_excess_messages() {
2899 let mailbox = UiDialogMailbox::new();
2900 assert!(mailbox
2901 .notify(serde_json::json!({"message":"too big".repeat(1000)}))
2902 .is_err());
2903 assert!(mailbox
2904 .notify(serde_json::json!({"message":"text","notifyType":"debug"}))
2905 .is_err());
2906 for index in 0..MAX_UI_NOTIFICATIONS {
2907 mailbox
2908 .notify(serde_json::json!({"message":index.to_string()}))
2909 .unwrap();
2910 }
2911 assert!(mailbox
2912 .notify(serde_json::json!({"message":"full"}))
2913 .is_err());
2914 let batch = mailbox.take_notifications();
2915 assert_eq!(batch.len(), MAX_UI_NOTIFICATIONS);
2916 assert_eq!(batch[0].message, "0");
2917 assert_eq!(batch[0].notify_type, None);
2918 }
2919
2920 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2925 async fn list_commands_routes_to_the_host_and_defaults_to_empty() {
2926 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2927 prompt: String::new(),
2928 saw: Mutex::new(Vec::new()),
2929 });
2930 let bridge = ActionBridge::with_ui_dialog(
2931 tokio::runtime::Handle::current(),
2932 host,
2933 UiDialogMailbox::new(),
2934 );
2935 let user_data = bridge.user_data();
2936 let mut out = StbString::empty();
2937 let rc = trampoline_runtime_action(
2938 u32::from(RuntimeActionId::ListCommands),
2939 StbStringRef::from_str("{}"),
2940 &mut out,
2941 user_data,
2942 );
2943 assert_eq!(
2944 rc, 0,
2945 "ListCommands must not fail on a host with no registry"
2946 );
2947 let payload: serde_json::Value = serde_json::from_str(
2948 &unsafe {
2949 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2950 }
2951 .to_string_lossy(),
2952 )
2953 .expect("JSON");
2954 assert_eq!(
2955 payload
2956 .get("commands")
2957 .and_then(|c| c.as_array())
2958 .map(Vec::len),
2959 Some(0),
2960 "an empty registry is an empty list, not an error: {payload}"
2961 );
2962 }
2963
2964 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2968 async fn v2_dispatch_routes_ui_dialog_action_17() {
2969 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2970 prompt: String::new(),
2971 saw: Mutex::new(Vec::new()),
2972 });
2973 let bridge = ActionBridge::with_ui_dialog(
2974 tokio::runtime::Handle::current(),
2975 host,
2976 UiDialogMailbox::new(),
2977 );
2978 let user_data = bridge.user_data();
2979
2980 let mut out = StbString::empty();
2981 let rc = trampoline_runtime_action(
2982 17,
2983 StbStringRef::from_str(r#"{"op":"open","requestId":"r1","ui":{}}"#),
2984 &mut out,
2985 user_data,
2986 );
2987 assert_eq!(rc, 1);
2988 let payload: serde_json::Value = serde_json::from_str(
2989 &unsafe {
2990 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2991 }
2992 .to_string_lossy(),
2993 )
2994 .expect("structured error JSON");
2995 assert!(
2996 payload["error"]
2997 .as_str()
2998 .is_some_and(|error| error.contains("interactive UI")),
2999 "unexpected payload: {payload}"
3000 );
3001
3002 let one_past_last = rpi_plugin_sdk::RuntimeActionId::MAX + 1;
3006 let mut out = StbString::empty();
3007 assert_eq!(
3008 trampoline_runtime_action(
3009 one_past_last,
3010 StbStringRef::from_str("{}"),
3011 &mut out,
3012 user_data
3013 ),
3014 2
3015 );
3016 drop(unsafe {
3018 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
3019 });
3020 }
3021
3022 #[tokio::test(flavor = "current_thread")]
3023 async fn component_bridge_isolates_plugins_and_cleans_up_reload_and_drop() {
3024 let host = Arc::new(MockHost {
3025 prompt: String::new(),
3026 saw: Mutex::new(Vec::new()),
3027 });
3028 let root = ActionBridge::new(tokio::runtime::Handle::current(), host);
3029 let a = root.for_plugin("a");
3030 let b = root.for_plugin("b");
3031 let mailbox = root.extension_status_mailbox();
3032 for plugin in [&a, &b] {
3033 let mut out = StbString::empty();
3034 assert_eq!(
3035 trampoline_runtime_action(
3036 22,
3037 StbStringRef::from_str(
3038 r#"{"op":"register","id":"same","slot":"footer.after"}"#
3039 ),
3040 &mut out,
3041 plugin.user_data()
3042 ),
3043 0
3044 );
3045 drop(unsafe {
3047 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
3048 });
3049 }
3050 assert_eq!(mailbox.panels().len(), 2);
3051 drop(a);
3052 assert_eq!(mailbox.panels().len(), 1);
3053 root.invalidate();
3054 assert!(mailbox.panels().is_empty());
3055 }
3056
3057 #[test]
3063 fn relay_ui_dialog_runs_off_the_executor() {
3064 let mailbox = UiDialogMailbox::new();
3065 mailbox.attach();
3066 let out = dispatch_relay_ui_dialog(&mailbox, serde_json::json!({"op":"release"}))
3067 .expect("release is a supported op");
3068 assert_eq!(out["requeued"], serde_json::json!(0));
3069 }
3070
3071 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3074 async fn v2_dispatch_routes_set_status_action_18() {
3075 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
3076 prompt: String::new(),
3077 saw: Mutex::new(Vec::new()),
3078 });
3079 let status = crate::status::ExtensionStatusMailbox::new();
3080 let bridge = ActionBridge::with_reload_and_ui(
3081 tokio::runtime::Handle::current(),
3082 host,
3083 Arc::new(|| Box::pin(async {})),
3084 UiDialogMailbox::new(),
3085 status.clone(),
3086 crate::editor_text::EditorTextMailbox::new(),
3087 );
3088 let user_data = bridge.user_data();
3089
3090 let mut out = StbString::empty();
3091 let rc = trampoline_runtime_action(
3092 18,
3093 StbStringRef::from_str(r#"{"key":"langfuse","value":"langfuse ✓ (trace sent)"}"#),
3094 &mut out,
3095 user_data,
3096 );
3097 assert_eq!(rc, 0);
3098 assert_eq!(status.text(), "langfuse ✓ (trace sent)");
3099 drop(unsafe {
3101 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
3102 });
3103
3104 let mut out = StbString::empty();
3106 assert_eq!(
3107 trampoline_runtime_action(
3108 18,
3109 StbStringRef::from_str(r#"{"key":"langfuse","value":""}"#),
3110 &mut out,
3111 user_data
3112 ),
3113 0
3114 );
3115 assert_eq!(status.text(), "");
3116 drop(unsafe {
3118 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
3119 });
3120
3121 let mut out = StbString::empty();
3123 assert_eq!(
3124 trampoline_runtime_action(18, StbStringRef::from_str("{}"), &mut out, user_data),
3125 1
3126 );
3127 drop(unsafe {
3129 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
3130 });
3131 }
3132 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3139 async fn trampoline_ceiling_matches_the_highest_defined_action() {
3140 let highest = RuntimeActionId::MAX;
3141 assert_eq!(
3142 highest,
3143 RuntimeActionId::ALL
3144 .iter()
3145 .copied()
3146 .map(u32::from)
3147 .max()
3148 .unwrap(),
3149 "RuntimeActionId::MAX must be the maximum of RuntimeActionId::ALL"
3150 );
3151 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
3152 prompt: String::new(),
3153 saw: Mutex::new(Vec::new()),
3154 });
3155 let bridge = ActionBridge::with_ui_dialog(
3156 tokio::runtime::Handle::current(),
3157 host,
3158 UiDialogMailbox::new(),
3159 );
3160 let mut out = StbString::empty();
3161 let rc = trampoline_runtime_action(
3162 highest,
3163 StbStringRef::from_str("{}"),
3164 &mut out,
3165 bridge.user_data(),
3166 );
3167 assert_ne!(
3168 rc, 2,
3169 "the highest defined action id ({highest}) must not be rejected as unknown — \
3170 the trampoline ceiling is stale"
3171 );
3172 if rc == 0 {
3173 drop(unsafe {
3175 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
3176 });
3177 }
3178 }
3179}
3180
3181impl Drop for ActionBridge {
3182 fn drop(&mut self) {
3183 bridges()
3184 .lock()
3185 .unwrap_or_else(|e| e.into_inner())
3186 .retain(|_, entry| !std::ptr::eq(entry.bridge.as_ptr(), self));
3187 if self.invocation.is_some() {
3188 return;
3189 }
3190 if let Some((owner, _)) = &self.plugin_identity {
3191 self.ext_status.remove_owner(*owner);
3192 self.host.cancel_child_agents(*owner);
3193 self.host.cancel_side_questions(*owner);
3194 }
3195 }
3196}
3197
3198#[cfg(test)]
3199mod runtime_tests;
3200
3201#[cfg(test)]
3202mod relay_tests {
3203 use super::*;
3204
3205 fn request(id: &str) -> UiDialogRequest {
3206 UiDialogRequest {
3207 request_id: id.to_string(),
3208 tool_call_id: Some(format!("tool-{id}")),
3209 ui: serde_json::json!({"question": "ok?"}),
3210 raw: serde_json::json!({}),
3211 }
3212 }
3213
3214 #[test]
3218 fn reserved_requests_are_invisible_to_the_tui() {
3219 let mailbox = UiDialogMailbox::new();
3220 mailbox.attach();
3221 let reserved = format!("{PLUGIN_RESERVED_PREFIX}gate-1");
3222 mailbox
3223 .handle(serde_json::json!({
3224 "op": "open",
3225 "requestId": reserved,
3226 "toolCallId": "t1",
3227 "ui": {}
3228 }))
3229 .unwrap();
3230 mailbox
3231 .handle(serde_json::json!({
3232 "op": "open",
3233 "requestId": "plain-1",
3234 "toolCallId": "t2",
3235 "ui": {}
3236 }))
3237 .unwrap();
3238
3239 let taken = mailbox
3241 .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
3242 .expect("the unreserved request must reach the TUI");
3243 assert_eq!(taken.request_id, "plain-1");
3244
3245 let own = mailbox
3247 .take_pending_filtered(|r| mailbox.is_reserved(&r.request_id))
3248 .expect("the plugin must still see its reserved request");
3249 assert_eq!(own.request_id, reserved);
3250 }
3251
3252 #[test]
3254 fn release_or_detach_clears_takeover_and_requeues_unanswered() {
3255 let mailbox = UiDialogMailbox::new();
3256 mailbox.attach();
3257 mailbox
3258 .handle(serde_json::json!({
3259 "op": "open", "requestId": "plain-r", "toolCallId": "t", "ui": {}
3260 }))
3261 .unwrap();
3262
3263 mailbox.set_external_takeover(true);
3265 assert_eq!(mailbox.take_all_unreserved().len(), 1);
3266 assert_eq!(mailbox.release_takeover(), 1);
3267 assert!(
3268 !mailbox.external_takeover(),
3269 "release must hand delivery back to the TUI"
3270 );
3271 assert_eq!(
3273 mailbox
3274 .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
3275 .map(|r| r.request_id),
3276 Some("plain-r".to_string())
3277 );
3278
3279 mailbox.set_external_takeover(true);
3281 mailbox.detach();
3282 assert!(!mailbox.external_takeover(), "detach must clear takeover");
3283 }
3284
3285 #[test]
3288 fn tui_take_is_atomic_against_takeover() {
3289 let mailbox = UiDialogMailbox::new();
3290 mailbox.attach();
3291 mailbox.set_external_takeover(true);
3292 mailbox
3293 .handle(serde_json::json!({
3294 "op": "open", "requestId": "plain-a", "toolCallId": "t", "ui": {}
3295 }))
3296 .unwrap();
3297 assert!(
3298 mailbox.take_pending_unless_external(|_| true).is_none(),
3299 "the TUI must stand down while a relay owns delivery"
3300 );
3301 assert_eq!(mailbox.take_all_unreserved().len(), 1);
3303 }
3304
3305 #[test]
3308 fn relay_take_returns_unreserved_and_keeps_reserved() {
3309 let mailbox = UiDialogMailbox::new();
3310 mailbox.attach();
3311 mailbox
3312 .handle(serde_json::json!({
3313 "op": "open",
3314 "requestId": format!("{PLUGIN_RESERVED_PREFIX}keep"),
3315 "toolCallId": "t1",
3316 "ui": {}
3317 }))
3318 .unwrap();
3319 mailbox
3320 .handle(serde_json::json!({
3321 "op": "open",
3322 "requestId": "relay-1",
3323 "toolCallId": "t2",
3324 "ui": {}
3325 }))
3326 .unwrap();
3327
3328 let taken = mailbox.take_all_unreserved();
3329 assert_eq!(taken.len(), 1);
3330 assert_eq!(taken[0].request_id, "relay-1");
3331 assert_eq!(mailbox.pending_len(), 1);
3333 }
3334
3335 #[test]
3338 fn a_relayed_request_can_still_be_answered() {
3339 let mailbox = UiDialogMailbox::new();
3340 mailbox.attach();
3341 mailbox
3342 .handle(serde_json::json!({
3343 "op": "open",
3344 "requestId": "relay-1",
3345 "toolCallId": "t1",
3346 "ui": {}
3347 }))
3348 .unwrap();
3349 let taken = mailbox.take_all_unreserved();
3350 assert_eq!(taken.len(), 1);
3351
3352 mailbox
3353 .handle(serde_json::json!({
3354 "op": "respond",
3355 "requestId": "relay-1",
3356 "answer": {"ok": true}
3357 }))
3358 .unwrap();
3359 assert_eq!(
3361 mailbox
3362 .take_pending_filtered(|_| true)
3363 .map(|r| r.request_id),
3364 None,
3365 "an answered request must not resurface"
3366 );
3367 }
3368
3369 #[test]
3372 fn take_pending_still_takes_reserved_entries() {
3373 let mailbox = UiDialogMailbox::new();
3374 mailbox.attach();
3375 let reserved = format!("{PLUGIN_RESERVED_PREFIX}x");
3376 mailbox
3377 .handle(serde_json::json!({
3378 "op": "open",
3379 "requestId": reserved,
3380 "toolCallId": "t1",
3381 "ui": {}
3382 }))
3383 .unwrap();
3384 assert_eq!(
3385 mailbox.take_pending().map(|r| r.request_id),
3386 Some(format!("{PLUGIN_RESERVED_PREFIX}x"))
3387 );
3388 }
3389
3390 #[test]
3396 fn external_takeover_makes_the_tui_stand_down() {
3397 let mailbox = UiDialogMailbox::new();
3398 mailbox.attach();
3399 mailbox
3400 .handle(serde_json::json!({
3401 "op": "open",
3402 "requestId": "plain-1",
3403 "toolCallId": "t1",
3404 "ui": {}
3405 }))
3406 .unwrap();
3407
3408 assert!(!mailbox.external_takeover());
3409 mailbox.set_external_takeover(true);
3410 assert!(mailbox.external_takeover());
3411
3412 let tui_take = |m: &UiDialogMailbox| {
3414 if m.external_takeover() {
3415 return None;
3416 }
3417 m.take_pending_filtered(|r| !m.is_reserved(&r.request_id))
3418 };
3419 assert!(
3420 tui_take(&mailbox).is_none(),
3421 "the TUI must not steal a request an external UI owns"
3422 );
3423 assert_eq!(mailbox.take_all_unreserved().len(), 1);
3425 }
3426
3427 #[test]
3429 fn clearing_takeover_returns_dialogs_to_the_tui() {
3430 let mailbox = UiDialogMailbox::new();
3431 mailbox.attach();
3432 mailbox.set_external_takeover(true);
3433 mailbox.set_external_takeover(false);
3434 mailbox
3435 .handle(serde_json::json!({
3436 "op": "open",
3437 "requestId": "plain-2",
3438 "toolCallId": "t2",
3439 "ui": {}
3440 }))
3441 .unwrap();
3442 assert_eq!(
3443 mailbox
3444 .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
3445 .map(|r| r.request_id),
3446 Some("plain-2".to_string())
3447 );
3448 }
3449
3450 #[test]
3451 fn request_helper_matches_the_prefix_rule() {
3452 let mailbox = UiDialogMailbox::new();
3453 mailbox.attach();
3454 assert!(mailbox.is_reserved(&request(PLUGIN_RESERVED_PREFIX).request_id));
3455 assert!(!mailbox.is_reserved(&request("plain").request_id));
3456 }
3457}