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 fn child_agent_roster(&self) -> Vec<serde_json::Value> {
691 Vec::new()
692 }
693 fn stop_child_agent(&self, _child_id: &str) -> Result<serde_json::Value, String> {
702 Err("child agent control is not supported by this host; upgrade rpi".into())
703 }
704 async fn send_message(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
709 async fn send_user_message(&self, args: serde_json::Value)
711 -> Result<serde_json::Value, String>;
712 async fn append_entry(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
722 async fn set_session_name(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
724 async fn get_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
726 async fn set_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
728 async fn set_model(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
730 async fn get_thinking_level(
732 &self,
733 args: serde_json::Value,
734 ) -> Result<serde_json::Value, String>;
735 async fn set_thinking_level(
737 &self,
738 args: serde_json::Value,
739 ) -> Result<serde_json::Value, String>;
740 async fn compact(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
742 async fn get_system_prompt(&self, args: serde_json::Value)
744 -> Result<serde_json::Value, String>;
745 async fn new_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
747 async fn fork(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
749 async fn navigate_tree(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
751 async fn switch_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
753 async fn reload(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
757
758 async fn reload_models(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
768 Err("reload_models is not supported by this host".to_string())
769 }
770
771 async fn get_cli_flag(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
774 Err("CLI flag lookup is not configured".to_string())
775 }
776
777 async fn ui_dialog(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
781 Err("ask_user requires an interactive UI".to_string())
782 }
783
784 async fn list_commands(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
795 Ok(serde_json::json!({ "commands": [] }))
796 }
797
798 fn publish_registry(&self, _snapshot: std::sync::Arc<crate::registry::RegistrySnapshot>) {}
809
810 fn publish_registry_opt(
816 &self,
817 snapshot: Option<std::sync::Arc<crate::registry::RegistrySnapshot>>,
818 ) {
819 if let Some(snapshot) = snapshot {
820 self.publish_registry(snapshot);
821 }
822 }
823
824 async fn abort(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
832 Ok(serde_json::json!({
833 "aborted": false,
834 "steer": [],
835 "followUp": [],
836 }))
837 }
838
839 fn stop_round(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
849 Ok(serde_json::json!({ "requested": true }))
850 }
851
852 async fn get_execution_context(
854 &self,
855 _args: serde_json::Value,
856 ) -> Result<serde_json::Value, String> {
857 Err("execution context is not supported by this host".into())
858 }
859
860 async fn child_agent(
862 &self,
863 _owner: u64,
864 _args: serde_json::Value,
865 ) -> Result<serde_json::Value, String> {
866 Err("ChildAgent is not supported by this host".into())
867 }
868
869 async fn get_session_branch(
879 &self,
880 _args: serde_json::Value,
881 ) -> Result<serde_json::Value, String> {
882 Err("session branch lookup is not configured".to_string())
883 }
884}
885
886pub struct ActionBridge {
913 invocation: Option<(bool, String, tokio_util::sync::CancellationToken)>,
915 execution_context: Option<serde_json::Value>,
916 tool_program: Option<Arc<rpi_agent::tool_program::ToolProgram>>,
917 stdio: crate::StdioLifecycle,
918 plugin_identity: Option<(u64, String)>,
919 component_owners: Arc<std::sync::Mutex<Vec<u64>>>,
920 pub(crate) runtime: Handle,
922 pub(crate) host: Arc<dyn RuntimeActionHost>,
924 pub(crate) reload:
926 Option<Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>>,
927 ui_dialog: UiDialogMailbox,
930 ext_status: crate::status::ExtensionStatusMailbox,
934 editor_text: crate::editor_text::EditorTextMailbox,
938 active: Arc<AtomicBool>,
941}
942
943impl ActionBridge {
944 pub fn user_data(self: &Arc<Self>) -> *mut c_void {
946 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1);
947 let mut registry = bridges().lock().unwrap_or_else(|e| e.into_inner());
948 if let Some((&id, _)) = registry
949 .iter()
950 .find(|(_, entry)| entry.bridge.as_ptr() == Arc::as_ptr(self))
951 {
952 return id as *mut c_void;
953 }
954 let mut id = NEXT.load(Ordering::Relaxed);
955 loop {
956 let next = id.checked_add(1).expect("runtime handle space exhausted");
957 match NEXT.compare_exchange_weak(id, next, Ordering::Relaxed, Ordering::Relaxed) {
958 Ok(_) => break,
959 Err(current) => id = current,
960 }
961 }
962 registry.insert(
963 id,
964 RegistryEntry {
965 bridge: Arc::downgrade(self),
966 active: Arc::downgrade(&self.active),
967 },
968 );
969 id as *mut c_void
970 }
971 pub(crate) fn resolve_handle(id: usize) -> Option<Arc<Self>> {
972 bridges()
973 .lock()
974 .unwrap_or_else(|e| e.into_inner())
975 .get(&id)
976 .and_then(|entry| entry.bridge.upgrade())
977 }
978 pub(crate) fn for_invocation(
979 &self,
980 child: bool,
981 signal: tokio_util::sync::CancellationToken,
982 ) -> Arc<Self> {
983 let tool_program = rpi_agent::tool_program::current();
984 if let Some(program) = &tool_program {
985 program.bind_signal(signal.clone());
986 }
987 Arc::new(Self {
988 invocation: Some((child, uuid::Uuid::new_v4().to_string(), signal)),
989 execution_context: rpi_agent::tool_execution_scope::execution_context(),
990 tool_program,
991 stdio: self.stdio.clone(),
992 plugin_identity: self.plugin_identity.clone(),
993 component_owners: self.component_owners.clone(),
994 runtime: self.runtime.clone(),
995 host: self.host.clone(),
996 reload: self.reload.clone(),
997 ui_dialog: self.ui_dialog.clone(),
998 ext_status: self.ext_status.clone(),
999 editor_text: self.editor_text.clone(),
1000 active: self.active.clone(),
1001 })
1002 }
1003 pub(crate) fn resolve_result_reference(
1006 &self,
1007 id: &str,
1008 ) -> Result<(rpi_agent::AgentToolResult, bool), String> {
1009 if !self.is_active()
1010 || !self
1011 .invocation
1012 .as_ref()
1013 .is_some_and(|(_, _, signal)| !signal.is_cancelled())
1014 {
1015 return Err("result reference requires a live invocation bridge".into());
1016 }
1017 self.tool_program
1018 .as_ref()
1019 .ok_or("result reference requires an effective ToolProgram")?
1020 .resolve_result_reference(id)
1021 }
1022 pub(crate) fn resolve_content_parts(
1024 &self,
1025 parts: Vec<rpi_agent::tool_program::ToolProgramContentPart>,
1026 ) -> Result<Vec<rpi_agent::TextContentOrImage>, String> {
1027 if !self.is_active()
1028 || !self
1029 .invocation
1030 .as_ref()
1031 .is_some_and(|(_, _, signal)| !signal.is_cancelled())
1032 {
1033 return Err("content parts require a live invocation bridge".into());
1034 }
1035 self.tool_program
1036 .as_ref()
1037 .ok_or("content parts require an effective ToolProgram")?
1038 .resolve_content_parts(parts)
1039 }
1040 pub(crate) fn invocation_key(&self) -> Option<&str> {
1041 self.invocation.as_ref().map(|(_, key, _)| key.as_str())
1042 }
1043 pub(crate) fn enter_invocation(self: &Arc<Self>) -> InvocationGuard {
1044 InvocationGuard {
1045 previous: CURRENT_INVOCATION.with(|slot| slot.replace(Some(self.clone()))),
1046 _thread_bound: std::marker::PhantomData,
1047 }
1048 }
1049 pub fn new(runtime: Handle, host: Arc<dyn RuntimeActionHost>) -> Arc<Self> {
1052 Arc::new(Self {
1053 invocation: None,
1054 tool_program: None,
1055 execution_context: None,
1056 stdio: crate::StdioLifecycle::default(),
1057 plugin_identity: None,
1058 component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1059 runtime,
1060 host,
1061 reload: None,
1062 ui_dialog: UiDialogMailbox::new(),
1063 ext_status: crate::status::ExtensionStatusMailbox::new(),
1064 editor_text: crate::editor_text::EditorTextMailbox::new(),
1065 active: Arc::new(AtomicBool::new(true)),
1066 })
1067 }
1068
1069 pub fn with_reload(
1072 runtime: Handle,
1073 host: Arc<dyn RuntimeActionHost>,
1074 reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>,
1075 ) -> Arc<Self> {
1076 Self::with_reload_and_ui(
1077 runtime,
1078 host,
1079 reload,
1080 UiDialogMailbox::new(),
1081 crate::status::ExtensionStatusMailbox::new(),
1082 crate::editor_text::EditorTextMailbox::new(),
1083 )
1084 }
1085
1086 pub fn with_ui_dialog(
1088 runtime: Handle,
1089 host: Arc<dyn RuntimeActionHost>,
1090 ui_dialog: UiDialogMailbox,
1091 ) -> Arc<Self> {
1092 Arc::new(Self {
1093 invocation: None,
1094 tool_program: None,
1095 execution_context: None,
1096 stdio: crate::StdioLifecycle::default(),
1097 plugin_identity: None,
1098 component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1099 runtime,
1100 host,
1101 reload: None,
1102 ui_dialog,
1103 ext_status: crate::status::ExtensionStatusMailbox::new(),
1104 editor_text: crate::editor_text::EditorTextMailbox::new(),
1105 active: Arc::new(AtomicBool::new(true)),
1106 })
1107 }
1108
1109 pub fn with_reload_and_ui(
1111 runtime: Handle,
1112 host: Arc<dyn RuntimeActionHost>,
1113 reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>,
1114 ui_dialog: UiDialogMailbox,
1115 ext_status: crate::status::ExtensionStatusMailbox,
1116 editor_text: crate::editor_text::EditorTextMailbox,
1117 ) -> Arc<Self> {
1118 Arc::new(Self {
1119 invocation: None,
1120 tool_program: None,
1121 execution_context: None,
1122 stdio: crate::StdioLifecycle::default(),
1123 plugin_identity: None,
1124 component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1125 runtime,
1126 host,
1127 reload: Some(reload),
1128 ui_dialog,
1129 ext_status,
1130 editor_text,
1131 active: Arc::new(AtomicBool::new(true)),
1132 })
1133 }
1134
1135 pub(crate) fn for_plugin(&self, name: &str) -> Arc<Self> {
1136 static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1137 let owner = NEXT_ID.fetch_add(1, Ordering::Relaxed);
1138 self.component_owners
1139 .lock()
1140 .unwrap_or_else(|e| e.into_inner())
1141 .push(owner);
1142 Arc::new(Self {
1143 invocation: None,
1144 tool_program: None,
1145 execution_context: None,
1146 component_owners: self.component_owners.clone(),
1147 stdio: self.stdio.clone(),
1148 plugin_identity: Some((owner, name.to_owned())),
1149 runtime: self.runtime.clone(),
1150 host: self.host.clone(),
1151 reload: self.reload.clone(),
1152 ui_dialog: self.ui_dialog.clone(),
1153 ext_status: self.ext_status.clone(),
1154 editor_text: self.editor_text.clone(),
1155 active: self.active.clone(),
1156 })
1157 }
1158
1159 pub fn stdio_lifecycle(&self) -> crate::StdioLifecycle {
1160 self.stdio.clone()
1161 }
1162
1163 pub(crate) fn claim_stdio(&self) -> Result<(), String> {
1164 let (id, name) = self
1165 .plugin_identity
1166 .as_ref()
1167 .ok_or("missing plugin identity")?;
1168 self.stdio.claim(*id, name)
1169 }
1170
1171 pub(crate) fn release_stdio_claim(&self) {
1172 if let Some((id, _)) = &self.plugin_identity {
1173 self.stdio.release_failed_registration(*id);
1174 self.ext_status.remove_owner(*id);
1175 }
1176 }
1177
1178 pub fn ui_dialog_mailbox(&self) -> UiDialogMailbox {
1180 self.ui_dialog.clone()
1181 }
1182
1183 pub fn extension_status_mailbox(&self) -> crate::status::ExtensionStatusMailbox {
1185 self.ext_status.clone()
1186 }
1187
1188 pub fn editor_text_mailbox(&self) -> crate::editor_text::EditorTextMailbox {
1190 self.editor_text.clone()
1191 }
1192
1193 pub fn invalidate(&self) {
1198 let owners = {
1199 let owners = self
1200 .component_owners
1201 .lock()
1202 .unwrap_or_else(|e| e.into_inner());
1203 self.active.store(false, Ordering::SeqCst);
1204 for owner in owners.iter() {
1205 self.ext_status.remove_owner(*owner);
1206 }
1207 owners.clone()
1208 };
1209 let live = self.bridges_for_owner();
1211 for bridge in live {
1212 if let Some(program) = &bridge.tool_program {
1213 program.cancel_all();
1214 }
1215 }
1216 for owner in owners {
1219 self.host.cancel_child_agents(owner);
1220 self.host.cancel_side_questions(owner);
1221 }
1222 }
1223
1224 fn bridges_for_owner(&self) -> Vec<Arc<Self>> {
1225 let active = Arc::downgrade(&self.active);
1226 bridges()
1232 .lock()
1233 .unwrap_or_else(|e| e.into_inner())
1234 .values()
1235 .filter(|entry| entry.active.ptr_eq(&active))
1236 .filter_map(|entry| entry.bridge.upgrade())
1237 .collect()
1238 }
1239
1240 pub fn is_active(&self) -> bool {
1242 self.active.load(Ordering::SeqCst)
1243 }
1244
1245 pub fn clone_host(&self) -> Arc<dyn RuntimeActionHost> {
1252 Arc::clone(&self.host)
1253 }
1254}
1255
1256#[derive(Clone)]
1269pub struct ReloadMailbox {
1270 tx: Arc<std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<()>>>>,
1271}
1272
1273impl Default for ReloadMailbox {
1274 fn default() -> Self {
1275 Self {
1276 tx: Arc::new(std::sync::Mutex::new(None)),
1277 }
1278 }
1279}
1280
1281impl ReloadMailbox {
1282 pub fn new() -> Self {
1284 Self::default()
1285 }
1286
1287 pub fn install(&self, tx: tokio::sync::mpsc::UnboundedSender<()>) {
1291 *self.tx.lock().unwrap() = Some(tx);
1292 }
1293
1294 pub fn signal(&self) -> Result<(), ()> {
1299 let g = self.tx.lock().unwrap();
1300 match &*g {
1301 Some(tx) => {
1302 let _ = tx.send(());
1303 Ok(())
1304 }
1305 None => Err(()),
1306 }
1307 }
1308
1309 pub fn clear(&self) {
1311 *self.tx.lock().unwrap() = None;
1312 }
1313}
1314
1315pub struct ReloadModelsMailbox {
1326 tx: Arc<std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<ReloadModelsRequest>>>>,
1327}
1328
1329impl Default for ReloadModelsMailbox {
1330 fn default() -> Self {
1331 Self {
1332 tx: Arc::new(std::sync::Mutex::new(None)),
1333 }
1334 }
1335}
1336
1337pub struct ReloadModelsRequest {
1339 pub reply: tokio::sync::oneshot::Sender<Result<usize, String>>,
1341}
1342
1343impl Clone for ReloadModelsMailbox {
1344 fn clone(&self) -> Self {
1345 Self {
1346 tx: Arc::clone(&self.tx),
1347 }
1348 }
1349}
1350
1351impl ReloadModelsMailbox {
1352 pub fn new() -> Self {
1353 Self::default()
1354 }
1355
1356 pub fn install(&self, tx: tokio::sync::mpsc::UnboundedSender<ReloadModelsRequest>) {
1358 *self.tx.lock().unwrap() = Some(tx);
1359 }
1360
1361 pub async fn request(&self) -> Result<usize, String> {
1366 let (reply, wait) = tokio::sync::oneshot::channel();
1367 let tx = self.tx.lock().unwrap().clone();
1368 let Some(tx) = tx else {
1369 return Err("reload_models is not available (no TUI attached)".to_string());
1370 };
1371 tx.send(ReloadModelsRequest { reply })
1372 .map_err(|_| "reload_models request dropped (TUI gone)".to_string())?;
1373 wait.await
1374 .map_err(|_| "reload_models request dropped (TUI gone)".to_string())?
1375 }
1376
1377 pub fn clear(&self) {
1379 *self.tx.lock().unwrap() = None;
1380 }
1381}
1382
1383pub fn reload_callback_from_mailbox(
1390 mailbox: ReloadMailbox,
1391) -> Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync> {
1392 Arc::new(move || {
1393 let m = mailbox.clone();
1394 Box::pin(async move {
1395 let _ = m.signal();
1396 })
1397 })
1398}
1399
1400fn dispatch_relay_ui_dialog(
1415 ui_dialog: &UiDialogMailbox,
1416 args: serde_json::Value,
1417) -> Result<serde_json::Value, String> {
1418 let op = args
1419 .get("op")
1420 .and_then(serde_json::Value::as_str)
1421 .unwrap_or("take");
1422 match op {
1423 "take" => {
1424 ui_dialog.set_external_takeover(true);
1428 let requests: Vec<serde_json::Value> = ui_dialog
1429 .take_all_unreserved()
1430 .into_iter()
1431 .map(|request| {
1432 serde_json::json!({
1433 "requestId": request.request_id,
1434 "toolCallId": request.tool_call_id,
1435 "ui": request.ui,
1436 })
1437 })
1438 .collect();
1439 Ok(serde_json::json!({ "requests": requests }))
1440 }
1441 "release" => {
1444 let requeued = ui_dialog.release_takeover();
1445 Ok(serde_json::json!({ "requeued": requeued }))
1446 }
1447 "respond" | "cancel" | "forget" => ui_dialog.handle(args),
1449 other => Err(format!("RelayUiDialog does not support op `{other}`")),
1450 }
1451}
1452
1453async fn dispatch(
1454 host: &Arc<dyn RuntimeActionHost>,
1455 ui_dialog: &UiDialogMailbox,
1456 ext_status: &crate::status::ExtensionStatusMailbox,
1457 editor_text: &crate::editor_text::EditorTextMailbox,
1458 action: RuntimeActionId,
1459 args: serde_json::Value,
1460) -> Result<serde_json::Value, String> {
1461 match action {
1462 RuntimeActionId::SendMessage => host.send_message(args).await,
1463 RuntimeActionId::SendUserMessage => host.send_user_message(args).await,
1464 RuntimeActionId::AppendEntry => host.append_entry(args).await,
1465 RuntimeActionId::SetSessionName => host.set_session_name(args).await,
1466 RuntimeActionId::GetActiveTools => host.get_active_tools(args).await,
1467 RuntimeActionId::SetActiveTools => host.set_active_tools(args).await,
1468 RuntimeActionId::SetModel => host.set_model(args).await,
1469 RuntimeActionId::GetThinkingLevel => host.get_thinking_level(args).await,
1470 RuntimeActionId::SetThinkingLevel => host.set_thinking_level(args).await,
1471 RuntimeActionId::Compact => host.compact(args).await,
1472 RuntimeActionId::GetSystemPrompt => host.get_system_prompt(args).await,
1473 RuntimeActionId::NewSession => host.new_session(args).await,
1474 RuntimeActionId::Fork => host.fork(args).await,
1475 RuntimeActionId::NavigateTree => host.navigate_tree(args).await,
1476 RuntimeActionId::SwitchSession => host.switch_session(args).await,
1477 RuntimeActionId::Reload => host.reload(args).await,
1478 RuntimeActionId::ReloadModels => host.reload_models(args).await,
1479 RuntimeActionId::GetCliFlag => host.get_cli_flag(args).await,
1480 RuntimeActionId::UiDialog => ui_dialog.handle(args),
1481 RuntimeActionId::SetStatus => ext_status.handle(args),
1484 RuntimeActionId::UiComponent => Err("UiComponent requires a plugin bridge".into()),
1485 RuntimeActionId::SetEditorText => editor_text.handle(args),
1488 RuntimeActionId::GetEditorText => editor_text.handle_get(args),
1491 RuntimeActionId::GetSessionBranch => host.get_session_branch(args).await,
1492 RuntimeActionId::GetExecutionContext => host.get_execution_context(args).await,
1493 RuntimeActionId::ToolProgram => Err("ToolProgram requires a live invocation bridge".into()),
1494 RuntimeActionId::ChildAgent => Err("ChildAgent requires a plugin bridge".into()),
1495 RuntimeActionId::SideQuestion => Err("SideQuestion requires a plugin bridge".into()),
1496 RuntimeActionId::ListCommands => host.list_commands(args).await,
1497 RuntimeActionId::Abort => host.abort(args).await,
1498 RuntimeActionId::RelayUiDialog => dispatch_relay_ui_dialog(ui_dialog, args),
1502 RuntimeActionId::StopRound => host.stop_round(args),
1503 RuntimeActionId::StdioLifecycle => {
1504 Err("stdio lifecycle requires a plugin context".to_owned())
1505 }
1506 }
1507}
1508
1509pub extern "C" fn trampoline_runtime_action(
1533 action_id: u32,
1534 args_json: StbStringRef,
1535 out: *mut StbString,
1536 user_data: *mut c_void,
1537) -> i32 {
1538 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1539 run_action(
1540 action_id,
1541 rpi_plugin_sdk::RuntimeActionId::MAX,
1543 args_json,
1544 out,
1545 user_data,
1546 )
1547 }));
1548 match outcome {
1549 Ok(rc) => rc,
1550 Err(_) => {
1551 tracing::error!("runtime_action trampoline panicked — reporting host error");
1555 if !out.is_null() {
1556 unsafe {
1557 *out = StbString::from_string(
1558 r#"{"error":"runtime_action panicked"}"#.to_string(),
1559 );
1560 }
1561 }
1562 1
1563 }
1564 }
1565}
1566
1567fn run_action(
1569 action_id: u32,
1570 max_action_id: u32,
1571 args_json: StbStringRef,
1572 out: *mut StbString,
1573 user_data: *mut c_void,
1574) -> i32 {
1575 let action = match RuntimeActionId::try_from(action_id) {
1579 Ok(action) if action_id <= max_action_id => action,
1580 Ok(_) | Err(_) => {
1581 if !out.is_null() {
1582 let json = serde_json::json!({
1583 "error": format!("unknown runtime action id {action_id}")
1584 })
1585 .to_string();
1586 unsafe {
1590 *out = StbString::from_string(json);
1591 }
1592 }
1593 return 2;
1594 }
1595 };
1596
1597 if user_data.is_null() {
1598 return -1;
1599 }
1600 let invocation = CURRENT_INVOCATION.with(|slot| slot.borrow().clone());
1603 let invocation_thread = invocation.is_some();
1604 let bridge = invocation.or_else(|| ActionBridge::resolve_handle(user_data as usize));
1605 let Some(bridge) = bridge else {
1606 if !out.is_null() {
1607 unsafe {
1609 *out = StbString::from_string("{\"error\":\"expired runtime handle\"}".into());
1610 }
1611 }
1612 return 1;
1613 };
1614
1615 if !bridge.is_active() {
1623 if out.is_null() {
1624 return 1;
1625 }
1626 let json = serde_json::json!({
1627 "error": "runtime_action on a stale ActionBridge (session reloaded/swapped)"
1628 })
1629 .to_string();
1630 unsafe {
1631 *out = StbString::from_string(json);
1632 }
1633 return 1;
1634 }
1635
1636 let args_str = unsafe { args_json.as_str() };
1639 let mut args: serde_json::Value = if args_str.is_empty() {
1640 serde_json::Value::Object(serde_json::Map::new())
1641 } else {
1642 serde_json::from_str(args_str)
1643 .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new()))
1644 };
1645
1646 let runtime_key = args
1647 .as_object_mut()
1648 .and_then(|args| args.remove("__rpiRuntimeKey"));
1649
1650 let (tx, rx) = mpsc::sync_channel::<Result<serde_json::Value, String>>(1);
1655 let host = Arc::clone(&bridge.host);
1659 let ui_dialog = bridge.ui_dialog.clone();
1660 let ext_status = bridge.ext_status.clone();
1661 let editor_text = bridge.editor_text.clone();
1662 let reload_cb = bridge.reload.clone();
1663 let execution_context = bridge.execution_context.clone();
1664 if action == RuntimeActionId::StdioLifecycle {
1665 let result = bridge.stdio.handle(
1666 bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id),
1667 args,
1668 );
1669 let _ = tx.send(result);
1670 } else if action == RuntimeActionId::UiComponent {
1671 let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1672 let _owners = bridge
1673 .component_owners
1674 .lock()
1675 .unwrap_or_else(|e| e.into_inner());
1676 let result = if bridge.is_active() {
1677 ext_status.component(owner, args)
1678 } else {
1679 Err("stale plugin bridge".into())
1680 };
1681 let _ = tx.send(result);
1682 } else if action == RuntimeActionId::SideQuestion {
1683 let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1684 if owner == 0 || bridge.invocation.is_some() {
1685 let _ = tx.send(Err(
1686 "SideQuestion requires a plugin command, not a tool invocation".into(),
1687 ));
1688 } else {
1689 let weak = Arc::downgrade(&bridge);
1692 let sink: SideQuestionSink = Arc::new(move |args| {
1693 let bridge = weak.upgrade().ok_or("expired side question bridge")?;
1694 let _owners = bridge
1695 .component_owners
1696 .lock()
1697 .unwrap_or_else(|e| e.into_inner());
1698 if !bridge.is_active() {
1699 return Err("stale side question bridge".into());
1700 }
1701 if args["op"] == "check" {
1702 return Ok(serde_json::json!({"ok":true}));
1703 }
1704 bridge.ext_status.component(owner, args)
1705 });
1706 bridge.runtime.spawn(async move {
1707 let _ = tx.send(host.side_question(owner, args, sink).await);
1708 });
1709 }
1710 } else if action == RuntimeActionId::GetActiveTools && bridge.tool_program.is_some() {
1711 let tools = bridge
1712 .tool_program
1713 .as_ref()
1714 .expect("checked")
1715 .active_tool_names();
1716 let _ = tx.send(Ok(serde_json::json!({"tools":tools})));
1717 } else if action == RuntimeActionId::SetActiveTools && bridge.execution_context.is_some() {
1718 let _ = tx.send(Err(
1719 "cannot replace active tools from a narrowed execution".into()
1720 ));
1721 } else if action == RuntimeActionId::ToolProgram {
1722 let cleanup = matches!(
1723 args.get("op").and_then(serde_json::Value::as_str),
1724 Some("poll" | "cancel" | "dispose" | "release_result")
1725 );
1726 let authenticated = bridge.invocation.as_ref().is_some_and(|(_, key, signal)| {
1727 (cleanup || !signal.is_cancelled())
1728 && (invocation_thread
1729 || runtime_key.as_ref().and_then(serde_json::Value::as_str)
1730 == Some(key.as_str()))
1731 });
1732 if let Some(capability) = bridge.tool_program.clone().filter(|_| authenticated) {
1733 let signal = bridge.invocation.as_ref().expect("authenticated").2.clone();
1734 bridge.runtime.spawn(async move {
1735 if signal.is_cancelled() {
1736 capability.cancel_all();
1737 if !cleanup {
1738 let _ = tx.send(Err("parent invocation is no longer active".into()));
1739 return;
1740 }
1741 }
1742 let _ = tx.send(host.tool_program(capability, args).await);
1743 });
1744 } else {
1745 let _ = tx.send(Err(
1746 "ToolProgram requires an authenticated executing invocation".into(),
1747 ));
1748 }
1749 } else if action == RuntimeActionId::ChildAgent {
1750 let cleanup = matches!(
1755 args.get("op").and_then(serde_json::Value::as_str),
1756 Some("poll" | "cancel" | "dispose")
1757 );
1758 let allowed = bridge
1759 .invocation
1760 .as_ref()
1761 .is_some_and(|(child, key, signal)| {
1762 !child
1763 && (cleanup || !signal.is_cancelled())
1764 && (invocation_thread
1765 || runtime_key.as_ref().and_then(serde_json::Value::as_str)
1766 == Some(key.as_str()))
1767 });
1768 if !allowed {
1769 let _ = tx.send(Err("ChildAgent requires a live parent tool invocation; recursive child agents are not allowed".into()));
1770 } else {
1771 let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1772 let signal = bridge
1773 .invocation
1774 .as_ref()
1775 .expect("authorized invocation")
1776 .2
1777 .clone();
1778 bridge.runtime.spawn(async move {
1779 let result = rpi_agent::tool_execution_scope::with_invocation_signal(
1780 signal,
1781 host.child_agent(owner, args),
1782 )
1783 .await;
1784 let _ = tx.send(result);
1785 });
1786 }
1787 } else if action == RuntimeActionId::SetStatus {
1788 std::thread::spawn(move || {
1793 let _ = tx.send(ext_status.handle(args));
1794 });
1795 } else if action == RuntimeActionId::SetEditorText {
1796 std::thread::spawn(move || {
1799 let _ = tx.send(editor_text.handle(args));
1800 });
1801 } else if action == RuntimeActionId::RelayUiDialog {
1802 std::thread::spawn(move || {
1808 let _ = tx.send(dispatch_relay_ui_dialog(&ui_dialog, args));
1809 });
1810 } else if action == RuntimeActionId::UiDialog {
1811 std::thread::spawn(move || {
1817 let _ = tx.send(ui_dialog.handle(args));
1818 });
1819 } else {
1820 bridge.runtime.spawn(async move {
1821 let mut r = if action == RuntimeActionId::Reload {
1822 if let Some(cb) = reload_cb {
1823 cb().await;
1824 Ok(serde_json::Value::Null)
1825 } else {
1826 host.reload(args).await
1827 }
1828 } else {
1829 dispatch(&host, &ui_dialog, &ext_status, &editor_text, action, args).await
1830 };
1831 if action == RuntimeActionId::GetExecutionContext {
1832 if let (Ok(context), Some(serde_json::Value::Object(fields))) =
1833 (&mut r, execution_context)
1834 {
1835 if let Some(object) = context.as_object_mut() {
1836 object.extend(fields);
1837 }
1838 }
1839 }
1840 let _ = tx.send(r);
1843 });
1844 }
1845
1846 let received = if Handle::try_current()
1852 .is_ok_and(|handle| handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread)
1853 {
1854 tokio::task::block_in_place(|| rx.recv())
1855 } else {
1856 rx.recv()
1857 };
1858 let result = match received {
1859 Ok(r) => r,
1860 Err(_) => {
1861 return -2;
1866 }
1867 };
1868
1869 if out.is_null() {
1872 return match result {
1874 Ok(_) => 0,
1875 Err(_) => 1,
1876 };
1877 }
1878
1879 let (rc, payload) = match result {
1880 Ok(value) => {
1881 let json = serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string());
1882 (0, json)
1883 }
1884 Err(msg) => {
1885 let json = serde_json::json!({ "error": msg }).to_string();
1886 (1, json)
1887 }
1888 };
1889 unsafe {
1895 *out = StbString::from_string(payload);
1896 }
1897 rc
1898}
1899
1900#[cfg(test)]
1909mod tests {
1910 use super::*;
1911 use std::sync::Mutex;
1912
1913 #[test]
1922 fn host_child_agent_control_has_no_plugin_action_id() {
1923 assert!(
1924 RuntimeActionId::try_from(31).is_ok(),
1925 "ReloadModels must remain a valid runtime action id"
1926 );
1927 assert!(
1932 RuntimeActionId::try_from(32).is_ok(),
1933 "GetEditorText must remain a valid runtime action id"
1934 );
1935 assert!(
1936 RuntimeActionId::try_from(33).is_err(),
1937 "a new RuntimeActionId was added: re-verify that host-only child-agent control \
1938 (un-owner-scoped roster/stop) is still unreachable from the plugin ABI"
1939 );
1940 }
1941
1942 #[tokio::test(flavor = "current_thread")]
1943 async fn stdio_claim_is_exclusive_and_only_its_scoped_context_can_finish() {
1944 let master = ActionBridge::new(
1945 Handle::current(),
1946 Arc::new(MockHost {
1947 prompt: String::new(),
1948 saw: Mutex::new(Vec::new()),
1949 }),
1950 );
1951 let diag: Arc<dyn crate::PluginDiagnostics> = Arc::new(crate::NullDiagnostics);
1952 let owner = crate::HostApi::with_action_bridge(
1953 "owner",
1954 crate::ExtensionRegistry::new(),
1955 diag.clone(),
1956 master.clone(),
1957 );
1958 let other = crate::HostApi::with_action_bridge(
1959 "other",
1960 crate::ExtensionRegistry::new(),
1961 diag,
1962 master.clone(),
1963 );
1964 let vtable = owner.build_vtable();
1965 let claim = r#"{"ownsStdio":true}"#;
1966 {
1967 let _registration = crate::enter_current_api(&owner);
1968 assert_eq!(vtable.declare.unwrap()(StbStringRef::from_str(claim)), 0);
1969 }
1970 let other_vtable = other.build_vtable();
1971 let finish = StbStringRef::from_str(r#"{"op":"finish","exitCode":7}"#);
1972 let mut out = StbString::empty();
1973 assert_eq!(
1975 (other_vtable.runtime_action)(
1976 RuntimeActionId::StdioLifecycle as u32,
1977 finish,
1978 &mut out,
1979 other_vtable.user_data
1980 ),
1981 1
1982 );
1983 unsafe { (other_vtable.free_string)(out) };
1985 assert_eq!(
1986 (vtable.runtime_action)(
1987 RuntimeActionId::StdioLifecycle as u32,
1988 finish,
1989 &mut out,
1990 vtable.user_data
1991 ),
1992 0
1993 );
1994 unsafe { (vtable.free_string)(out) };
1996 assert_eq!(master.stdio_lifecycle().wait().await, 7);
1997 {
1998 let _registration = crate::enter_current_api(&other);
1999 assert_ne!(
2000 other_vtable.declare.unwrap()(StbStringRef::from_str(claim)),
2001 0
2002 );
2003 }
2004 assert!(master
2005 .stdio_lifecycle()
2006 .validate()
2007 .unwrap_err()
2008 .contains("owner"));
2009 }
2010
2011 struct MockHost {
2016 prompt: String,
2017 saw: Mutex<Vec<RuntimeActionId>>,
2018 }
2019
2020 #[test]
2021 fn runtime_action_from_a_tokio_worker_does_not_block_its_dispatch() {
2022 const CHILD: &str = "RPI_RUNTIME_ACTION_WORKER_REGRESSION_CHILD";
2023 if std::env::var_os(CHILD).is_some() {
2024 let runtime = tokio::runtime::Builder::new_multi_thread()
2025 .worker_threads(1)
2026 .enable_all()
2027 .build()
2028 .unwrap();
2029 runtime.block_on(async {
2030 tokio::spawn(async {
2033 let host = Arc::new(MockHost {
2034 prompt: "worker callback".into(),
2035 saw: Mutex::new(Vec::new()),
2036 });
2037 let bridge = ActionBridge::new(Handle::current(), host);
2038 let mut out = StbString::empty();
2039 assert_eq!(
2040 trampoline_runtime_action(
2041 RuntimeActionId::GetSystemPrompt.into(),
2042 StbStringRef::from_str("{}"),
2043 &mut out,
2044 bridge.user_data(),
2045 ),
2046 0
2047 );
2048 let text = unsafe {
2050 rpi_plugin_sdk::callbacks::OwnedString::from_raw(
2051 out,
2052 Some(crate::host_free_string),
2053 )
2054 }
2055 .to_string_lossy();
2056 assert_eq!(
2057 serde_json::from_str::<serde_json::Value>(&text).unwrap()["prompt"],
2058 "worker callback"
2059 );
2060 })
2061 .await
2062 .unwrap();
2063 });
2064 return;
2065 }
2066 let mut child = std::process::Command::new(std::env::current_exe().unwrap())
2069 .args([
2070 "--exact",
2071 "actions::tests::runtime_action_from_a_tokio_worker_does_not_block_its_dispatch",
2072 "--nocapture",
2073 ])
2074 .env(CHILD, "1")
2075 .stdout(std::process::Stdio::piped())
2076 .stderr(std::process::Stdio::piped())
2077 .spawn()
2078 .unwrap();
2079 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2080 while child.try_wait().unwrap().is_none() {
2081 if std::time::Instant::now() >= deadline {
2082 let _ = child.kill();
2083 let _ = child.wait();
2084 panic!("runtime action blocked the worker needed by its own dispatch");
2085 }
2086 std::thread::sleep(std::time::Duration::from_millis(10));
2087 }
2088 let output = child.wait_with_output().unwrap();
2089 assert!(
2090 output.status.success(),
2091 "{}\n{}",
2092 String::from_utf8_lossy(&output.stdout),
2093 String::from_utf8_lossy(&output.stderr)
2094 );
2095 }
2096
2097 #[async_trait::async_trait]
2098 impl RuntimeActionHost for MockHost {
2099 async fn send_message(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2100 unreachable!("not under test")
2101 }
2102 async fn send_user_message(
2103 &self,
2104 _: serde_json::Value,
2105 ) -> Result<serde_json::Value, String> {
2106 unreachable!("not under test")
2107 }
2108 async fn append_entry(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2109 unreachable!("not under test")
2110 }
2111 async fn set_session_name(
2112 &self,
2113 _: serde_json::Value,
2114 ) -> Result<serde_json::Value, String> {
2115 unreachable!("not under test")
2116 }
2117 async fn get_active_tools(
2118 &self,
2119 _: serde_json::Value,
2120 ) -> Result<serde_json::Value, String> {
2121 unreachable!("not under test")
2122 }
2123 async fn set_active_tools(
2124 &self,
2125 _: serde_json::Value,
2126 ) -> Result<serde_json::Value, String> {
2127 unreachable!("not under test")
2128 }
2129 async fn set_model(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2130 unreachable!("not under test")
2131 }
2132 async fn get_thinking_level(
2133 &self,
2134 _: serde_json::Value,
2135 ) -> Result<serde_json::Value, String> {
2136 unreachable!("not under test")
2137 }
2138 async fn set_thinking_level(
2139 &self,
2140 _: serde_json::Value,
2141 ) -> Result<serde_json::Value, String> {
2142 unreachable!("not under test")
2143 }
2144 async fn compact(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2145 unreachable!("not under test")
2146 }
2147 async fn get_system_prompt(
2148 &self,
2149 _: serde_json::Value,
2150 ) -> Result<serde_json::Value, String> {
2151 self.saw
2152 .lock()
2153 .unwrap()
2154 .push(RuntimeActionId::GetSystemPrompt);
2155 Ok(serde_json::json!({ "prompt": self.prompt }))
2156 }
2157 async fn new_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2158 unreachable!("not under test")
2159 }
2160 async fn fork(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2161 unreachable!("not under test")
2162 }
2163 async fn navigate_tree(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2164 unreachable!("not under test")
2165 }
2166 async fn switch_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2167 unreachable!("not under test")
2168 }
2169 async fn reload(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2170 self.saw.lock().unwrap().push(RuntimeActionId::Reload);
2171 Ok(serde_json::Value::Null)
2172 }
2173 async fn get_cli_flag(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2174 self.saw.lock().unwrap().push(RuntimeActionId::GetCliFlag);
2175 Ok(serde_json::json!({ "value": true }))
2176 }
2177 }
2178
2179 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2183 async fn trampoline_round_trips_get_system_prompt() {
2184 let host = Arc::new(MockHost {
2185 prompt: "hello from host".to_string(),
2186 saw: Mutex::new(Vec::new()),
2187 });
2188 let host_for_assert = Arc::clone(&host);
2189 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2190 let runtime = tokio::runtime::Handle::current();
2191 let bridge = ActionBridge::new(runtime, host_dyn);
2192 let user_data = bridge.user_data();
2193
2194 let args_str = "{}";
2196 let args_ref = StbStringRef::from_str(args_str);
2197
2198 let mut out = StbString::empty();
2199 let rc = trampoline_runtime_action(
2200 RuntimeActionId::GetSystemPrompt.into(),
2201 args_ref,
2202 &mut out as *mut StbString,
2203 user_data,
2204 );
2205 assert_eq!(rc, 0, "success return code");
2206
2207 let json_text = unsafe {
2210 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2211 }
2212 .to_string_lossy();
2213 let parsed: serde_json::Value = serde_json::from_str(&json_text).expect("valid json");
2214 assert_eq!(parsed["prompt"], "hello from host");
2215
2216 let saw = host_for_assert.saw.lock().unwrap().clone();
2219 assert_eq!(saw, vec![RuntimeActionId::GetSystemPrompt]);
2220 }
2221
2222 #[tokio::test]
2228 async fn trampoline_routes_set_editor_text_into_the_mailbox() {
2229 let host = Arc::new(MockHost {
2230 prompt: String::new(),
2231 saw: Mutex::new(Vec::new()),
2232 });
2233 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2234 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2235 let mailbox = bridge.editor_text_mailbox();
2236 let user_data = bridge.user_data();
2237
2238 let args_ref =
2239 StbStringRef::from_str(r#"{"text":"from voice","mode":"append","autoSendMs":2000}"#);
2240 let mut out = StbString::empty();
2241 let rc = trampoline_runtime_action(
2242 RuntimeActionId::SetEditorText.into(),
2243 args_ref,
2244 &mut out as *mut StbString,
2245 user_data,
2246 );
2247 assert_eq!(rc, 0, "success return code");
2248
2249 let parsed: serde_json::Value = serde_json::from_str(
2251 &unsafe {
2252 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2253 }
2254 .to_string_lossy(),
2255 )
2256 .expect("valid json");
2257 assert_eq!(parsed["ok"], serde_json::json!(true));
2258 assert_eq!(parsed["chars"], serde_json::json!(10));
2259
2260 let edit = mailbox.take_pending().expect("queued edit");
2262 assert_eq!(edit.text, "from voice");
2263 assert_eq!(edit.mode, crate::EditorTextMode::Append);
2264 assert_eq!(edit.auto_send_ms, Some(2000));
2265 assert!(mailbox.take_pending().is_none());
2266 }
2267
2268 #[tokio::test]
2269 async fn trampoline_null_user_data_returns_minus_one() {
2270 let args_ref = StbStringRef::from_str("{}");
2271 let mut out = StbString::empty();
2272 let rc = trampoline_runtime_action(
2273 RuntimeActionId::GetSystemPrompt.into(),
2274 args_ref,
2275 &mut out as *mut StbString,
2276 std::ptr::null_mut(),
2277 );
2278 assert_eq!(rc, -1, "null user_data ⇒ no bridge");
2279 }
2280
2281 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2282 async fn trampoline_intercepts_reload_when_bridge_has_callback() {
2283 use std::sync::atomic::{AtomicUsize, Ordering};
2287 let reload_calls = Arc::new(AtomicUsize::new(0));
2288 let reload_calls_for_cb = Arc::clone(&reload_calls);
2289 let reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync> =
2290 Arc::new(move || {
2291 let c = Arc::clone(&reload_calls_for_cb);
2292 Box::pin(async move {
2293 c.fetch_add(1, Ordering::SeqCst);
2294 })
2295 });
2296 let host = Arc::new(MockHost {
2297 prompt: String::new(),
2298 saw: Mutex::new(Vec::new()),
2299 });
2300 let host_for_assert = Arc::clone(&host);
2301 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2302 let runtime = tokio::runtime::Handle::current();
2303 let bridge = ActionBridge::with_reload(runtime, host_dyn, reload);
2304 let user_data = bridge.user_data();
2305
2306 let args_ref = StbStringRef::from_str("{}");
2307 let mut out = StbString::empty();
2308 let rc = trampoline_runtime_action(
2309 RuntimeActionId::Reload.into(),
2310 args_ref,
2311 &mut out as *mut StbString,
2312 user_data,
2313 );
2314 assert_eq!(rc, 0);
2315 assert_eq!(reload_calls.load(Ordering::SeqCst), 1);
2317 assert!(host_for_assert.saw.lock().unwrap().is_empty());
2318 drop(unsafe {
2320 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2321 });
2322 }
2323
2324 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2329 async fn trampoline_rejects_stale_bridge_with_invalidate() {
2330 let host = Arc::new(MockHost {
2331 prompt: String::new(),
2332 saw: Mutex::new(Vec::new()),
2333 });
2334 let host_for_assert = Arc::clone(&host);
2335 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2336 let runtime = tokio::runtime::Handle::current();
2337 let bridge = ActionBridge::new(runtime, host_dyn);
2338 let user_data = bridge.user_data();
2339
2340 bridge.invalidate();
2342 assert!(!bridge.is_active());
2343
2344 let args_ref = StbStringRef::from_str("{}");
2345 let mut out = StbString::empty();
2346 let rc = trampoline_runtime_action(
2347 RuntimeActionId::GetSystemPrompt.into(),
2348 args_ref,
2349 &mut out as *mut StbString,
2350 user_data,
2351 );
2352 assert_eq!(rc, 1, "stale bridge ⇒ error return code");
2354 let json_text = unsafe {
2356 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2357 }
2358 .to_string_lossy();
2359 assert!(
2360 json_text.contains("stale"),
2361 "stale-bridge error payload: {json_text}"
2362 );
2363
2364 assert!(
2365 host_for_assert.saw.lock().unwrap().is_empty(),
2366 "host dispatch must NOT run on a stale bridge"
2367 );
2368 }
2369
2370 #[tokio::test]
2371 async fn trampoline_rejects_unknown_numeric_id_without_dispatch() {
2372 let host = Arc::new(MockHost {
2373 prompt: String::new(),
2374 saw: Mutex::new(Vec::new()),
2375 });
2376 let host_for_assert = Arc::clone(&host);
2377 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2378 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2379 let user_data = bridge.user_data();
2380
2381 let mut out = StbString::empty();
2382 let rc = trampoline_runtime_action(
2383 0xFFFF_FFFE,
2384 StbStringRef::from_str("{}"),
2385 &mut out,
2386 user_data,
2387 );
2388
2389 assert_eq!(rc, 2, "unknown action id must be a protocol error");
2390 let payload: serde_json::Value = serde_json::from_str(
2391 &unsafe {
2392 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2393 }
2394 .to_string_lossy(),
2395 )
2396 .expect("structured error JSON");
2397 assert_eq!(payload["error"], "unknown runtime action id 4294967294");
2398
2399 assert!(
2400 host_for_assert.saw.lock().unwrap().is_empty(),
2401 "unknown action id must not reach host dispatch"
2402 );
2403 }
2404
2405 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2406 async fn v2_trampoline_accepts_new_action() {
2407 let host = Arc::new(MockHost {
2408 prompt: "v2".to_string(),
2409 saw: Mutex::new(Vec::new()),
2410 });
2411 let host_for_assert = Arc::clone(&host);
2412 let host_dyn: Arc<dyn RuntimeActionHost> = host;
2413 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2414 let user_data = bridge.user_data();
2415
2416 let mut v2_out = StbString::empty();
2417 assert_eq!(
2418 trampoline_runtime_action(
2419 RuntimeActionId::GetCliFlag.into(),
2420 StbStringRef::from_str(r#"{"name":"flag"}"#),
2421 &mut v2_out,
2422 user_data,
2423 ),
2424 0
2425 );
2426 drop(unsafe {
2428 rpi_plugin_sdk::callbacks::OwnedString::from_raw(v2_out, Some(crate::host_free_string))
2429 });
2430
2431 assert_eq!(
2432 *host_for_assert.saw.lock().unwrap(),
2433 vec![RuntimeActionId::GetCliFlag]
2434 );
2435 }
2436
2437 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2442 async fn reload_mailbox_signals_installed_receiver() {
2443 let mailbox = ReloadMailbox::new();
2444 assert!(matches!(mailbox.signal(), Err(())));
2446
2447 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2448 mailbox.install(tx);
2449 let cb = reload_callback_from_mailbox(mailbox.clone());
2450 cb().await;
2451 assert_eq!(
2452 rx.recv().await,
2453 Some(()),
2454 "installed receiver saw the signal"
2455 );
2456 mailbox.clear();
2457 }
2458
2459 fn open_args(id: &str, tool_call: &str) -> serde_json::Value {
2462 serde_json::json!({
2463 "op": "open",
2464 "requestId": id,
2465 "toolCallId": tool_call,
2466 "ui": {"kind": "selector", "questions": [
2467 {"id": "q1", "question": "Which target?", "options": ["Linux"]}
2468 ]},
2469 })
2470 }
2471
2472 #[test]
2475 fn ui_dialog_open_requires_an_attached_ui() {
2476 let mailbox = UiDialogMailbox::new();
2477 let error = mailbox.handle(open_args("r1", "c1")).unwrap_err();
2478 assert!(error.contains("interactive UI"), "got: {error}");
2479 }
2480
2481 #[test]
2482 fn ui_dialog_attachment_generation_exhaustion_fails_closed() {
2483 let mailbox = UiDialogMailbox::new();
2484 mailbox
2485 .state
2486 .lock()
2487 .expect("ui dialog mailbox poisoned")
2488 .attachment_generation = u64::MAX;
2489
2490 assert_eq!(mailbox.try_attach_with_generation(), None);
2491 assert_eq!(mailbox.attachment_generation(), Some(u64::MAX));
2492 assert!(!mailbox.is_attached());
2493
2494 mailbox.attach();
2497 assert!(!mailbox.is_attached());
2498 }
2499
2500 #[test]
2501 fn ui_dialog_attachment_lock_poison_fails_closed_without_panicking() {
2502 let mailbox = UiDialogMailbox::new();
2503 let state = mailbox.state.clone();
2504 assert!(std::thread::spawn(move || {
2505 let _guard = state.lock().unwrap();
2506 panic!("poison synthetic dialog mailbox state");
2507 })
2508 .join()
2509 .is_err());
2510
2511 assert_eq!(mailbox.try_attach_with_generation(), None);
2512 assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2513 mailbox.attach();
2515 }))
2516 .is_ok());
2517 }
2518
2519 #[test]
2520 fn ui_dialog_observation_lock_poison_fails_closed_without_panicking() {
2521 let mailbox = UiDialogMailbox::new();
2522 let state = mailbox.state.clone();
2523 assert!(std::thread::spawn(move || {
2524 let _guard = state.lock().unwrap();
2525 panic!("poison synthetic dialog observation state");
2526 })
2527 .join()
2528 .is_err());
2529
2530 assert_eq!(mailbox.attachment_generation(), None);
2531 assert!(!mailbox.is_attached());
2532 }
2533
2534 #[test]
2535 fn ui_dialog_detach_generation_lock_poison_fails_closed_without_panicking() {
2536 let mailbox = UiDialogMailbox::new();
2537 let state = mailbox.state.clone();
2538 assert!(std::thread::spawn(move || {
2539 let _guard = state.lock().unwrap();
2540 panic!("poison synthetic dialog retirement state");
2541 })
2542 .join()
2543 .is_err());
2544
2545 assert!(!mailbox.detach_if_generation(1));
2546 }
2547
2548 #[test]
2549 fn ui_dialog_compat_detach_lock_poison_fails_closed_without_panicking() {
2550 let mailbox = UiDialogMailbox::new();
2551 let state = mailbox.state.clone();
2552 assert!(std::thread::spawn(move || {
2553 let _guard = state.lock().unwrap();
2554 panic!("poison synthetic dialog compatibility retirement state");
2555 })
2556 .join()
2557 .is_err());
2558
2559 assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2560 mailbox.detach();
2561 }))
2562 .is_ok());
2563 assert_eq!(mailbox.try_attach_with_generation(), None);
2564 }
2565
2566 #[test]
2567 fn ui_dialog_open_poll_answer_round_trip() {
2568 let mailbox = UiDialogMailbox::new();
2569 mailbox.attach();
2570
2571 let opened = mailbox.handle(open_args("r1", "c1")).unwrap();
2572 assert_eq!(opened["status"], "pending");
2573 assert_eq!(opened["toolCallId"], "c1");
2574
2575 let request = mailbox.take_pending().expect("request visible to TUI");
2576 assert_eq!(request.request_id, "r1");
2577 assert_eq!(request.tool_call_id.as_deref(), Some("c1"));
2578 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2580 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2581
2582 mailbox
2583 .respond("r1", serde_json::json!("7890"))
2584 .expect("respond");
2585 let answered = mailbox.poll("r1").unwrap();
2586 assert_eq!(answered["status"], "answered");
2587 assert_eq!(answered["answer"], "7890");
2588 assert!(mailbox.poll("r1").is_err());
2590 }
2591
2592 #[test]
2593 fn ui_dialog_forget_reclaims_terminal_entries_without_stranding_pending_ones() {
2594 let mailbox = UiDialogMailbox::new();
2595 mailbox.attach();
2596
2597 mailbox.handle(open_args("r1", "c1")).unwrap();
2600 assert_eq!(
2601 mailbox.forget("r1"),
2602 Err("UI request `r1` is still pending".to_string())
2603 );
2604 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2605
2606 mailbox.cancel("r1").unwrap();
2609 assert_eq!(mailbox.forget("r1"), Ok(true));
2610 assert_eq!(mailbox.forget("r1"), Ok(false)); assert!(mailbox.poll("r1").is_err());
2612
2613 mailbox.handle(open_args("r2", "c2")).unwrap();
2616 mailbox
2617 .respond("r2", serde_json::json!({"values": ["Linux"]}))
2618 .unwrap();
2619 let forgotten = mailbox
2620 .handle(serde_json::json!({"op": "forget", "requestId": "r2"}))
2621 .unwrap();
2622 assert_eq!(forgotten["status"], "forgotten");
2623 assert_eq!(forgotten["removed"], true);
2624 assert!(mailbox.poll("r2").is_err());
2625
2626 assert_eq!(mailbox.forget("missing"), Ok(false));
2629 let reopened = mailbox.handle(open_args("r1", "c1")).unwrap();
2630 assert_eq!(reopened["status"], "pending");
2631 }
2632
2633 #[test]
2634 fn ui_dialog_cancel_is_reported_once() {
2635 let mailbox = UiDialogMailbox::new();
2636 mailbox.attach();
2637 mailbox.handle(open_args("r1", "c1")).unwrap();
2638 mailbox.cancel("r1").unwrap();
2639 let cancelled = mailbox.poll("r1").unwrap();
2640 assert_eq!(cancelled["status"], "cancelled");
2641 assert!(mailbox.poll("r1").is_err());
2642 }
2643
2644 #[test]
2645 fn ui_dialog_tool_cancel_preserves_other_calls_and_rejects_late_questions() {
2646 let mailbox = UiDialogMailbox::new();
2647 mailbox.attach();
2648 mailbox.handle(open_args("r1", "c1")).unwrap();
2649 mailbox.handle(open_args("r2", "c2")).unwrap();
2650 mailbox.cancel_tool_call("c1");
2651 assert_eq!(mailbox.poll("r1").unwrap()["status"], "cancelled");
2652 assert_eq!(mailbox.take_pending().unwrap().request_id, "r2");
2653 assert_eq!(mailbox.poll("r2").unwrap()["status"], "pending");
2654 assert_eq!(
2655 mailbox.handle(open_args("late", "c1")).unwrap()["status"],
2656 "cancelled"
2657 );
2658 assert!(mailbox.take_pending().is_none());
2659 }
2660
2661 #[test]
2662 fn ui_dialog_concurrent_requests_do_not_cross_answers() {
2663 let mailbox = UiDialogMailbox::new();
2664 mailbox.attach();
2665 mailbox.handle(open_args("r1", "c1")).unwrap();
2666 mailbox.handle(open_args("r2", "c2")).unwrap();
2667
2668 let first = mailbox.take_pending().unwrap().request_id;
2669 let second = mailbox.take_pending().unwrap().request_id;
2670 assert_ne!(first, second);
2671
2672 mailbox
2674 .respond(&second, serde_json::json!("second"))
2675 .unwrap();
2676 assert_eq!(mailbox.poll(&first).unwrap()["status"], "pending");
2677 let second_answer = mailbox.poll(&second).unwrap();
2678 assert_eq!(second_answer["answer"], "second");
2679
2680 mailbox.respond(&first, serde_json::json!("first")).unwrap();
2681 assert_eq!(mailbox.poll(&first).unwrap()["answer"], "first");
2682 }
2683
2684 #[test]
2685 fn ui_dialog_detach_cancels_outstanding() {
2686 let mailbox = UiDialogMailbox::new();
2687 mailbox.attach();
2688 mailbox.handle(open_args("r1", "c1")).unwrap();
2689 mailbox.detach();
2690 assert!(!mailbox.is_attached());
2691 assert_eq!(mailbox.pending_len(), 0);
2692 assert!(mailbox.handle(open_args("r2", "c2")).is_err());
2694 assert_eq!(mailbox.poll("r1").unwrap()["status"], "cancelled");
2695 }
2696
2697 #[test]
2698 fn ui_dialog_duplicate_open_does_not_reenqueue() {
2699 let mailbox = UiDialogMailbox::new();
2700 mailbox.attach();
2701 mailbox.handle(open_args("r1", "c1")).unwrap();
2702 let again = mailbox.handle(open_args("r1", "c1")).unwrap();
2703 assert_eq!(again["status"], "pending");
2704 assert_eq!(mailbox.pending_len(), 1);
2705 mailbox.take_pending().unwrap();
2706 assert!(mailbox.take_pending().is_none());
2707 }
2708
2709 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2714 async fn list_commands_routes_to_the_host_and_defaults_to_empty() {
2715 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2716 prompt: String::new(),
2717 saw: Mutex::new(Vec::new()),
2718 });
2719 let bridge = ActionBridge::with_ui_dialog(
2720 tokio::runtime::Handle::current(),
2721 host,
2722 UiDialogMailbox::new(),
2723 );
2724 let user_data = bridge.user_data();
2725 let mut out = StbString::empty();
2726 let rc = trampoline_runtime_action(
2727 u32::from(RuntimeActionId::ListCommands),
2728 StbStringRef::from_str("{}"),
2729 &mut out,
2730 user_data,
2731 );
2732 assert_eq!(
2733 rc, 0,
2734 "ListCommands must not fail on a host with no registry"
2735 );
2736 let payload: serde_json::Value = serde_json::from_str(
2737 &unsafe {
2738 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2739 }
2740 .to_string_lossy(),
2741 )
2742 .expect("JSON");
2743 assert_eq!(
2744 payload
2745 .get("commands")
2746 .and_then(|c| c.as_array())
2747 .map(Vec::len),
2748 Some(0),
2749 "an empty registry is an empty list, not an error: {payload}"
2750 );
2751 }
2752
2753 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2757 async fn v2_dispatch_routes_ui_dialog_action_17() {
2758 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2759 prompt: String::new(),
2760 saw: Mutex::new(Vec::new()),
2761 });
2762 let bridge = ActionBridge::with_ui_dialog(
2763 tokio::runtime::Handle::current(),
2764 host,
2765 UiDialogMailbox::new(),
2766 );
2767 let user_data = bridge.user_data();
2768
2769 let mut out = StbString::empty();
2770 let rc = trampoline_runtime_action(
2771 17,
2772 StbStringRef::from_str(r#"{"op":"open","requestId":"r1","ui":{}}"#),
2773 &mut out,
2774 user_data,
2775 );
2776 assert_eq!(rc, 1);
2777 let payload: serde_json::Value = serde_json::from_str(
2778 &unsafe {
2779 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2780 }
2781 .to_string_lossy(),
2782 )
2783 .expect("structured error JSON");
2784 assert!(
2785 payload["error"]
2786 .as_str()
2787 .is_some_and(|error| error.contains("interactive UI")),
2788 "unexpected payload: {payload}"
2789 );
2790
2791 let one_past_last = rpi_plugin_sdk::RuntimeActionId::MAX + 1;
2795 let mut out = StbString::empty();
2796 assert_eq!(
2797 trampoline_runtime_action(
2798 one_past_last,
2799 StbStringRef::from_str("{}"),
2800 &mut out,
2801 user_data
2802 ),
2803 2
2804 );
2805 drop(unsafe {
2807 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2808 });
2809 }
2810
2811 #[tokio::test(flavor = "current_thread")]
2812 async fn component_bridge_isolates_plugins_and_cleans_up_reload_and_drop() {
2813 let host = Arc::new(MockHost {
2814 prompt: String::new(),
2815 saw: Mutex::new(Vec::new()),
2816 });
2817 let root = ActionBridge::new(tokio::runtime::Handle::current(), host);
2818 let a = root.for_plugin("a");
2819 let b = root.for_plugin("b");
2820 let mailbox = root.extension_status_mailbox();
2821 for plugin in [&a, &b] {
2822 let mut out = StbString::empty();
2823 assert_eq!(
2824 trampoline_runtime_action(
2825 22,
2826 StbStringRef::from_str(
2827 r#"{"op":"register","id":"same","slot":"footer.after"}"#
2828 ),
2829 &mut out,
2830 plugin.user_data()
2831 ),
2832 0
2833 );
2834 drop(unsafe {
2836 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2837 });
2838 }
2839 assert_eq!(mailbox.panels().len(), 2);
2840 drop(a);
2841 assert_eq!(mailbox.panels().len(), 1);
2842 root.invalidate();
2843 assert!(mailbox.panels().is_empty());
2844 }
2845
2846 #[test]
2852 fn relay_ui_dialog_runs_off_the_executor() {
2853 let mailbox = UiDialogMailbox::new();
2854 mailbox.attach();
2855 let out = dispatch_relay_ui_dialog(&mailbox, serde_json::json!({"op":"release"}))
2856 .expect("release is a supported op");
2857 assert_eq!(out["requeued"], serde_json::json!(0));
2858 }
2859
2860 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2863 async fn v2_dispatch_routes_set_status_action_18() {
2864 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2865 prompt: String::new(),
2866 saw: Mutex::new(Vec::new()),
2867 });
2868 let status = crate::status::ExtensionStatusMailbox::new();
2869 let bridge = ActionBridge::with_reload_and_ui(
2870 tokio::runtime::Handle::current(),
2871 host,
2872 Arc::new(|| Box::pin(async {})),
2873 UiDialogMailbox::new(),
2874 status.clone(),
2875 crate::editor_text::EditorTextMailbox::new(),
2876 );
2877 let user_data = bridge.user_data();
2878
2879 let mut out = StbString::empty();
2880 let rc = trampoline_runtime_action(
2881 18,
2882 StbStringRef::from_str(r#"{"key":"langfuse","value":"langfuse ✓ (trace sent)"}"#),
2883 &mut out,
2884 user_data,
2885 );
2886 assert_eq!(rc, 0);
2887 assert_eq!(status.text(), "langfuse ✓ (trace sent)");
2888 drop(unsafe {
2890 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2891 });
2892
2893 let mut out = StbString::empty();
2895 assert_eq!(
2896 trampoline_runtime_action(
2897 18,
2898 StbStringRef::from_str(r#"{"key":"langfuse","value":""}"#),
2899 &mut out,
2900 user_data
2901 ),
2902 0
2903 );
2904 assert_eq!(status.text(), "");
2905 drop(unsafe {
2907 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2908 });
2909
2910 let mut out = StbString::empty();
2912 assert_eq!(
2913 trampoline_runtime_action(18, StbStringRef::from_str("{}"), &mut out, user_data),
2914 1
2915 );
2916 drop(unsafe {
2918 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2919 });
2920 }
2921 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2928 async fn trampoline_ceiling_matches_the_highest_defined_action() {
2929 let highest = RuntimeActionId::MAX;
2930 assert_eq!(
2931 highest,
2932 RuntimeActionId::ALL
2933 .iter()
2934 .copied()
2935 .map(u32::from)
2936 .max()
2937 .unwrap(),
2938 "RuntimeActionId::MAX must be the maximum of RuntimeActionId::ALL"
2939 );
2940 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2941 prompt: String::new(),
2942 saw: Mutex::new(Vec::new()),
2943 });
2944 let bridge = ActionBridge::with_ui_dialog(
2945 tokio::runtime::Handle::current(),
2946 host,
2947 UiDialogMailbox::new(),
2948 );
2949 let mut out = StbString::empty();
2950 let rc = trampoline_runtime_action(
2951 highest,
2952 StbStringRef::from_str("{}"),
2953 &mut out,
2954 bridge.user_data(),
2955 );
2956 assert_ne!(
2957 rc, 2,
2958 "the highest defined action id ({highest}) must not be rejected as unknown — \
2959 the trampoline ceiling is stale"
2960 );
2961 if rc == 0 {
2962 drop(unsafe {
2964 rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2965 });
2966 }
2967 }
2968}
2969
2970impl Drop for ActionBridge {
2971 fn drop(&mut self) {
2972 bridges()
2973 .lock()
2974 .unwrap_or_else(|e| e.into_inner())
2975 .retain(|_, entry| !std::ptr::eq(entry.bridge.as_ptr(), self));
2976 if self.invocation.is_some() {
2977 return;
2978 }
2979 if let Some((owner, _)) = &self.plugin_identity {
2980 self.ext_status.remove_owner(*owner);
2981 self.host.cancel_child_agents(*owner);
2982 self.host.cancel_side_questions(*owner);
2983 }
2984 }
2985}
2986
2987#[cfg(test)]
2988mod runtime_tests;
2989
2990#[cfg(test)]
2991mod relay_tests {
2992 use super::*;
2993
2994 fn request(id: &str) -> UiDialogRequest {
2995 UiDialogRequest {
2996 request_id: id.to_string(),
2997 tool_call_id: Some(format!("tool-{id}")),
2998 ui: serde_json::json!({"question": "ok?"}),
2999 raw: serde_json::json!({}),
3000 }
3001 }
3002
3003 #[test]
3007 fn reserved_requests_are_invisible_to_the_tui() {
3008 let mailbox = UiDialogMailbox::new();
3009 mailbox.attach();
3010 let reserved = format!("{PLUGIN_RESERVED_PREFIX}gate-1");
3011 mailbox
3012 .handle(serde_json::json!({
3013 "op": "open",
3014 "requestId": reserved,
3015 "toolCallId": "t1",
3016 "ui": {}
3017 }))
3018 .unwrap();
3019 mailbox
3020 .handle(serde_json::json!({
3021 "op": "open",
3022 "requestId": "plain-1",
3023 "toolCallId": "t2",
3024 "ui": {}
3025 }))
3026 .unwrap();
3027
3028 let taken = mailbox
3030 .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
3031 .expect("the unreserved request must reach the TUI");
3032 assert_eq!(taken.request_id, "plain-1");
3033
3034 let own = mailbox
3036 .take_pending_filtered(|r| mailbox.is_reserved(&r.request_id))
3037 .expect("the plugin must still see its reserved request");
3038 assert_eq!(own.request_id, reserved);
3039 }
3040
3041 #[test]
3043 fn release_or_detach_clears_takeover_and_requeues_unanswered() {
3044 let mailbox = UiDialogMailbox::new();
3045 mailbox.attach();
3046 mailbox
3047 .handle(serde_json::json!({
3048 "op": "open", "requestId": "plain-r", "toolCallId": "t", "ui": {}
3049 }))
3050 .unwrap();
3051
3052 mailbox.set_external_takeover(true);
3054 assert_eq!(mailbox.take_all_unreserved().len(), 1);
3055 assert_eq!(mailbox.release_takeover(), 1);
3056 assert!(
3057 !mailbox.external_takeover(),
3058 "release must hand delivery back to the TUI"
3059 );
3060 assert_eq!(
3062 mailbox
3063 .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
3064 .map(|r| r.request_id),
3065 Some("plain-r".to_string())
3066 );
3067
3068 mailbox.set_external_takeover(true);
3070 mailbox.detach();
3071 assert!(!mailbox.external_takeover(), "detach must clear takeover");
3072 }
3073
3074 #[test]
3077 fn tui_take_is_atomic_against_takeover() {
3078 let mailbox = UiDialogMailbox::new();
3079 mailbox.attach();
3080 mailbox.set_external_takeover(true);
3081 mailbox
3082 .handle(serde_json::json!({
3083 "op": "open", "requestId": "plain-a", "toolCallId": "t", "ui": {}
3084 }))
3085 .unwrap();
3086 assert!(
3087 mailbox.take_pending_unless_external(|_| true).is_none(),
3088 "the TUI must stand down while a relay owns delivery"
3089 );
3090 assert_eq!(mailbox.take_all_unreserved().len(), 1);
3092 }
3093
3094 #[test]
3097 fn relay_take_returns_unreserved_and_keeps_reserved() {
3098 let mailbox = UiDialogMailbox::new();
3099 mailbox.attach();
3100 mailbox
3101 .handle(serde_json::json!({
3102 "op": "open",
3103 "requestId": format!("{PLUGIN_RESERVED_PREFIX}keep"),
3104 "toolCallId": "t1",
3105 "ui": {}
3106 }))
3107 .unwrap();
3108 mailbox
3109 .handle(serde_json::json!({
3110 "op": "open",
3111 "requestId": "relay-1",
3112 "toolCallId": "t2",
3113 "ui": {}
3114 }))
3115 .unwrap();
3116
3117 let taken = mailbox.take_all_unreserved();
3118 assert_eq!(taken.len(), 1);
3119 assert_eq!(taken[0].request_id, "relay-1");
3120 assert_eq!(mailbox.pending_len(), 1);
3122 }
3123
3124 #[test]
3127 fn a_relayed_request_can_still_be_answered() {
3128 let mailbox = UiDialogMailbox::new();
3129 mailbox.attach();
3130 mailbox
3131 .handle(serde_json::json!({
3132 "op": "open",
3133 "requestId": "relay-1",
3134 "toolCallId": "t1",
3135 "ui": {}
3136 }))
3137 .unwrap();
3138 let taken = mailbox.take_all_unreserved();
3139 assert_eq!(taken.len(), 1);
3140
3141 mailbox
3142 .handle(serde_json::json!({
3143 "op": "respond",
3144 "requestId": "relay-1",
3145 "answer": {"ok": true}
3146 }))
3147 .unwrap();
3148 assert_eq!(
3150 mailbox
3151 .take_pending_filtered(|_| true)
3152 .map(|r| r.request_id),
3153 None,
3154 "an answered request must not resurface"
3155 );
3156 }
3157
3158 #[test]
3161 fn take_pending_still_takes_reserved_entries() {
3162 let mailbox = UiDialogMailbox::new();
3163 mailbox.attach();
3164 let reserved = format!("{PLUGIN_RESERVED_PREFIX}x");
3165 mailbox
3166 .handle(serde_json::json!({
3167 "op": "open",
3168 "requestId": reserved,
3169 "toolCallId": "t1",
3170 "ui": {}
3171 }))
3172 .unwrap();
3173 assert_eq!(
3174 mailbox.take_pending().map(|r| r.request_id),
3175 Some(format!("{PLUGIN_RESERVED_PREFIX}x"))
3176 );
3177 }
3178
3179 #[test]
3185 fn external_takeover_makes_the_tui_stand_down() {
3186 let mailbox = UiDialogMailbox::new();
3187 mailbox.attach();
3188 mailbox
3189 .handle(serde_json::json!({
3190 "op": "open",
3191 "requestId": "plain-1",
3192 "toolCallId": "t1",
3193 "ui": {}
3194 }))
3195 .unwrap();
3196
3197 assert!(!mailbox.external_takeover());
3198 mailbox.set_external_takeover(true);
3199 assert!(mailbox.external_takeover());
3200
3201 let tui_take = |m: &UiDialogMailbox| {
3203 if m.external_takeover() {
3204 return None;
3205 }
3206 m.take_pending_filtered(|r| !m.is_reserved(&r.request_id))
3207 };
3208 assert!(
3209 tui_take(&mailbox).is_none(),
3210 "the TUI must not steal a request an external UI owns"
3211 );
3212 assert_eq!(mailbox.take_all_unreserved().len(), 1);
3214 }
3215
3216 #[test]
3218 fn clearing_takeover_returns_dialogs_to_the_tui() {
3219 let mailbox = UiDialogMailbox::new();
3220 mailbox.attach();
3221 mailbox.set_external_takeover(true);
3222 mailbox.set_external_takeover(false);
3223 mailbox
3224 .handle(serde_json::json!({
3225 "op": "open",
3226 "requestId": "plain-2",
3227 "toolCallId": "t2",
3228 "ui": {}
3229 }))
3230 .unwrap();
3231 assert_eq!(
3232 mailbox
3233 .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
3234 .map(|r| r.request_id),
3235 Some("plain-2".to_string())
3236 );
3237 }
3238
3239 #[test]
3240 fn request_helper_matches_the_prefix_rule() {
3241 let mailbox = UiDialogMailbox::new();
3242 mailbox.attach();
3243 assert!(mailbox.is_reserved(&request(PLUGIN_RESERVED_PREFIX).request_id));
3244 assert!(!mailbox.is_reserved(&request("plain").request_id));
3245 }
3246}