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 = StbStringRef::from_str(
1050 r#"{"text":"from voice","mode":"append","autoSendMs":2000}"#,
1051 );
1052 let mut out = StbString::empty();
1053 let rc = trampoline_runtime_action(
1054 RuntimeActionId::SetEditorText.into(),
1055 args_ref,
1056 &mut out as *mut StbString,
1057 user_data,
1058 );
1059 assert_eq!(rc, 0, "success return code");
1060
1061 let parsed: serde_json::Value =
1062 serde_json::from_str(&out.to_string_lossy()).expect("valid json");
1063 assert_eq!(parsed["ok"], serde_json::json!(true));
1064 assert_eq!(parsed["chars"], serde_json::json!(10));
1065 crate::host_free_string(out);
1066
1067 let edit = mailbox.take_pending().expect("queued edit");
1069 assert_eq!(edit.text, "from voice");
1070 assert_eq!(edit.mode, crate::EditorTextMode::Append);
1071 assert_eq!(edit.auto_send_ms, Some(2000));
1072 assert!(mailbox.take_pending().is_none());
1073 }
1074
1075 #[tokio::test]
1076 async fn trampoline_null_user_data_returns_minus_one() {
1077 let args_ref = StbStringRef::from_str("{}");
1078 let mut out = StbString::empty();
1079 let rc = trampoline_runtime_action(
1080 RuntimeActionId::GetSystemPrompt.into(),
1081 args_ref,
1082 &mut out as *mut StbString,
1083 std::ptr::null_mut(),
1084 );
1085 assert_eq!(rc, -1, "null user_data ⇒ no bridge");
1086 }
1087
1088 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1089 async fn trampoline_intercepts_reload_when_bridge_has_callback() {
1090 use std::sync::atomic::{AtomicUsize, Ordering};
1094 let reload_calls = Arc::new(AtomicUsize::new(0));
1095 let reload_calls_for_cb = Arc::clone(&reload_calls);
1096 let reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync> =
1097 Arc::new(move || {
1098 let c = Arc::clone(&reload_calls_for_cb);
1099 Box::pin(async move {
1100 c.fetch_add(1, Ordering::SeqCst);
1101 })
1102 });
1103 let host = Arc::new(MockHost {
1104 prompt: String::new(),
1105 saw: Mutex::new(Vec::new()),
1106 });
1107 let host_for_assert = Arc::clone(&host);
1108 let host_dyn: Arc<dyn RuntimeActionHost> = host;
1109 let runtime = tokio::runtime::Handle::current();
1110 let bridge = ActionBridge::with_reload(runtime, host_dyn, reload);
1111 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1112
1113 let args_ref = StbStringRef::from_str("{}");
1114 let mut out = StbString::empty();
1115 let rc = trampoline_runtime_action(
1116 RuntimeActionId::Reload.into(),
1117 args_ref,
1118 &mut out as *mut StbString,
1119 user_data,
1120 );
1121 assert_eq!(rc, 0);
1122 assert_eq!(reload_calls.load(Ordering::SeqCst), 1);
1124 assert!(host_for_assert.saw.lock().unwrap().is_empty());
1125 crate::host_free_string(out);
1126 }
1127
1128 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1133 async fn trampoline_rejects_stale_bridge_with_invalidate() {
1134 let host = Arc::new(MockHost {
1135 prompt: String::new(),
1136 saw: Mutex::new(Vec::new()),
1137 });
1138 let host_for_assert = Arc::clone(&host);
1139 let host_dyn: Arc<dyn RuntimeActionHost> = host;
1140 let runtime = tokio::runtime::Handle::current();
1141 let bridge = ActionBridge::new(runtime, host_dyn);
1142 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1143
1144 bridge.invalidate();
1146 assert!(!bridge.is_active());
1147
1148 let args_ref = StbStringRef::from_str("{}");
1149 let mut out = StbString::empty();
1150 let rc = trampoline_runtime_action(
1151 RuntimeActionId::GetSystemPrompt.into(),
1152 args_ref,
1153 &mut out as *mut StbString,
1154 user_data,
1155 );
1156 assert_eq!(rc, 1, "stale bridge ⇒ error return code");
1158 let json_text = out.to_string_lossy();
1159 assert!(
1160 json_text.contains("stale"),
1161 "stale-bridge error payload: {json_text}"
1162 );
1163 crate::host_free_string(out);
1164 assert!(
1165 host_for_assert.saw.lock().unwrap().is_empty(),
1166 "host dispatch must NOT run on a stale bridge"
1167 );
1168 }
1169
1170 #[tokio::test]
1171 async fn trampoline_rejects_unknown_numeric_id_without_dispatch() {
1172 let host = Arc::new(MockHost {
1173 prompt: String::new(),
1174 saw: Mutex::new(Vec::new()),
1175 });
1176 let host_for_assert = Arc::clone(&host);
1177 let host_dyn: Arc<dyn RuntimeActionHost> = host;
1178 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
1179 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1180
1181 let mut out = StbString::empty();
1182 let rc = trampoline_runtime_action(
1183 0xFFFF_FFFE,
1184 StbStringRef::from_str("{}"),
1185 &mut out,
1186 user_data,
1187 );
1188
1189 assert_eq!(rc, 2, "unknown action id must be a protocol error");
1190 let payload: serde_json::Value =
1191 serde_json::from_str(&out.to_string_lossy()).expect("structured error JSON");
1192 assert_eq!(payload["error"], "unknown runtime action id 4294967294");
1193 crate::host_free_string(out);
1194 assert!(
1195 host_for_assert.saw.lock().unwrap().is_empty(),
1196 "unknown action id must not reach host dispatch"
1197 );
1198 }
1199
1200 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1201 async fn v2_trampoline_accepts_new_action() {
1202 let host = Arc::new(MockHost {
1203 prompt: "v2".to_string(),
1204 saw: Mutex::new(Vec::new()),
1205 });
1206 let host_for_assert = Arc::clone(&host);
1207 let host_dyn: Arc<dyn RuntimeActionHost> = host;
1208 let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
1209 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1210
1211 let mut v2_out = StbString::empty();
1212 assert_eq!(
1213 trampoline_runtime_action(
1214 RuntimeActionId::GetCliFlag.into(),
1215 StbStringRef::from_str(r#"{"name":"flag"}"#),
1216 &mut v2_out,
1217 user_data,
1218 ),
1219 0
1220 );
1221 crate::host_free_string(v2_out);
1222
1223 assert_eq!(
1224 *host_for_assert.saw.lock().unwrap(),
1225 vec![RuntimeActionId::GetCliFlag]
1226 );
1227 }
1228
1229 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1234 async fn reload_mailbox_signals_installed_receiver() {
1235 let mailbox = ReloadMailbox::new();
1236 assert!(matches!(mailbox.signal(), Err(())));
1238
1239 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1240 mailbox.install(tx);
1241 let cb = reload_callback_from_mailbox(mailbox.clone());
1242 cb().await;
1243 assert_eq!(
1244 rx.recv().await,
1245 Some(()),
1246 "installed receiver saw the signal"
1247 );
1248 mailbox.clear();
1249 }
1250
1251 fn open_args(id: &str, tool_call: &str) -> serde_json::Value {
1254 serde_json::json!({
1255 "op": "open",
1256 "requestId": id,
1257 "toolCallId": tool_call,
1258 "ui": {"kind": "selector", "questions": [
1259 {"id": "q1", "question": "Which target?", "options": ["Linux"]}
1260 ]},
1261 })
1262 }
1263
1264 #[test]
1267 fn ui_dialog_open_requires_an_attached_ui() {
1268 let mailbox = UiDialogMailbox::new();
1269 let error = mailbox.handle(open_args("r1", "c1")).unwrap_err();
1270 assert!(error.contains("interactive UI"), "got: {error}");
1271 }
1272
1273 #[test]
1274 fn ui_dialog_open_poll_answer_round_trip() {
1275 let mailbox = UiDialogMailbox::new();
1276 mailbox.attach();
1277
1278 let opened = mailbox.handle(open_args("r1", "c1")).unwrap();
1279 assert_eq!(opened["status"], "pending");
1280 assert_eq!(opened["toolCallId"], "c1");
1281
1282 let request = mailbox.take_pending().expect("request visible to TUI");
1283 assert_eq!(request.request_id, "r1");
1284 assert_eq!(request.tool_call_id.as_deref(), Some("c1"));
1285 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
1287 assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
1288
1289 mailbox
1290 .respond("r1", serde_json::json!("7890"))
1291 .expect("respond");
1292 let answered = mailbox.poll("r1").unwrap();
1293 assert_eq!(answered["status"], "answered");
1294 assert_eq!(answered["answer"], "7890");
1295 assert!(mailbox.poll("r1").is_err());
1297 }
1298
1299 #[test]
1300 fn ui_dialog_cancel_is_reported_once() {
1301 let mailbox = UiDialogMailbox::new();
1302 mailbox.attach();
1303 mailbox.handle(open_args("r1", "c1")).unwrap();
1304 mailbox.cancel("r1").unwrap();
1305 let cancelled = mailbox.poll("r1").unwrap();
1306 assert_eq!(cancelled["status"], "cancelled");
1307 assert!(mailbox.poll("r1").is_err());
1308 }
1309
1310 #[test]
1311 fn ui_dialog_concurrent_requests_do_not_cross_answers() {
1312 let mailbox = UiDialogMailbox::new();
1313 mailbox.attach();
1314 mailbox.handle(open_args("r1", "c1")).unwrap();
1315 mailbox.handle(open_args("r2", "c2")).unwrap();
1316
1317 let first = mailbox.take_pending().unwrap().request_id;
1318 let second = mailbox.take_pending().unwrap().request_id;
1319 assert_ne!(first, second);
1320
1321 mailbox
1323 .respond(&second, serde_json::json!("second"))
1324 .unwrap();
1325 assert_eq!(mailbox.poll(&first).unwrap()["status"], "pending");
1326 let second_answer = mailbox.poll(&second).unwrap();
1327 assert_eq!(second_answer["answer"], "second");
1328
1329 mailbox.respond(&first, serde_json::json!("first")).unwrap();
1330 assert_eq!(mailbox.poll(&first).unwrap()["answer"], "first");
1331 }
1332
1333 #[test]
1334 fn ui_dialog_detach_cancels_outstanding() {
1335 let mailbox = UiDialogMailbox::new();
1336 mailbox.attach();
1337 mailbox.handle(open_args("r1", "c1")).unwrap();
1338 mailbox.detach();
1339 assert!(!mailbox.is_attached());
1340 assert_eq!(mailbox.pending_len(), 0);
1341 assert!(mailbox.handle(open_args("r2", "c2")).is_err());
1343 assert_eq!(mailbox.poll("r1").unwrap()["status"], "cancelled");
1344 }
1345
1346 #[test]
1347 fn ui_dialog_duplicate_open_does_not_reenqueue() {
1348 let mailbox = UiDialogMailbox::new();
1349 mailbox.attach();
1350 mailbox.handle(open_args("r1", "c1")).unwrap();
1351 let again = mailbox.handle(open_args("r1", "c1")).unwrap();
1352 assert_eq!(again["status"], "pending");
1353 assert_eq!(mailbox.pending_len(), 1);
1354 mailbox.take_pending().unwrap();
1355 assert!(mailbox.take_pending().is_none());
1356 }
1357
1358 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1362 async fn v2_dispatch_routes_ui_dialog_action_17() {
1363 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
1364 prompt: String::new(),
1365 saw: Mutex::new(Vec::new()),
1366 });
1367 let bridge = ActionBridge::with_ui_dialog(
1368 tokio::runtime::Handle::current(),
1369 host,
1370 UiDialogMailbox::new(),
1371 );
1372 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1373
1374 let mut out = StbString::empty();
1375 let rc = trampoline_runtime_action(
1376 17,
1377 StbStringRef::from_str(r#"{"op":"open","requestId":"r1","ui":{}}"#),
1378 &mut out,
1379 user_data,
1380 );
1381 assert_eq!(rc, 1);
1382 let payload: serde_json::Value =
1383 serde_json::from_str(&out.to_string_lossy()).expect("structured error JSON");
1384 assert!(
1385 payload["error"]
1386 .as_str()
1387 .is_some_and(|error| error.contains("interactive UI")),
1388 "unexpected payload: {payload}"
1389 );
1390 crate::host_free_string(out);
1391
1392 let mut out = StbString::empty();
1395 assert_eq!(
1396 trampoline_runtime_action(20, StbStringRef::from_str("{}"), &mut out, user_data),
1397 2
1398 );
1399 crate::host_free_string(out);
1400 }
1401
1402 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1405 async fn v2_dispatch_routes_set_status_action_18() {
1406 let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
1407 prompt: String::new(),
1408 saw: Mutex::new(Vec::new()),
1409 });
1410 let status = crate::status::ExtensionStatusMailbox::new();
1411 let bridge = ActionBridge::with_reload_and_ui(
1412 tokio::runtime::Handle::current(),
1413 host,
1414 Arc::new(|| Box::pin(async {})),
1415 UiDialogMailbox::new(),
1416 status.clone(),
1417 crate::editor_text::EditorTextMailbox::new(),
1418 );
1419 let user_data = Arc::as_ptr(&bridge) as *mut c_void;
1420
1421 let mut out = StbString::empty();
1422 let rc = trampoline_runtime_action(
1423 18,
1424 StbStringRef::from_str(r#"{"key":"langfuse","value":"langfuse ✓ (trace sent)"}"#),
1425 &mut out,
1426 user_data,
1427 );
1428 assert_eq!(rc, 0);
1429 assert_eq!(status.text(), "langfuse ✓ (trace sent)");
1430 crate::host_free_string(out);
1431
1432 let mut out = StbString::empty();
1434 assert_eq!(
1435 trampoline_runtime_action(
1436 18,
1437 StbStringRef::from_str(r#"{"key":"langfuse","value":""}"#),
1438 &mut out,
1439 user_data
1440 ),
1441 0
1442 );
1443 assert_eq!(status.text(), "");
1444 crate::host_free_string(out);
1445
1446 let mut out = StbString::empty();
1448 assert_eq!(
1449 trampoline_runtime_action(18, StbStringRef::from_str("{}"), &mut out, user_data),
1450 1
1451 );
1452 crate::host_free_string(out);
1453 }
1454}