Skip to main content

rpi_extensions/
actions.rs

1//! B5a — the plugin→host `runtime_action` bridge (inverted FFI).
2//!
3//! A plugin invokes `PluginApi::runtime_action` to drive the harness (send a
4//! message, switch models, fork a session, reload extensions, …). Unlike the
5//! register trampolines — which run synchronously inside the selected register
6//! entrypoint
7//! and recover host state via the thread-local `CURRENT_HOST_API` —
8//! `runtime_action` is called **post-register**, from (a) a `spawn_blocking`
9//! pool thread mid-tool-drive, or (b) a foreign thread the plugin spawned
10//! itself. Neither has the thread-local set, and the host cannot predict which
11//! threads a plugin will call from. Thread-local is the wrong tool here.
12//!
13//! The verified-correct recovery channel is [`PluginApi::user_data`]: it is
14//! `Send+Sync`, populated at vtable build, passed back unchanged on every call,
15//! and the SDK designates it "the host's opaque context". Today every register
16//! trampoline ignores `user_data` (the register path uses the thread-local), so
17//! repurposing `user_data` for the action bridge breaks nothing.
18//!
19//! [`ActionBridge`] holds a [`tokio::runtime::Handle`] **captured at build
20//! time** (the host is on the runtime when it constructs the bridge) — the fix
21//! for the foreign-thread case: `Handle::spawn` works from any thread, no
22//! ambient runtime needed. The real [`trampoline_runtime_action`] derefs
23//! `user_data` as `&ActionBridge`, drives the host's async dispatch on the
24//! runtime via a `std::sync::mpsc::sync_channel(1)`, and parks the plugin thread
25//! on `rx.recv()` (STD — not `tokio::oneshot`, whose `recv` needs a runtime the
26//! plugin's foreign thread lacks).
27//!
28//! ## Cycle-free leaf DAG
29//!
30//! [`RuntimeActionHost`] is defined here (NOT in `rpi-harness`) so
31//! `rpi-extensions` stays a leaf: the trait names only JSON + primitives — no
32//! `rpi-harness` types cross. The host impl (`HarnessActionHost`) lives in
33//! `rpi-cli`, where it can name the harness freely; `rpi-extensions` only
34//! carries the async surface. This preserves the documented DAG
35//! (`lib.rs:10-16`: `rpi-extensions` does NOT depend on `rpi-harness`).
36
37use 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/// A pending host UI request emitted by a plugin runtime action.
46///
47/// The request and tool-call ids are intentionally separate: a single tool
48/// call may ask more than one question, while concurrent tool calls must never
49/// consume one another's answers. `raw` retains the complete action envelope;
50/// `ui` is the normalized UI payload that TUI renderers generally need.
51#[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/// Thread-safe mailbox connecting plugin runtime actions to an interactive
72/// host (normally the TUI). It deliberately carries only JSON and primitives,
73/// so the extension crate remains independent of the UI crate.
74#[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    /// Mark an interactive consumer as available. Re-attaching is idempotent.
97    pub fn attach(&self) {
98        self.state
99            .lock()
100            .expect("ui dialog mailbox poisoned")
101            .attached = true;
102    }
103
104    /// Detach the consumer and cancel every outstanding request. This prevents
105    /// a TUI restart/reload from leaving plugin polls blocked forever.
106    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    /// Remove and return the next request for presentation by the TUI.
124    /// Cancelled/answered requests are skipped; duplicate `open` calls never
125    /// enqueue the same request id twice.
126    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    /// Supply an answer for a request. Repeating the same operation is
147    /// idempotent; answering a cancelled/unknown request is an explicit error.
148    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    /// Mark one request cancelled. The terminal state remains visible to the
167    /// plugin's next `poll`, then is reclaimed by that poll.
168    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    /// Cancel all requests currently known to the mailbox.
184    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    /// Poll a request and consume a terminal answer/cancellation. Pending
194    /// polls are cheap and preserve the request for subsequent calls.
195    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    /// Parse and execute the JSON action envelope used by runtime action 17.
229    /// Supported operations are `open`, `poll`, `cancel`; `response` is also
230    /// accepted as a convenience for hosts that proxy answers through JSON.
231    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/// The host-side implementation the bridge delegates to. Defined in
307/// `rpi-extensions` (NOT `rpi-harness`) so the crate DAG stays a leaf: this is a
308/// trait the **host** (`rpi-cli`) implements over the harness — `rpi-extensions`
309/// only names the async surface + carries JSON params/results. No `rpi-harness`
310/// types appear in the trait.
311///
312/// Each method corresponds to one [`RuntimeActionId`] variant. Complex args
313/// arrive as parsed JSON (`serde_json::Value`); complex results return as
314/// `serde_json::Value`. The host maps its native types (Model, AgentMessage, …)
315/// to/from JSON at the impl boundary. Errors are `String` (become the action's
316/// nonzero `i32` + `{"error": msg}` JSON on the plugin side).
317///
318/// The 18 methods map 1:1 to [`RuntimeActionId`]; `dispatch` below is the
319/// exhaustive switch that connects the FFI id to the method.
320#[async_trait::async_trait]
321pub trait RuntimeActionHost: Send + Sync {
322    /// `SendMessage` — drive a full agent run from an assistant/user message.
323    async fn send_message(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
324    /// `SendUserMessage` — drive a run from a user-text message.
325    async fn send_user_message(&self, args: serde_json::Value)
326        -> Result<serde_json::Value, String>;
327    /// `AppendEntry` — append a raw entry to the session transcript (no run).
328    async fn append_entry(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
329    /// `SetSessionName` — set the session's display name.
330    async fn set_session_name(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
331    /// `GetActiveTools` — the active tool-name list.
332    async fn get_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
333    /// `SetActiveTools` — replace the active tool-name list.
334    async fn set_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
335    /// `SetModel` — switch the active model (by id; host resolves to a `Model`).
336    async fn set_model(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
337    /// `GetThinkingLevel` — the current thinking level.
338    async fn get_thinking_level(
339        &self,
340        args: serde_json::Value,
341    ) -> Result<serde_json::Value, String>;
342    /// `SetThinkingLevel` — set the thinking level.
343    async fn set_thinking_level(
344        &self,
345        args: serde_json::Value,
346    ) -> Result<serde_json::Value, String>;
347    /// `Compact` — compact the session transcript.
348    async fn compact(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
349    /// `GetSystemPrompt` — the live composed system prompt.
350    async fn get_system_prompt(&self, args: serde_json::Value)
351        -> Result<serde_json::Value, String>;
352    /// `NewSession` — start a fresh session and switch to it.
353    async fn new_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
354    /// `Fork` — fork the current session and switch to the fork.
355    async fn fork(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
356    /// `NavigateTree` — navigate/rewind the session tree.
357    async fn navigate_tree(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
358    /// `SwitchSession` — hot-switch to an existing session by id.
359    async fn switch_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
360    /// `Reload` — re-run extension discovery + Part-A resource loaders (a CLI
361    /// concern; the host impl wires it to the `ActionBridge.reload` callback in
362    /// B5d — until then this returns an "unsupported" error string).
363    async fn reload(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
364
365    /// `GetCliFlag` — read a parsed extension CLI flag. Args are
366    /// `{"name":"flag"}` and the result is `{"value": <bool|string|null>}`.
367    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    /// `UiDialog` fallback for hosts that do not install an interactive
372    /// mailbox. The default is deliberately an error so headless runs cannot
373    /// accidentally report a fabricated user answer.
374    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
379/// The host-side bridge carried in [`PluginApi::user_data`] so
380/// [`trampoline_runtime_action`] can recover the harness state from any thread.
381///
382/// `runtime: Handle` is captured at build time (the host is on the runtime when
383/// it constructs the bridge) — this is the foreign-thread fix. `host` is the
384/// `rpi-cli` impl over the harness. `reload` is a CLI-owned callback that
385/// re-runs extension discovery + Part-A loaders (a CLI concern, NOT a harness
386/// op) — wired by `rpi-cli` in B5d via [`reload_callback_from_mailbox`].
387///
388/// ## Staleness (B5d)
389///
390/// `active: Arc<AtomicBool>` is shared with a [`ReloadMailbox`]-driven swap
391/// site. A `/reload` (TUI command OR a plugin's `runtime_action(Reload)`) builds
392/// a fresh `ExtensionSession` + a fresh `ActionBridge`, calls
393/// [`invalidate`](Self::invalidate) on the old bridge, and swaps the new one in.
394/// In-flight `runtime_action` calls that recovered the OLD bridge from
395/// `user_data` (the pointer a plugin stored during the prior `register`) then
396/// hit the staleness guard in [`run_action`] and fail with a structured error
397/// instead of driving a half-swapped harness. (Plugins load fresh on reload,
398/// handing them the NEW bridge pointer; the guard only catches the race window
399/// where an old call is still parked on `rx.recv()`.)
400///
401/// Held behind `Arc` (pointer-stable for the bridge's lifetime via
402/// [`Arc::as_ptr`]); `rpi-cli` keeps one clone for the session lifetime so the
403/// pointer a plugin stored during register stays valid post-register. (The
404/// transient `HostApi` built per `load_one` holds a clone only during register
405/// — when it drops after `take_registry`, the master `Arc` in `rpi-cli` keeps
406/// the allocation alive.)
407pub struct ActionBridge {
408    /// Captured at build time from a thread running the target runtime.
409    pub(crate) runtime: Handle,
410    /// The host impl (`HarnessActionHost` in rpi-cli).
411    pub(crate) host: Arc<dyn RuntimeActionHost>,
412    /// B5d reload callback; `None` until the TUI wires `/reload`.
413    pub(crate) reload:
414        Option<Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>>,
415    /// Session-scoped UI mailbox. It is cloned into reload-created bridges so
416    /// a TUI attachment and in-flight requests survive extension reloads.
417    ui_dialog: UiDialogMailbox,
418    /// Session-scoped extension status registry (`SetStatus` runtime action).
419    /// Shared with the TUI, which polls [`ExtensionStatusMailbox::revision`]
420    /// and repaints the footer only when an extension actually wrote.
421    ext_status: crate::status::ExtensionStatusMailbox,
422    /// Session-scoped editor-text queue (`SetEditorText` runtime action). Shared
423    /// with the TUI, which drains it once per tick and writes the draft into the
424    /// prompt editor.
425    editor_text: crate::editor_text::EditorTextMailbox,
426    /// B5d staleness flag. Shared so [`invalidate`] flips it for every clone.
427    /// `true` while this bridge is the live session's bridge.
428    active: Arc<AtomicBool>,
429}
430
431impl ActionBridge {
432    /// Build a bridge. The `Handle` MUST be captured from a thread running the
433    /// target runtime (pi-cli builds the bridge on the async main thread).
434    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    /// Same as [`new`](Self::new) with a reload callback (B5d wires this via
447    /// [`reload_callback_from_mailbox`]).
448    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    /// Build a bridge with an explicit session-scoped UI mailbox.
464    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    /// `with_reload` variant that preserves a mailbox across bridge swaps.
481    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    /// Clone the session mailbox for TUI attachment or a reload-created bridge.
501    pub fn ui_dialog_mailbox(&self) -> UiDialogMailbox {
502        self.ui_dialog.clone()
503    }
504
505    /// Clone the session status registry (TUI rendering + reload-created bridges).
506    pub fn extension_status_mailbox(&self) -> crate::status::ExtensionStatusMailbox {
507        self.ext_status.clone()
508    }
509
510    /// Clone the session editor-text queue (TUI drain + reload-created bridges).
511    pub fn editor_text_mailbox(&self) -> crate::editor_text::EditorTextMailbox {
512        self.editor_text.clone()
513    }
514
515    /// Mark this bridge stale (B5d). A `/reload` that swaps in a fresh bridge
516    /// calls this on the old one so in-flight `runtime_action` calls parked on
517    /// the old `user_data` pointer fail fast with a staleness error instead of
518    /// driving the swapped-out session. Idempotent.
519    pub fn invalidate(&self) {
520        self.active.store(false, Ordering::SeqCst);
521    }
522
523    /// Whether this bridge is still the live session's bridge.
524    pub fn is_active(&self) -> bool {
525        self.active.load(Ordering::SeqCst)
526    }
527
528    /// B5d: clone the host impl so a `/reload` can build a FRESH `ActionBridge`
529    /// over the SAME `RuntimeActionHost` (the host's harness cell already points
530    /// at the live harness — the harness is NOT rebuilt on reload — so the host
531    /// is reusable across reloads; only the bridge's staleness flag + reload
532    /// callback differ). The fresh bridge gets a fresh `active` flag (true) +
533    /// the reload callback the TUI installed; the old bridge is `invalidate`d.
534    pub fn clone_host(&self) -> Arc<dyn RuntimeActionHost> {
535        Arc::clone(&self.host)
536    }
537}
538
539/// A reload-signal mail slot (B5d). The reload callback (built by
540/// [`reload_callback_from_mailbox`]) captures a clone; the TUI installs a
541/// `tokio` unbounded sender after it starts. When a plugin calls
542/// `runtime_action(Reload)`, the callback signals `()` (if a TUI is installed)
543/// and the TUI performs the reload **asynchronously** — the plugin's call
544/// returns `Ok(null)` immediately, so the calling plugin's cdylib is NOT
545/// unmapped while its `runtime_action` frame is still on the stack (the reload,
546/// which drops the old keepalive, happens after the call returns). This breaks
547/// the self-unmapping race a synchronous plugin-initiated reload would have.
548///
549/// rpi-extensions carries only `()` (no pi-cli `TuiMessage` type) — preserving
550/// the leaf DAG. The TUI owns the receiver + the actual reload routine.
551#[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    /// A fresh empty mail slot (no TUI installed yet).
566    pub fn new() -> Self {
567        Self::default()
568    }
569
570    /// Install the TUI's reload-signal sender (after the TUI starts). Replaces
571    /// any prior sender. The TUI drops the receiver on shutdown; a sender held
572    /// here keeps the channel half-open, so [`clear`] on shutdown is advised.
573    pub fn install(&self, tx: tokio::sync::mpsc::UnboundedSender<()>) {
574        *self.tx.lock().unwrap() = Some(tx);
575    }
576
577    /// Signal a reload (plugin-initiated via `runtime_action(Reload)`).
578    /// `Ok(())` if a TUI is installed (the signal was enqueued; the TUI may
579    /// still be mid-reload). `Err(())` if no TUI is installed (the host returns
580    /// a "reload not available" error to the plugin).
581    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    /// Drop the installed sender (TUI shutdown). Idempotent.
593    pub fn clear(&self) {
594        *self.tx.lock().unwrap() = None;
595    }
596}
597
598/// Build the reload callback the bridge carries, backed by a [`ReloadMailbox`].
599/// When a plugin calls `runtime_action(Reload)`, the bridge's spawn site awaits
600/// this callback, which signals the TUI (if installed) and returns; the plugin
601/// receives `Ok(null)` and the TUI performs the reload asynchronously. If no
602/// TUI is installed, the callback returns without signalling and the host's
603/// [`RuntimeActionHost::reload`] fallback surfaces the "not configured" error.
604pub 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
615// `Handle` is Send+Sync, `Arc<dyn RuntimeActionHost>` (with `Send + Sync` bound)
616// is Send+Sync, and the reload closure is `Send + Sync` — so `ActionBridge` is
617// naturally Send+Sync; no manual unsafe impl needed.
618
619/// Dispatch one action to the host. Async — runs on the bridge's runtime.
620/// Handles all 19 ids; `Reload` delegates to [`RuntimeActionHost::reload`]
621/// (the "no callback configured" fallback). When the bridge has a reload
622/// callback, the spawn site intercepts `Reload` and awaits the callback
623/// instead (a CLI concern, not a harness op) — this helper is the plain
624/// host-only path.
625async 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        // UI-only action: handled by the bridge (no harness call), exactly like
653        // `UiDialog`. Written straight into the shared registry the TUI polls.
654        RuntimeActionId::SetStatus => ext_status.handle(args),
655        // Editor-only action: served by the bridge (no harness call), exactly
656        // like `SetStatus`/`UiDialog`. The TUI drains the queue each tick.
657        RuntimeActionId::SetEditorText => editor_text.handle(args),
658    }
659}
660
661/// The real `runtime_action` trampoline — replaces `stub_runtime_action` when a
662/// bridge is present (see [`HostApi::build_vtable`](crate::HostApi)).
663///
664/// Recovers `&ActionBridge` from `user_data`, parses `args_json`, drives the
665/// host's async dispatch on the bridge's runtime via `Handle::spawn`, and parks
666/// the plugin thread on a std `mpsc` `recv` (works from ANY thread — no ambient
667/// runtime needed, which is the load-bearing property for foreign plugin
668/// threads).
669///
670/// ## Return codes
671/// - `0` — success; `*out` written with the result JSON (host-owned
672///   [`StbString`]; the plugin frees it via the host `free_string` from the
673///   vtable).
674/// - `1` — host-level error; `*out` written with `{"error": msg}` JSON.
675/// - `2` — unknown numeric action id; `*out` contains a structured error and
676///   no host method is dispatched.
677/// - `-1` — no bridge present (`user_data` null; should not happen when wired).
678/// - `-2` — the spawned task dropped its sender without sending (runtime
679///   shutdown / dispatch panic); no result available.
680///
681/// The whole body is `catch_unwind`-wrapped — a panic across FFI ⇒ abort (same
682/// policy as the tool partial callback, `tool.rs:206`).
683pub 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            // Highest id this ABI defines — bump when adding an action.
693            u32::from(RuntimeActionId::SetEditorText),
694            args_json,
695            out,
696            user_data,
697        )
698    }));
699    match outcome {
700        Ok(rc) => rc,
701        Err(_) => {
702            // A panic in the host-side dispatch was caught. Do not abort the
703            // process: report a host-level error to the caller (documented
704            // code `1`) with a structured payload when `out` is writable.
705            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
718/// Inner synchronous driver (split out so the `catch_unwind` wrapper is clean).
719fn 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    // Validate the raw FFI integer before dereferencing host state or entering
727    // the enum-based dispatch. Unknown values are ordinary protocol errors;
728    // they never become invalid Rust enum discriminants.
729    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                // SAFETY: `out` is non-null and points to the caller-provided
738                // output slot. The plugin reclaims this host allocation via
739                // `host_free_string` from the vtable.
740                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    // SAFETY: the host guarantees `user_data` points at a live `ActionBridge`.
752    // `rpi-cli` builds one `Arc<ActionBridge>` per session and keeps it for the
753    // harness lifetime; `Arc::as_ptr` is pointer-stable while any clone lives.
754    // We only borrow for the duration of this call.
755    let bridge: &ActionBridge = unsafe { &*(user_data as *const ActionBridge) };
756
757    // B5d staleness guard: a `/reload` that swapped in a fresh bridge calls
758    // `invalidate` on the old one. A plugin that still holds the old pointer
759    // (stored during the prior `register`) must not drive the swapped-out
760    // session. Surface a structured "stale bridge" error so the plugin's
761    // `runtime_action` returns nonzero + `{"error": ...}` instead of racing
762    // the swap. (The new bridge's pointer was handed to the reloaded plugins;
763    // this guard only catches the race window where an old call is still parked.)
764    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    // Parse args. An empty/invalid JSON blob collapses to `{}` — getters ignore
779    // args; setters that require a field surface a clear error string.
780    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    // Drive the host's async dispatch on the bridge's runtime. STD mpsc so the
789    // plugin thread can recv from any thread (no ambient runtime). sync_channel
790    // (1): bounded; the send completes once the value is delivered. rx.recv()
791    // parks the plugin thread until the spawn finishes (or its sender drops).
792    let (tx, rx) = mpsc::sync_channel::<Result<serde_json::Value, String>>(1);
793    // Clone the bridge's host + reload callback into the spawned task. We pass
794    // an owned `Arc<dyn RuntimeActionHost>` plus a reload-option snapshot so the
795    // `dispatch` helper has everything it needs without borrowing `bridge`.
796    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        // Same reasoning as `UiDialog`: this action never touches the harness,
803        // so it must not need a Tokio worker. A plugin calling it from inside a
804        // single-threaded runtime (a tool poll callback, say) would otherwise
805        // park that executor and deadlock.
806        std::thread::spawn(move || {
807            let _ = tx.send(ext_status.handle(args));
808        });
809    } else if action == RuntimeActionId::SetEditorText {
810        // Editor-only, like `SetStatus`: no harness call, so keep it off the
811        // Tokio worker for the same single-thread-runtime reason.
812        std::thread::spawn(move || {
813            let _ = tx.send(editor_text.handle(args));
814        });
815    } else if action == RuntimeActionId::UiDialog {
816        // UiDialog is intentionally synchronous at the plugin ABI boundary:
817        // `open` waits until the TUI answers. Never park that wait inside the
818        // Tokio worker that services the bridge. A SEARCH/extension tool that
819        // invokes `ui_request/open` from a single-thread runtime would
820        // otherwise block the executor before the TUI can deliver the answer.
821        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            // If the plugin thread already moved on (dropped rx), discard — a
837            // send error is NOT a host fault.
838            let _ = tx.send(r);
839        });
840    }
841
842    let result = match rx.recv() {
843        Ok(r) => r,
844        Err(_) => {
845            // Spawned task dropped the sender without sending: runtime shutdown
846            // or the dispatch future panicked (caught inside dispatch? no —
847            // dispatch is plain async, a panic would propagate to the spawn and
848            // drop the sender). No result to return.
849            return -2;
850        }
851    };
852
853    // Write the result (or error) into `*out` as a host-owned StbString. The
854    // plugin frees it via the vtable's `free_string` (= `host_free_string`).
855    if out.is_null() {
856        // Nothing to write to; still report the outcome via the return code.
857        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    // SAFETY: `out` is a valid `*mut StbString` the plugin provided for this
874    // call (null checked above). `from_string` allocates a `Box<[u8]>` the host
875    // owns; the plugin reclaims it via `host_free_string` (which reconstructs
876    // the Box from ptr+len — matches `from_string`'s allocation, same pattern
877    // used by translate.rs/tool.rs).
878    unsafe {
879        *out = StbString::from_string(payload);
880    }
881    rc
882}
883
884// ===========================================================================
885// Tests — round-trip the real trampoline + dispatch + Handle::spawn + mpsc
886// against a mock host. This is the B5a unit proof: plugin→host `runtime_action`
887// recovers the `ActionBridge` via `user_data`, drives the host's async method on
888// the runtime, parks the caller on `rx.recv()`, and writes the result JSON back
889// through `*out` (freed via `host_free_string`). No cdylib needed — the trampoline
890// is the same `extern "C" fn` a plugin's vtable carries.
891// ===========================================================================
892#[cfg(test)]
893mod tests {
894    use super::*;
895    use std::sync::Mutex;
896
897    /// A minimal `RuntimeActionHost` that answers `get_system_prompt` with a
898    /// canned string and `reload` with Ok(null); every other action returns an
899    /// "unimplemented" error. Enough to prove the dispatch switch + the async
900    /// spawn + the mpsc round-trip + the StbString write.
901    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    /// NOTE: these tests use `flavor = "multi_thread"`. The trampoline parks the
989    /// caller on a std `mpsc::rx.recv()` (sync blocking) while the dispatch runs
990    /// via `Handle::spawn` on the runtime. Under a current-thread runtime the
991    /// test's own worker is the only thread that can poll the spawned task —
992    /// blocking it on `recv` self-deadlocks. In the real host the caller is a
993    /// plugin / `spawn_blocking` thread (never a runtime worker), so there is no
994    /// deadlock; multi_thread here mirrors that (another worker runs the spawn
995    /// while the test thread parks).
996    #[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        // Build a StbStringRef for the args. `{}` — getters ignore it.
1009        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        // Read the result JSON back + reclaim the host-owned StbString.
1022        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        // The host saw exactly the one action. `host_for_assert` is a clone of
1028        // the `Arc<MockHost>` kept before it was coerced to the trait object.
1029        let saw = host_for_assert.saw.lock().unwrap().clone();
1030        assert_eq!(saw, vec![RuntimeActionId::GetSystemPrompt]);
1031    }
1032
1033    /// The `SetEditorText` runtime action must reach the bridge's editor-text
1034    /// mailbox through the ABI trampoline. This is the wiring a plugin relies on
1035    /// (a voice extension writes a transcription draft here); a broken action id
1036    /// or a dropped dispatch would be invisible to the plugin — it only sees
1037    /// `ok: true` — so pin it here.
1038    #[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        // The queued edit is what the host will apply to the prompt editor.
1067        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        // A bridge with a reload callback: the spawn site intercepts Reload and
1090        // runs the callback instead of the host's `reload` method. Proves the
1091        // bridge-level special-casing (the host impl is the fallback only).
1092        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        // The callback ran once; the host's `reload` did NOT.
1122        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    /// B5d: an invalidated bridge rejects `runtime_action` with a stale-bridge
1128    /// error instead of dispatching. A `/reload` calls `invalidate` on the old
1129    /// bridge; an in-flight call that still holds the old pointer must fail
1130    /// fast rather than drive the swapped-out session.
1131    #[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        // Invalidate (as a `/reload` would on the old bridge).
1144        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        // Nonzero (error), and the host method never ran (no dispatch).
1156        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    /// `ReloadMailbox` + `reload_callback_from_mailbox` round-trip: signalling
1229    /// fires the installed receiver; an uninstalled mailbox yields `Err` (the
1230    /// host's "not configured" fallback). Exercises the B5d reload-signal path
1231    /// the TUI installs.
1232    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1233    async fn reload_mailbox_signals_installed_receiver() {
1234        let mailbox = ReloadMailbox::new();
1235        // No receiver installed yet ⇒ signal fails.
1236        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    // ---- UiDialogMailbox (runtime action 17 / ask_user) ----
1251
1252    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    /// Headless hosts (nothing attached) must fail loudly rather than fabricate
1264    /// a user answer.
1265    #[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        // A pending poll is non-destructive and remains available.
1285        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        // Polling consumes the terminal entry.
1295        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        // Answer the SECOND request first; the first must stay pending.
1321        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        // Re-opening without a consumer is an explicit error again.
1341        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    /// The v2 trampoline must route action 17 into the session mailbox rather
1358    /// than rejecting it as unknown, and a detached mailbox must surface the
1359    /// explicit "requires an interactive UI" error (headless contract).
1360    #[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        // A genuinely unknown id is still rejected (no silent acceptance).
1392        // 20 is one past the highest defined action (`SetEditorText` = 19).
1393        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    /// Action 18 (`SetStatus`) is bridge-local, like `UiDialog`: it writes the
1402    /// shared registry the TUI polls and never touches the harness.
1403    #[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        // Clearing through the same action empties the line again.
1432        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        // A missing key is a host-level error (rc=1), not an unknown action.
1446        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}