1use std::collections::{HashMap, VecDeque};
32use std::ffi::c_void;
33use std::sync::atomic::{AtomicBool, Ordering};
34use std::sync::{mpsc, Arc, Mutex, OnceLock, Weak};
35
36struct RegistryEntry {
39 bridge: Weak<ActionBridge>,
40 active: Weak<AtomicBool>,
41}
42static BRIDGES: OnceLock<Mutex<HashMap<usize, RegistryEntry>>> = OnceLock::new();
43fn bridges() -> &'static Mutex<HashMap<usize, RegistryEntry>> {
44 BRIDGES.get_or_init(Mutex::default)
45}
46thread_local! {
47 static CURRENT_INVOCATION: std::cell::RefCell<Option<Arc<ActionBridge>>> = const { std::cell::RefCell::new(None) };
48}
49pub(crate) struct InvocationGuard {
50 previous: Option<Arc<ActionBridge>>,
51 _thread_bound: std::marker::PhantomData<std::rc::Rc<()>>,
52}
53impl Drop for InvocationGuard {
54 fn drop(&mut self) {
55 CURRENT_INVOCATION.with(|slot| *slot.borrow_mut() = self.previous.take());
56 }
57}
58
59use rpi_plugin_sdk::{RuntimeActionId, StbString, StbStringRef};
60use tokio::runtime::Handle;
61
62pub const PLUGIN_RESERVED_PREFIX: &str = "pidingo:";
72
73#[derive(Clone, Debug, PartialEq)]
80pub struct UiDialogRequest {
81 pub request_id: String,
82 pub tool_call_id: Option<String>,
83 pub ui: serde_json::Value,
84 pub raw: serde_json::Value,
85}
86
87struct UiDialogEntry {
88 request: UiDialogRequest,
89 answer: Option<serde_json::Value>,
90 cancelled: bool,
91}
92
93struct UiDialogState {
94 attached: bool,
95 attachment_generation: u64,
98 external_takeover: bool,
105 pending: VecDeque<String>,
106 active: HashMap<String, UiDialogEntry>,
107 cancelled_tool_calls: std::collections::HashSet<String>,
108}
109
110#[derive(Clone)]
114pub struct UiDialogMailbox {
115 state: Arc<Mutex<UiDialogState>>,
116}
117
118impl Default for UiDialogMailbox {
119 fn default() -> Self {
120 Self::new()
121 }
122}
123
124impl UiDialogMailbox {
125 pub fn new() -> Self {
126 Self {
127 state: Arc::new(Mutex::new(UiDialogState {
128 attached: false,
129 attachment_generation: 0,
130 external_takeover: false,
131 pending: VecDeque::new(),
132 active: HashMap::new(),
133 cancelled_tool_calls: std::collections::HashSet::new(),
134 })),
135 }
136 }
137
138 pub fn attach(&self) {
141 let _ = self.try_attach_with_generation();
142 }
143
144 pub fn try_attach_with_generation(&self) -> Option<u64> {
150 let mut state = self.state.lock().ok()?;
154 let generation = state.attachment_generation.checked_add(1)?;
155 state.attachment_generation = generation;
156 state.attached = true;
157 Some(generation)
158 }
159
160 pub fn attachment_generation(&self) -> Option<u64> {
163 self.state
164 .lock()
165 .ok()
166 .map(|state| state.attachment_generation)
167 }
168
169 pub fn set_external_takeover(&self, takeover: bool) {
180 self.state
181 .lock()
182 .expect("ui dialog mailbox poisoned")
183 .external_takeover = takeover;
184 }
185
186 pub fn external_takeover(&self) -> bool {
188 self.state
189 .lock()
190 .expect("ui dialog mailbox poisoned")
191 .external_takeover
192 }
193
194 pub fn detach(&self) {
197 let Ok(mut state) = self.state.lock() else {
200 return;
201 };
202 Self::detach_locked(&mut state);
203 }
204
205 pub fn detach_if_generation(&self, generation: u64) -> bool {
208 let Ok(mut state) = self.state.lock() else {
212 return false;
213 };
214 if state.attachment_generation != generation {
215 return false;
216 }
217 Self::detach_locked(&mut state);
218 true
219 }
220
221 fn detach_locked(state: &mut UiDialogState) {
222 state.attached = false;
223 state.external_takeover = false;
227 state.pending.clear();
228 for entry in state.active.values_mut() {
229 entry.cancelled = true;
230 entry.answer = None;
231 }
232 }
233
234 pub fn release_takeover(&self) -> usize {
243 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
244 state.external_takeover = false;
245 let mut requeued: Vec<String> = state
246 .active
247 .iter()
248 .filter(|(_, entry)| !entry.cancelled && entry.answer.is_none())
249 .map(|(request_id, _)| request_id.clone())
250 .filter(|request_id| !state.pending.contains(request_id))
251 .collect();
252 if requeued.is_empty() {
253 return 0;
254 }
255 let count = requeued.len();
256 requeued.sort();
258 for request_id in requeued.into_iter().rev() {
259 state.pending.push_front(request_id);
260 }
261 count
262 }
263
264 pub fn is_attached(&self) -> bool {
265 self.state.lock().ok().is_some_and(|state| state.attached)
266 }
267
268 pub fn take_pending(&self) -> Option<UiDialogRequest> {
272 self.take_pending_filtered(|_| true)
273 }
274
275 pub fn take_pending_unless_external<F>(&self, keep: F) -> Option<UiDialogRequest>
284 where
285 F: Fn(&UiDialogRequest) -> bool,
286 {
287 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
288 if state.external_takeover {
289 return None;
290 }
291 Self::take_pending_locked(&mut state, keep)
292 }
293
294 pub fn take_pending_filtered<F>(&self, keep: F) -> Option<UiDialogRequest>
309 where
310 F: Fn(&UiDialogRequest) -> bool,
311 {
312 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
313 Self::take_pending_locked(&mut state, keep)
314 }
315
316 fn take_pending_locked<F>(
317 state: &mut std::sync::MutexGuard<'_, UiDialogState>,
318 keep: F,
319 ) -> Option<UiDialogRequest>
320 where
321 F: Fn(&UiDialogRequest) -> bool,
322 {
323 let mut scanned = 0usize;
324 let total = state.pending.len();
325 while scanned < total {
326 scanned += 1;
327 let Some(request_id) = state.pending.pop_front() else {
328 break;
329 };
330 let Some(entry) = state.active.get(&request_id) else {
331 continue;
332 };
333 if entry.cancelled || entry.answer.is_some() {
334 continue;
335 }
336 let request = entry.request.clone();
337 if keep(&request) {
338 return Some(request);
339 }
340 state.pending.push_back(request_id);
342 }
343 None
344 }
345
346 pub fn take_all_unreserved(&self) -> Vec<UiDialogRequest> {
355 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
356 let mut out: Vec<UiDialogRequest> = Vec::new();
357 let drained = std::mem::take(&mut state.pending);
359 for request_id in drained {
360 let Some(entry) = state.active.get(&request_id) else {
361 continue;
362 };
363 if entry.cancelled || entry.answer.is_some() {
364 continue;
365 }
366 if request_id.starts_with(PLUGIN_RESERVED_PREFIX) {
367 state.pending.push_back(request_id);
368 } else {
369 out.push(entry.request.clone());
370 }
371 }
372 out
373 }
374
375 pub fn is_reserved(&self, request_id: &str) -> bool {
377 request_id.starts_with(PLUGIN_RESERVED_PREFIX)
378 }
379
380 pub fn pending_len(&self) -> usize {
381 self.state
382 .lock()
383 .expect("ui dialog mailbox poisoned")
384 .pending
385 .len()
386 }
387
388 pub fn is_pending(&self, request_id: &str) -> bool {
390 self.state
391 .lock()
392 .expect("ui dialog mailbox poisoned")
393 .active
394 .get(request_id)
395 .is_some_and(|entry| !entry.cancelled && entry.answer.is_none())
396 }
397
398 pub fn respond(&self, request_id: &str, answer: serde_json::Value) -> Result<(), String> {
401 let mut state = self
402 .state
403 .lock()
404 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
405 let entry = state
406 .active
407 .get_mut(request_id)
408 .ok_or_else(|| format!("unknown UI request `{request_id}`"))?;
409 if entry.cancelled {
410 return Err(format!("UI request `{request_id}` was cancelled"));
411 }
412 if entry.answer.is_none() {
413 entry.answer = Some(answer);
414 }
415 Ok(())
416 }
417
418 pub fn cancel(&self, request_id: &str) -> Result<(), String> {
421 let mut state = self
422 .state
423 .lock()
424 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
425 let entry = state
426 .active
427 .get_mut(request_id)
428 .ok_or_else(|| format!("unknown UI request `{request_id}`"))?;
429 entry.cancelled = true;
430 entry.answer = None;
431 state.pending.retain(|id| id != request_id);
432 Ok(())
433 }
434
435 pub fn cancel_all(&self) {
437 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
438 state.pending.clear();
439 for entry in state.active.values_mut() {
440 entry.cancelled = true;
441 entry.answer = None;
442 }
443 }
444
445 pub fn cancel_tool_call(&self, tool_call_id: &str) {
448 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
449 state.cancelled_tool_calls.insert(tool_call_id.to_string());
452 for entry in state.active.values_mut() {
453 if entry.request.tool_call_id.as_deref() == Some(tool_call_id) {
454 entry.cancelled = true;
455 entry.answer = None;
456 }
457 }
458 let cancelled: std::collections::HashSet<String> = state
459 .active
460 .iter()
461 .filter(|(_, entry)| entry.cancelled)
462 .map(|(id, _)| id.clone())
463 .collect();
464 state.pending.retain(|id| !cancelled.contains(id));
465 }
466
467 pub fn poll(&self, request_id: &str) -> Result<serde_json::Value, String> {
470 let mut state = self
471 .state
472 .lock()
473 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
474 let terminal = match state.active.get(request_id) {
475 Some(entry) if entry.cancelled => Some(serde_json::json!({
476 "status": "cancelled",
477 "requestId": request_id,
478 "toolCallId": entry.request.tool_call_id,
479 })),
480 Some(entry) if entry.answer.is_some() => Some(serde_json::json!({
481 "status": "answered",
482 "requestId": request_id,
483 "toolCallId": entry.request.tool_call_id,
484 "answer": entry.answer.clone().unwrap_or(serde_json::Value::Null),
485 })),
486 Some(entry) => Some(serde_json::json!({
487 "status": "pending",
488 "requestId": request_id,
489 "toolCallId": entry.request.tool_call_id,
490 })),
491 None => None,
492 };
493 let Some(result) = terminal else {
494 return Err(format!("unknown UI request `{request_id}`"));
495 };
496 if result.get("status").and_then(serde_json::Value::as_str) != Some("pending") {
497 state.active.remove(request_id);
498 }
499 Ok(result)
500 }
501
502 pub fn forget(&self, request_id: &str) -> Result<bool, String> {
514 let mut state = self
515 .state
516 .lock()
517 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
518 let Some(entry) = state.active.get(request_id) else {
519 return Ok(false);
520 };
521 if !entry.cancelled && entry.answer.is_none() {
522 return Err(format!("UI request `{request_id}` is still pending"));
523 }
524 state.active.remove(request_id);
525 state.pending.retain(|id| id != request_id);
526 Ok(true)
527 }
528
529 pub fn handle(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
534 let op = args
535 .get("op")
536 .and_then(serde_json::Value::as_str)
537 .unwrap_or("open");
538 let request_id = || {
539 args.get("requestId")
540 .or_else(|| args.get("request_id"))
541 .and_then(serde_json::Value::as_str)
542 .map(str::to_owned)
543 .filter(|id| !id.trim().is_empty())
544 .ok_or_else(|| "missing non-empty `requestId`".to_string())
545 };
546 match op {
547 "open" => {
548 let id = request_id()?;
549 let mut state = self
550 .state
551 .lock()
552 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
553 if !state.attached {
554 return Err("ask_user requires an interactive UI".to_string());
555 }
556 if let Some(entry) = state.active.get(&id) {
557 return Ok(if entry.cancelled {
558 serde_json::json!({"status":"cancelled","requestId":id})
559 } else if let Some(answer) = &entry.answer {
560 serde_json::json!({"status":"answered","requestId":id,"answer":answer})
561 } else {
562 serde_json::json!({"status":"pending","requestId":id})
563 });
564 }
565 let tool_call_id = args
566 .get("toolCallId")
567 .or_else(|| args.get("tool_call_id"))
568 .and_then(serde_json::Value::as_str)
569 .map(str::to_owned);
570 if tool_call_id
571 .as_ref()
572 .is_some_and(|id| state.cancelled_tool_calls.contains(id))
573 {
574 return Ok(serde_json::json!({
575 "status": "cancelled", "requestId": id, "toolCallId": tool_call_id,
576 }));
577 }
578 let ui = args.get("ui").cloned().unwrap_or_else(|| args.clone());
579 rpi_plugin_sdk::dialogs::validate(&ui, tool_call_id.as_deref())?;
580 state.active.insert(
581 id.clone(),
582 UiDialogEntry {
583 request: UiDialogRequest {
584 request_id: id.clone(),
585 tool_call_id: tool_call_id.clone(),
586 ui,
587 raw: args,
588 },
589 answer: None,
590 cancelled: false,
591 },
592 );
593 state.pending.push_back(id.clone());
594 Ok(serde_json::json!({"status":"pending","requestId":id,"toolCallId":tool_call_id}))
595 }
596 "poll" => self.poll(&request_id()?),
597 "cancel" => {
598 let id = request_id()?;
599 self.cancel(&id)?;
600 Ok(serde_json::json!({"status":"cancelled","requestId":id}))
601 }
602 "forget" => {
603 let id = request_id()?;
604 let removed = self.forget(&id)?;
605 Ok(serde_json::json!({"status":"forgotten","requestId":id,"removed":removed}))
606 }
607 "response" | "respond" => {
608 let id = request_id()?;
609 let answer = args
610 .get("answer")
611 .or_else(|| args.get("value"))
612 .cloned()
613 .unwrap_or(serde_json::Value::Null);
614 self.respond(&id, answer)?;
615 Ok(serde_json::json!({"status":"answered","requestId":id}))
616 }
617 other => Err(format!("unknown UI dialog operation `{other}`")),
618 }
619 }
620}
621
622pub type SideQuestionSink =
624 Arc<dyn Fn(serde_json::Value) -> Result<serde_json::Value, String> + Send + Sync>;
625
626#[async_trait::async_trait]
641pub trait RuntimeActionHost: Send + Sync {
642 async fn tool_program(
644 &self,
645 capability: Arc<rpi_agent::tool_program::ToolProgram>,
646 args: serde_json::Value,
647 ) -> Result<serde_json::Value, String> {
648 capability.handle(args).await
649 }
650 fn cancel_side_questions(&self, _owner: u64) {}
652 fn side_question_revision(&self) -> u64 {
654 0
655 }
656 fn side_question_views(&self) -> Vec<serde_json::Value> {
657 Vec::new()
658 }
659 async fn side_question_ui(
660 &self,
661 _owner: u64,
662 _thread_id: String,
663 _args: serde_json::Value,
664 ) -> Result<serde_json::Value, String> {
665 Err("SideQuestion UI is not supported by this host".into())
666 }
667 async fn side_question(
669 &self,
670 _owner: u64,
671 _args: serde_json::Value,
672 _sink: SideQuestionSink,
673 ) -> Result<serde_json::Value, String> {
674 Err("SideQuestion is not supported by this host; upgrade rpi".into())
675 }
676
677 fn replace_model_catalog(&self, _models: Vec<rpi_ai::Model>) {}
679 fn cancel_child_agents(&self, _owner: u64) {}
681 async fn send_message(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
686 async fn send_user_message(&self, args: serde_json::Value)
688 -> Result<serde_json::Value, String>;
689 async fn append_entry(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
699 async fn set_session_name(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
701 async fn get_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
703 async fn set_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
705 async fn set_model(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
707 async fn get_thinking_level(
709 &self,
710 args: serde_json::Value,
711 ) -> Result<serde_json::Value, String>;
712 async fn set_thinking_level(
714 &self,
715 args: serde_json::Value,
716 ) -> Result<serde_json::Value, String>;
717 async fn compact(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
719 async fn get_system_prompt(&self, args: serde_json::Value)
721 -> Result<serde_json::Value, String>;
722 async fn new_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
724 async fn fork(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
726 async fn navigate_tree(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
728 async fn switch_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
730 async fn reload(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
734
735 async fn reload_models(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
745 Err("reload_models is not supported by this host".to_string())
746 }
747
748 async fn get_cli_flag(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
751 Err("CLI flag lookup is not configured".to_string())
752 }
753
754 async fn ui_dialog(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
758 Err("ask_user requires an interactive UI".to_string())
759 }
760
761 async fn list_commands(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
772 Ok(serde_json::json!({ "commands": [] }))
773 }
774
775 fn publish_registry(&self, _snapshot: std::sync::Arc<crate::registry::RegistrySnapshot>) {}
786
787 fn publish_registry_opt(
793 &self,
794 snapshot: Option<std::sync::Arc<crate::registry::RegistrySnapshot>>,
795 ) {
796 if let Some(snapshot) = snapshot {
797 self.publish_registry(snapshot);
798 }
799 }
800
801 async fn abort(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
809 Ok(serde_json::json!({
810 "aborted": false,
811 "steer": [],
812 "followUp": [],
813 }))
814 }
815
816 fn stop_round(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
826 Ok(serde_json::json!({ "requested": true }))
827 }
828
829 async fn get_execution_context(
831 &self,
832 _args: serde_json::Value,
833 ) -> Result<serde_json::Value, String> {
834 Err("execution context is not supported by this host".into())
835 }
836
837 async fn child_agent(
839 &self,
840 _owner: u64,
841 _args: serde_json::Value,
842 ) -> Result<serde_json::Value, String> {
843 Err("ChildAgent is not supported by this host".into())
844 }
845
846 async fn get_session_branch(
856 &self,
857 _args: serde_json::Value,
858 ) -> Result<serde_json::Value, String> {
859 Err("session branch lookup is not configured".to_string())
860 }
861}
862
863pub struct ActionBridge {
890 invocation: Option<(bool, String, tokio_util::sync::CancellationToken)>,
892 execution_context: Option<serde_json::Value>,
893 tool_program: Option<Arc<rpi_agent::tool_program::ToolProgram>>,
894 stdio: crate::StdioLifecycle,
895 plugin_identity: Option<(u64, String)>,
896 component_owners: Arc<std::sync::Mutex<Vec<u64>>>,
897 pub(crate) runtime: Handle,
899 pub(crate) host: Arc<dyn RuntimeActionHost>,
901 pub(crate) reload:
903 Option<Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>>,
904 ui_dialog: UiDialogMailbox,
907 ext_status: crate::status::ExtensionStatusMailbox,
911 editor_text: crate::editor_text::EditorTextMailbox,
915 active: Arc<AtomicBool>,
918}
919
920impl ActionBridge {
921 pub fn user_data(self: &Arc<Self>) -> *mut c_void {
923 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1);
924 let mut registry = bridges().lock().unwrap_or_else(|e| e.into_inner());
925 if let Some((&id, _)) = registry
926 .iter()
927 .find(|(_, entry)| entry.bridge.as_ptr() == Arc::as_ptr(self))
928 {
929 return id as *mut c_void;
930 }
931 let mut id = NEXT.load(Ordering::Relaxed);
932 loop {
933 let next = id.checked_add(1).expect("runtime handle space exhausted");
934 match NEXT.compare_exchange_weak(id, next, Ordering::Relaxed, Ordering::Relaxed) {
935 Ok(_) => break,
936 Err(current) => id = current,
937 }
938 }
939 registry.insert(
940 id,
941 RegistryEntry {
942 bridge: Arc::downgrade(self),
943 active: Arc::downgrade(&self.active),
944 },
945 );
946 id as *mut c_void
947 }
948 pub(crate) fn resolve_handle(id: usize) -> Option<Arc<Self>> {
949 bridges()
950 .lock()
951 .unwrap_or_else(|e| e.into_inner())
952 .get(&id)
953 .and_then(|entry| entry.bridge.upgrade())
954 }
955 pub(crate) fn for_invocation(
956 &self,
957 child: bool,
958 signal: tokio_util::sync::CancellationToken,
959 ) -> Arc<Self> {
960 let tool_program = rpi_agent::tool_program::current();
961 if let Some(program) = &tool_program {
962 program.bind_signal(signal.clone());
963 }
964 Arc::new(Self {
965 invocation: Some((child, uuid::Uuid::new_v4().to_string(), signal)),
966 execution_context: rpi_agent::tool_execution_scope::execution_context(),
967 tool_program,
968 stdio: self.stdio.clone(),
969 plugin_identity: self.plugin_identity.clone(),
970 component_owners: self.component_owners.clone(),
971 runtime: self.runtime.clone(),
972 host: self.host.clone(),
973 reload: self.reload.clone(),
974 ui_dialog: self.ui_dialog.clone(),
975 ext_status: self.ext_status.clone(),
976 editor_text: self.editor_text.clone(),
977 active: self.active.clone(),
978 })
979 }
980 pub(crate) fn resolve_result_reference(
983 &self,
984 id: &str,
985 ) -> Result<(rpi_agent::AgentToolResult, bool), String> {
986 if !self.is_active()
987 || !self
988 .invocation
989 .as_ref()
990 .is_some_and(|(_, _, signal)| !signal.is_cancelled())
991 {
992 return Err("result reference requires a live invocation bridge".into());
993 }
994 self.tool_program
995 .as_ref()
996 .ok_or("result reference requires an effective ToolProgram")?
997 .resolve_result_reference(id)
998 }
999 pub(crate) fn resolve_content_parts(
1001 &self,
1002 parts: Vec<rpi_agent::tool_program::ToolProgramContentPart>,
1003 ) -> Result<Vec<rpi_agent::TextContentOrImage>, String> {
1004 if !self.is_active()
1005 || !self
1006 .invocation
1007 .as_ref()
1008 .is_some_and(|(_, _, signal)| !signal.is_cancelled())
1009 {
1010 return Err("content parts require a live invocation bridge".into());
1011 }
1012 self.tool_program
1013 .as_ref()
1014 .ok_or("content parts require an effective ToolProgram")?
1015 .resolve_content_parts(parts)
1016 }
1017 pub(crate) fn invocation_key(&self) -> Option<&str> {
1018 self.invocation.as_ref().map(|(_, key, _)| key.as_str())
1019 }
1020 pub(crate) fn enter_invocation(self: &Arc<Self>) -> InvocationGuard {
1021 InvocationGuard {
1022 previous: CURRENT_INVOCATION.with(|slot| slot.replace(Some(self.clone()))),
1023 _thread_bound: std::marker::PhantomData,
1024 }
1025 }
1026 pub fn new(runtime: Handle, host: Arc<dyn RuntimeActionHost>) -> Arc<Self> {
1029 Arc::new(Self {
1030 invocation: None,
1031 tool_program: None,
1032 execution_context: None,
1033 stdio: crate::StdioLifecycle::default(),
1034 plugin_identity: None,
1035 component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1036 runtime,
1037 host,
1038 reload: None,
1039 ui_dialog: UiDialogMailbox::new(),
1040 ext_status: crate::status::ExtensionStatusMailbox::new(),
1041 editor_text: crate::editor_text::EditorTextMailbox::new(),
1042 active: Arc::new(AtomicBool::new(true)),
1043 })
1044 }
1045
1046 pub fn with_reload(
1049 runtime: Handle,
1050 host: Arc<dyn RuntimeActionHost>,
1051 reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>,
1052 ) -> Arc<Self> {
1053 Self::with_reload_and_ui(
1054 runtime,
1055 host,
1056 reload,
1057 UiDialogMailbox::new(),
1058 crate::status::ExtensionStatusMailbox::new(),
1059 crate::editor_text::EditorTextMailbox::new(),
1060 )
1061 }
1062
1063 pub fn with_ui_dialog(
1065 runtime: Handle,
1066 host: Arc<dyn RuntimeActionHost>,
1067 ui_dialog: UiDialogMailbox,
1068 ) -> Arc<Self> {
1069 Arc::new(Self {
1070 invocation: None,
1071 tool_program: None,
1072 execution_context: None,
1073 stdio: crate::StdioLifecycle::default(),
1074 plugin_identity: None,
1075 component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1076 runtime,
1077 host,
1078 reload: None,
1079 ui_dialog,
1080 ext_status: crate::status::ExtensionStatusMailbox::new(),
1081 editor_text: crate::editor_text::EditorTextMailbox::new(),
1082 active: Arc::new(AtomicBool::new(true)),
1083 })
1084 }
1085
1086 pub fn with_reload_and_ui(
1088 runtime: Handle,
1089 host: Arc<dyn RuntimeActionHost>,
1090 reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>,
1091 ui_dialog: UiDialogMailbox,
1092 ext_status: crate::status::ExtensionStatusMailbox,
1093 editor_text: crate::editor_text::EditorTextMailbox,
1094 ) -> Arc<Self> {
1095 Arc::new(Self {
1096 invocation: None,
1097 tool_program: None,
1098 execution_context: None,
1099 stdio: crate::StdioLifecycle::default(),
1100 plugin_identity: None,
1101 component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1102 runtime,
1103 host,
1104 reload: Some(reload),
1105 ui_dialog,
1106 ext_status,
1107 editor_text,
1108 active: Arc::new(AtomicBool::new(true)),
1109 })
1110 }
1111
1112 pub(crate) fn for_plugin(&self, name: &str) -> Arc<Self> {
1113 static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1114 let owner = NEXT_ID.fetch_add(1, Ordering::Relaxed);
1115 self.component_owners
1116 .lock()
1117 .unwrap_or_else(|e| e.into_inner())
1118 .push(owner);
1119 Arc::new(Self {
1120 invocation: None,
1121 tool_program: None,
1122 execution_context: None,
1123 component_owners: self.component_owners.clone(),
1124 stdio: self.stdio.clone(),
1125 plugin_identity: Some((owner, name.to_owned())),
1126 runtime: self.runtime.clone(),
1127 host: self.host.clone(),
1128 reload: self.reload.clone(),
1129 ui_dialog: self.ui_dialog.clone(),
1130 ext_status: self.ext_status.clone(),
1131 editor_text: self.editor_text.clone(),
1132 active: self.active.clone(),
1133 })
1134 }
1135
1136 pub fn stdio_lifecycle(&self) -> crate::StdioLifecycle {
1137 self.stdio.clone()
1138 }
1139
1140 pub(crate) fn claim_stdio(&self) -> Result<(), String> {
1141 let (id, name) = self
1142 .plugin_identity
1143 .as_ref()
1144 .ok_or("missing plugin identity")?;
1145 self.stdio.claim(*id, name)
1146 }
1147
1148 pub(crate) fn release_stdio_claim(&self) {
1149 if let Some((id, _)) = &self.plugin_identity {
1150 self.stdio.release_failed_registration(*id);
1151 self.ext_status.remove_owner(*id);
1152 }
1153 }
1154
1155 pub fn ui_dialog_mailbox(&self) -> UiDialogMailbox {
1157 self.ui_dialog.clone()
1158 }
1159
1160 pub fn extension_status_mailbox(&self) -> crate::status::ExtensionStatusMailbox {
1162 self.ext_status.clone()
1163 }
1164
1165 pub fn editor_text_mailbox(&self) -> crate::editor_text::EditorTextMailbox {
1167 self.editor_text.clone()
1168 }
1169
1170 pub fn invalidate(&self) {
1175 let owners = {
1176 let owners = self
1177 .component_owners
1178 .lock()
1179 .unwrap_or_else(|e| e.into_inner());
1180 self.active.store(false, Ordering::SeqCst);
1181 for owner in owners.iter() {
1182 self.ext_status.remove_owner(*owner);
1183 }
1184 owners.clone()
1185 };
1186 let live = self.bridges_for_owner();
1188 for bridge in live {
1189 if let Some(program) = &bridge.tool_program {
1190 program.cancel_all();
1191 }
1192 }
1193 for owner in owners {
1196 self.host.cancel_child_agents(owner);
1197 self.host.cancel_side_questions(owner);
1198 }
1199 }
1200
1201 fn bridges_for_owner(&self) -> Vec<Arc<Self>> {
1202 let active = Arc::downgrade(&self.active);
1203 bridges()
1209 .lock()
1210 .unwrap_or_else(|e| e.into_inner())
1211 .values()
1212 .filter(|entry| entry.active.ptr_eq(&active))
1213 .filter_map(|entry| entry.bridge.upgrade())
1214 .collect()
1215 }
1216
1217 pub fn is_active(&self) -> bool {
1219 self.active.load(Ordering::SeqCst)
1220 }
1221
1222 pub fn clone_host(&self) -> Arc<dyn RuntimeActionHost> {
1229 Arc::clone(&self.host)
1230 }
1231}
1232
1233#[derive(Clone)]
1246pub struct ReloadMailbox {
1247 tx: Arc<std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<()>>>>,
1248}
1249
1250impl Default for ReloadMailbox {
1251 fn default() -> Self {
1252 Self {
1253 tx: Arc::new(std::sync::Mutex::new(None)),
1254 }
1255 }
1256}
1257
1258impl ReloadMailbox {
1259 pub fn new() -> Self {
1261 Self::default()
1262 }
1263
1264 pub fn install(&self, tx: tokio::sync::mpsc::UnboundedSender<()>) {
1268 *self.tx.lock().unwrap() = Some(tx);
1269 }
1270
1271 pub fn signal(&self) -> Result<(), ()> {
1276 let g = self.tx.lock().unwrap();
1277 match &*g {
1278 Some(tx) => {
1279 let _ = tx.send(());
1280 Ok(())
1281 }
1282 None => Err(()),
1283 }
1284 }
1285
1286 pub fn clear(&self) {
1288 *self.tx.lock().unwrap() = None;
1289 }
1290}
1291
1292pub struct ReloadModelsMailbox {
1303 tx: Arc<std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<ReloadModelsRequest>>>>,
1304}
1305
1306impl Default for ReloadModelsMailbox {
1307 fn default() -> Self {
1308 Self {
1309 tx: Arc::new(std::sync::Mutex::new(None)),
1310 }
1311 }
1312}
1313
1314pub struct ReloadModelsRequest {
1316 pub reply: tokio::sync::oneshot::Sender<Result<usize, String>>,
1318}
1319
1320impl Clone for ReloadModelsMailbox {
1321 fn clone(&self) -> Self {
1322 Self {
1323 tx: Arc::clone(&self.tx),
1324 }
1325 }
1326}
1327
1328impl ReloadModelsMailbox {
1329 pub fn new() -> Self {
1330 Self::default()
1331 }
1332
1333 pub fn install(&self, tx: tokio::sync::mpsc::UnboundedSender<ReloadModelsRequest>) {
1335 *self.tx.lock().unwrap() = Some(tx);
1336 }
1337
1338 pub async fn request(&self) -> Result<usize, String> {
1343 let (reply, wait) = tokio::sync::oneshot::channel();
1344 let tx = self.tx.lock().unwrap().clone();
1345 let Some(tx) = tx else {
1346 return Err("reload_models is not available (no TUI attached)".to_string());
1347 };
1348 tx.send(ReloadModelsRequest { reply })
1349 .map_err(|_| "reload_models request dropped (TUI gone)".to_string())?;
1350 wait.await
1351 .map_err(|_| "reload_models request dropped (TUI gone)".to_string())?
1352 }
1353
1354 pub fn clear(&self) {
1356 *self.tx.lock().unwrap() = None;
1357 }
1358}
1359
1360pub fn reload_callback_from_mailbox(
1367 mailbox: ReloadMailbox,
1368) -> Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync> {
1369 Arc::new(move || {
1370 let m = mailbox.clone();
1371 Box::pin(async move {
1372 let _ = m.signal();
1373 })
1374 })
1375}
1376
1377fn dispatch_relay_ui_dialog(
1392 ui_dialog: &UiDialogMailbox,
1393 args: serde_json::Value,
1394) -> Result<serde_json::Value, String> {
1395 let op = args
1396 .get("op")
1397 .and_then(serde_json::Value::as_str)
1398 .unwrap_or("take");
1399 match op {
1400 "take" => {
1401 ui_dialog.set_external_takeover(true);
1405 let requests: Vec<serde_json::Value> = ui_dialog
1406 .take_all_unreserved()
1407 .into_iter()
1408 .map(|request| {
1409 serde_json::json!({
1410 "requestId": request.request_id,
1411 "toolCallId": request.tool_call_id,
1412 "ui": request.ui,
1413 })
1414 })
1415 .collect();
1416 Ok(serde_json::json!({ "requests": requests }))
1417 }
1418 "release" => {
1421 let requeued = ui_dialog.release_takeover();
1422 Ok(serde_json::json!({ "requeued": requeued }))
1423 }
1424 "respond" | "cancel" | "forget" => ui_dialog.handle(args),
1426 other => Err(format!("RelayUiDialog does not support op `{other}`")),
1427 }
1428}
1429
1430async fn dispatch(
1431 host: &Arc<dyn RuntimeActionHost>,
1432 ui_dialog: &UiDialogMailbox,
1433 ext_status: &crate::status::ExtensionStatusMailbox,
1434 editor_text: &crate::editor_text::EditorTextMailbox,
1435 action: RuntimeActionId,
1436 args: serde_json::Value,
1437) -> Result<serde_json::Value, String> {
1438 match action {
1439 RuntimeActionId::SendMessage => host.send_message(args).await,
1440 RuntimeActionId::SendUserMessage => host.send_user_message(args).await,
1441 RuntimeActionId::AppendEntry => host.append_entry(args).await,
1442 RuntimeActionId::SetSessionName => host.set_session_name(args).await,
1443 RuntimeActionId::GetActiveTools => host.get_active_tools(args).await,
1444 RuntimeActionId::SetActiveTools => host.set_active_tools(args).await,
1445 RuntimeActionId::SetModel => host.set_model(args).await,
1446 RuntimeActionId::GetThinkingLevel => host.get_thinking_level(args).await,
1447 RuntimeActionId::SetThinkingLevel => host.set_thinking_level(args).await,
1448 RuntimeActionId::Compact => host.compact(args).await,
1449 RuntimeActionId::GetSystemPrompt => host.get_system_prompt(args).await,
1450 RuntimeActionId::NewSession => host.new_session(args).await,
1451 RuntimeActionId::Fork => host.fork(args).await,
1452 RuntimeActionId::NavigateTree => host.navigate_tree(args).await,
1453 RuntimeActionId::SwitchSession => host.switch_session(args).await,
1454 RuntimeActionId::Reload => host.reload(args).await,
1455 RuntimeActionId::ReloadModels => host.reload_models(args).await,
1456 RuntimeActionId::GetCliFlag => host.get_cli_flag(args).await,
1457 RuntimeActionId::UiDialog => ui_dialog.handle(args),
1458 RuntimeActionId::SetStatus => ext_status.handle(args),
1461 RuntimeActionId::UiComponent => Err("UiComponent requires a plugin bridge".into()),
1462 RuntimeActionId::SetEditorText => editor_text.handle(args),
1465 RuntimeActionId::GetSessionBranch => host.get_session_branch(args).await,
1466 RuntimeActionId::GetExecutionContext => host.get_execution_context(args).await,
1467 RuntimeActionId::ToolProgram => Err("ToolProgram requires a live invocation bridge".into()),
1468 RuntimeActionId::ChildAgent => Err("ChildAgent requires a plugin bridge".into()),
1469 RuntimeActionId::SideQuestion => Err("SideQuestion requires a plugin bridge".into()),
1470 RuntimeActionId::ListCommands => host.list_commands(args).await,
1471 RuntimeActionId::Abort => host.abort(args).await,
1472 RuntimeActionId::RelayUiDialog => dispatch_relay_ui_dialog(ui_dialog, args),
1476 RuntimeActionId::StopRound => host.stop_round(args),
1477 RuntimeActionId::StdioLifecycle => {
1478 Err("stdio lifecycle requires a plugin context".to_owned())
1479 }
1480 }
1481}
1482
1483pub extern "C" fn trampoline_runtime_action(
1507 action_id: u32,
1508 args_json: StbStringRef,
1509 out: *mut StbString,
1510 user_data: *mut c_void,
1511) -> i32 {
1512 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1513 run_action(
1514 action_id,
1515 rpi_plugin_sdk::RuntimeActionId::MAX,
1517 args_json,
1518 out,
1519 user_data,
1520 )
1521 }));
1522 match outcome {
1523 Ok(rc) => rc,
1524 Err(_) => {
1525 tracing::error!("runtime_action trampoline panicked — reporting host error");
1529 if !out.is_null() {
1530 unsafe {
1531 *out = StbString::from_string(
1532 r#"{"error":"runtime_action panicked"}"#.to_string(),
1533 );
1534 }
1535 }
1536 1
1537 }
1538 }
1539}
1540
1541fn run_action(
1543 action_id: u32,
1544 max_action_id: u32,
1545 args_json: StbStringRef,
1546 out: *mut StbString,
1547 user_data: *mut c_void,
1548) -> i32 {
1549 let action = match RuntimeActionId::try_from(action_id) {
1553 Ok(action) if action_id <= max_action_id => action,
1554 Ok(_) | Err(_) => {
1555 if !out.is_null() {
1556 let json = serde_json::json!({
1557 "error": format!("unknown runtime action id {action_id}")
1558 })
1559 .to_string();
1560 unsafe {
1564 *out = StbString::from_string(json);
1565 }
1566 }
1567 return 2;
1568 }
1569 };
1570
1571 if user_data.is_null() {
1572 return -1;
1573 }
1574 let invocation = CURRENT_INVOCATION.with(|slot| slot.borrow().clone());
1577 let invocation_thread = invocation.is_some();
1578 let bridge = invocation.or_else(|| ActionBridge::resolve_handle(user_data as usize));
1579 let Some(bridge) = bridge else {
1580 if !out.is_null() {
1581 unsafe {
1583 *out = StbString::from_string("{\"error\":\"expired runtime handle\"}".into());
1584 }
1585 }
1586 return 1;
1587 };
1588
1589 if !bridge.is_active() {
1597 if out.is_null() {
1598 return 1;
1599 }
1600 let json = serde_json::json!({
1601 "error": "runtime_action on a stale ActionBridge (session reloaded/swapped)"
1602 })
1603 .to_string();
1604 unsafe {
1605 *out = StbString::from_string(json);
1606 }
1607 return 1;
1608 }
1609
1610 let args_str = unsafe { args_json.as_str() };
1613 let mut args: serde_json::Value = if args_str.is_empty() {
1614 serde_json::Value::Object(serde_json::Map::new())
1615 } else {
1616 serde_json::from_str(args_str)
1617 .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new()))
1618 };
1619
1620 let runtime_key = args
1621 .as_object_mut()
1622 .and_then(|args| args.remove("__rpiRuntimeKey"));
1623
1624 let (tx, rx) = mpsc::sync_channel::<Result<serde_json::Value, String>>(1);
1629 let host = Arc::clone(&bridge.host);
1633 let ui_dialog = bridge.ui_dialog.clone();
1634 let ext_status = bridge.ext_status.clone();
1635 let editor_text = bridge.editor_text.clone();
1636 let reload_cb = bridge.reload.clone();
1637 let execution_context = bridge.execution_context.clone();
1638 if action == RuntimeActionId::StdioLifecycle {
1639 let result = bridge.stdio.handle(
1640 bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id),
1641 args,
1642 );
1643 let _ = tx.send(result);
1644 } else if action == RuntimeActionId::UiComponent {
1645 let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1646 let _owners = bridge
1647 .component_owners
1648 .lock()
1649 .unwrap_or_else(|e| e.into_inner());
1650 let result = if bridge.is_active() {
1651 ext_status.component(owner, args)
1652 } else {
1653 Err("stale plugin bridge".into())
1654 };
1655 let _ = tx.send(result);
1656 } else if action == RuntimeActionId::SideQuestion {
1657 let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1658 if owner == 0 || bridge.invocation.is_some() {
1659 let _ = tx.send(Err(
1660 "SideQuestion requires a plugin command, not a tool invocation".into(),
1661 ));
1662 } else {
1663 let weak = Arc::downgrade(&bridge);
1666 let sink: SideQuestionSink = Arc::new(move |args| {
1667 let bridge = weak.upgrade().ok_or("expired side question bridge")?;
1668 let _owners = bridge
1669 .component_owners
1670 .lock()
1671 .unwrap_or_else(|e| e.into_inner());
1672 if !bridge.is_active() {
1673 return Err("stale side question bridge".into());
1674 }
1675 if args["op"] == "check" {
1676 return Ok(serde_json::json!({"ok":true}));
1677 }
1678 bridge.ext_status.component(owner, args)
1679 });
1680 bridge.runtime.spawn(async move {
1681 let _ = tx.send(host.side_question(owner, args, sink).await);
1682 });
1683 }
1684 } else if action == RuntimeActionId::GetActiveTools && bridge.tool_program.is_some() {
1685 let tools = bridge
1686 .tool_program
1687 .as_ref()
1688 .expect("checked")
1689 .active_tool_names();
1690 let _ = tx.send(Ok(serde_json::json!({"tools":tools})));
1691 } else if action == RuntimeActionId::SetActiveTools && bridge.execution_context.is_some() {
1692 let _ = tx.send(Err(
1693 "cannot replace active tools from a narrowed execution".into()
1694 ));
1695 } else if action == RuntimeActionId::ToolProgram {
1696 let cleanup = matches!(
1697 args.get("op").and_then(serde_json::Value::as_str),
1698 Some("poll" | "cancel" | "dispose" | "release_result")
1699 );
1700 let authenticated = bridge.invocation.as_ref().is_some_and(|(_, key, signal)| {
1701 (cleanup || !signal.is_cancelled())
1702 && (invocation_thread
1703 || runtime_key.as_ref().and_then(serde_json::Value::as_str)
1704 == Some(key.as_str()))
1705 });
1706 if let Some(capability) = bridge.tool_program.clone().filter(|_| authenticated) {
1707 let signal = bridge.invocation.as_ref().expect("authenticated").2.clone();
1708 bridge.runtime.spawn(async move {
1709 if signal.is_cancelled() {
1710 capability.cancel_all();
1711 if !cleanup {
1712 let _ = tx.send(Err("parent invocation is no longer active".into()));
1713 return;
1714 }
1715 }
1716 let _ = tx.send(host.tool_program(capability, args).await);
1717 });
1718 } else {
1719 let _ = tx.send(Err(
1720 "ToolProgram requires an authenticated executing invocation".into(),
1721 ));
1722 }
1723 } else if action == RuntimeActionId::ChildAgent {
1724 let cleanup = matches!(
1729 args.get("op").and_then(serde_json::Value::as_str),
1730 Some("poll" | "cancel" | "dispose")
1731 );
1732 let allowed = bridge
1733 .invocation
1734 .as_ref()
1735 .is_some_and(|(child, key, signal)| {
1736 !child
1737 && (cleanup || !signal.is_cancelled())
1738 && (invocation_thread
1739 || runtime_key.as_ref().and_then(serde_json::Value::as_str)
1740 == Some(key.as_str()))
1741 });
1742 if !allowed {
1743 let _ = tx.send(Err("ChildAgent requires a live parent tool invocation; recursive child agents are not allowed".into()));
1744 } else {
1745 let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1746 let signal = bridge
1747 .invocation
1748 .as_ref()
1749 .expect("authorized invocation")
1750 .2
1751 .clone();
1752 bridge.runtime.spawn(async move {
1753 let result = rpi_agent::tool_execution_scope::with_invocation_signal(
1754 signal,
1755 host.child_agent(owner, args),
1756 )
1757 .await;
1758 let _ = tx.send(result);
1759 });
1760 }
1761 } else if action == RuntimeActionId::SetStatus {
1762 std::thread::spawn(move || {
1767 let _ = tx.send(ext_status.handle(args));
1768 });
1769 } else if action == RuntimeActionId::SetEditorText {
1770 std::thread::spawn(move || {
1773 let _ = tx.send(editor_text.handle(args));
1774 });
1775 } else if action == RuntimeActionId::RelayUiDialog {
1776 std::thread::spawn(move || {
1782 let _ = tx.send(dispatch_relay_ui_dialog(&ui_dialog, args));
1783 });
1784 } else if action == RuntimeActionId::UiDialog {
1785 std::thread::spawn(move || {
1791 let _ = tx.send(ui_dialog.handle(args));
1792 });
1793 } else {
1794 bridge.runtime.spawn(async move {
1795 let mut r = if action == RuntimeActionId::Reload {
1796 if let Some(cb) = reload_cb {
1797 cb().await;
1798 Ok(serde_json::Value::Null)
1799 } else {
1800 host.reload(args).await
1801 }
1802 } else {
1803 dispatch(&host, &ui_dialog, &ext_status, &editor_text, action, args).await
1804 };
1805 if action == RuntimeActionId::GetExecutionContext {
1806 if let (Ok(context), Some(serde_json::Value::Object(fields))) =
1807 (&mut r, execution_context)
1808 {
1809 if let Some(object) = context.as_object_mut() {
1810 object.extend(fields);
1811 }
1812 }
1813 }
1814 let _ = tx.send(r);
1817 });
1818 }
1819
1820 let received = if Handle::try_current()
1826 .is_ok_and(|handle| handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread)
1827 {
1828 tokio::task::block_in_place(|| rx.recv())
1829 } else {
1830 rx.recv()
1831 };
1832 let result = match received {
1833 Ok(r) => r,
1834 Err(_) => {
1835 return -2;
1840 }
1841 };
1842
1843 if out.is_null() {
1846 return match result {
1848 Ok(_) => 0,
1849 Err(_) => 1,
1850 };
1851 }
1852
1853 let (rc, payload) = match result {
1854 Ok(value) => {
1855 let json = serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string());
1856 (0, json)
1857 }
1858 Err(msg) => {
1859 let json = serde_json::json!({ "error": msg }).to_string();
1860 (1, json)
1861 }
1862 };
1863 unsafe {
1869 *out = StbString::from_string(payload);
1870 }
1871 rc
1872}
1873
1874#[cfg(test)]
1883mod tests {
1884 use super::*;
1885 use std::sync::Mutex;
1886
1887 #[tokio::test(flavor = "current_thread")]
1888 async fn stdio_claim_is_exclusive_and_only_its_scoped_context_can_finish() {
1889 let master = ActionBridge::new(
1890 Handle::current(),
1891 Arc::new(MockHost {
1892 prompt: String::new(),
1893 saw: Mutex::new(Vec::new()),
1894 }),
1895 );
1896 let diag: Arc<dyn crate::PluginDiagnostics> = Arc::new(crate::NullDiagnostics);
1897 let owner = crate::HostApi::with_action_bridge(
1898 "owner",
1899 crate::ExtensionRegistry::new(),
1900 diag.clone(),
1901 master.clone(),
1902 );
1903 let other = crate::HostApi::with_action_bridge(
1904 "other",
1905 crate::ExtensionRegistry::new(),
1906 diag,
1907 master.clone(),
1908 );
1909 let vtable = owner.build_vtable();
1910 let claim = r#"{"ownsStdio":true}"#;
1911 {
1912 let _registration = crate::enter_current_api(&owner);
1913 assert_eq!(vtable.declare.unwrap()(StbStringRef::from_str(claim)), 0);
1914 }
1915 let other_vtable = other.build_vtable();
1916 let finish = StbStringRef::from_str(r#"{"op":"finish","exitCode":7}"#);
1917 let mut out = StbString::empty();
1918 assert_eq!(
1920 (other_vtable.runtime_action)(
1921 RuntimeActionId::StdioLifecycle as u32,
1922 finish,
1923 &mut out,
1924 other_vtable.user_data
1925 ),
1926 1
1927 );
1928 unsafe { (other_vtable.free_string)(out) };
1930 assert_eq!(
1931 (vtable.runtime_action)(
1932 RuntimeActionId::StdioLifecycle as u32,
1933 finish,
1934 &mut out,
1935 vtable.user_data
1936 ),
1937 0
1938 );
1939 unsafe { (vtable.free_string)(out) };
1941 assert_eq!(master.stdio_lifecycle().wait().await, 7);
1942 {
1943 let _registration = crate::enter_current_api(&other);
1944 assert_ne!(
1945 other_vtable.declare.unwrap()(StbStringRef::from_str(claim)),
1946 0
1947 );
1948 }
1949 assert!(master
1950 .stdio_lifecycle()
1951 .validate()
1952 .unwrap_err()
1953 .contains("owner"));
1954 }
1955
1956 struct MockHost {
1961 prompt: String,
1962 saw: Mutex<Vec<RuntimeActionId>>,
1963 }
1964
1965 #[test]
1966 fn runtime_action_from_a_tokio_worker_does_not_block_its_dispatch() {
1967 const CHILD: &str = "RPI_RUNTIME_ACTION_WORKER_REGRESSION_CHILD";
1968 if std::env::var_os(CHILD).is_some() {
1969 let runtime = tokio::runtime::Builder::new_multi_thread()
1970 .worker_threads(1)
1971 .enable_all()
1972 .build()
1973 .unwrap();
1974 runtime.block_on(async {
1975 tokio::spawn(async {
1978 let host = Arc::new(MockHost {
1979 prompt: "worker callback".into(),
1980 saw: Mutex::new(Vec::new()),
1981 });
1982 let bridge = ActionBridge::new(Handle::current(), host);
1983 let mut out = StbString::empty();
1984 assert_eq!(
1985 trampoline_runtime_action(
1986 RuntimeActionId::GetSystemPrompt.into(),
1987 StbStringRef::from_str("{}"),
1988 &mut out,
1989 bridge.user_data(),
1990 ),
1991 0
1992 );
1993 let text = unsafe {
1995 rpi_plugin_sdk::callbacks::OwnedString::from_raw(
1996 out,
1997 Some(crate::host_free_string),
1998 )
1999 }
2000 .to_string_lossy();
2001 assert_eq!(
2002 serde_json::from_str::<serde_json::Value>(&text).unwrap()["prompt"],
2003 "worker callback"
2004 );
2005 })
2006 .await
2007 .unwrap();
2008 });
2009 return;
2010 }
2011 let mut child = std::process::Command::new(std::env::current_exe().unwrap())
2014 .args([
2015 "--exact",
2016 "actions::tests::runtime_action_from_a_tokio_worker_does_not_block_its_dispatch",
2017 "--nocapture",
2018 ])
2019 .env(CHILD, "1")
2020 .stdout(std::process::Stdio::piped())
2021 .stderr(std::process::Stdio::piped())
2022 .spawn()
2023 .unwrap();
2024 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2025 while child.try_wait().unwrap().is_none() {
2026 if std::time::Instant::now() >= deadline {
2027 let _ = child.kill();
2028 let _ = child.wait();
2029 panic!("runtime action blocked the worker needed by its own dispatch");
2030 }
2031 std::thread::sleep(std::time::Duration::from_millis(10));
2032 }
2033 let output = child.wait_with_output().unwrap();
2034 assert!(
2035 output.status.success(),
2036 "{}\n{}",
2037 String::from_utf8_lossy(&output.stdout),
2038 String::from_utf8_lossy(&output.stderr)
2039 );
2040 }
2041
2042 #[async_trait::async_trait]
2043 impl RuntimeActionHost for MockHost {
2044 async fn send_message(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2045 unreachable!("not under test")
2046 }
2047 async fn send_user_message(
2048 &self,
2049 _: serde_json::Value,
2050 ) -> Result<serde_json::Value, String> {
2051 unreachable!("not under test")
2052 }
2053 async fn append_entry(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2054 unreachable!("not under test")
2055 }
2056 async fn set_session_name(
2057 &self,
2058 _: serde_json::Value,
2059 ) -> Result<serde_json::Value, String> {
2060 unreachable!("not under test")
2061 }
2062 async fn get_active_tools(
2063 &self,
2064 _: serde_json::Value,
2065 ) -> Result<serde_json::Value, String> {
2066 unreachable!("not under test")
2067 }
2068 async fn set_active_tools(
2069 &self,
2070 _: serde_json::Value,
2071 ) -> Result<serde_json::Value, String> {
2072 unreachable!("not under test")
2073 }
2074 async fn set_model(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2075 unreachable!("not under test")
2076 }
2077 async fn get_thinking_level(
2078 &self,
2079 _: serde_json::Value,
2080 ) -> Result<serde_json::Value, String> {
2081 unreachable!("not under test")
2082 }
2083 async fn set_thinking_level(
2084 &self,
2085 _: serde_json::Value,
2086 ) -> Result<serde_json::Value, String> {
2087 unreachable!("not under test")
2088 }
2089 async fn compact(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2090 unreachable!("not under test")
2091 }
2092 async fn get_system_prompt(
2093 &self,
2094 _: serde_json::Value,
2095 ) -> Result<serde_json::Value, String> {
2096 self.saw
2097 .lock()
2098 .unwrap()
2099 .push(RuntimeActionId::GetSystemPrompt);
2100 Ok(serde_json::json!({ "prompt": self.prompt }))
2101 }
2102 async fn new_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2103 unreachable!("not under test")
2104 }
2105 async fn fork(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2106 unreachable!("not under test")
2107 }
2108 async fn navigate_tree(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2109 unreachable!("not under test")
2110 }
2111 async fn switch_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2112 unreachable!("not under test")
2113 }
2114 async fn reload(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2115 self.saw.lock().unwrap().push(RuntimeActionId::Reload);
2116 Ok(serde_json::Value::Null)
2117 }
2118 async fn get_cli_flag(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2119 self.saw.lock().unwrap().push(RuntimeActionId::GetCliFlag);
2120 Ok(serde_json::json!({ "value": true }))
2121 }
2122 }
2123
2124 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2128 async fn trampoline_round_trips_get_system_prompt() {
2129 let host = Arc::new(MockHost {
2130 prompt: "hello from host".to_string(),
2131 saw: Mutex::new(Vec::new()),
2132 });
2133 let host_for_assert = Arc::clone(&host);
2134 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2135 let runtime = tokio::runtime::Handle::current();
2136 let bridge = ActionBridge::new(runtime, host_dyn);
2137 let user_data = bridge.user_data();
2138
2139 let args_str = "{}";
2141 let args_ref = StbStringRef::from_str(args_str);
2142
2143 let mut out = StbString::empty();
2144 let rc = trampoline_runtime_action(
2145 RuntimeActionId::GetSystemPrompt.into(),
2146 args_ref,
2147 &mut out as *mut StbString,
2148 user_data,
2149 );
2150 assert_eq!(rc, 0, "success return code");
2151
2152 let json_text = unsafe {
2155 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2156 }
2157 .to_string_lossy();
2158 let parsed: serde_json::Value = serde_json::from_str(&json_text).expect("valid json");
2159 assert_eq!(parsed["prompt"], "hello from host");
2160
2161 let saw = host_for_assert.saw.lock().unwrap().clone();
2164 assert_eq!(saw, vec![RuntimeActionId::GetSystemPrompt]);
2165 }
2166
2167 #[tokio::test]
2173 async fn trampoline_routes_set_editor_text_into_the_mailbox() {
2174 let host = Arc::new(MockHost {
2175 prompt: String::new(),
2176 saw: Mutex::new(Vec::new()),
2177 });
2178 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2179 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2180 let mailbox = bridge.editor_text_mailbox();
2181 let user_data = bridge.user_data();
2182
2183 let args_ref =
2184 StbStringRef::from_str(r#"{"text":"from voice","mode":"append","autoSendMs":2000}"#);
2185 let mut out = StbString::empty();
2186 let rc = trampoline_runtime_action(
2187 RuntimeActionId::SetEditorText.into(),
2188 args_ref,
2189 &mut out as *mut StbString,
2190 user_data,
2191 );
2192 assert_eq!(rc, 0, "success return code");
2193
2194 let parsed: serde_json::Value = serde_json::from_str(
2196 &unsafe {
2197 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2198 }
2199 .to_string_lossy(),
2200 )
2201 .expect("valid json");
2202 assert_eq!(parsed["ok"], serde_json::json!(true));
2203 assert_eq!(parsed["chars"], serde_json::json!(10));
2204
2205 let edit = mailbox.take_pending().expect("queued edit");
2207 assert_eq!(edit.text, "from voice");
2208 assert_eq!(edit.mode, crate::EditorTextMode::Append);
2209 assert_eq!(edit.auto_send_ms, Some(2000));
2210 assert!(mailbox.take_pending().is_none());
2211 }
2212
2213 #[tokio::test]
2214 async fn trampoline_null_user_data_returns_minus_one() {
2215 let args_ref = StbStringRef::from_str("{}");
2216 let mut out = StbString::empty();
2217 let rc = trampoline_runtime_action(
2218 RuntimeActionId::GetSystemPrompt.into(),
2219 args_ref,
2220 &mut out as *mut StbString,
2221 std::ptr::null_mut(),
2222 );
2223 assert_eq!(rc, -1, "null user_data ⇒ no bridge");
2224 }
2225
2226 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2227 async fn trampoline_intercepts_reload_when_bridge_has_callback() {
2228 use std::sync::atomic::{AtomicUsize, Ordering};
2232 let reload_calls = Arc::new(AtomicUsize::new(0));
2233 let reload_calls_for_cb = Arc::clone(&reload_calls);
2234 let reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync> =
2235 Arc::new(move || {
2236 let c = Arc::clone(&reload_calls_for_cb);
2237 Box::pin(async move {
2238 c.fetch_add(1, Ordering::SeqCst);
2239 })
2240 });
2241 let host = Arc::new(MockHost {
2242 prompt: String::new(),
2243 saw: Mutex::new(Vec::new()),
2244 });
2245 let host_for_assert = Arc::clone(&host);
2246 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2247 let runtime = tokio::runtime::Handle::current();
2248 let bridge = ActionBridge::with_reload(runtime, host_dyn, reload);
2249 let user_data = bridge.user_data();
2250
2251 let args_ref = StbStringRef::from_str("{}");
2252 let mut out = StbString::empty();
2253 let rc = trampoline_runtime_action(
2254 RuntimeActionId::Reload.into(),
2255 args_ref,
2256 &mut out as *mut StbString,
2257 user_data,
2258 );
2259 assert_eq!(rc, 0);
2260 assert_eq!(reload_calls.load(Ordering::SeqCst), 1);
2262 assert!(host_for_assert.saw.lock().unwrap().is_empty());
2263 drop(unsafe {
2265 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2266 });
2267 }
2268
2269 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2274 async fn trampoline_rejects_stale_bridge_with_invalidate() {
2275 let host = Arc::new(MockHost {
2276 prompt: String::new(),
2277 saw: Mutex::new(Vec::new()),
2278 });
2279 let host_for_assert = Arc::clone(&host);
2280 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2281 let runtime = tokio::runtime::Handle::current();
2282 let bridge = ActionBridge::new(runtime, host_dyn);
2283 let user_data = bridge.user_data();
2284
2285 bridge.invalidate();
2287 assert!(!bridge.is_active());
2288
2289 let args_ref = StbStringRef::from_str("{}");
2290 let mut out = StbString::empty();
2291 let rc = trampoline_runtime_action(
2292 RuntimeActionId::GetSystemPrompt.into(),
2293 args_ref,
2294 &mut out as *mut StbString,
2295 user_data,
2296 );
2297 assert_eq!(rc, 1, "stale bridge ⇒ error return code");
2299 let json_text = unsafe {
2301 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2302 }
2303 .to_string_lossy();
2304 assert!(
2305 json_text.contains("stale"),
2306 "stale-bridge error payload: {json_text}"
2307 );
2308
2309 assert!(
2310 host_for_assert.saw.lock().unwrap().is_empty(),
2311 "host dispatch must NOT run on a stale bridge"
2312 );
2313 }
2314
2315 #[tokio::test]
2316 async fn trampoline_rejects_unknown_numeric_id_without_dispatch() {
2317 let host = Arc::new(MockHost {
2318 prompt: String::new(),
2319 saw: Mutex::new(Vec::new()),
2320 });
2321 let host_for_assert = Arc::clone(&host);
2322 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2323 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2324 let user_data = bridge.user_data();
2325
2326 let mut out = StbString::empty();
2327 let rc = trampoline_runtime_action(
2328 0xFFFF_FFFE,
2329 StbStringRef::from_str("{}"),
2330 &mut out,
2331 user_data,
2332 );
2333
2334 assert_eq!(rc, 2, "unknown action id must be a protocol error");
2335 let payload: serde_json::Value = serde_json::from_str(
2336 &unsafe {
2337 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2338 }
2339 .to_string_lossy(),
2340 )
2341 .expect("structured error JSON");
2342 assert_eq!(payload["error"], "unknown runtime action id 4294967294");
2343
2344 assert!(
2345 host_for_assert.saw.lock().unwrap().is_empty(),
2346 "unknown action id must not reach host dispatch"
2347 );
2348 }
2349
2350 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2351 async fn v2_trampoline_accepts_new_action() {
2352 let host = Arc::new(MockHost {
2353 prompt: "v2".to_string(),
2354 saw: Mutex::new(Vec::new()),
2355 });
2356 let host_for_assert = Arc::clone(&host);
2357 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2358 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2359 let user_data = bridge.user_data();
2360
2361 let mut v2_out = StbString::empty();
2362 assert_eq!(
2363 trampoline_runtime_action(
2364 RuntimeActionId::GetCliFlag.into(),
2365 StbStringRef::from_str(r#"{"name":"flag"}"#),
2366 &mut v2_out,
2367 user_data,
2368 ),
2369 0
2370 );
2371 drop(unsafe {
2373 rpi_plugin_sdk::callbacks::OwnedString::from_raw(v2_out, Some(crate::host_free_string))
2374 });
2375
2376 assert_eq!(
2377 *host_for_assert.saw.lock().unwrap(),
2378 vec![RuntimeActionId::GetCliFlag]
2379 );
2380 }
2381
2382 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2387 async fn reload_mailbox_signals_installed_receiver() {
2388 let mailbox = ReloadMailbox::new();
2389 assert!(matches!(mailbox.signal(), Err(())));
2391
2392 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2393 mailbox.install(tx);
2394 let cb = reload_callback_from_mailbox(mailbox.clone());
2395 cb().await;
2396 assert_eq!(
2397 rx.recv().await,
2398 Some(()),
2399 "installed receiver saw the signal"
2400 );
2401 mailbox.clear();
2402 }
2403
2404 fn open_args(id: &str, tool_call: &str) -> serde_json::Value {
2407 serde_json::json!({
2408 "op": "open",
2409 "requestId": id,
2410 "toolCallId": tool_call,
2411 "ui": {"kind": "selector", "questions": [
2412 {"id": "q1", "question": "Which target?", "options": ["Linux"]}
2413 ]},
2414 })
2415 }
2416
2417 #[test]
2420 fn ui_dialog_open_requires_an_attached_ui() {
2421 let mailbox = UiDialogMailbox::new();
2422 let error = mailbox.handle(open_args("r1", "c1")).unwrap_err();
2423 assert!(error.contains("interactive UI"), "got: {error}");
2424 }
2425
2426 #[test]
2427 fn ui_dialog_attachment_generation_exhaustion_fails_closed() {
2428 let mailbox = UiDialogMailbox::new();
2429 mailbox
2430 .state
2431 .lock()
2432 .expect("ui dialog mailbox poisoned")
2433 .attachment_generation = u64::MAX;
2434
2435 assert_eq!(mailbox.try_attach_with_generation(), None);
2436 assert_eq!(mailbox.attachment_generation(), Some(u64::MAX));
2437 assert!(!mailbox.is_attached());
2438
2439 mailbox.attach();
2442 assert!(!mailbox.is_attached());
2443 }
2444
2445 #[test]
2446 fn ui_dialog_attachment_lock_poison_fails_closed_without_panicking() {
2447 let mailbox = UiDialogMailbox::new();
2448 let state = mailbox.state.clone();
2449 assert!(std::thread::spawn(move || {
2450 let _guard = state.lock().unwrap();
2451 panic!("poison synthetic dialog mailbox state");
2452 })
2453 .join()
2454 .is_err());
2455
2456 assert_eq!(mailbox.try_attach_with_generation(), None);
2457 assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2458 mailbox.attach();
2460 }))
2461 .is_ok());
2462 }
2463
2464 #[test]
2465 fn ui_dialog_observation_lock_poison_fails_closed_without_panicking() {
2466 let mailbox = UiDialogMailbox::new();
2467 let state = mailbox.state.clone();
2468 assert!(std::thread::spawn(move || {
2469 let _guard = state.lock().unwrap();
2470 panic!("poison synthetic dialog observation state");
2471 })
2472 .join()
2473 .is_err());
2474
2475 assert_eq!(mailbox.attachment_generation(), None);
2476 assert!(!mailbox.is_attached());
2477 }
2478
2479 #[test]
2480 fn ui_dialog_detach_generation_lock_poison_fails_closed_without_panicking() {
2481 let mailbox = UiDialogMailbox::new();
2482 let state = mailbox.state.clone();
2483 assert!(std::thread::spawn(move || {
2484 let _guard = state.lock().unwrap();
2485 panic!("poison synthetic dialog retirement state");
2486 })
2487 .join()
2488 .is_err());
2489
2490 assert!(!mailbox.detach_if_generation(1));
2491 }
2492
2493 #[test]
2494 fn ui_dialog_compat_detach_lock_poison_fails_closed_without_panicking() {
2495 let mailbox = UiDialogMailbox::new();
2496 let state = mailbox.state.clone();
2497 assert!(std::thread::spawn(move || {
2498 let _guard = state.lock().unwrap();
2499 panic!("poison synthetic dialog compatibility retirement state");
2500 })
2501 .join()
2502 .is_err());
2503
2504 assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2505 mailbox.detach();
2506 }))
2507 .is_ok());
2508 assert_eq!(mailbox.try_attach_with_generation(), None);
2509 }
2510
2511 #[test]
2512 fn ui_dialog_open_poll_answer_round_trip() {
2513 let mailbox = UiDialogMailbox::new();
2514 mailbox.attach();
2515
2516 let opened = mailbox.handle(open_args("r1", "c1")).unwrap();
2517 assert_eq!(opened["status"], "pending");
2518 assert_eq!(opened["toolCallId"], "c1");
2519
2520 let request = mailbox.take_pending().expect("request visible to TUI");
2521 assert_eq!(request.request_id, "r1");
2522 assert_eq!(request.tool_call_id.as_deref(), Some("c1"));
2523 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2525 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2526
2527 mailbox
2528 .respond("r1", serde_json::json!("7890"))
2529 .expect("respond");
2530 let answered = mailbox.poll("r1").unwrap();
2531 assert_eq!(answered["status"], "answered");
2532 assert_eq!(answered["answer"], "7890");
2533 assert!(mailbox.poll("r1").is_err());
2535 }
2536
2537 #[test]
2538 fn ui_dialog_forget_reclaims_terminal_entries_without_stranding_pending_ones() {
2539 let mailbox = UiDialogMailbox::new();
2540 mailbox.attach();
2541
2542 mailbox.handle(open_args("r1", "c1")).unwrap();
2545 assert_eq!(
2546 mailbox.forget("r1"),
2547 Err("UI request `r1` is still pending".to_string())
2548 );
2549 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2550
2551 mailbox.cancel("r1").unwrap();
2554 assert_eq!(mailbox.forget("r1"), Ok(true));
2555 assert_eq!(mailbox.forget("r1"), Ok(false)); assert!(mailbox.poll("r1").is_err());
2557
2558 mailbox.handle(open_args("r2", "c2")).unwrap();
2561 mailbox
2562 .respond("r2", serde_json::json!({"values": ["Linux"]}))
2563 .unwrap();
2564 let forgotten = mailbox
2565 .handle(serde_json::json!({"op": "forget", "requestId": "r2"}))
2566 .unwrap();
2567 assert_eq!(forgotten["status"], "forgotten");
2568 assert_eq!(forgotten["removed"], true);
2569 assert!(mailbox.poll("r2").is_err());
2570
2571 assert_eq!(mailbox.forget("missing"), Ok(false));
2574 let reopened = mailbox.handle(open_args("r1", "c1")).unwrap();
2575 assert_eq!(reopened["status"], "pending");
2576 }
2577
2578 #[test]
2579 fn ui_dialog_cancel_is_reported_once() {
2580 let mailbox = UiDialogMailbox::new();
2581 mailbox.attach();
2582 mailbox.handle(open_args("r1", "c1")).unwrap();
2583 mailbox.cancel("r1").unwrap();
2584 let cancelled = mailbox.poll("r1").unwrap();
2585 assert_eq!(cancelled["status"], "cancelled");
2586 assert!(mailbox.poll("r1").is_err());
2587 }
2588
2589 #[test]
2590 fn ui_dialog_tool_cancel_preserves_other_calls_and_rejects_late_questions() {
2591 let mailbox = UiDialogMailbox::new();
2592 mailbox.attach();
2593 mailbox.handle(open_args("r1", "c1")).unwrap();
2594 mailbox.handle(open_args("r2", "c2")).unwrap();
2595 mailbox.cancel_tool_call("c1");
2596 assert_eq!(mailbox.poll("r1").unwrap()["status"], "cancelled");
2597 assert_eq!(mailbox.take_pending().unwrap().request_id, "r2");
2598 assert_eq!(mailbox.poll("r2").unwrap()["status"], "pending");
2599 assert_eq!(
2600 mailbox.handle(open_args("late", "c1")).unwrap()["status"],
2601 "cancelled"
2602 );
2603 assert!(mailbox.take_pending().is_none());
2604 }
2605
2606 #[test]
2607 fn ui_dialog_concurrent_requests_do_not_cross_answers() {
2608 let mailbox = UiDialogMailbox::new();
2609 mailbox.attach();
2610 mailbox.handle(open_args("r1", "c1")).unwrap();
2611 mailbox.handle(open_args("r2", "c2")).unwrap();
2612
2613 let first = mailbox.take_pending().unwrap().request_id;
2614 let second = mailbox.take_pending().unwrap().request_id;
2615 assert_ne!(first, second);
2616
2617 mailbox
2619 .respond(&second, serde_json::json!("second"))
2620 .unwrap();
2621 assert_eq!(mailbox.poll(&first).unwrap()["status"], "pending");
2622 let second_answer = mailbox.poll(&second).unwrap();
2623 assert_eq!(second_answer["answer"], "second");
2624
2625 mailbox.respond(&first, serde_json::json!("first")).unwrap();
2626 assert_eq!(mailbox.poll(&first).unwrap()["answer"], "first");
2627 }
2628
2629 #[test]
2630 fn ui_dialog_detach_cancels_outstanding() {
2631 let mailbox = UiDialogMailbox::new();
2632 mailbox.attach();
2633 mailbox.handle(open_args("r1", "c1")).unwrap();
2634 mailbox.detach();
2635 assert!(!mailbox.is_attached());
2636 assert_eq!(mailbox.pending_len(), 0);
2637 assert!(mailbox.handle(open_args("r2", "c2")).is_err());
2639 assert_eq!(mailbox.poll("r1").unwrap()["status"], "cancelled");
2640 }
2641
2642 #[test]
2643 fn ui_dialog_duplicate_open_does_not_reenqueue() {
2644 let mailbox = UiDialogMailbox::new();
2645 mailbox.attach();
2646 mailbox.handle(open_args("r1", "c1")).unwrap();
2647 let again = mailbox.handle(open_args("r1", "c1")).unwrap();
2648 assert_eq!(again["status"], "pending");
2649 assert_eq!(mailbox.pending_len(), 1);
2650 mailbox.take_pending().unwrap();
2651 assert!(mailbox.take_pending().is_none());
2652 }
2653
2654 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2659 async fn list_commands_routes_to_the_host_and_defaults_to_empty() {
2660 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2661 prompt: String::new(),
2662 saw: Mutex::new(Vec::new()),
2663 });
2664 let bridge = ActionBridge::with_ui_dialog(
2665 tokio::runtime::Handle::current(),
2666 host,
2667 UiDialogMailbox::new(),
2668 );
2669 let user_data = bridge.user_data();
2670 let mut out = StbString::empty();
2671 let rc = trampoline_runtime_action(
2672 u32::from(RuntimeActionId::ListCommands),
2673 StbStringRef::from_str("{}"),
2674 &mut out,
2675 user_data,
2676 );
2677 assert_eq!(
2678 rc, 0,
2679 "ListCommands must not fail on a host with no registry"
2680 );
2681 let payload: serde_json::Value = serde_json::from_str(
2682 &unsafe {
2683 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2684 }
2685 .to_string_lossy(),
2686 )
2687 .expect("JSON");
2688 assert_eq!(
2689 payload
2690 .get("commands")
2691 .and_then(|c| c.as_array())
2692 .map(Vec::len),
2693 Some(0),
2694 "an empty registry is an empty list, not an error: {payload}"
2695 );
2696 }
2697
2698 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2702 async fn v2_dispatch_routes_ui_dialog_action_17() {
2703 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2704 prompt: String::new(),
2705 saw: Mutex::new(Vec::new()),
2706 });
2707 let bridge = ActionBridge::with_ui_dialog(
2708 tokio::runtime::Handle::current(),
2709 host,
2710 UiDialogMailbox::new(),
2711 );
2712 let user_data = bridge.user_data();
2713
2714 let mut out = StbString::empty();
2715 let rc = trampoline_runtime_action(
2716 17,
2717 StbStringRef::from_str(r#"{"op":"open","requestId":"r1","ui":{}}"#),
2718 &mut out,
2719 user_data,
2720 );
2721 assert_eq!(rc, 1);
2722 let payload: serde_json::Value = serde_json::from_str(
2723 &unsafe {
2724 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2725 }
2726 .to_string_lossy(),
2727 )
2728 .expect("structured error JSON");
2729 assert!(
2730 payload["error"]
2731 .as_str()
2732 .is_some_and(|error| error.contains("interactive UI")),
2733 "unexpected payload: {payload}"
2734 );
2735
2736 let one_past_last = rpi_plugin_sdk::RuntimeActionId::MAX + 1;
2740 let mut out = StbString::empty();
2741 assert_eq!(
2742 trampoline_runtime_action(
2743 one_past_last,
2744 StbStringRef::from_str("{}"),
2745 &mut out,
2746 user_data
2747 ),
2748 2
2749 );
2750 drop(unsafe {
2752 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2753 });
2754 }
2755
2756 #[tokio::test(flavor = "current_thread")]
2757 async fn component_bridge_isolates_plugins_and_cleans_up_reload_and_drop() {
2758 let host = Arc::new(MockHost {
2759 prompt: String::new(),
2760 saw: Mutex::new(Vec::new()),
2761 });
2762 let root = ActionBridge::new(tokio::runtime::Handle::current(), host);
2763 let a = root.for_plugin("a");
2764 let b = root.for_plugin("b");
2765 let mailbox = root.extension_status_mailbox();
2766 for plugin in [&a, &b] {
2767 let mut out = StbString::empty();
2768 assert_eq!(
2769 trampoline_runtime_action(
2770 22,
2771 StbStringRef::from_str(
2772 r#"{"op":"register","id":"same","slot":"footer.after"}"#
2773 ),
2774 &mut out,
2775 plugin.user_data()
2776 ),
2777 0
2778 );
2779 drop(unsafe {
2781 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2782 });
2783 }
2784 assert_eq!(mailbox.panels().len(), 2);
2785 drop(a);
2786 assert_eq!(mailbox.panels().len(), 1);
2787 root.invalidate();
2788 assert!(mailbox.panels().is_empty());
2789 }
2790
2791 #[test]
2797 fn relay_ui_dialog_runs_off_the_executor() {
2798 let mailbox = UiDialogMailbox::new();
2799 mailbox.attach();
2800 let out = dispatch_relay_ui_dialog(&mailbox, serde_json::json!({"op":"release"}))
2801 .expect("release is a supported op");
2802 assert_eq!(out["requeued"], serde_json::json!(0));
2803 }
2804
2805 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2808 async fn v2_dispatch_routes_set_status_action_18() {
2809 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2810 prompt: String::new(),
2811 saw: Mutex::new(Vec::new()),
2812 });
2813 let status = crate::status::ExtensionStatusMailbox::new();
2814 let bridge = ActionBridge::with_reload_and_ui(
2815 tokio::runtime::Handle::current(),
2816 host,
2817 Arc::new(|| Box::pin(async {})),
2818 UiDialogMailbox::new(),
2819 status.clone(),
2820 crate::editor_text::EditorTextMailbox::new(),
2821 );
2822 let user_data = bridge.user_data();
2823
2824 let mut out = StbString::empty();
2825 let rc = trampoline_runtime_action(
2826 18,
2827 StbStringRef::from_str(r#"{"key":"langfuse","value":"langfuse ✓ (trace sent)"}"#),
2828 &mut out,
2829 user_data,
2830 );
2831 assert_eq!(rc, 0);
2832 assert_eq!(status.text(), "langfuse ✓ (trace sent)");
2833 drop(unsafe {
2835 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2836 });
2837
2838 let mut out = StbString::empty();
2840 assert_eq!(
2841 trampoline_runtime_action(
2842 18,
2843 StbStringRef::from_str(r#"{"key":"langfuse","value":""}"#),
2844 &mut out,
2845 user_data
2846 ),
2847 0
2848 );
2849 assert_eq!(status.text(), "");
2850 drop(unsafe {
2852 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2853 });
2854
2855 let mut out = StbString::empty();
2857 assert_eq!(
2858 trampoline_runtime_action(18, StbStringRef::from_str("{}"), &mut out, user_data),
2859 1
2860 );
2861 drop(unsafe {
2863 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2864 });
2865 }
2866 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2873 async fn trampoline_ceiling_matches_the_highest_defined_action() {
2874 let highest = RuntimeActionId::MAX;
2875 assert_eq!(
2876 highest,
2877 RuntimeActionId::ALL
2878 .iter()
2879 .copied()
2880 .map(u32::from)
2881 .max()
2882 .unwrap(),
2883 "RuntimeActionId::MAX must be the maximum of RuntimeActionId::ALL"
2884 );
2885 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2886 prompt: String::new(),
2887 saw: Mutex::new(Vec::new()),
2888 });
2889 let bridge = ActionBridge::with_ui_dialog(
2890 tokio::runtime::Handle::current(),
2891 host,
2892 UiDialogMailbox::new(),
2893 );
2894 let mut out = StbString::empty();
2895 let rc = trampoline_runtime_action(
2896 highest,
2897 StbStringRef::from_str("{}"),
2898 &mut out,
2899 bridge.user_data(),
2900 );
2901 assert_ne!(
2902 rc, 2,
2903 "the highest defined action id ({highest}) must not be rejected as unknown — \
2904 the trampoline ceiling is stale"
2905 );
2906 if rc == 0 {
2907 drop(unsafe {
2909 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2910 });
2911 }
2912 }
2913}
2914
2915impl Drop for ActionBridge {
2916 fn drop(&mut self) {
2917 bridges()
2918 .lock()
2919 .unwrap_or_else(|e| e.into_inner())
2920 .retain(|_, entry| !std::ptr::eq(entry.bridge.as_ptr(), self));
2921 if self.invocation.is_some() {
2922 return;
2923 }
2924 if let Some((owner, _)) = &self.plugin_identity {
2925 self.ext_status.remove_owner(*owner);
2926 self.host.cancel_child_agents(*owner);
2927 self.host.cancel_side_questions(*owner);
2928 }
2929 }
2930}
2931
2932#[cfg(test)]
2933mod runtime_tests;
2934
2935#[cfg(test)]
2936mod relay_tests {
2937 use super::*;
2938
2939 fn request(id: &str) -> UiDialogRequest {
2940 UiDialogRequest {
2941 request_id: id.to_string(),
2942 tool_call_id: Some(format!("tool-{id}")),
2943 ui: serde_json::json!({"question": "ok?"}),
2944 raw: serde_json::json!({}),
2945 }
2946 }
2947
2948 #[test]
2952 fn reserved_requests_are_invisible_to_the_tui() {
2953 let mailbox = UiDialogMailbox::new();
2954 mailbox.attach();
2955 let reserved = format!("{PLUGIN_RESERVED_PREFIX}gate-1");
2956 mailbox
2957 .handle(serde_json::json!({
2958 "op": "open",
2959 "requestId": reserved,
2960 "toolCallId": "t1",
2961 "ui": {}
2962 }))
2963 .unwrap();
2964 mailbox
2965 .handle(serde_json::json!({
2966 "op": "open",
2967 "requestId": "plain-1",
2968 "toolCallId": "t2",
2969 "ui": {}
2970 }))
2971 .unwrap();
2972
2973 let taken = mailbox
2975 .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
2976 .expect("the unreserved request must reach the TUI");
2977 assert_eq!(taken.request_id, "plain-1");
2978
2979 let own = mailbox
2981 .take_pending_filtered(|r| mailbox.is_reserved(&r.request_id))
2982 .expect("the plugin must still see its reserved request");
2983 assert_eq!(own.request_id, reserved);
2984 }
2985
2986 #[test]
2988 fn release_or_detach_clears_takeover_and_requeues_unanswered() {
2989 let mailbox = UiDialogMailbox::new();
2990 mailbox.attach();
2991 mailbox
2992 .handle(serde_json::json!({
2993 "op": "open", "requestId": "plain-r", "toolCallId": "t", "ui": {}
2994 }))
2995 .unwrap();
2996
2997 mailbox.set_external_takeover(true);
2999 assert_eq!(mailbox.take_all_unreserved().len(), 1);
3000 assert_eq!(mailbox.release_takeover(), 1);
3001 assert!(
3002 !mailbox.external_takeover(),
3003 "release must hand delivery back to the TUI"
3004 );
3005 assert_eq!(
3007 mailbox
3008 .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
3009 .map(|r| r.request_id),
3010 Some("plain-r".to_string())
3011 );
3012
3013 mailbox.set_external_takeover(true);
3015 mailbox.detach();
3016 assert!(!mailbox.external_takeover(), "detach must clear takeover");
3017 }
3018
3019 #[test]
3022 fn tui_take_is_atomic_against_takeover() {
3023 let mailbox = UiDialogMailbox::new();
3024 mailbox.attach();
3025 mailbox.set_external_takeover(true);
3026 mailbox
3027 .handle(serde_json::json!({
3028 "op": "open", "requestId": "plain-a", "toolCallId": "t", "ui": {}
3029 }))
3030 .unwrap();
3031 assert!(
3032 mailbox.take_pending_unless_external(|_| true).is_none(),
3033 "the TUI must stand down while a relay owns delivery"
3034 );
3035 assert_eq!(mailbox.take_all_unreserved().len(), 1);
3037 }
3038
3039 #[test]
3042 fn relay_take_returns_unreserved_and_keeps_reserved() {
3043 let mailbox = UiDialogMailbox::new();
3044 mailbox.attach();
3045 mailbox
3046 .handle(serde_json::json!({
3047 "op": "open",
3048 "requestId": format!("{PLUGIN_RESERVED_PREFIX}keep"),
3049 "toolCallId": "t1",
3050 "ui": {}
3051 }))
3052 .unwrap();
3053 mailbox
3054 .handle(serde_json::json!({
3055 "op": "open",
3056 "requestId": "relay-1",
3057 "toolCallId": "t2",
3058 "ui": {}
3059 }))
3060 .unwrap();
3061
3062 let taken = mailbox.take_all_unreserved();
3063 assert_eq!(taken.len(), 1);
3064 assert_eq!(taken[0].request_id, "relay-1");
3065 assert_eq!(mailbox.pending_len(), 1);
3067 }
3068
3069 #[test]
3072 fn a_relayed_request_can_still_be_answered() {
3073 let mailbox = UiDialogMailbox::new();
3074 mailbox.attach();
3075 mailbox
3076 .handle(serde_json::json!({
3077 "op": "open",
3078 "requestId": "relay-1",
3079 "toolCallId": "t1",
3080 "ui": {}
3081 }))
3082 .unwrap();
3083 let taken = mailbox.take_all_unreserved();
3084 assert_eq!(taken.len(), 1);
3085
3086 mailbox
3087 .handle(serde_json::json!({
3088 "op": "respond",
3089 "requestId": "relay-1",
3090 "answer": {"ok": true}
3091 }))
3092 .unwrap();
3093 assert_eq!(
3095 mailbox
3096 .take_pending_filtered(|_| true)
3097 .map(|r| r.request_id),
3098 None,
3099 "an answered request must not resurface"
3100 );
3101 }
3102
3103 #[test]
3106 fn take_pending_still_takes_reserved_entries() {
3107 let mailbox = UiDialogMailbox::new();
3108 mailbox.attach();
3109 let reserved = format!("{PLUGIN_RESERVED_PREFIX}x");
3110 mailbox
3111 .handle(serde_json::json!({
3112 "op": "open",
3113 "requestId": reserved,
3114 "toolCallId": "t1",
3115 "ui": {}
3116 }))
3117 .unwrap();
3118 assert_eq!(
3119 mailbox.take_pending().map(|r| r.request_id),
3120 Some(format!("{PLUGIN_RESERVED_PREFIX}x"))
3121 );
3122 }
3123
3124 #[test]
3130 fn external_takeover_makes_the_tui_stand_down() {
3131 let mailbox = UiDialogMailbox::new();
3132 mailbox.attach();
3133 mailbox
3134 .handle(serde_json::json!({
3135 "op": "open",
3136 "requestId": "plain-1",
3137 "toolCallId": "t1",
3138 "ui": {}
3139 }))
3140 .unwrap();
3141
3142 assert!(!mailbox.external_takeover());
3143 mailbox.set_external_takeover(true);
3144 assert!(mailbox.external_takeover());
3145
3146 let tui_take = |m: &UiDialogMailbox| {
3148 if m.external_takeover() {
3149 return None;
3150 }
3151 m.take_pending_filtered(|r| !m.is_reserved(&r.request_id))
3152 };
3153 assert!(
3154 tui_take(&mailbox).is_none(),
3155 "the TUI must not steal a request an external UI owns"
3156 );
3157 assert_eq!(mailbox.take_all_unreserved().len(), 1);
3159 }
3160
3161 #[test]
3163 fn clearing_takeover_returns_dialogs_to_the_tui() {
3164 let mailbox = UiDialogMailbox::new();
3165 mailbox.attach();
3166 mailbox.set_external_takeover(true);
3167 mailbox.set_external_takeover(false);
3168 mailbox
3169 .handle(serde_json::json!({
3170 "op": "open",
3171 "requestId": "plain-2",
3172 "toolCallId": "t2",
3173 "ui": {}
3174 }))
3175 .unwrap();
3176 assert_eq!(
3177 mailbox
3178 .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
3179 .map(|r| r.request_id),
3180 Some("plain-2".to_string())
3181 );
3182 }
3183
3184 #[test]
3185 fn request_helper_matches_the_prefix_rule() {
3186 let mailbox = UiDialogMailbox::new();
3187 mailbox.attach();
3188 assert!(mailbox.is_reserved(&request(PLUGIN_RESERVED_PREFIX).request_id));
3189 assert!(!mailbox.is_reserved(&request("plain").request_id));
3190 }
3191}