1use std::collections::{HashMap, VecDeque};
38use std::ffi::c_void;
39use std::sync::atomic::{AtomicBool, Ordering};
40use std::sync::{mpsc, Arc, Mutex};
41
42use rpi_plugin_sdk::{RuntimeActionId, StbString, StbStringRef};
43use tokio::runtime::Handle;
44
45#[derive(Clone, Debug, PartialEq)]
52pub struct UiDialogRequest {
53 pub request_id: String,
54 pub tool_call_id: Option<String>,
55 pub ui: serde_json::Value,
56 pub raw: serde_json::Value,
57}
58
59struct UiDialogEntry {
60 request: UiDialogRequest,
61 answer: Option<serde_json::Value>,
62 cancelled: bool,
63}
64
65struct UiDialogState {
66 attached: bool,
67 pending: VecDeque<String>,
68 active: HashMap<String, UiDialogEntry>,
69}
70
71#[derive(Clone)]
75pub struct UiDialogMailbox {
76 state: Arc<Mutex<UiDialogState>>,
77}
78
79impl Default for UiDialogMailbox {
80 fn default() -> Self {
81 Self::new()
82 }
83}
84
85impl UiDialogMailbox {
86 pub fn new() -> Self {
87 Self {
88 state: Arc::new(Mutex::new(UiDialogState {
89 attached: false,
90 pending: VecDeque::new(),
91 active: HashMap::new(),
92 })),
93 }
94 }
95
96 pub fn attach(&self) {
98 self.state
99 .lock()
100 .expect("ui dialog mailbox poisoned")
101 .attached = true;
102 }
103
104 pub fn detach(&self) {
107 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
108 state.attached = false;
109 state.pending.clear();
110 for entry in state.active.values_mut() {
111 entry.cancelled = true;
112 entry.answer = None;
113 }
114 }
115
116 pub fn is_attached(&self) -> bool {
117 self.state
118 .lock()
119 .expect("ui dialog mailbox poisoned")
120 .attached
121 }
122
123 pub fn take_pending(&self) -> Option<UiDialogRequest> {
127 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
128 while let Some(request_id) = state.pending.pop_front() {
129 if let Some(entry) = state.active.get(&request_id) {
130 if !entry.cancelled && entry.answer.is_none() {
131 return Some(entry.request.clone());
132 }
133 }
134 }
135 None
136 }
137
138 pub fn pending_len(&self) -> usize {
139 self.state
140 .lock()
141 .expect("ui dialog mailbox poisoned")
142 .pending
143 .len()
144 }
145
146 pub fn respond(&self, request_id: &str, answer: serde_json::Value) -> Result<(), String> {
149 let mut state = self
150 .state
151 .lock()
152 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
153 let entry = state
154 .active
155 .get_mut(request_id)
156 .ok_or_else(|| format!("unknown UI request `{request_id}`"))?;
157 if entry.cancelled {
158 return Err(format!("UI request `{request_id}` was cancelled"));
159 }
160 if entry.answer.is_none() {
161 entry.answer = Some(answer);
162 }
163 Ok(())
164 }
165
166 pub fn cancel(&self, request_id: &str) -> Result<(), String> {
169 let mut state = self
170 .state
171 .lock()
172 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
173 let entry = state
174 .active
175 .get_mut(request_id)
176 .ok_or_else(|| format!("unknown UI request `{request_id}`"))?;
177 entry.cancelled = true;
178 entry.answer = None;
179 state.pending.retain(|id| id != request_id);
180 Ok(())
181 }
182
183 pub fn cancel_all(&self) {
185 let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
186 state.pending.clear();
187 for entry in state.active.values_mut() {
188 entry.cancelled = true;
189 entry.answer = None;
190 }
191 }
192
193 pub fn poll(&self, request_id: &str) -> Result<serde_json::Value, String> {
196 let mut state = self
197 .state
198 .lock()
199 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
200 let terminal = match state.active.get(request_id) {
201 Some(entry) if entry.cancelled => Some(serde_json::json!({
202 "status": "cancelled",
203 "requestId": request_id,
204 "toolCallId": entry.request.tool_call_id,
205 })),
206 Some(entry) if entry.answer.is_some() => Some(serde_json::json!({
207 "status": "answered",
208 "requestId": request_id,
209 "toolCallId": entry.request.tool_call_id,
210 "answer": entry.answer.clone().unwrap_or(serde_json::Value::Null),
211 })),
212 Some(entry) => Some(serde_json::json!({
213 "status": "pending",
214 "requestId": request_id,
215 "toolCallId": entry.request.tool_call_id,
216 })),
217 None => None,
218 };
219 let Some(result) = terminal else {
220 return Err(format!("unknown UI request `{request_id}`"));
221 };
222 if result.get("status").and_then(serde_json::Value::as_str) != Some("pending") {
223 state.active.remove(request_id);
224 }
225 Ok(result)
226 }
227
228 pub fn handle(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
232 let op = args
233 .get("op")
234 .and_then(serde_json::Value::as_str)
235 .unwrap_or("open");
236 let request_id = || {
237 args.get("requestId")
238 .or_else(|| args.get("request_id"))
239 .and_then(serde_json::Value::as_str)
240 .map(str::to_owned)
241 .filter(|id| !id.trim().is_empty())
242 .ok_or_else(|| "missing non-empty `requestId`".to_string())
243 };
244 match op {
245 "open" => {
246 let id = request_id()?;
247 let mut state = self
248 .state
249 .lock()
250 .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
251 if !state.attached {
252 return Err("ask_user requires an interactive UI".to_string());
253 }
254 if let Some(entry) = state.active.get(&id) {
255 return Ok(if entry.cancelled {
256 serde_json::json!({"status":"cancelled","requestId":id})
257 } else if let Some(answer) = &entry.answer {
258 serde_json::json!({"status":"answered","requestId":id,"answer":answer})
259 } else {
260 serde_json::json!({"status":"pending","requestId":id})
261 });
262 }
263 let tool_call_id = args
264 .get("toolCallId")
265 .or_else(|| args.get("tool_call_id"))
266 .and_then(serde_json::Value::as_str)
267 .map(str::to_owned);
268 let ui = args.get("ui").cloned().unwrap_or_else(|| args.clone());
269 state.active.insert(
270 id.clone(),
271 UiDialogEntry {
272 request: UiDialogRequest {
273 request_id: id.clone(),
274 tool_call_id: tool_call_id.clone(),
275 ui,
276 raw: args,
277 },
278 answer: None,
279 cancelled: false,
280 },
281 );
282 state.pending.push_back(id.clone());
283 Ok(serde_json::json!({"status":"pending","requestId":id,"toolCallId":tool_call_id}))
284 }
285 "poll" => self.poll(&request_id()?),
286 "cancel" => {
287 let id = request_id()?;
288 self.cancel(&id)?;
289 Ok(serde_json::json!({"status":"cancelled","requestId":id}))
290 }
291 "response" | "respond" => {
292 let id = request_id()?;
293 let answer = args
294 .get("answer")
295 .or_else(|| args.get("value"))
296 .cloned()
297 .unwrap_or(serde_json::Value::Null);
298 self.respond(&id, answer)?;
299 Ok(serde_json::json!({"status":"answered","requestId":id}))
300 }
301 other => Err(format!("unknown UI dialog operation `{other}`")),
302 }
303 }
304}
305
306#[async_trait::async_trait]
321pub trait RuntimeActionHost: Send + Sync {
322 async fn send_message(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
324 async fn send_user_message(&self, args: serde_json::Value)
326 -> Result<serde_json::Value, String>;
327 async fn append_entry(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
329 async fn set_session_name(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
331 async fn get_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
333 async fn set_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
335 async fn set_model(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
337 async fn get_thinking_level(
339 &self,
340 args: serde_json::Value,
341 ) -> Result<serde_json::Value, String>;
342 async fn set_thinking_level(
344 &self,
345 args: serde_json::Value,
346 ) -> Result<serde_json::Value, String>;
347 async fn compact(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
349 async fn get_system_prompt(&self, args: serde_json::Value)
351 -> Result<serde_json::Value, String>;
352 async fn new_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
354 async fn fork(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
356 async fn navigate_tree(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
358 async fn switch_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
360 async fn reload(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
364
365 async fn get_cli_flag(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
368 Err("CLI flag lookup is not configured".to_string())
369 }
370
371 async fn ui_dialog(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
375 Err("ask_user requires an interactive UI".to_string())
376 }
377}
378
379pub struct ActionBridge {
408 pub(crate) runtime: Handle,
410 pub(crate) host: Arc<dyn RuntimeActionHost>,
412 pub(crate) reload:
414 Option<Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>>,
415 ui_dialog: UiDialogMailbox,
418 ext_status: crate::status::ExtensionStatusMailbox,
422 editor_text: crate::editor_text::EditorTextMailbox,
426 active: Arc<AtomicBool>,
429}
430
431impl ActionBridge {
432 pub fn new(runtime: Handle, host: Arc<dyn RuntimeActionHost>) -> Arc<Self> {
435 Arc::new(Self {
436 runtime,
437 host,
438 reload: None,
439 ui_dialog: UiDialogMailbox::new(),
440 ext_status: crate::status::ExtensionStatusMailbox::new(),
441 editor_text: crate::editor_text::EditorTextMailbox::new(),
442 active: Arc::new(AtomicBool::new(true)),
443 })
444 }
445
446 pub fn with_reload(
449 runtime: Handle,
450 host: Arc<dyn RuntimeActionHost>,
451 reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>,
452 ) -> Arc<Self> {
453 Self::with_reload_and_ui(
454 runtime,
455 host,
456 reload,
457 UiDialogMailbox::new(),
458 crate::status::ExtensionStatusMailbox::new(),
459 crate::editor_text::EditorTextMailbox::new(),
460 )
461 }
462
463 pub fn with_ui_dialog(
465 runtime: Handle,
466 host: Arc<dyn RuntimeActionHost>,
467 ui_dialog: UiDialogMailbox,
468 ) -> Arc<Self> {
469 Arc::new(Self {
470 runtime,
471 host,
472 reload: None,
473 ui_dialog,
474 ext_status: crate::status::ExtensionStatusMailbox::new(),
475 editor_text: crate::editor_text::EditorTextMailbox::new(),
476 active: Arc::new(AtomicBool::new(true)),
477 })
478 }
479
480 pub fn with_reload_and_ui(
482 runtime: Handle,
483 host: Arc<dyn RuntimeActionHost>,
484 reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>,
485 ui_dialog: UiDialogMailbox,
486 ext_status: crate::status::ExtensionStatusMailbox,
487 editor_text: crate::editor_text::EditorTextMailbox,
488 ) -> Arc<Self> {
489 Arc::new(Self {
490 runtime,
491 host,
492 reload: Some(reload),
493 ui_dialog,
494 ext_status,
495 editor_text,
496 active: Arc::new(AtomicBool::new(true)),
497 })
498 }
499
500 pub fn ui_dialog_mailbox(&self) -> UiDialogMailbox {
502 self.ui_dialog.clone()
503 }
504
505 pub fn extension_status_mailbox(&self) -> crate::status::ExtensionStatusMailbox {
507 self.ext_status.clone()
508 }
509
510 pub fn editor_text_mailbox(&self) -> crate::editor_text::EditorTextMailbox {
512 self.editor_text.clone()
513 }
514
515 pub fn invalidate(&self) {
520 self.active.store(false, Ordering::SeqCst);
521 }
522
523 pub fn is_active(&self) -> bool {
525 self.active.load(Ordering::SeqCst)
526 }
527
528 pub fn clone_host(&self) -> Arc<dyn RuntimeActionHost> {
535 Arc::clone(&self.host)
536 }
537}
538
539#[derive(Clone)]
552pub struct ReloadMailbox {
553 tx: Arc<std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<()>>>>,
554}
555
556impl Default for ReloadMailbox {
557 fn default() -> Self {
558 Self {
559 tx: Arc::new(std::sync::Mutex::new(None)),
560 }
561 }
562}
563
564impl ReloadMailbox {
565 pub fn new() -> Self {
567 Self::default()
568 }
569
570 pub fn install(&self, tx: tokio::sync::mpsc::UnboundedSender<()>) {
574 *self.tx.lock().unwrap() = Some(tx);
575 }
576
577 pub fn signal(&self) -> Result<(), ()> {
582 let g = self.tx.lock().unwrap();
583 match &*g {
584 Some(tx) => {
585 let _ = tx.send(());
586 Ok(())
587 }
588 None => Err(()),
589 }
590 }
591
592 pub fn clear(&self) {
594 *self.tx.lock().unwrap() = None;
595 }
596}
597
598pub fn reload_callback_from_mailbox(
605 mailbox: ReloadMailbox,
606) -> Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync> {
607 Arc::new(move || {
608 let m = mailbox.clone();
609 Box::pin(async move {
610 let _ = m.signal();
611 })
612 })
613}
614
615async fn dispatch(
626 host: &Arc<dyn RuntimeActionHost>,
627 ui_dialog: &UiDialogMailbox,
628 ext_status: &crate::status::ExtensionStatusMailbox,
629 editor_text: &crate::editor_text::EditorTextMailbox,
630 action: RuntimeActionId,
631 args: serde_json::Value,
632) -> Result<serde_json::Value, String> {
633 match action {
634 RuntimeActionId::SendMessage => host.send_message(args).await,
635 RuntimeActionId::SendUserMessage => host.send_user_message(args).await,
636 RuntimeActionId::AppendEntry => host.append_entry(args).await,
637 RuntimeActionId::SetSessionName => host.set_session_name(args).await,
638 RuntimeActionId::GetActiveTools => host.get_active_tools(args).await,
639 RuntimeActionId::SetActiveTools => host.set_active_tools(args).await,
640 RuntimeActionId::SetModel => host.set_model(args).await,
641 RuntimeActionId::GetThinkingLevel => host.get_thinking_level(args).await,
642 RuntimeActionId::SetThinkingLevel => host.set_thinking_level(args).await,
643 RuntimeActionId::Compact => host.compact(args).await,
644 RuntimeActionId::GetSystemPrompt => host.get_system_prompt(args).await,
645 RuntimeActionId::NewSession => host.new_session(args).await,
646 RuntimeActionId::Fork => host.fork(args).await,
647 RuntimeActionId::NavigateTree => host.navigate_tree(args).await,
648 RuntimeActionId::SwitchSession => host.switch_session(args).await,
649 RuntimeActionId::Reload => host.reload(args).await,
650 RuntimeActionId::GetCliFlag => host.get_cli_flag(args).await,
651 RuntimeActionId::UiDialog => ui_dialog.handle(args),
652 RuntimeActionId::SetStatus => ext_status.handle(args),
655 RuntimeActionId::SetEditorText => editor_text.handle(args),
658 }
659}
660
661pub extern "C" fn trampoline_runtime_action(
684 action_id: u32,
685 args_json: StbStringRef,
686 out: *mut StbString,
687 user_data: *mut c_void,
688) -> i32 {
689 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
690 run_action(
691 action_id,
692 u32::from(RuntimeActionId::SetEditorText),
694 args_json,
695 out,
696 user_data,
697 )
698 }));
699 match outcome {
700 Ok(rc) => rc,
701 Err(_) => {
702 tracing::error!("runtime_action trampoline panicked — reporting host error");
706 if !out.is_null() {
707 unsafe {
708 *out = StbString::from_string(
709 r#"{"error":"runtime_action panicked"}"#.to_string(),
710 );
711 }
712 }
713 1
714 }
715 }
716}
717
718fn run_action(
720 action_id: u32,
721 max_action_id: u32,
722 args_json: StbStringRef,
723 out: *mut StbString,
724 user_data: *mut c_void,
725) -> i32 {
726 let action = match RuntimeActionId::try_from(action_id) {
730 Ok(action) if action_id <= max_action_id => action,
731 Ok(_) | Err(_) => {
732 if !out.is_null() {
733 let json = serde_json::json!({
734 "error": format!("unknown runtime action id {action_id}")
735 })
736 .to_string();
737 unsafe {
741 *out = StbString::from_string(json);
742 }
743 }
744 return 2;
745 }
746 };
747
748 if user_data.is_null() {
749 return -1;
750 }
751 let bridge: &ActionBridge = unsafe { &*(user_data as *const ActionBridge) };
756
757 if !bridge.is_active() {
765 if out.is_null() {
766 return 1;
767 }
768 let json = serde_json::json!({
769 "error": "runtime_action on a stale ActionBridge (session reloaded/swapped)"
770 })
771 .to_string();
772 unsafe {
773 *out = StbString::from_string(json);
774 }
775 return 1;
776 }
777
778 let args_str = unsafe { args_json.as_str() };
781 let args: serde_json::Value = if args_str.is_empty() {
782 serde_json::Value::Object(serde_json::Map::new())
783 } else {
784 serde_json::from_str(args_str)
785 .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new()))
786 };
787
788 let (tx, rx) = mpsc::sync_channel::<Result<serde_json::Value, String>>(1);
793 let host = Arc::clone(&bridge.host);
797 let ui_dialog = bridge.ui_dialog.clone();
798 let ext_status = bridge.ext_status.clone();
799 let editor_text = bridge.editor_text.clone();
800 let reload_cb = bridge.reload.clone();
801 if action == RuntimeActionId::SetStatus {
802 std::thread::spawn(move || {
807 let _ = tx.send(ext_status.handle(args));
808 });
809 } else if action == RuntimeActionId::SetEditorText {
810 std::thread::spawn(move || {
813 let _ = tx.send(editor_text.handle(args));
814 });
815 } else if action == RuntimeActionId::UiDialog {
816 std::thread::spawn(move || {
822 let _ = tx.send(ui_dialog.handle(args));
823 });
824 } else {
825 bridge.runtime.spawn(async move {
826 let r = if action == RuntimeActionId::Reload {
827 if let Some(cb) = reload_cb {
828 cb().await;
829 Ok(serde_json::Value::Null)
830 } else {
831 host.reload(args).await
832 }
833 } else {
834 dispatch(&host, &ui_dialog, &ext_status, &editor_text, action, args).await
835 };
836 let _ = tx.send(r);
839 });
840 }
841
842 let result = match rx.recv() {
843 Ok(r) => r,
844 Err(_) => {
845 return -2;
850 }
851 };
852
853 if out.is_null() {
856 return match result {
858 Ok(_) => 0,
859 Err(_) => 1,
860 };
861 }
862
863 let (rc, payload) = match result {
864 Ok(value) => {
865 let json = serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string());
866 (0, json)
867 }
868 Err(msg) => {
869 let json = serde_json::json!({ "error": msg }).to_string();
870 (1, json)
871 }
872 };
873 unsafe {
879 *out = StbString::from_string(payload);
880 }
881 rc
882}
883
884#[cfg(test)]
893mod tests {
894 use super::*;
895 use std::sync::Mutex;
896
897 struct MockHost {
902 prompt: String,
903 saw: Mutex<Vec<RuntimeActionId>>,
904 }
905
906 #[async_trait::async_trait]
907 impl RuntimeActionHost for MockHost {
908 async fn send_message(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
909 unreachable!("not under test")
910 }
911 async fn send_user_message(
912 &self,
913 _: serde_json::Value,
914 ) -> Result<serde_json::Value, String> {
915 unreachable!("not under test")
916 }
917 async fn append_entry(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
918 unreachable!("not under test")
919 }
920 async fn set_session_name(
921 &self,
922 _: serde_json::Value,
923 ) -> Result<serde_json::Value, String> {
924 unreachable!("not under test")
925 }
926 async fn get_active_tools(
927 &self,
928 _: serde_json::Value,
929 ) -> Result<serde_json::Value, String> {
930 unreachable!("not under test")
931 }
932 async fn set_active_tools(
933 &self,
934 _: serde_json::Value,
935 ) -> Result<serde_json::Value, String> {
936 unreachable!("not under test")
937 }
938 async fn set_model(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
939 unreachable!("not under test")
940 }
941 async fn get_thinking_level(
942 &self,
943 _: serde_json::Value,
944 ) -> Result<serde_json::Value, String> {
945 unreachable!("not under test")
946 }
947 async fn set_thinking_level(
948 &self,
949 _: serde_json::Value,
950 ) -> Result<serde_json::Value, String> {
951 unreachable!("not under test")
952 }
953 async fn compact(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
954 unreachable!("not under test")
955 }
956 async fn get_system_prompt(
957 &self,
958 _: serde_json::Value,
959 ) -> Result<serde_json::Value, String> {
960 self.saw
961 .lock()
962 .unwrap()
963 .push(RuntimeActionId::GetSystemPrompt);
964 Ok(serde_json::json!({ "prompt": self.prompt }))
965 }
966 async fn new_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
967 unreachable!("not under test")
968 }
969 async fn fork(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
970 unreachable!("not under test")
971 }
972 async fn navigate_tree(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
973 unreachable!("not under test")
974 }
975 async fn switch_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
976 unreachable!("not under test")
977 }
978 async fn reload(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
979 self.saw.lock().unwrap().push(RuntimeActionId::Reload);
980 Ok(serde_json::Value::Null)
981 }
982 async fn get_cli_flag(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
983 self.saw.lock().unwrap().push(RuntimeActionId::GetCliFlag);
984 Ok(serde_json::json!({ "value": true }))
985 }
986 }
987
988 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
997 async fn trampoline_round_trips_get_system_prompt() {
998 let host = Arc::new(MockHost {
999 prompt: "hello from host".to_string(),
1000 saw: Mutex::new(Vec::new()),
1001 });
1002 let host_for_assert = Arc::clone(&host);
1003 let host_dyn: Arc<dyn RuntimeActionHost> = host;
1004 let runtime = tokio::runtime::Handle::current();
1005 let bridge = ActionBridge::new(runtime, host_dyn);
1006 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1007
1008 let args_str = "{}";
1010 let args_ref = StbStringRef::from_str(args_str);
1011
1012 let mut out = StbString::empty();
1013 let rc = trampoline_runtime_action(
1014 RuntimeActionId::GetSystemPrompt.into(),
1015 args_ref,
1016 &mut out as *mut StbString,
1017 user_data,
1018 );
1019 assert_eq!(rc, 0, "success return code");
1020
1021 let json_text = out.to_string_lossy();
1023 let parsed: serde_json::Value = serde_json::from_str(&json_text).expect("valid json");
1024 assert_eq!(parsed["prompt"], "hello from host");
1025 crate::host_free_string(out);
1026
1027 let saw = host_for_assert.saw.lock().unwrap().clone();
1030 assert_eq!(saw, vec![RuntimeActionId::GetSystemPrompt]);
1031 }
1032
1033 #[tokio::test]
1039 async fn trampoline_routes_set_editor_text_into_the_mailbox() {
1040 let host = Arc::new(MockHost {
1041 prompt: String::new(),
1042 saw: Mutex::new(Vec::new()),
1043 });
1044 let host_dyn: Arc<dyn RuntimeActionHost> = host;
1045 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
1046 let mailbox = bridge.editor_text_mailbox();
1047 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1048
1049 let args_ref =
1050 StbStringRef::from_str(r#"{"text":"from voice","mode":"append","autoSendMs":2000}"#);
1051 let mut out = StbString::empty();
1052 let rc = trampoline_runtime_action(
1053 RuntimeActionId::SetEditorText.into(),
1054 args_ref,
1055 &mut out as *mut StbString,
1056 user_data,
1057 );
1058 assert_eq!(rc, 0, "success return code");
1059
1060 let parsed: serde_json::Value =
1061 serde_json::from_str(&out.to_string_lossy()).expect("valid json");
1062 assert_eq!(parsed["ok"], serde_json::json!(true));
1063 assert_eq!(parsed["chars"], serde_json::json!(10));
1064 crate::host_free_string(out);
1065
1066 let edit = mailbox.take_pending().expect("queued edit");
1068 assert_eq!(edit.text, "from voice");
1069 assert_eq!(edit.mode, crate::EditorTextMode::Append);
1070 assert_eq!(edit.auto_send_ms, Some(2000));
1071 assert!(mailbox.take_pending().is_none());
1072 }
1073
1074 #[tokio::test]
1075 async fn trampoline_null_user_data_returns_minus_one() {
1076 let args_ref = StbStringRef::from_str("{}");
1077 let mut out = StbString::empty();
1078 let rc = trampoline_runtime_action(
1079 RuntimeActionId::GetSystemPrompt.into(),
1080 args_ref,
1081 &mut out as *mut StbString,
1082 std::ptr::null_mut(),
1083 );
1084 assert_eq!(rc, -1, "null user_data ⇒ no bridge");
1085 }
1086
1087 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1088 async fn trampoline_intercepts_reload_when_bridge_has_callback() {
1089 use std::sync::atomic::{AtomicUsize, Ordering};
1093 let reload_calls = Arc::new(AtomicUsize::new(0));
1094 let reload_calls_for_cb = Arc::clone(&reload_calls);
1095 let reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync> =
1096 Arc::new(move || {
1097 let c = Arc::clone(&reload_calls_for_cb);
1098 Box::pin(async move {
1099 c.fetch_add(1, Ordering::SeqCst);
1100 })
1101 });
1102 let host = Arc::new(MockHost {
1103 prompt: String::new(),
1104 saw: Mutex::new(Vec::new()),
1105 });
1106 let host_for_assert = Arc::clone(&host);
1107 let host_dyn: Arc<dyn RuntimeActionHost> = host;
1108 let runtime = tokio::runtime::Handle::current();
1109 let bridge = ActionBridge::with_reload(runtime, host_dyn, reload);
1110 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1111
1112 let args_ref = StbStringRef::from_str("{}");
1113 let mut out = StbString::empty();
1114 let rc = trampoline_runtime_action(
1115 RuntimeActionId::Reload.into(),
1116 args_ref,
1117 &mut out as *mut StbString,
1118 user_data,
1119 );
1120 assert_eq!(rc, 0);
1121 assert_eq!(reload_calls.load(Ordering::SeqCst), 1);
1123 assert!(host_for_assert.saw.lock().unwrap().is_empty());
1124 crate::host_free_string(out);
1125 }
1126
1127 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1132 async fn trampoline_rejects_stale_bridge_with_invalidate() {
1133 let host = Arc::new(MockHost {
1134 prompt: String::new(),
1135 saw: Mutex::new(Vec::new()),
1136 });
1137 let host_for_assert = Arc::clone(&host);
1138 let host_dyn: Arc<dyn RuntimeActionHost> = host;
1139 let runtime = tokio::runtime::Handle::current();
1140 let bridge = ActionBridge::new(runtime, host_dyn);
1141 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1142
1143 bridge.invalidate();
1145 assert!(!bridge.is_active());
1146
1147 let args_ref = StbStringRef::from_str("{}");
1148 let mut out = StbString::empty();
1149 let rc = trampoline_runtime_action(
1150 RuntimeActionId::GetSystemPrompt.into(),
1151 args_ref,
1152 &mut out as *mut StbString,
1153 user_data,
1154 );
1155 assert_eq!(rc, 1, "stale bridge ⇒ error return code");
1157 let json_text = out.to_string_lossy();
1158 assert!(
1159 json_text.contains("stale"),
1160 "stale-bridge error payload: {json_text}"
1161 );
1162 crate::host_free_string(out);
1163 assert!(
1164 host_for_assert.saw.lock().unwrap().is_empty(),
1165 "host dispatch must NOT run on a stale bridge"
1166 );
1167 }
1168
1169 #[tokio::test]
1170 async fn trampoline_rejects_unknown_numeric_id_without_dispatch() {
1171 let host = Arc::new(MockHost {
1172 prompt: String::new(),
1173 saw: Mutex::new(Vec::new()),
1174 });
1175 let host_for_assert = Arc::clone(&host);
1176 let host_dyn: Arc<dyn RuntimeActionHost> = host;
1177 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
1178 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1179
1180 let mut out = StbString::empty();
1181 let rc = trampoline_runtime_action(
1182 0xFFFF_FFFE,
1183 StbStringRef::from_str("{}"),
1184 &mut out,
1185 user_data,
1186 );
1187
1188 assert_eq!(rc, 2, "unknown action id must be a protocol error");
1189 let payload: serde_json::Value =
1190 serde_json::from_str(&out.to_string_lossy()).expect("structured error JSON");
1191 assert_eq!(payload["error"], "unknown runtime action id 4294967294");
1192 crate::host_free_string(out);
1193 assert!(
1194 host_for_assert.saw.lock().unwrap().is_empty(),
1195 "unknown action id must not reach host dispatch"
1196 );
1197 }
1198
1199 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1200 async fn v2_trampoline_accepts_new_action() {
1201 let host = Arc::new(MockHost {
1202 prompt: "v2".to_string(),
1203 saw: Mutex::new(Vec::new()),
1204 });
1205 let host_for_assert = Arc::clone(&host);
1206 let host_dyn: Arc<dyn RuntimeActionHost> = host;
1207 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
1208 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1209
1210 let mut v2_out = StbString::empty();
1211 assert_eq!(
1212 trampoline_runtime_action(
1213 RuntimeActionId::GetCliFlag.into(),
1214 StbStringRef::from_str(r#"{"name":"flag"}"#),
1215 &mut v2_out,
1216 user_data,
1217 ),
1218 0
1219 );
1220 crate::host_free_string(v2_out);
1221
1222 assert_eq!(
1223 *host_for_assert.saw.lock().unwrap(),
1224 vec![RuntimeActionId::GetCliFlag]
1225 );
1226 }
1227
1228 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1233 async fn reload_mailbox_signals_installed_receiver() {
1234 let mailbox = ReloadMailbox::new();
1235 assert!(matches!(mailbox.signal(), Err(())));
1237
1238 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1239 mailbox.install(tx);
1240 let cb = reload_callback_from_mailbox(mailbox.clone());
1241 cb().await;
1242 assert_eq!(
1243 rx.recv().await,
1244 Some(()),
1245 "installed receiver saw the signal"
1246 );
1247 mailbox.clear();
1248 }
1249
1250 fn open_args(id: &str, tool_call: &str) -> serde_json::Value {
1253 serde_json::json!({
1254 "op": "open",
1255 "requestId": id,
1256 "toolCallId": tool_call,
1257 "ui": {"kind": "selector", "questions": [
1258 {"id": "q1", "question": "Which target?", "options": ["Linux"]}
1259 ]},
1260 })
1261 }
1262
1263 #[test]
1266 fn ui_dialog_open_requires_an_attached_ui() {
1267 let mailbox = UiDialogMailbox::new();
1268 let error = mailbox.handle(open_args("r1", "c1")).unwrap_err();
1269 assert!(error.contains("interactive UI"), "got: {error}");
1270 }
1271
1272 #[test]
1273 fn ui_dialog_open_poll_answer_round_trip() {
1274 let mailbox = UiDialogMailbox::new();
1275 mailbox.attach();
1276
1277 let opened = mailbox.handle(open_args("r1", "c1")).unwrap();
1278 assert_eq!(opened["status"], "pending");
1279 assert_eq!(opened["toolCallId"], "c1");
1280
1281 let request = mailbox.take_pending().expect("request visible to TUI");
1282 assert_eq!(request.request_id, "r1");
1283 assert_eq!(request.tool_call_id.as_deref(), Some("c1"));
1284 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
1286 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
1287
1288 mailbox
1289 .respond("r1", serde_json::json!("7890"))
1290 .expect("respond");
1291 let answered = mailbox.poll("r1").unwrap();
1292 assert_eq!(answered["status"], "answered");
1293 assert_eq!(answered["answer"], "7890");
1294 assert!(mailbox.poll("r1").is_err());
1296 }
1297
1298 #[test]
1299 fn ui_dialog_cancel_is_reported_once() {
1300 let mailbox = UiDialogMailbox::new();
1301 mailbox.attach();
1302 mailbox.handle(open_args("r1", "c1")).unwrap();
1303 mailbox.cancel("r1").unwrap();
1304 let cancelled = mailbox.poll("r1").unwrap();
1305 assert_eq!(cancelled["status"], "cancelled");
1306 assert!(mailbox.poll("r1").is_err());
1307 }
1308
1309 #[test]
1310 fn ui_dialog_concurrent_requests_do_not_cross_answers() {
1311 let mailbox = UiDialogMailbox::new();
1312 mailbox.attach();
1313 mailbox.handle(open_args("r1", "c1")).unwrap();
1314 mailbox.handle(open_args("r2", "c2")).unwrap();
1315
1316 let first = mailbox.take_pending().unwrap().request_id;
1317 let second = mailbox.take_pending().unwrap().request_id;
1318 assert_ne!(first, second);
1319
1320 mailbox
1322 .respond(&second, serde_json::json!("second"))
1323 .unwrap();
1324 assert_eq!(mailbox.poll(&first).unwrap()["status"], "pending");
1325 let second_answer = mailbox.poll(&second).unwrap();
1326 assert_eq!(second_answer["answer"], "second");
1327
1328 mailbox.respond(&first, serde_json::json!("first")).unwrap();
1329 assert_eq!(mailbox.poll(&first).unwrap()["answer"], "first");
1330 }
1331
1332 #[test]
1333 fn ui_dialog_detach_cancels_outstanding() {
1334 let mailbox = UiDialogMailbox::new();
1335 mailbox.attach();
1336 mailbox.handle(open_args("r1", "c1")).unwrap();
1337 mailbox.detach();
1338 assert!(!mailbox.is_attached());
1339 assert_eq!(mailbox.pending_len(), 0);
1340 assert!(mailbox.handle(open_args("r2", "c2")).is_err());
1342 assert_eq!(mailbox.poll("r1").unwrap()["status"], "cancelled");
1343 }
1344
1345 #[test]
1346 fn ui_dialog_duplicate_open_does_not_reenqueue() {
1347 let mailbox = UiDialogMailbox::new();
1348 mailbox.attach();
1349 mailbox.handle(open_args("r1", "c1")).unwrap();
1350 let again = mailbox.handle(open_args("r1", "c1")).unwrap();
1351 assert_eq!(again["status"], "pending");
1352 assert_eq!(mailbox.pending_len(), 1);
1353 mailbox.take_pending().unwrap();
1354 assert!(mailbox.take_pending().is_none());
1355 }
1356
1357 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1361 async fn v2_dispatch_routes_ui_dialog_action_17() {
1362 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
1363 prompt: String::new(),
1364 saw: Mutex::new(Vec::new()),
1365 });
1366 let bridge = ActionBridge::with_ui_dialog(
1367 tokio::runtime::Handle::current(),
1368 host,
1369 UiDialogMailbox::new(),
1370 );
1371 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1372
1373 let mut out = StbString::empty();
1374 let rc = trampoline_runtime_action(
1375 17,
1376 StbStringRef::from_str(r#"{"op":"open","requestId":"r1","ui":{}}"#),
1377 &mut out,
1378 user_data,
1379 );
1380 assert_eq!(rc, 1);
1381 let payload: serde_json::Value =
1382 serde_json::from_str(&out.to_string_lossy()).expect("structured error JSON");
1383 assert!(
1384 payload["error"]
1385 .as_str()
1386 .is_some_and(|error| error.contains("interactive UI")),
1387 "unexpected payload: {payload}"
1388 );
1389 crate::host_free_string(out);
1390
1391 let mut out = StbString::empty();
1394 assert_eq!(
1395 trampoline_runtime_action(20, StbStringRef::from_str("{}"), &mut out, user_data),
1396 2
1397 );
1398 crate::host_free_string(out);
1399 }
1400
1401 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1404 async fn v2_dispatch_routes_set_status_action_18() {
1405 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
1406 prompt: String::new(),
1407 saw: Mutex::new(Vec::new()),
1408 });
1409 let status = crate::status::ExtensionStatusMailbox::new();
1410 let bridge = ActionBridge::with_reload_and_ui(
1411 tokio::runtime::Handle::current(),
1412 host,
1413 Arc::new(|| Box::pin(async {})),
1414 UiDialogMailbox::new(),
1415 status.clone(),
1416 crate::editor_text::EditorTextMailbox::new(),
1417 );
1418 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1419
1420 let mut out = StbString::empty();
1421 let rc = trampoline_runtime_action(
1422 18,
1423 StbStringRef::from_str(r#"{"key":"langfuse","value":"langfuse ✓ (trace sent)"}"#),
1424 &mut out,
1425 user_data,
1426 );
1427 assert_eq!(rc, 0);
1428 assert_eq!(status.text(), "langfuse ✓ (trace sent)");
1429 crate::host_free_string(out);
1430
1431 let mut out = StbString::empty();
1433 assert_eq!(
1434 trampoline_runtime_action(
1435 18,
1436 StbStringRef::from_str(r#"{"key":"langfuse","value":""}"#),
1437 &mut out,
1438 user_data
1439 ),
1440 0
1441 );
1442 assert_eq!(status.text(), "");
1443 crate::host_free_string(out);
1444
1445 let mut out = StbString::empty();
1447 assert_eq!(
1448 trampoline_runtime_action(18, StbStringRef::from_str("{}"), &mut out, user_data),
1449 1
1450 );
1451 crate::host_free_string(out);
1452 }
1453}