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, either from a host tool driver or
9//! a foreign worker. `PluginApi::user_data` carries an opaque, non-reused handle
10//! resolved through a weak registry, never a dereferenceable bridge address.
11//! Expired registrations fail safely, including candidate reload rollback.
12//!
13//! Synchronous tool callbacks inherit a host-owned invocation via a scoped
14//! thread-local; workers forward the invocation handle and capability injected
15//! into `__rpi`. ChildAgent rejects registration-only, cancelled and child
16//! invocations. A cached registration cannot override a child's driver scope.
17//!
18//! [`ActionBridge`] captures a Tokio [`Handle`] at construction. Dispatch can
19//! therefore spawn from foreign threads and return over a standard synchronous
20//! channel without depending on the plugin thread having a Tokio runtime.
21//!
22//! ## Cycle-free leaf DAG
23//!
24//! [`RuntimeActionHost`] is defined here (NOT in `rpi-harness`) so
25//! `rpi-extensions` stays a leaf: the trait names only JSON + primitives — no
26//! `rpi-harness` types cross. The host impl (`HarnessActionHost`) lives in
27//! `rpi-cli`, where it can name the harness freely; `rpi-extensions` only
28//! carries the async surface. This preserves the documented DAG
29//! (`lib.rs:10-16`: `rpi-extensions` does NOT depend on `rpi-harness`).
30
31use std::collections::{HashMap, VecDeque};
32use std::ffi::c_void;
33use std::sync::atomic::{AtomicBool, Ordering};
34use std::sync::{mpsc, Arc, Mutex, OnceLock, Weak};
35
36// Opaque, non-reused IDs, never addresses. A copied PluginApi may outlive its
37// registration (e.g. a failed reload); resolving it must not dereference freed memory.
38struct RegistryEntry {
39    bridge: Weak<ActionBridge>,
40    active: Weak<AtomicBool>,
41}
42static BRIDGES: OnceLock<Mutex<HashMap<usize, RegistryEntry>>> = OnceLock::new();
43fn bridges() -> &'static Mutex<HashMap<usize, RegistryEntry>> {
44    BRIDGES.get_or_init(Mutex::default)
45}
46thread_local! {
47    static CURRENT_INVOCATION: std::cell::RefCell<Option<Arc<ActionBridge>>> = const { std::cell::RefCell::new(None) };
48}
49pub(crate) struct InvocationGuard {
50    previous: Option<Arc<ActionBridge>>,
51    _thread_bound: std::marker::PhantomData<std::rc::Rc<()>>,
52}
53impl Drop for InvocationGuard {
54    fn drop(&mut self) {
55        CURRENT_INVOCATION.with(|slot| *slot.borrow_mut() = self.previous.take());
56    }
57}
58
59use rpi_plugin_sdk::{RuntimeActionId, StbString, StbStringRef};
60use tokio::runtime::Handle;
61
62/// Prefix a plugin uses to mark a `requestId` as **not the TUI's to consume**.
63///
64/// Why it exists: the interactive TUI and plugins share one [`UiDialogMailbox`].
65/// Without this convention a plugin's question (a remote UI's permission gate,
66/// say) gets taken by the TUI and drawn in the terminal — while the user is
67/// looking at a remote client, which sees nothing.
68///
69/// Paired with [`UiDialogMailbox::take_pending_filtered`] (the TUI passes
70/// `|r| !is_reserved(&r.request_id)`).
71pub const PLUGIN_RESERVED_PREFIX: &str = "pidingo:";
72
73/// A pending host UI request emitted by a plugin runtime action.
74///
75/// The request and tool-call ids are intentionally separate: a single tool
76/// call may ask more than one question, while concurrent tool calls must never
77/// consume one another's answers. `raw` retains the complete action envelope;
78/// `ui` is the normalized UI payload that TUI renderers generally need.
79#[derive(Clone, Debug, PartialEq)]
80pub struct UiDialogRequest {
81    pub request_id: String,
82    pub tool_call_id: Option<String>,
83    pub ui: serde_json::Value,
84    pub raw: serde_json::Value,
85}
86
87struct UiDialogEntry {
88    request: UiDialogRequest,
89    answer: Option<serde_json::Value>,
90    cancelled: bool,
91}
92
93struct UiDialogState {
94    attached: bool,
95    /// Monotonic local attachment generation used to retire stale UI bridges
96    /// without allowing them to detach a newer bridge.
97    attachment_generation: u64,
98    /// An external UI (a relay) has taken over dialog delivery.
99    ///
100    /// While set, the local TUI must not take requests: both consumers draw
101    /// from the same `pending` queue, so whoever runs first wins and the other
102    /// never sees the question. With a remote client attached, the question has
103    /// to reach *that* client — the terminal is not where the user is looking.
104    external_takeover: bool,
105    pending: VecDeque<String>,
106    active: HashMap<String, UiDialogEntry>,
107    cancelled_tool_calls: std::collections::HashSet<String>,
108}
109
110/// Thread-safe mailbox connecting plugin runtime actions to an interactive
111/// host (normally the TUI). It deliberately carries only JSON and primitives,
112/// so the extension crate remains independent of the UI crate.
113#[derive(Clone)]
114pub struct UiDialogMailbox {
115    state: Arc<Mutex<UiDialogState>>,
116}
117
118impl Default for UiDialogMailbox {
119    fn default() -> Self {
120        Self::new()
121    }
122}
123
124impl UiDialogMailbox {
125    pub fn new() -> Self {
126        Self {
127            state: Arc::new(Mutex::new(UiDialogState {
128                attached: false,
129                attachment_generation: 0,
130                external_takeover: false,
131                pending: VecDeque::new(),
132                active: HashMap::new(),
133                cancelled_tool_calls: std::collections::HashSet::new(),
134            })),
135        }
136    }
137
138    /// Mark an interactive consumer as available. Re-attaching starts a new
139    /// local generation so stale bridge shutdown cannot retire its successor.
140    pub fn attach(&self) {
141        let _ = self.try_attach_with_generation();
142    }
143
144    /// Attach and return the local generation owned by this consumer.
145    ///
146    /// Generation exhaustion is a fail-closed condition: do not reuse the
147    /// final generation, because a stale bridge could then retire a newer
148    /// consumer with the same identity.
149    pub fn try_attach_with_generation(&self) -> Option<u64> {
150        // Attachment is an admission boundary. A poisoned mailbox cannot
151        // safely publish either the generation or the attached bit, so refuse
152        // rather than panic or partially admit an interactive consumer.
153        let mut state = self.state.lock().ok()?;
154        let generation = state.attachment_generation.checked_add(1)?;
155        state.attachment_generation = generation;
156        state.attached = true;
157        Some(generation)
158    }
159
160    /// Return the current local attachment generation, if the mailbox state
161    /// can be read safely.
162    pub fn attachment_generation(&self) -> Option<u64> {
163        self.state
164            .lock()
165            .ok()
166            .map(|state| state.attachment_generation)
167    }
168
169    /// Hand dialog delivery to an external UI (or take it back).
170    ///
171    /// The TUI and a relay both call "take"; without an owner, whichever polls
172    /// first wins and the other never sees the request — a third-party
173    /// extension's question can end up drawn in a terminal nobody is watching.
174    /// A caller that owns the user's attention (a remote client) sets this, and
175    /// the local TUI then skips taking entirely.
176    ///
177    /// Idempotent, and independent of [`Self::attach`]: the TUI stays "attached"
178    /// while a remote client is in charge, it just does not consume.
179    pub fn set_external_takeover(&self, takeover: bool) {
180        self.state
181            .lock()
182            .expect("ui dialog mailbox poisoned")
183            .external_takeover = takeover;
184    }
185
186    /// Whether an external UI currently owns dialog delivery.
187    pub fn external_takeover(&self) -> bool {
188        self.state
189            .lock()
190            .expect("ui dialog mailbox poisoned")
191            .external_takeover
192    }
193
194    /// Detach the consumer and cancel every outstanding request. This prevents
195    /// a TUI restart/reload from leaving plugin polls blocked forever.
196    pub fn detach(&self) {
197        // Compatibility retirement has no success channel. If the mailbox
198        // state is poisoned, refuse without claiming that ownership changed.
199        let Ok(mut state) = self.state.lock() else {
200            return;
201        };
202        Self::detach_locked(&mut state);
203    }
204
205    /// Detach only if this consumer still owns the current local generation.
206    /// A stale bridge is a no-op and cannot cancel a newer TUI's dialogs.
207    pub fn detach_if_generation(&self, generation: u64) -> bool {
208        // Retirement is also an ownership boundary. A poisoned mailbox cannot
209        // prove that this generation is current, so report no detachment
210        // instead of panicking or claiming that a live owner was retired.
211        let Ok(mut state) = self.state.lock() else {
212            return false;
213        };
214        if state.attachment_generation != generation {
215            return false;
216        }
217        Self::detach_locked(&mut state);
218        true
219    }
220
221    fn detach_locked(state: &mut UiDialogState) {
222        state.attached = false;
223        // Release ownership with the consumer. A stale takeover flag would make
224        // the TUI refuse every later dialog, so losing the relay client would
225        // leave the user unable to answer anything.
226        state.external_takeover = false;
227        state.pending.clear();
228        for entry in state.active.values_mut() {
229            entry.cancelled = true;
230            entry.answer = None;
231        }
232    }
233
234    /// Give dialog delivery back to the local TUI.
235    ///
236    /// Requests already taken by the relay but never answered are put back in
237    /// the queue so the TUI draws them. They are not answered or cancelled
238    /// here: fabricating a reply for a question nobody read would be worse than
239    /// asking it again.
240    ///
241    /// Returns the number of requests handed back.
242    pub fn release_takeover(&self) -> usize {
243        let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
244        state.external_takeover = false;
245        let mut requeued: Vec<String> = state
246            .active
247            .iter()
248            .filter(|(_, entry)| !entry.cancelled && entry.answer.is_none())
249            .map(|(request_id, _)| request_id.clone())
250            .filter(|request_id| !state.pending.contains(request_id))
251            .collect();
252        if requeued.is_empty() {
253            return 0;
254        }
255        let count = requeued.len();
256        // Stable order so a restored queue does not reshuffle the prompts.
257        requeued.sort();
258        for request_id in requeued.into_iter().rev() {
259            state.pending.push_front(request_id);
260        }
261        count
262    }
263
264    pub fn is_attached(&self) -> bool {
265        self.state.lock().ok().is_some_and(|state| state.attached)
266    }
267
268    /// Remove and return the next request for presentation by the TUI.
269    /// Cancelled/answered requests are skipped; duplicate `open` calls never
270    /// enqueue the same request id twice.
271    pub fn take_pending(&self) -> Option<UiDialogRequest> {
272        self.take_pending_filtered(|_| true)
273    }
274
275    /// Take a request for the local TUI, but only while no external UI owns
276    /// delivery.
277    ///
278    /// The takeover check and the dequeue must be one critical section. Checking
279    /// `external_takeover()` and then calling [`Self::take_pending_filtered`]
280    /// acquires the lock twice, and a relay can claim ownership in between: the
281    /// TUI would then dequeue a question meant for the remote client, so nobody
282    /// the user is watching ever sees it.
283    pub fn take_pending_unless_external<F>(&self, keep: F) -> Option<UiDialogRequest>
284    where
285        F: Fn(&UiDialogRequest) -> bool,
286    {
287        let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
288        if state.external_takeover {
289            return None;
290        }
291        Self::take_pending_locked(&mut state, keep)
292    }
293
294    /// Like [`take_pending`], but only takes a request `keep` accepts; the rest
295    /// **stay queued** for whoever they belong to.
296    ///
297    /// The TUI and plugins race on the same mailbox. When a plugin marks a
298    /// request as belonging to a host consumer (a remote UI's gate), the TUI
299    /// must not swallow it: the user would never see the question in the remote
300    /// client, while a duplicate pops up in the terminal.
301    ///
302    /// ## Reserved-prefix convention
303    ///
304    /// A `requestId` starting with [`PLUGIN_RESERVED_PREFIX`] is never taken by
305    /// the TUI. `take_pending()` takes everything (it passes `|_| true`), so
306    /// skipping reserved entries has to be explicit:
307    /// `take_pending_filtered(|r| !self.is_reserved(&r.request_id))`.
308    pub fn take_pending_filtered<F>(&self, keep: F) -> Option<UiDialogRequest>
309    where
310        F: Fn(&UiDialogRequest) -> bool,
311    {
312        let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
313        Self::take_pending_locked(&mut state, keep)
314    }
315
316    fn take_pending_locked<F>(
317        state: &mut std::sync::MutexGuard<'_, UiDialogState>,
318        keep: F,
319    ) -> Option<UiDialogRequest>
320    where
321        F: Fn(&UiDialogRequest) -> bool,
322    {
323        let mut scanned = 0usize;
324        let total = state.pending.len();
325        while scanned < total {
326            scanned += 1;
327            let Some(request_id) = state.pending.pop_front() else {
328                break;
329            };
330            let Some(entry) = state.active.get(&request_id) else {
331                continue;
332            };
333            if entry.cancelled || entry.answer.is_some() {
334                continue;
335            }
336            let request = entry.request.clone();
337            if keep(&request) {
338                return Some(request);
339            }
340            // Not mine — put it back for whoever should handle it.
341            state.pending.push_back(request_id);
342        }
343        None
344    }
345
346    /// Take **every request no plugin reserved** (the `RelayUiDialog` `take`).
347    ///
348    /// For "a remote UI takes over": while an external client is attached, a
349    /// third-party extension's question should be forwarded there instead of
350    /// popping up in the terminal. Reserved entries stay behind.
351    ///
352    /// Taken requests leave `pending` but stay in `active`, so a later
353    /// `respond` / `cancel` with the same `requestId` still resolves them.
354    pub fn take_all_unreserved(&self) -> Vec<UiDialogRequest> {
355        let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
356        let mut out: Vec<UiDialogRequest> = Vec::new();
357        // One pass does both: drain everything, then push back what stays.
358        let drained = std::mem::take(&mut state.pending);
359        for request_id in drained {
360            let Some(entry) = state.active.get(&request_id) else {
361                continue;
362            };
363            if entry.cancelled || entry.answer.is_some() {
364                continue;
365            }
366            if request_id.starts_with(PLUGIN_RESERVED_PREFIX) {
367                state.pending.push_back(request_id);
368            } else {
369                out.push(entry.request.clone());
370            }
371        }
372        out
373    }
374
375    /// Whether `request_id` is reserved by a plugin (the TUI must not consume it).
376    pub fn is_reserved(&self, request_id: &str) -> bool {
377        request_id.starts_with(PLUGIN_RESERVED_PREFIX)
378    }
379
380    pub fn pending_len(&self) -> usize {
381        self.state
382            .lock()
383            .expect("ui dialog mailbox poisoned")
384            .pending
385            .len()
386    }
387
388    /// Inspect lifecycle without consuming the answer reserved for a plugin.
389    pub fn is_pending(&self, request_id: &str) -> bool {
390        self.state
391            .lock()
392            .expect("ui dialog mailbox poisoned")
393            .active
394            .get(request_id)
395            .is_some_and(|entry| !entry.cancelled && entry.answer.is_none())
396    }
397
398    /// Supply an answer for a request. Repeating the same operation is
399    /// idempotent; answering a cancelled/unknown request is an explicit error.
400    pub fn respond(&self, request_id: &str, answer: serde_json::Value) -> Result<(), String> {
401        let mut state = self
402            .state
403            .lock()
404            .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
405        let entry = state
406            .active
407            .get_mut(request_id)
408            .ok_or_else(|| format!("unknown UI request `{request_id}`"))?;
409        if entry.cancelled {
410            return Err(format!("UI request `{request_id}` was cancelled"));
411        }
412        if entry.answer.is_none() {
413            entry.answer = Some(answer);
414        }
415        Ok(())
416    }
417
418    /// Mark one request cancelled. The terminal state remains visible to the
419    /// plugin's next `poll`, then is reclaimed by that poll.
420    pub fn cancel(&self, request_id: &str) -> Result<(), String> {
421        let mut state = self
422            .state
423            .lock()
424            .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
425        let entry = state
426            .active
427            .get_mut(request_id)
428            .ok_or_else(|| format!("unknown UI request `{request_id}`"))?;
429        entry.cancelled = true;
430        entry.answer = None;
431        state.pending.retain(|id| id != request_id);
432        Ok(())
433    }
434
435    /// Cancel all requests currently known to the mailbox.
436    pub fn cancel_all(&self) {
437        let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
438        state.pending.clear();
439        for entry in state.active.values_mut() {
440            entry.cancelled = true;
441            entry.answer = None;
442        }
443    }
444
445    /// Cancel approval requests belonging to one tool without disturbing
446    /// questions from concurrent tool calls.
447    pub fn cancel_tool_call(&self, tool_call_id: &str) {
448        let mut state = self.state.lock().expect("ui dialog mailbox poisoned");
449        // A callback can reach `open` just after the host cancels its call.
450        // Remember the cancellation so it cannot enqueue an orphan question.
451        state.cancelled_tool_calls.insert(tool_call_id.to_string());
452        for entry in state.active.values_mut() {
453            if entry.request.tool_call_id.as_deref() == Some(tool_call_id) {
454                entry.cancelled = true;
455                entry.answer = None;
456            }
457        }
458        let cancelled: std::collections::HashSet<String> = state
459            .active
460            .iter()
461            .filter(|(_, entry)| entry.cancelled)
462            .map(|(id, _)| id.clone())
463            .collect();
464        state.pending.retain(|id| !cancelled.contains(id));
465    }
466
467    /// Poll a request and consume a terminal answer/cancellation. Pending
468    /// polls are cheap and preserve the request for subsequent calls.
469    pub fn poll(&self, request_id: &str) -> Result<serde_json::Value, String> {
470        let mut state = self
471            .state
472            .lock()
473            .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
474        let terminal = match state.active.get(request_id) {
475            Some(entry) if entry.cancelled => Some(serde_json::json!({
476                "status": "cancelled",
477                "requestId": request_id,
478                "toolCallId": entry.request.tool_call_id,
479            })),
480            Some(entry) if entry.answer.is_some() => Some(serde_json::json!({
481                "status": "answered",
482                "requestId": request_id,
483                "toolCallId": entry.request.tool_call_id,
484                "answer": entry.answer.clone().unwrap_or(serde_json::Value::Null),
485            })),
486            Some(entry) => Some(serde_json::json!({
487                "status": "pending",
488                "requestId": request_id,
489                "toolCallId": entry.request.tool_call_id,
490            })),
491            None => None,
492        };
493        let Some(result) = terminal else {
494            return Err(format!("unknown UI request `{request_id}`"));
495        };
496        if result.get("status").and_then(serde_json::Value::as_str) != Some("pending") {
497            state.active.remove(request_id);
498        }
499        Ok(result)
500    }
501
502    /// Reclaim a terminal request that nobody will `poll` again.
503    ///
504    /// `cancel()` deliberately keeps the terminal entry visible so the owning
505    /// plugin can observe `cancelled` on its next `poll`, and `poll()` removes
506    /// it at that point. But a plugin that abandons a question (timeout, tool
507    /// cancellation, process abort) never polls again, leaving the entry in
508    /// `active` for the lifetime of the host. Callers that know no further
509    /// poll is coming use this to release it. Pending requests are never
510    /// removed: deleting one would silently strand the UI that is still
511    /// waiting for an answer.
512    /// Returns `true` when a terminal entry was actually removed.
513    pub fn forget(&self, request_id: &str) -> Result<bool, String> {
514        let mut state = self
515            .state
516            .lock()
517            .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
518        let Some(entry) = state.active.get(request_id) else {
519            return Ok(false);
520        };
521        if !entry.cancelled && entry.answer.is_none() {
522            return Err(format!("UI request `{request_id}` is still pending"));
523        }
524        state.active.remove(request_id);
525        state.pending.retain(|id| id != request_id);
526        Ok(true)
527    }
528
529    /// Parse and execute the JSON action envelope used by runtime action 17.
530    /// Supported operations are `open`, `poll`, `cancel`, `forget`; `response`
531    /// is also accepted as a convenience for hosts that proxy answers through
532    /// JSON.
533    pub fn handle(&self, args: serde_json::Value) -> Result<serde_json::Value, String> {
534        let op = args
535            .get("op")
536            .and_then(serde_json::Value::as_str)
537            .unwrap_or("open");
538        let request_id = || {
539            args.get("requestId")
540                .or_else(|| args.get("request_id"))
541                .and_then(serde_json::Value::as_str)
542                .map(str::to_owned)
543                .filter(|id| !id.trim().is_empty())
544                .ok_or_else(|| "missing non-empty `requestId`".to_string())
545        };
546        match op {
547            "open" => {
548                let id = request_id()?;
549                let mut state = self
550                    .state
551                    .lock()
552                    .map_err(|_| "ui dialog mailbox poisoned".to_string())?;
553                if !state.attached {
554                    return Err("ask_user requires an interactive UI".to_string());
555                }
556                if let Some(entry) = state.active.get(&id) {
557                    return Ok(if entry.cancelled {
558                        serde_json::json!({"status":"cancelled","requestId":id})
559                    } else if let Some(answer) = &entry.answer {
560                        serde_json::json!({"status":"answered","requestId":id,"answer":answer})
561                    } else {
562                        serde_json::json!({"status":"pending","requestId":id})
563                    });
564                }
565                let tool_call_id = args
566                    .get("toolCallId")
567                    .or_else(|| args.get("tool_call_id"))
568                    .and_then(serde_json::Value::as_str)
569                    .map(str::to_owned);
570                if tool_call_id
571                    .as_ref()
572                    .is_some_and(|id| state.cancelled_tool_calls.contains(id))
573                {
574                    return Ok(serde_json::json!({
575                        "status": "cancelled", "requestId": id, "toolCallId": tool_call_id,
576                    }));
577                }
578                let ui = args.get("ui").cloned().unwrap_or_else(|| args.clone());
579                rpi_plugin_sdk::dialogs::validate(&ui, tool_call_id.as_deref())?;
580                state.active.insert(
581                    id.clone(),
582                    UiDialogEntry {
583                        request: UiDialogRequest {
584                            request_id: id.clone(),
585                            tool_call_id: tool_call_id.clone(),
586                            ui,
587                            raw: args,
588                        },
589                        answer: None,
590                        cancelled: false,
591                    },
592                );
593                state.pending.push_back(id.clone());
594                Ok(serde_json::json!({"status":"pending","requestId":id,"toolCallId":tool_call_id}))
595            }
596            "poll" => self.poll(&request_id()?),
597            "cancel" => {
598                let id = request_id()?;
599                self.cancel(&id)?;
600                Ok(serde_json::json!({"status":"cancelled","requestId":id}))
601            }
602            "forget" => {
603                let id = request_id()?;
604                let removed = self.forget(&id)?;
605                Ok(serde_json::json!({"status":"forgotten","requestId":id,"removed":removed}))
606            }
607            "response" | "respond" => {
608                let id = request_id()?;
609                let answer = args
610                    .get("answer")
611                    .or_else(|| args.get("value"))
612                    .cloned()
613                    .unwrap_or(serde_json::Value::Null);
614                self.respond(&id, answer)?;
615                Ok(serde_json::json!({"status":"answered","requestId":id}))
616            }
617            other => Err(format!("unknown UI dialog operation `{other}`")),
618        }
619    }
620}
621
622/// Host-only, owner-bound UI writer. It contains no plugin callbacks or pointers.
623pub type SideQuestionSink =
624    Arc<dyn Fn(serde_json::Value) -> Result<serde_json::Value, String> + Send + Sync>;
625
626/// The host-side implementation the bridge delegates to. Defined in
627/// `rpi-extensions` (NOT `rpi-harness`) so the crate DAG stays a leaf: this is a
628/// trait the **host** (`rpi-cli`) implements over the harness — `rpi-extensions`
629/// only names the async surface + carries JSON params/results. No `rpi-harness`
630/// types appear in the trait.
631///
632/// Each method corresponds to one [`RuntimeActionId`] variant. Complex args
633/// arrive as parsed JSON (`serde_json::Value`); complex results return as
634/// `serde_json::Value`. The host maps its native types (Model, AgentMessage, …)
635/// to/from JSON at the impl boundary. Errors are `String` (become the action's
636/// nonzero `i32` + `{"error": msg}` JSON on the plugin side).
637///
638/// `dispatch` below connects the FFI id to the method; owner-scoped actions
639/// are routed directly by the plugin bridge.
640#[async_trait::async_trait]
641pub trait RuntimeActionHost: Send + Sync {
642    /// Action 30: an authenticated host-owned executing invocation, never registry JSON.
643    async fn tool_program(
644        &self,
645        capability: Arc<rpi_agent::tool_program::ToolProgram>,
646        args: serde_json::Value,
647    ) -> Result<serde_json::Value, String> {
648        capability.handle(args).await
649    }
650    /// Revoke side questions when their plugin bridge is retired.
651    fn cancel_side_questions(&self, _owner: u64) {}
652    /// Host-internal TUI snapshots; never exposed as a cross-owner plugin action.
653    fn side_question_revision(&self) -> u64 {
654        0
655    }
656    fn side_question_views(&self) -> Vec<serde_json::Value> {
657        Vec::new()
658    }
659    async fn side_question_ui(
660        &self,
661        _owner: u64,
662        _thread_id: String,
663        _args: serde_json::Value,
664    ) -> Result<serde_json::Value, String> {
665        Err("SideQuestion UI is not supported by this host".into())
666    }
667    /// Owner-scoped read-only inference, including host-owned UI publication.
668    async fn side_question(
669        &self,
670        _owner: u64,
671        _args: serde_json::Value,
672        _sink: SideQuestionSink,
673    ) -> Result<serde_json::Value, String> {
674        Err("SideQuestion is not supported by this host; upgrade rpi".into())
675    }
676
677    /// Refresh the host-side model selector after provider packages reload.
678    fn replace_model_catalog(&self, _models: Vec<rpi_ai::Model>) {}
679    /// Invalidate child handles owned by an unloading/reloaded plugin.
680    fn cancel_child_agents(&self, _owner: u64) {}
681    /// `SendMessage` — Pi-compatible `triggerTurn` and `deliverAs` scheduling.
682    /// Defaults append while idle and steer while running; explicit `true`
683    /// starts an idle run, `false` only updates context, and `nextTurn` waits
684    /// for a new explicit prompt. Results distinguish appended/queued/run.
685    async fn send_message(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
686    /// `SendUserMessage` — drive a run from a user-text message.
687    async fn send_user_message(&self, args: serde_json::Value)
688        -> Result<serde_json::Value, String>;
689    /// `AppendEntry` — append without starting a run. `customType`/`data`
690    /// persists extension data only. A `message` is durably queued during an
691    /// operation and committed after its current turn; the returned `entryId`
692    /// is reserved and may not yet resolve to a transcript entry. Optional
693    /// `expected: {sessionId, leafId, customType, entryId}` performs a conditional
694    /// write against that exact branch snapshot; a successful reply must confirm
695    /// `scoped: true`. Scoped messages additionally require `outboxKey` and must
696    /// be custom messages: acceptance is idempotent on the current branch and
697    /// pending context stays with its source state entry.
698    async fn append_entry(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
699    /// `SetSessionName` — set the session's display name.
700    async fn set_session_name(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
701    /// `GetActiveTools` — the active tool-name list.
702    async fn get_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
703    /// `SetActiveTools` — replace the active tool-name list.
704    async fn set_active_tools(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
705    /// `SetModel` — switch the active model (by id; host resolves to a `Model`).
706    async fn set_model(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
707    /// `GetThinkingLevel` — the current thinking level.
708    async fn get_thinking_level(
709        &self,
710        args: serde_json::Value,
711    ) -> Result<serde_json::Value, String>;
712    /// `SetThinkingLevel` — set the thinking level.
713    async fn set_thinking_level(
714        &self,
715        args: serde_json::Value,
716    ) -> Result<serde_json::Value, String>;
717    /// `Compact` — compact the session transcript.
718    async fn compact(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
719    /// `GetSystemPrompt` — the live composed system prompt.
720    async fn get_system_prompt(&self, args: serde_json::Value)
721        -> Result<serde_json::Value, String>;
722    /// `NewSession` — start a fresh session and switch to it.
723    async fn new_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
724    /// `Fork` — fork the current session and switch to the fork.
725    async fn fork(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
726    /// `NavigateTree` — navigate/rewind the session tree.
727    async fn navigate_tree(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
728    /// `SwitchSession` — hot-switch to an existing session by id.
729    async fn switch_session(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
730    /// `Reload` — re-run extension discovery + Part-A resource loaders (a CLI
731    /// concern; the host impl wires it to the `ActionBridge.reload` callback in
732    /// B5d — until then this returns an "unsupported" error string).
733    async fn reload(&self, args: serde_json::Value) -> Result<serde_json::Value, String>;
734
735    /// `ReloadModels` — re-read the model/provider catalog from disk **without**
736    /// reloading extensions.
737    ///
738    /// The cheap counterpart of [`Self::reload`]: it swaps the model catalog
739    /// and the provider runtime bindings, but leaves the extension registry,
740    /// the emitter and the event snapshot untouched — so an in-flight run keeps
741    /// receiving plugin events.
742    ///
743    /// Defaults to "not supported" so hosts that never wired it keep working.
744    async fn reload_models(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
745        Err("reload_models is not supported by this host".to_string())
746    }
747
748    /// `GetCliFlag` — read a parsed extension CLI flag. Args are
749    /// `{"name":"flag"}` and the result is `{"value": <bool|string|null>}`.
750    async fn get_cli_flag(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
751        Err("CLI flag lookup is not configured".to_string())
752    }
753
754    /// `UiDialog` fallback for hosts that do not install an interactive
755    /// mailbox. The default is deliberately an error so headless runs cannot
756    /// accidentally report a fabricated user answer.
757    async fn ui_dialog(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
758        Err("ask_user requires an interactive UI".to_string())
759    }
760
761    /// Enumerate the registered slash commands.
762    ///
763    /// Args: `{}`. Result: `{"commands":[{name, description, source}]}` where
764    /// `source` is `builtin` / `extension` / `prompt`. A host with no registry
765    /// returns an empty list (genuinely "none registered"), not an error: the
766    /// remote UI should degrade to "no completion available".
767    ///
768    /// Added because the plugin ABI had no way to enumerate commands, so a
769    /// remote client could not offer slash-command completion at all — it saw
770    /// an empty list and could not tell that apart from "no host attached".
771    async fn list_commands(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
772        Ok(serde_json::json!({ "commands": [] }))
773    }
774
775    /// Publish a freshly loaded extension registry to the host.
776    ///
777    /// Called after extension discovery **and after a successful `/reload`**, so
778    /// `ListCommands` keeps answering with the current command set. Hosts that
779    /// do not cache a registry (RPC mode reads the snapshot directly) keep the
780    /// default no-op.
781    ///
782    /// Why it is on the trait instead of a downcast: `/reload` only has the
783    /// `Arc<dyn RuntimeActionHost>` from the old bridge, so there is no concrete
784    /// type to downcast to. A default no-op keeps every other host source-compatible.
785    fn publish_registry(&self, _snapshot: std::sync::Arc<crate::registry::RegistrySnapshot>) {}
786
787    /// Publish the registry, or `None` when a reload found no plugins at all.
788    ///
789    /// Distinct from [`Self::publish_registry`] because "no extensions" is a
790    /// real state: a nonempty -> empty reload must replace the cached snapshot
791    /// rather than leave removed commands advertised.
792    fn publish_registry_opt(
793        &self,
794        snapshot: Option<std::sync::Arc<crate::registry::RegistrySnapshot>>,
795    ) {
796        if let Some(snapshot) = snapshot {
797            self.publish_registry(snapshot);
798        }
799    }
800
801    /// Abort the current run on the main lane.
802    ///
803    /// Args: `{}`. Result: `{"aborted": bool, "runId": "…"?, "steer": [...],
804    /// "followUp": [...]}`. Reclaimed queue entries are `{"text","images"}`.
805    ///
806    /// The default implementation reports "nothing to cancel": a host with no
807    /// run loop has nothing to abort, and a stop button must stay idempotent.
808    async fn abort(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
809        Ok(serde_json::json!({
810            "aborted": false,
811            "steer": [],
812            "followUp": [],
813        }))
814    }
815
816    /// Finish the current turn, then stop — the gentle counterpart of
817    /// [`Self::abort`].
818    ///
819    /// Args: `{}`; result: `{"requested": true}`. The flag is one-shot and
820    /// cleared when the next run starts, so setting it while idle is harmless.
821    ///
822    /// The default implementation reports "requested" without acting: a host
823    /// with no run loop has nothing to stop at a turn boundary, and returning an
824    /// error would make a plugin treat a benign call as a failure.
825    fn stop_round(&self, _args: serde_json::Value) -> Result<serde_json::Value, String> {
826        Ok(serde_json::json!({ "requested": true }))
827    }
828
829    /// Safe, effective runtime metadata; never serialize credential bindings.
830    async fn get_execution_context(
831        &self,
832        _args: serde_json::Value,
833    ) -> Result<serde_json::Value, String> {
834        Err("execution context is not supported by this host".into())
835    }
836
837    /// Independent child lifecycle. `owner` is supplied by the bridge, NOT JSON.
838    async fn child_agent(
839        &self,
840        _owner: u64,
841        _args: serde_json::Value,
842    ) -> Result<serde_json::Value, String> {
843        Err("ChildAgent is not supported by this host".into())
844    }
845
846    /// `GetSessionBranch` — query custom entries on the current main branch.
847    /// Required: non-empty `customTypes` string array. Optional: `afterSeq`
848    /// (exclusive), `limit` (positive), `order` (`oldestFirst` default or
849    /// `newestFirst`). Unknown/legacy keys and unfiltered `{}` are rejected.
850    /// Sorting/limit apply globally across the requested types; identifiers
851    /// match exactly. Consumers must require `filtered == true` in the reply
852    /// rather than accepting an older host's unfiltered successful response.
853    /// This host also returns pinned `sessionId`, `leafId`, and `scopedAppend:
854    /// true` for callers performing conditional state writes or outbox delivery.
855    async fn get_session_branch(
856        &self,
857        _args: serde_json::Value,
858    ) -> Result<serde_json::Value, String> {
859        Err("session branch lookup is not configured".to_string())
860    }
861}
862
863/// The host-side bridge carried in [`PluginApi::user_data`] so
864/// [`trampoline_runtime_action`] can recover the harness state from any thread.
865///
866/// `runtime: Handle` is captured at build time (the host is on the runtime when
867/// it constructs the bridge) — this is the foreign-thread fix. `host` is the
868/// `rpi-cli` impl over the harness. `reload` is a CLI-owned callback that
869/// re-runs extension discovery + Part-A loaders (a CLI concern, NOT a harness
870/// op) — wired by `rpi-cli` in B5d via [`reload_callback_from_mailbox`].
871///
872/// ## Staleness (B5d)
873///
874/// `active: Arc<AtomicBool>` is shared with a [`ReloadMailbox`]-driven swap
875/// site. A `/reload` (TUI command OR a plugin's `runtime_action(Reload)`) builds
876/// a fresh `ExtensionSession` + a fresh `ActionBridge`, calls
877/// [`invalidate`](Self::invalidate) on the old bridge, and swaps the new one in.
878/// In-flight `runtime_action` calls that recovered the OLD bridge from
879/// `user_data` (the pointer a plugin stored during the prior `register`) then
880/// hit the staleness guard in [`run_action`] and fail with a structured error
881/// instead of driving a half-swapped harness. (Plugins load fresh on reload,
882/// handing them the NEW bridge pointer; the guard only catches the race window
883/// where an old call is still parked on `rx.recv()`.)
884///
885/// Held behind `Arc`. FFI callers carry only an opaque registry handle; each
886/// dispatch upgrades its weak entry before accessing the bridge. A tool driver
887/// owns its invocation bridge through its last foreign callback. Failed reloads
888/// and dropped candidate sessions cannot leave dereferenceable dangling pointers.
889pub struct ActionBridge {
890    /// Some(child) only for a live host-created tool invocation.
891    invocation: Option<(bool, String, tokio_util::sync::CancellationToken)>,
892    execution_context: Option<serde_json::Value>,
893    tool_program: Option<Arc<rpi_agent::tool_program::ToolProgram>>,
894    stdio: crate::StdioLifecycle,
895    plugin_identity: Option<(u64, String)>,
896    component_owners: Arc<std::sync::Mutex<Vec<u64>>>,
897    /// Captured at build time from a thread running the target runtime.
898    pub(crate) runtime: Handle,
899    /// The host impl (`HarnessActionHost` in rpi-cli).
900    pub(crate) host: Arc<dyn RuntimeActionHost>,
901    /// B5d reload callback; `None` until the TUI wires `/reload`.
902    pub(crate) reload:
903        Option<Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>>,
904    /// Session-scoped UI mailbox. It is cloned into reload-created bridges so
905    /// a TUI attachment and in-flight requests survive extension reloads.
906    ui_dialog: UiDialogMailbox,
907    /// Session-scoped extension status registry (`SetStatus` runtime action).
908    /// Shared with the TUI, which polls [`ExtensionStatusMailbox::revision`]
909    /// and repaints the footer only when an extension actually wrote.
910    ext_status: crate::status::ExtensionStatusMailbox,
911    /// Session-scoped editor-text queue (`SetEditorText` runtime action). Shared
912    /// with the TUI, which drains it once per tick and writes the draft into the
913    /// prompt editor.
914    editor_text: crate::editor_text::EditorTextMailbox,
915    /// B5d staleness flag. Shared so [`invalidate`] flips it for every clone.
916    /// `true` while this bridge is the live session's bridge.
917    active: Arc<AtomicBool>,
918}
919
920impl ActionBridge {
921    /// Stable opaque context, valid only while this bridge is retained.
922    pub fn user_data(self: &Arc<Self>) -> *mut c_void {
923        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1);
924        let mut registry = bridges().lock().unwrap_or_else(|e| e.into_inner());
925        if let Some((&id, _)) = registry
926            .iter()
927            .find(|(_, entry)| entry.bridge.as_ptr() == Arc::as_ptr(self))
928        {
929            return id as *mut c_void;
930        }
931        let mut id = NEXT.load(Ordering::Relaxed);
932        loop {
933            let next = id.checked_add(1).expect("runtime handle space exhausted");
934            match NEXT.compare_exchange_weak(id, next, Ordering::Relaxed, Ordering::Relaxed) {
935                Ok(_) => break,
936                Err(current) => id = current,
937            }
938        }
939        registry.insert(
940            id,
941            RegistryEntry {
942                bridge: Arc::downgrade(self),
943                active: Arc::downgrade(&self.active),
944            },
945        );
946        id as *mut c_void
947    }
948    pub(crate) fn resolve_handle(id: usize) -> Option<Arc<Self>> {
949        bridges()
950            .lock()
951            .unwrap_or_else(|e| e.into_inner())
952            .get(&id)
953            .and_then(|entry| entry.bridge.upgrade())
954    }
955    pub(crate) fn for_invocation(
956        &self,
957        child: bool,
958        signal: tokio_util::sync::CancellationToken,
959    ) -> Arc<Self> {
960        let tool_program = rpi_agent::tool_program::current();
961        if let Some(program) = &tool_program {
962            program.bind_signal(signal.clone());
963        }
964        Arc::new(Self {
965            invocation: Some((child, uuid::Uuid::new_v4().to_string(), signal)),
966            execution_context: rpi_agent::tool_execution_scope::execution_context(),
967            tool_program,
968            stdio: self.stdio.clone(),
969            plugin_identity: self.plugin_identity.clone(),
970            component_owners: self.component_owners.clone(),
971            runtime: self.runtime.clone(),
972            host: self.host.clone(),
973            reload: self.reload.clone(),
974            ui_dialog: self.ui_dialog.clone(),
975            ext_status: self.ext_status.clone(),
976            editor_text: self.editor_text.clone(),
977            active: self.active.clone(),
978        })
979    }
980    /// Native receipt selection uses the driver-captured invocation, never a
981    /// task-local lookup on a blocking worker or a registration/root binding.
982    pub(crate) fn resolve_result_reference(
983        &self,
984        id: &str,
985    ) -> Result<(rpi_agent::AgentToolResult, bool), String> {
986        if !self.is_active()
987            || !self
988                .invocation
989                .as_ref()
990                .is_some_and(|(_, _, signal)| !signal.is_cancelled())
991        {
992            return Err("result reference requires a live invocation bridge".into());
993        }
994        self.tool_program
995            .as_ref()
996            .ok_or("result reference requires an effective ToolProgram")?
997            .resolve_result_reference(id)
998    }
999    /// Content-only plans use the same captured live authority as full receipts.
1000    pub(crate) fn resolve_content_parts(
1001        &self,
1002        parts: Vec<rpi_agent::tool_program::ToolProgramContentPart>,
1003    ) -> Result<Vec<rpi_agent::TextContentOrImage>, String> {
1004        if !self.is_active()
1005            || !self
1006                .invocation
1007                .as_ref()
1008                .is_some_and(|(_, _, signal)| !signal.is_cancelled())
1009        {
1010            return Err("content parts require a live invocation bridge".into());
1011        }
1012        self.tool_program
1013            .as_ref()
1014            .ok_or("content parts require an effective ToolProgram")?
1015            .resolve_content_parts(parts)
1016    }
1017    pub(crate) fn invocation_key(&self) -> Option<&str> {
1018        self.invocation.as_ref().map(|(_, key, _)| key.as_str())
1019    }
1020    pub(crate) fn enter_invocation(self: &Arc<Self>) -> InvocationGuard {
1021        InvocationGuard {
1022            previous: CURRENT_INVOCATION.with(|slot| slot.replace(Some(self.clone()))),
1023            _thread_bound: std::marker::PhantomData,
1024        }
1025    }
1026    /// Build a bridge. The `Handle` MUST be captured from a thread running the
1027    /// target runtime (pi-cli builds the bridge on the async main thread).
1028    pub fn new(runtime: Handle, host: Arc<dyn RuntimeActionHost>) -> Arc<Self> {
1029        Arc::new(Self {
1030            invocation: None,
1031            tool_program: None,
1032            execution_context: None,
1033            stdio: crate::StdioLifecycle::default(),
1034            plugin_identity: None,
1035            component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1036            runtime,
1037            host,
1038            reload: None,
1039            ui_dialog: UiDialogMailbox::new(),
1040            ext_status: crate::status::ExtensionStatusMailbox::new(),
1041            editor_text: crate::editor_text::EditorTextMailbox::new(),
1042            active: Arc::new(AtomicBool::new(true)),
1043        })
1044    }
1045
1046    /// Same as [`new`](Self::new) with a reload callback (B5d wires this via
1047    /// [`reload_callback_from_mailbox`]).
1048    pub fn with_reload(
1049        runtime: Handle,
1050        host: Arc<dyn RuntimeActionHost>,
1051        reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>,
1052    ) -> Arc<Self> {
1053        Self::with_reload_and_ui(
1054            runtime,
1055            host,
1056            reload,
1057            UiDialogMailbox::new(),
1058            crate::status::ExtensionStatusMailbox::new(),
1059            crate::editor_text::EditorTextMailbox::new(),
1060        )
1061    }
1062
1063    /// Build a bridge with an explicit session-scoped UI mailbox.
1064    pub fn with_ui_dialog(
1065        runtime: Handle,
1066        host: Arc<dyn RuntimeActionHost>,
1067        ui_dialog: UiDialogMailbox,
1068    ) -> Arc<Self> {
1069        Arc::new(Self {
1070            invocation: None,
1071            tool_program: None,
1072            execution_context: None,
1073            stdio: crate::StdioLifecycle::default(),
1074            plugin_identity: None,
1075            component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1076            runtime,
1077            host,
1078            reload: None,
1079            ui_dialog,
1080            ext_status: crate::status::ExtensionStatusMailbox::new(),
1081            editor_text: crate::editor_text::EditorTextMailbox::new(),
1082            active: Arc::new(AtomicBool::new(true)),
1083        })
1084    }
1085
1086    /// `with_reload` variant that preserves a mailbox across bridge swaps.
1087    pub fn with_reload_and_ui(
1088        runtime: Handle,
1089        host: Arc<dyn RuntimeActionHost>,
1090        reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>,
1091        ui_dialog: UiDialogMailbox,
1092        ext_status: crate::status::ExtensionStatusMailbox,
1093        editor_text: crate::editor_text::EditorTextMailbox,
1094    ) -> Arc<Self> {
1095        Arc::new(Self {
1096            invocation: None,
1097            tool_program: None,
1098            execution_context: None,
1099            stdio: crate::StdioLifecycle::default(),
1100            plugin_identity: None,
1101            component_owners: Arc::new(std::sync::Mutex::new(Vec::new())),
1102            runtime,
1103            host,
1104            reload: Some(reload),
1105            ui_dialog,
1106            ext_status,
1107            editor_text,
1108            active: Arc::new(AtomicBool::new(true)),
1109        })
1110    }
1111
1112    pub(crate) fn for_plugin(&self, name: &str) -> Arc<Self> {
1113        static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1114        let owner = NEXT_ID.fetch_add(1, Ordering::Relaxed);
1115        self.component_owners
1116            .lock()
1117            .unwrap_or_else(|e| e.into_inner())
1118            .push(owner);
1119        Arc::new(Self {
1120            invocation: None,
1121            tool_program: None,
1122            execution_context: None,
1123            component_owners: self.component_owners.clone(),
1124            stdio: self.stdio.clone(),
1125            plugin_identity: Some((owner, name.to_owned())),
1126            runtime: self.runtime.clone(),
1127            host: self.host.clone(),
1128            reload: self.reload.clone(),
1129            ui_dialog: self.ui_dialog.clone(),
1130            ext_status: self.ext_status.clone(),
1131            editor_text: self.editor_text.clone(),
1132            active: self.active.clone(),
1133        })
1134    }
1135
1136    pub fn stdio_lifecycle(&self) -> crate::StdioLifecycle {
1137        self.stdio.clone()
1138    }
1139
1140    pub(crate) fn claim_stdio(&self) -> Result<(), String> {
1141        let (id, name) = self
1142            .plugin_identity
1143            .as_ref()
1144            .ok_or("missing plugin identity")?;
1145        self.stdio.claim(*id, name)
1146    }
1147
1148    pub(crate) fn release_stdio_claim(&self) {
1149        if let Some((id, _)) = &self.plugin_identity {
1150            self.stdio.release_failed_registration(*id);
1151            self.ext_status.remove_owner(*id);
1152        }
1153    }
1154
1155    /// Clone the session mailbox for TUI attachment or a reload-created bridge.
1156    pub fn ui_dialog_mailbox(&self) -> UiDialogMailbox {
1157        self.ui_dialog.clone()
1158    }
1159
1160    /// Clone the session status registry (TUI rendering + reload-created bridges).
1161    pub fn extension_status_mailbox(&self) -> crate::status::ExtensionStatusMailbox {
1162        self.ext_status.clone()
1163    }
1164
1165    /// Clone the session editor-text queue (TUI drain + reload-created bridges).
1166    pub fn editor_text_mailbox(&self) -> crate::editor_text::EditorTextMailbox {
1167        self.editor_text.clone()
1168    }
1169
1170    /// Mark this bridge stale (B5d). A `/reload` that swaps in a fresh bridge
1171    /// calls this on the old one so in-flight `runtime_action` calls parked on
1172    /// the old `user_data` pointer fail fast with a staleness error instead of
1173    /// driving the swapped-out session. Idempotent.
1174    pub fn invalidate(&self) {
1175        let owners = {
1176            let owners = self
1177                .component_owners
1178                .lock()
1179                .unwrap_or_else(|e| e.into_inner());
1180            self.active.store(false, Ordering::SeqCst);
1181            for owner in owners.iter() {
1182                self.ext_status.remove_owner(*owner);
1183            }
1184            owners.clone()
1185        };
1186        // Cancel captured capabilities across FFI thread hops on reload/session retirement.
1187        let live = self.bridges_for_owner();
1188        for bridge in live {
1189            if let Some(program) = &bridge.tool_program {
1190                program.cancel_all();
1191            }
1192        }
1193        // Host cancellation may contend with a job publishing through its
1194        // sink. Never invoke it while holding the sink's lifecycle gate.
1195        for owner in owners {
1196            self.host.cancel_child_agents(owner);
1197            self.host.cancel_side_questions(owner);
1198        }
1199    }
1200
1201    fn bridges_for_owner(&self) -> Vec<Arc<Self>> {
1202        let active = Arc::downgrade(&self.active);
1203        // Filter weak owner identity BEFORE upgrading: even a transient upgrade
1204        // of another session's invocation delays its immediate handle retirement.
1205        // The weak metadata keeps that allocation's identity from being reused.
1206        // Collect every upgraded Arc out of the registry lock; dropping a last
1207        // Arc here would deadlock when ActionBridge::drop locks the registry.
1208        bridges()
1209            .lock()
1210            .unwrap_or_else(|e| e.into_inner())
1211            .values()
1212            .filter(|entry| entry.active.ptr_eq(&active))
1213            .filter_map(|entry| entry.bridge.upgrade())
1214            .collect()
1215    }
1216
1217    /// Whether this bridge is still the live session's bridge.
1218    pub fn is_active(&self) -> bool {
1219        self.active.load(Ordering::SeqCst)
1220    }
1221
1222    /// B5d: clone the host impl so a `/reload` can build a FRESH `ActionBridge`
1223    /// over the SAME `RuntimeActionHost` (the host's harness cell already points
1224    /// at the live harness — the harness is NOT rebuilt on reload — so the host
1225    /// is reusable across reloads; only the bridge's staleness flag + reload
1226    /// callback differ). The fresh bridge gets a fresh `active` flag (true) +
1227    /// the reload callback the TUI installed; the old bridge is `invalidate`d.
1228    pub fn clone_host(&self) -> Arc<dyn RuntimeActionHost> {
1229        Arc::clone(&self.host)
1230    }
1231}
1232
1233/// A reload-signal mail slot (B5d). The reload callback (built by
1234/// [`reload_callback_from_mailbox`]) captures a clone; the TUI installs a
1235/// `tokio` unbounded sender after it starts. When a plugin calls
1236/// `runtime_action(Reload)`, the callback signals `()` (if a TUI is installed)
1237/// and the TUI performs the reload **asynchronously** — the plugin's call
1238/// returns `Ok(null)` immediately, so the calling plugin's cdylib is NOT
1239/// unmapped while its `runtime_action` frame is still on the stack (the reload,
1240/// which drops the old keepalive, happens after the call returns). This breaks
1241/// the self-unmapping race a synchronous plugin-initiated reload would have.
1242///
1243/// rpi-extensions carries only `()` (no pi-cli `TuiMessage` type) — preserving
1244/// the leaf DAG. The TUI owns the receiver + the actual reload routine.
1245#[derive(Clone)]
1246pub struct ReloadMailbox {
1247    tx: Arc<std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<()>>>>,
1248}
1249
1250impl Default for ReloadMailbox {
1251    fn default() -> Self {
1252        Self {
1253            tx: Arc::new(std::sync::Mutex::new(None)),
1254        }
1255    }
1256}
1257
1258impl ReloadMailbox {
1259    /// A fresh empty mail slot (no TUI installed yet).
1260    pub fn new() -> Self {
1261        Self::default()
1262    }
1263
1264    /// Install the TUI's reload-signal sender (after the TUI starts). Replaces
1265    /// any prior sender. The TUI drops the receiver on shutdown; a sender held
1266    /// here keeps the channel half-open, so [`clear`] on shutdown is advised.
1267    pub fn install(&self, tx: tokio::sync::mpsc::UnboundedSender<()>) {
1268        *self.tx.lock().unwrap() = Some(tx);
1269    }
1270
1271    /// Signal a reload (plugin-initiated via `runtime_action(Reload)`).
1272    /// `Ok(())` if a TUI is installed (the signal was enqueued; the TUI may
1273    /// still be mid-reload). `Err(())` if no TUI is installed (the host returns
1274    /// a "reload not available" error to the plugin).
1275    pub fn signal(&self) -> Result<(), ()> {
1276        let g = self.tx.lock().unwrap();
1277        match &*g {
1278            Some(tx) => {
1279                let _ = tx.send(());
1280                Ok(())
1281            }
1282            None => Err(()),
1283        }
1284    }
1285
1286    /// Drop the installed sender (TUI shutdown). Idempotent.
1287    pub fn clear(&self) {
1288        *self.tx.lock().unwrap() = None;
1289    }
1290}
1291
1292/// A request/reply mailbox for `runtime_action(ReloadModels)`.
1293///
1294/// Unlike [`ReloadMailbox`] (fire-and-forget: the plugin does not care whether
1295/// the reload succeeded), this one **waits for the result**: the caller wants
1296/// to know how many models the refreshed catalog holds, and whether the
1297/// re-read failed at all.
1298///
1299/// The TUI owns the receiver and performs the actual work (it owns the
1300/// harness); the plugin-facing side only enqueues a request and awaits the
1301/// reply.
1302pub struct ReloadModelsMailbox {
1303    tx: Arc<std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<ReloadModelsRequest>>>>,
1304}
1305
1306impl Default for ReloadModelsMailbox {
1307    fn default() -> Self {
1308        Self {
1309            tx: Arc::new(std::sync::Mutex::new(None)),
1310        }
1311    }
1312}
1313
1314/// One pending `ReloadModels` request plus the channel to answer on.
1315pub struct ReloadModelsRequest {
1316    /// Answer channel: `Ok(model_count)` or `Err(reason)`.
1317    pub reply: tokio::sync::oneshot::Sender<Result<usize, String>>,
1318}
1319
1320impl Clone for ReloadModelsMailbox {
1321    fn clone(&self) -> Self {
1322        Self {
1323            tx: Arc::clone(&self.tx),
1324        }
1325    }
1326}
1327
1328impl ReloadModelsMailbox {
1329    pub fn new() -> Self {
1330        Self::default()
1331    }
1332
1333    /// Install the TUI's request sender. Replaces any prior sender.
1334    pub fn install(&self, tx: tokio::sync::mpsc::UnboundedSender<ReloadModelsRequest>) {
1335        *self.tx.lock().unwrap() = Some(tx);
1336    }
1337
1338    /// Enqueue a request and await the TUI's answer.
1339    ///
1340    /// `Err` when no TUI is installed (the host surfaces "not available") or
1341    /// when the TUI went away before answering.
1342    pub async fn request(&self) -> Result<usize, String> {
1343        let (reply, wait) = tokio::sync::oneshot::channel();
1344        let tx = self.tx.lock().unwrap().clone();
1345        let Some(tx) = tx else {
1346            return Err("reload_models is not available (no TUI attached)".to_string());
1347        };
1348        tx.send(ReloadModelsRequest { reply })
1349            .map_err(|_| "reload_models request dropped (TUI gone)".to_string())?;
1350        wait.await
1351            .map_err(|_| "reload_models request dropped (TUI gone)".to_string())?
1352    }
1353
1354    /// Drop the installed sender (TUI shutdown). Idempotent.
1355    pub fn clear(&self) {
1356        *self.tx.lock().unwrap() = None;
1357    }
1358}
1359
1360/// Build the reload callback the bridge carries, backed by a [`ReloadMailbox`].
1361/// When a plugin calls `runtime_action(Reload)`, the bridge's spawn site awaits
1362/// this callback, which signals the TUI (if installed) and returns; the plugin
1363/// receives `Ok(null)` and the TUI performs the reload asynchronously. If no
1364/// TUI is installed, the callback returns without signalling and the host's
1365/// [`RuntimeActionHost::reload`] fallback surfaces the "not configured" error.
1366pub fn reload_callback_from_mailbox(
1367    mailbox: ReloadMailbox,
1368) -> Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync> {
1369    Arc::new(move || {
1370        let m = mailbox.clone();
1371        Box::pin(async move {
1372            let _ = m.signal();
1373        })
1374    })
1375}
1376
1377// `Handle` is Send+Sync, `Arc<dyn RuntimeActionHost>` (with `Send + Sync` bound)
1378// is Send+Sync, and the reload closure is `Send + Sync` — so `ActionBridge` is
1379// naturally Send+Sync; no manual unsafe impl needed.
1380
1381/// Dispatch one action to the host. Async — runs on the bridge's runtime.
1382/// Handles all 19 ids; `Reload` delegates to [`RuntimeActionHost::reload`]
1383/// (the "no callback configured" fallback). When the bridge has a reload
1384/// callback, the spawn site intercepts `Reload` and awaits the callback
1385/// instead (a CLI concern, not a harness op) — this helper is the plain
1386/// host-only path.
1387/// The mailbox-only `RelayUiDialog` action.
1388///
1389/// Split out so the trampoline can run it on a plain thread instead of a Tokio
1390/// worker (see the `RelayUiDialog` arm at the spawn site).
1391fn dispatch_relay_ui_dialog(
1392    ui_dialog: &UiDialogMailbox,
1393    args: serde_json::Value,
1394) -> Result<serde_json::Value, String> {
1395    let op = args
1396        .get("op")
1397        .and_then(serde_json::Value::as_str)
1398        .unwrap_or("take");
1399    match op {
1400        "take" => {
1401            // Taking implies ownership: the caller is the UI that will present
1402            // these questions, so the local TUI must stand down rather than
1403            // compete for the same queue.
1404            ui_dialog.set_external_takeover(true);
1405            let requests: Vec<serde_json::Value> = ui_dialog
1406                .take_all_unreserved()
1407                .into_iter()
1408                .map(|request| {
1409                    serde_json::json!({
1410                        "requestId": request.request_id,
1411                        "toolCallId": request.tool_call_id,
1412                        "ui": request.ui,
1413                    })
1414                })
1415                .collect();
1416            Ok(serde_json::json!({ "requests": requests }))
1417        }
1418        // Give delivery back to the local TUI and re-queue anything the relay
1419        // took but never answered.
1420        "release" => {
1421            let requeued = ui_dialog.release_takeover();
1422            Ok(serde_json::json!({ "requeued": requeued }))
1423        }
1424        // Same request ids, same semantics as `UiDialog`.
1425        "respond" | "cancel" | "forget" => ui_dialog.handle(args),
1426        other => Err(format!("RelayUiDialog does not support op `{other}`")),
1427    }
1428}
1429
1430async fn dispatch(
1431    host: &Arc<dyn RuntimeActionHost>,
1432    ui_dialog: &UiDialogMailbox,
1433    ext_status: &crate::status::ExtensionStatusMailbox,
1434    editor_text: &crate::editor_text::EditorTextMailbox,
1435    action: RuntimeActionId,
1436    args: serde_json::Value,
1437) -> Result<serde_json::Value, String> {
1438    match action {
1439        RuntimeActionId::SendMessage => host.send_message(args).await,
1440        RuntimeActionId::SendUserMessage => host.send_user_message(args).await,
1441        RuntimeActionId::AppendEntry => host.append_entry(args).await,
1442        RuntimeActionId::SetSessionName => host.set_session_name(args).await,
1443        RuntimeActionId::GetActiveTools => host.get_active_tools(args).await,
1444        RuntimeActionId::SetActiveTools => host.set_active_tools(args).await,
1445        RuntimeActionId::SetModel => host.set_model(args).await,
1446        RuntimeActionId::GetThinkingLevel => host.get_thinking_level(args).await,
1447        RuntimeActionId::SetThinkingLevel => host.set_thinking_level(args).await,
1448        RuntimeActionId::Compact => host.compact(args).await,
1449        RuntimeActionId::GetSystemPrompt => host.get_system_prompt(args).await,
1450        RuntimeActionId::NewSession => host.new_session(args).await,
1451        RuntimeActionId::Fork => host.fork(args).await,
1452        RuntimeActionId::NavigateTree => host.navigate_tree(args).await,
1453        RuntimeActionId::SwitchSession => host.switch_session(args).await,
1454        RuntimeActionId::Reload => host.reload(args).await,
1455        RuntimeActionId::ReloadModels => host.reload_models(args).await,
1456        RuntimeActionId::GetCliFlag => host.get_cli_flag(args).await,
1457        RuntimeActionId::UiDialog => ui_dialog.handle(args),
1458        // UI-only action: handled by the bridge (no harness call), exactly like
1459        // `UiDialog`. Written straight into the shared registry the TUI polls.
1460        RuntimeActionId::SetStatus => ext_status.handle(args),
1461        RuntimeActionId::UiComponent => Err("UiComponent requires a plugin bridge".into()),
1462        // Editor-only action: served by the bridge (no harness call), exactly
1463        // like `SetStatus`/`UiDialog`. The TUI drains the queue each tick.
1464        RuntimeActionId::SetEditorText => editor_text.handle(args),
1465        RuntimeActionId::GetSessionBranch => host.get_session_branch(args).await,
1466        RuntimeActionId::GetExecutionContext => host.get_execution_context(args).await,
1467        RuntimeActionId::ToolProgram => Err("ToolProgram requires a live invocation bridge".into()),
1468        RuntimeActionId::ChildAgent => Err("ChildAgent requires a plugin bridge".into()),
1469        RuntimeActionId::SideQuestion => Err("SideQuestion requires a plugin bridge".into()),
1470        RuntimeActionId::ListCommands => host.list_commands(args).await,
1471        RuntimeActionId::Abort => host.abort(args).await,
1472        // Hand the mailbox to an external UI. Only correct while one is
1473        // attached — with no client, the caller should let the TUI draw the
1474        // dialog instead (otherwise nobody sees the question).
1475        RuntimeActionId::RelayUiDialog => dispatch_relay_ui_dialog(ui_dialog, args),
1476        RuntimeActionId::StopRound => host.stop_round(args),
1477        RuntimeActionId::StdioLifecycle => {
1478            Err("stdio lifecycle requires a plugin context".to_owned())
1479        }
1480    }
1481}
1482
1483/// The real `runtime_action` trampoline — replaces `stub_runtime_action` when a
1484/// bridge is present (see [`HostApi::build_vtable`](crate::HostApi)).
1485///
1486/// Resolves an `Arc<ActionBridge>` from an opaque handle (or the active tool
1487/// invocation), parses `args_json`, drives the host's async dispatch via
1488/// `Handle::spawn`, and parks
1489/// the plugin thread on a std `mpsc` `recv` (works from ANY thread — no ambient
1490/// runtime needed, which is the load-bearing property for foreign plugin
1491/// threads).
1492///
1493/// ## Return codes
1494/// - `0` — success; `*out` written with the result JSON (host-owned
1495///   [`StbString`]; the plugin frees it via the host `free_string` from the
1496///   vtable).
1497/// - `1` — host-level error; `*out` written with `{"error": msg}` JSON.
1498/// - `2` — unknown numeric action id; `*out` contains a structured error and
1499///   no host method is dispatched.
1500/// - `-1` — no bridge present (`user_data` null; should not happen when wired).
1501/// - `-2` — the spawned task dropped its sender without sending (runtime
1502///   shutdown / dispatch panic); no result available.
1503///
1504/// The whole body is `catch_unwind`-wrapped — a panic across FFI ⇒ abort (same
1505/// policy as the tool partial callback, `tool.rs:206`).
1506pub extern "C" fn trampoline_runtime_action(
1507    action_id: u32,
1508    args_json: StbStringRef,
1509    out: *mut StbString,
1510    user_data: *mut c_void,
1511) -> i32 {
1512    let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1513        run_action(
1514            action_id,
1515            // Highest id this ABI defines.
1516            rpi_plugin_sdk::RuntimeActionId::MAX,
1517            args_json,
1518            out,
1519            user_data,
1520        )
1521    }));
1522    match outcome {
1523        Ok(rc) => rc,
1524        Err(_) => {
1525            // A panic in the host-side dispatch was caught. Do not abort the
1526            // process: report a host-level error to the caller (documented
1527            // code `1`) with a structured payload when `out` is writable.
1528            tracing::error!("runtime_action trampoline panicked — reporting host error");
1529            if !out.is_null() {
1530                unsafe {
1531                    *out = StbString::from_string(
1532                        r#"{"error":"runtime_action panicked"}"#.to_string(),
1533                    );
1534                }
1535            }
1536            1
1537        }
1538    }
1539}
1540
1541/// Inner synchronous driver (split out so the `catch_unwind` wrapper is clean).
1542fn run_action(
1543    action_id: u32,
1544    max_action_id: u32,
1545    args_json: StbStringRef,
1546    out: *mut StbString,
1547    user_data: *mut c_void,
1548) -> i32 {
1549    // Validate the raw FFI integer before dereferencing host state or entering
1550    // the enum-based dispatch. Unknown values are ordinary protocol errors;
1551    // they never become invalid Rust enum discriminants.
1552    let action = match RuntimeActionId::try_from(action_id) {
1553        Ok(action) if action_id <= max_action_id => action,
1554        Ok(_) | Err(_) => {
1555            if !out.is_null() {
1556                let json = serde_json::json!({
1557                    "error": format!("unknown runtime action id {action_id}")
1558                })
1559                .to_string();
1560                // SAFETY: `out` is non-null and points to the caller-provided
1561                // output slot. The plugin reclaims this host allocation via
1562                // `host_free_string` from the vtable.
1563                unsafe {
1564                    *out = StbString::from_string(json);
1565                }
1566            }
1567            return 2;
1568        }
1569    };
1570
1571    if user_data.is_null() {
1572        return -1;
1573    }
1574    // Synchronous callbacks inherit the actual driver's invocation, not a
1575    // plugin-global registration pointer. Worker threads pass its opaque ID.
1576    let invocation = CURRENT_INVOCATION.with(|slot| slot.borrow().clone());
1577    let invocation_thread = invocation.is_some();
1578    let bridge = invocation.or_else(|| ActionBridge::resolve_handle(user_data as usize));
1579    let Some(bridge) = bridge else {
1580        if !out.is_null() {
1581            // SAFETY: the ABI caller supplies a writable output slot.
1582            unsafe {
1583                *out = StbString::from_string("{\"error\":\"expired runtime handle\"}".into());
1584            }
1585        }
1586        return 1;
1587    };
1588
1589    // B5d staleness guard: a `/reload` that swapped in a fresh bridge calls
1590    // `invalidate` on the old one. A plugin that still holds the old pointer
1591    // (stored during the prior `register`) must not drive the swapped-out
1592    // session. Surface a structured "stale bridge" error so the plugin's
1593    // `runtime_action` returns nonzero + `{"error": ...}` instead of racing
1594    // the swap. (The new bridge's pointer was handed to the reloaded plugins;
1595    // this guard only catches the race window where an old call is still parked.)
1596    if !bridge.is_active() {
1597        if out.is_null() {
1598            return 1;
1599        }
1600        let json = serde_json::json!({
1601            "error": "runtime_action on a stale ActionBridge (session reloaded/swapped)"
1602        })
1603        .to_string();
1604        unsafe {
1605            *out = StbString::from_string(json);
1606        }
1607        return 1;
1608    }
1609
1610    // Parse args. An empty/invalid JSON blob collapses to `{}` — getters ignore
1611    // args; setters that require a field surface a clear error string.
1612    let args_str = unsafe { args_json.as_str() };
1613    let mut args: serde_json::Value = if args_str.is_empty() {
1614        serde_json::Value::Object(serde_json::Map::new())
1615    } else {
1616        serde_json::from_str(args_str)
1617            .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new()))
1618    };
1619
1620    let runtime_key = args
1621        .as_object_mut()
1622        .and_then(|args| args.remove("__rpiRuntimeKey"));
1623
1624    // Drive the host's async dispatch on the bridge's runtime. STD mpsc so the
1625    // plugin thread can recv from any thread (no ambient runtime). sync_channel
1626    // (1): bounded; the send completes once the value is delivered. rx.recv()
1627    // parks the plugin thread until the spawn finishes (or its sender drops).
1628    let (tx, rx) = mpsc::sync_channel::<Result<serde_json::Value, String>>(1);
1629    // Clone the bridge's host + reload callback into the spawned task. We pass
1630    // an owned `Arc<dyn RuntimeActionHost>` plus a reload-option snapshot so the
1631    // `dispatch` helper has everything it needs without borrowing `bridge`.
1632    let host = Arc::clone(&bridge.host);
1633    let ui_dialog = bridge.ui_dialog.clone();
1634    let ext_status = bridge.ext_status.clone();
1635    let editor_text = bridge.editor_text.clone();
1636    let reload_cb = bridge.reload.clone();
1637    let execution_context = bridge.execution_context.clone();
1638    if action == RuntimeActionId::StdioLifecycle {
1639        let result = bridge.stdio.handle(
1640            bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id),
1641            args,
1642        );
1643        let _ = tx.send(result);
1644    } else if action == RuntimeActionId::UiComponent {
1645        let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1646        let _owners = bridge
1647            .component_owners
1648            .lock()
1649            .unwrap_or_else(|e| e.into_inner());
1650        let result = if bridge.is_active() {
1651            ext_status.component(owner, args)
1652        } else {
1653            Err("stale plugin bridge".into())
1654        };
1655        let _ = tx.send(result);
1656    } else if action == RuntimeActionId::SideQuestion {
1657        let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1658        if owner == 0 || bridge.invocation.is_some() {
1659            let _ = tx.send(Err(
1660                "SideQuestion requires a plugin command, not a tool invocation".into(),
1661            ));
1662        } else {
1663            // Serialize writes with invalidate(): no late publication can
1664            // resurrect components after owner retirement. Keep only weak state.
1665            let weak = Arc::downgrade(&bridge);
1666            let sink: SideQuestionSink = Arc::new(move |args| {
1667                let bridge = weak.upgrade().ok_or("expired side question bridge")?;
1668                let _owners = bridge
1669                    .component_owners
1670                    .lock()
1671                    .unwrap_or_else(|e| e.into_inner());
1672                if !bridge.is_active() {
1673                    return Err("stale side question bridge".into());
1674                }
1675                if args["op"] == "check" {
1676                    return Ok(serde_json::json!({"ok":true}));
1677                }
1678                bridge.ext_status.component(owner, args)
1679            });
1680            bridge.runtime.spawn(async move {
1681                let _ = tx.send(host.side_question(owner, args, sink).await);
1682            });
1683        }
1684    } else if action == RuntimeActionId::GetActiveTools && bridge.tool_program.is_some() {
1685        let tools = bridge
1686            .tool_program
1687            .as_ref()
1688            .expect("checked")
1689            .active_tool_names();
1690        let _ = tx.send(Ok(serde_json::json!({"tools":tools})));
1691    } else if action == RuntimeActionId::SetActiveTools && bridge.execution_context.is_some() {
1692        let _ = tx.send(Err(
1693            "cannot replace active tools from a narrowed execution".into()
1694        ));
1695    } else if action == RuntimeActionId::ToolProgram {
1696        let cleanup = matches!(
1697            args.get("op").and_then(serde_json::Value::as_str),
1698            Some("poll" | "cancel" | "dispose" | "release_result")
1699        );
1700        let authenticated = bridge.invocation.as_ref().is_some_and(|(_, key, signal)| {
1701            (cleanup || !signal.is_cancelled())
1702                && (invocation_thread
1703                    || runtime_key.as_ref().and_then(serde_json::Value::as_str)
1704                        == Some(key.as_str()))
1705        });
1706        if let Some(capability) = bridge.tool_program.clone().filter(|_| authenticated) {
1707            let signal = bridge.invocation.as_ref().expect("authenticated").2.clone();
1708            bridge.runtime.spawn(async move {
1709                if signal.is_cancelled() {
1710                    capability.cancel_all();
1711                    if !cleanup {
1712                        let _ = tx.send(Err("parent invocation is no longer active".into()));
1713                        return;
1714                    }
1715                }
1716                let _ = tx.send(host.tool_program(capability, args).await);
1717            });
1718        } else {
1719            let _ = tx.send(Err(
1720                "ToolProgram requires an authenticated executing invocation".into(),
1721            ));
1722        }
1723    } else if action == RuntimeActionId::ChildAgent {
1724        // A registration handle cannot assert that it is a parent invocation.
1725        // All child-originated invocations fail closed, regardless of tool name.
1726        // Cancellation stops admission, not authenticated reclamation. The
1727        // plugin's cancel/destroy path must still dispose its retained handles.
1728        let cleanup = matches!(
1729            args.get("op").and_then(serde_json::Value::as_str),
1730            Some("poll" | "cancel" | "dispose")
1731        );
1732        let allowed = bridge
1733            .invocation
1734            .as_ref()
1735            .is_some_and(|(child, key, signal)| {
1736                !child
1737                    && (cleanup || !signal.is_cancelled())
1738                    && (invocation_thread
1739                        || runtime_key.as_ref().and_then(serde_json::Value::as_str)
1740                            == Some(key.as_str()))
1741            });
1742        if !allowed {
1743            let _ = tx.send(Err("ChildAgent requires a live parent tool invocation; recursive child agents are not allowed".into()));
1744        } else {
1745            let owner = bridge.plugin_identity.as_ref().map_or(0, |(id, _)| *id);
1746            let signal = bridge
1747                .invocation
1748                .as_ref()
1749                .expect("authorized invocation")
1750                .2
1751                .clone();
1752            bridge.runtime.spawn(async move {
1753                let result = rpi_agent::tool_execution_scope::with_invocation_signal(
1754                    signal,
1755                    host.child_agent(owner, args),
1756                )
1757                .await;
1758                let _ = tx.send(result);
1759            });
1760        }
1761    } else if action == RuntimeActionId::SetStatus {
1762        // Same reasoning as `UiDialog`: this action never touches the harness,
1763        // so it must not need a Tokio worker. A plugin calling it from inside a
1764        // single-threaded runtime (a tool poll callback, say) would otherwise
1765        // park that executor and deadlock.
1766        std::thread::spawn(move || {
1767            let _ = tx.send(ext_status.handle(args));
1768        });
1769    } else if action == RuntimeActionId::SetEditorText {
1770        // Editor-only, like `SetStatus`: no harness call, so keep it off the
1771        // Tokio worker for the same single-thread-runtime reason.
1772        std::thread::spawn(move || {
1773            let _ = tx.send(editor_text.handle(args));
1774        });
1775    } else if action == RuntimeActionId::RelayUiDialog {
1776        // Mailbox-only, like `UiDialog`/`SetStatus`/`SetEditorText`: it never
1777        // touches the harness. Routing it through the generic runtime spawn
1778        // would park the blocking `rx.recv()` on a Tokio worker that the
1779        // mailbox-only op itself needs to complete — on a current-thread bridge
1780        // that deadlocks the only thread able to finish it.
1781        std::thread::spawn(move || {
1782            let _ = tx.send(dispatch_relay_ui_dialog(&ui_dialog, args));
1783        });
1784    } else if action == RuntimeActionId::UiDialog {
1785        // UiDialog is intentionally synchronous at the plugin ABI boundary:
1786        // `open` waits until the TUI answers. Never park that wait inside the
1787        // Tokio worker that services the bridge. A SEARCH/extension tool that
1788        // invokes `ui_request/open` from a single-thread runtime would
1789        // otherwise block the executor before the TUI can deliver the answer.
1790        std::thread::spawn(move || {
1791            let _ = tx.send(ui_dialog.handle(args));
1792        });
1793    } else {
1794        bridge.runtime.spawn(async move {
1795            let mut r = if action == RuntimeActionId::Reload {
1796                if let Some(cb) = reload_cb {
1797                    cb().await;
1798                    Ok(serde_json::Value::Null)
1799                } else {
1800                    host.reload(args).await
1801                }
1802            } else {
1803                dispatch(&host, &ui_dialog, &ext_status, &editor_text, action, args).await
1804            };
1805            if action == RuntimeActionId::GetExecutionContext {
1806                if let (Ok(context), Some(serde_json::Value::Object(fields))) =
1807                    (&mut r, execution_context)
1808                {
1809                    if let Some(object) = context.as_object_mut() {
1810                        object.extend(fields);
1811                    }
1812                }
1813            }
1814            // If the plugin thread already moved on (dropped rx), discard — a
1815            // send error is NOT a host fault.
1816            let _ = tx.send(r);
1817        });
1818    }
1819
1820    // Event observers can call back synchronously from a Tokio worker. A task
1821    // just spawned above may still occupy that worker's non-stealable LIFO
1822    // slot. Yield the scheduler before blocking so dispatch can actually run.
1823    // Foreign/plugin workers and current-thread mailbox-only calls keep the
1824    // ordinary blocking receive.
1825    let received = if Handle::try_current()
1826        .is_ok_and(|handle| handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread)
1827    {
1828        tokio::task::block_in_place(|| rx.recv())
1829    } else {
1830        rx.recv()
1831    };
1832    let result = match received {
1833        Ok(r) => r,
1834        Err(_) => {
1835            // Spawned task dropped the sender without sending: runtime shutdown
1836            // or the dispatch future panicked (caught inside dispatch? no —
1837            // dispatch is plain async, a panic would propagate to the spawn and
1838            // drop the sender). No result to return.
1839            return -2;
1840        }
1841    };
1842
1843    // Write the result (or error) into `*out` as a host-owned StbString. The
1844    // plugin frees it via the vtable's `free_string` (= `host_free_string`).
1845    if out.is_null() {
1846        // Nothing to write to; still report the outcome via the return code.
1847        return match result {
1848            Ok(_) => 0,
1849            Err(_) => 1,
1850        };
1851    }
1852
1853    let (rc, payload) = match result {
1854        Ok(value) => {
1855            let json = serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string());
1856            (0, json)
1857        }
1858        Err(msg) => {
1859            let json = serde_json::json!({ "error": msg }).to_string();
1860            (1, json)
1861        }
1862    };
1863    // SAFETY: `out` is a valid `*mut StbString` the plugin provided for this
1864    // call (null checked above). `from_string` allocates a `Box<[u8]>` the host
1865    // owns; the plugin reclaims it via `host_free_string` (which reconstructs
1866    // the Box from ptr+len — matches `from_string`'s allocation, same pattern
1867    // used by translate.rs/tool.rs).
1868    unsafe {
1869        *out = StbString::from_string(payload);
1870    }
1871    rc
1872}
1873
1874// ===========================================================================
1875// Tests — round-trip the real trampoline + dispatch + Handle::spawn + mpsc
1876// against a mock host. This is the B5a unit proof: plugin→host `runtime_action`
1877// recovers the `ActionBridge` via `user_data`, drives the host's async method on
1878// the runtime, parks the caller on `rx.recv()`, and writes the result JSON back
1879// through `*out` (freed via `host_free_string`). No cdylib needed — the trampoline
1880// is the same `extern "C" fn` a plugin's vtable carries.
1881// ===========================================================================
1882#[cfg(test)]
1883mod tests {
1884    use super::*;
1885    use std::sync::Mutex;
1886
1887    #[tokio::test(flavor = "current_thread")]
1888    async fn stdio_claim_is_exclusive_and_only_its_scoped_context_can_finish() {
1889        let master = ActionBridge::new(
1890            Handle::current(),
1891            Arc::new(MockHost {
1892                prompt: String::new(),
1893                saw: Mutex::new(Vec::new()),
1894            }),
1895        );
1896        let diag: Arc<dyn crate::PluginDiagnostics> = Arc::new(crate::NullDiagnostics);
1897        let owner = crate::HostApi::with_action_bridge(
1898            "owner",
1899            crate::ExtensionRegistry::new(),
1900            diag.clone(),
1901            master.clone(),
1902        );
1903        let other = crate::HostApi::with_action_bridge(
1904            "other",
1905            crate::ExtensionRegistry::new(),
1906            diag,
1907            master.clone(),
1908        );
1909        let vtable = owner.build_vtable();
1910        let claim = r#"{"ownsStdio":true}"#;
1911        {
1912            let _registration = crate::enter_current_api(&owner);
1913            assert_eq!(vtable.declare.unwrap()(StbStringRef::from_str(claim)), 0);
1914        }
1915        let other_vtable = other.build_vtable();
1916        let finish = StbStringRef::from_str(r#"{"op":"finish","exitCode":7}"#);
1917        let mut out = StbString::empty();
1918        // Direct, on a single-thread executor: this action must not park on Tokio.
1919        assert_eq!(
1920            (other_vtable.runtime_action)(
1921                RuntimeActionId::StdioLifecycle as u32,
1922                finish,
1923                &mut out,
1924                other_vtable.user_data
1925            ),
1926            1
1927        );
1928        // SAFETY: the action returned a live allocation from this vtable.
1929        unsafe { (other_vtable.free_string)(out) };
1930        assert_eq!(
1931            (vtable.runtime_action)(
1932                RuntimeActionId::StdioLifecycle as u32,
1933                finish,
1934                &mut out,
1935                vtable.user_data
1936            ),
1937            0
1938        );
1939        // SAFETY: the action returned a live allocation from this vtable.
1940        unsafe { (vtable.free_string)(out) };
1941        assert_eq!(master.stdio_lifecycle().wait().await, 7);
1942        {
1943            let _registration = crate::enter_current_api(&other);
1944            assert_ne!(
1945                other_vtable.declare.unwrap()(StbStringRef::from_str(claim)),
1946                0
1947            );
1948        }
1949        assert!(master
1950            .stdio_lifecycle()
1951            .validate()
1952            .unwrap_err()
1953            .contains("owner"));
1954    }
1955
1956    /// A minimal `RuntimeActionHost` that answers `get_system_prompt` with a
1957    /// canned string and `reload` with Ok(null); every other action returns an
1958    /// "unimplemented" error. Enough to prove the dispatch switch + the async
1959    /// spawn + the mpsc round-trip + the StbString write.
1960    struct MockHost {
1961        prompt: String,
1962        saw: Mutex<Vec<RuntimeActionId>>,
1963    }
1964
1965    #[test]
1966    fn runtime_action_from_a_tokio_worker_does_not_block_its_dispatch() {
1967        const CHILD: &str = "RPI_RUNTIME_ACTION_WORKER_REGRESSION_CHILD";
1968        if std::env::var_os(CHILD).is_some() {
1969            let runtime = tokio::runtime::Builder::new_multi_thread()
1970                .worker_threads(1)
1971                .enable_all()
1972                .build()
1973                .unwrap();
1974            runtime.block_on(async {
1975                // Lifecycle observers run directly on a worker. Their runtime
1976                // action spawns back onto that runtime, including its LIFO slot.
1977                tokio::spawn(async {
1978                    let host = Arc::new(MockHost {
1979                        prompt: "worker callback".into(),
1980                        saw: Mutex::new(Vec::new()),
1981                    });
1982                    let bridge = ActionBridge::new(Handle::current(), host);
1983                    let mut out = StbString::empty();
1984                    assert_eq!(
1985                        trampoline_runtime_action(
1986                            RuntimeActionId::GetSystemPrompt.into(),
1987                            StbStringRef::from_str("{}"),
1988                            &mut out,
1989                            bridge.user_data(),
1990                        ),
1991                        0
1992                    );
1993                    // SAFETY: the action returned a live host-owned string.
1994                    let text = unsafe {
1995                        rpi_plugin_sdk::callbacks::OwnedString::from_raw(
1996                            out,
1997                            Some(crate::host_free_string),
1998                        )
1999                    }
2000                    .to_string_lossy();
2001                    assert_eq!(
2002                        serde_json::from_str::<serde_json::Value>(&text).unwrap()["prompt"],
2003                        "worker callback"
2004                    );
2005                })
2006                .await
2007                .unwrap();
2008            });
2009            return;
2010        }
2011        // Isolate the old self-deadlock so a regression fails promptly instead
2012        // of hanging the test runner or leaving a blocked runtime thread behind.
2013        let mut child = std::process::Command::new(std::env::current_exe().unwrap())
2014            .args([
2015                "--exact",
2016                "actions::tests::runtime_action_from_a_tokio_worker_does_not_block_its_dispatch",
2017                "--nocapture",
2018            ])
2019            .env(CHILD, "1")
2020            .stdout(std::process::Stdio::piped())
2021            .stderr(std::process::Stdio::piped())
2022            .spawn()
2023            .unwrap();
2024        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2025        while child.try_wait().unwrap().is_none() {
2026            if std::time::Instant::now() >= deadline {
2027                let _ = child.kill();
2028                let _ = child.wait();
2029                panic!("runtime action blocked the worker needed by its own dispatch");
2030            }
2031            std::thread::sleep(std::time::Duration::from_millis(10));
2032        }
2033        let output = child.wait_with_output().unwrap();
2034        assert!(
2035            output.status.success(),
2036            "{}\n{}",
2037            String::from_utf8_lossy(&output.stdout),
2038            String::from_utf8_lossy(&output.stderr)
2039        );
2040    }
2041
2042    #[async_trait::async_trait]
2043    impl RuntimeActionHost for MockHost {
2044        async fn send_message(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2045            unreachable!("not under test")
2046        }
2047        async fn send_user_message(
2048            &self,
2049            _: serde_json::Value,
2050        ) -> Result<serde_json::Value, String> {
2051            unreachable!("not under test")
2052        }
2053        async fn append_entry(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2054            unreachable!("not under test")
2055        }
2056        async fn set_session_name(
2057            &self,
2058            _: serde_json::Value,
2059        ) -> Result<serde_json::Value, String> {
2060            unreachable!("not under test")
2061        }
2062        async fn get_active_tools(
2063            &self,
2064            _: serde_json::Value,
2065        ) -> Result<serde_json::Value, String> {
2066            unreachable!("not under test")
2067        }
2068        async fn set_active_tools(
2069            &self,
2070            _: serde_json::Value,
2071        ) -> Result<serde_json::Value, String> {
2072            unreachable!("not under test")
2073        }
2074        async fn set_model(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2075            unreachable!("not under test")
2076        }
2077        async fn get_thinking_level(
2078            &self,
2079            _: serde_json::Value,
2080        ) -> Result<serde_json::Value, String> {
2081            unreachable!("not under test")
2082        }
2083        async fn set_thinking_level(
2084            &self,
2085            _: serde_json::Value,
2086        ) -> Result<serde_json::Value, String> {
2087            unreachable!("not under test")
2088        }
2089        async fn compact(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2090            unreachable!("not under test")
2091        }
2092        async fn get_system_prompt(
2093            &self,
2094            _: serde_json::Value,
2095        ) -> Result<serde_json::Value, String> {
2096            self.saw
2097                .lock()
2098                .unwrap()
2099                .push(RuntimeActionId::GetSystemPrompt);
2100            Ok(serde_json::json!({ "prompt": self.prompt }))
2101        }
2102        async fn new_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2103            unreachable!("not under test")
2104        }
2105        async fn fork(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2106            unreachable!("not under test")
2107        }
2108        async fn navigate_tree(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2109            unreachable!("not under test")
2110        }
2111        async fn switch_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2112            unreachable!("not under test")
2113        }
2114        async fn reload(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2115            self.saw.lock().unwrap().push(RuntimeActionId::Reload);
2116            Ok(serde_json::Value::Null)
2117        }
2118        async fn get_cli_flag(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
2119            self.saw.lock().unwrap().push(RuntimeActionId::GetCliFlag);
2120            Ok(serde_json::json!({ "value": true }))
2121        }
2122    }
2123
2124    /// Async host actions need a multi-thread runtime when called synchronously
2125    /// from inside it. The trampoline yields that worker with block_in_place;
2126    /// foreign/plugin threads instead park on the ordinary channel receive.
2127    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2128    async fn trampoline_round_trips_get_system_prompt() {
2129        let host = Arc::new(MockHost {
2130            prompt: "hello from host".to_string(),
2131            saw: Mutex::new(Vec::new()),
2132        });
2133        let host_for_assert = Arc::clone(&host);
2134        let host_dyn: Arc<dyn RuntimeActionHost> = host;
2135        let runtime = tokio::runtime::Handle::current();
2136        let bridge = ActionBridge::new(runtime, host_dyn);
2137        let user_data = bridge.user_data();
2138
2139        // Build a StbStringRef for the args. `{}` — getters ignore it.
2140        let args_str = "{}";
2141        let args_ref = StbStringRef::from_str(args_str);
2142
2143        let mut out = StbString::empty();
2144        let rc = trampoline_runtime_action(
2145            RuntimeActionId::GetSystemPrompt.into(),
2146            args_ref,
2147            &mut out as *mut StbString,
2148            user_data,
2149        );
2150        assert_eq!(rc, 0, "success return code");
2151
2152        // Read the result JSON back + reclaim the host-owned StbString.
2153        // SAFETY: the action wrote a live host-owned output, freed below.
2154        let json_text = unsafe {
2155            rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2156        }
2157        .to_string_lossy();
2158        let parsed: serde_json::Value = serde_json::from_str(&json_text).expect("valid json");
2159        assert_eq!(parsed["prompt"], "hello from host");
2160
2161        // The host saw exactly the one action. `host_for_assert` is a clone of
2162        // the `Arc<MockHost>` kept before it was coerced to the trait object.
2163        let saw = host_for_assert.saw.lock().unwrap().clone();
2164        assert_eq!(saw, vec![RuntimeActionId::GetSystemPrompt]);
2165    }
2166
2167    /// The `SetEditorText` runtime action must reach the bridge's editor-text
2168    /// mailbox through the ABI trampoline. This is the wiring a plugin relies on
2169    /// (a voice extension writes a transcription draft here); a broken action id
2170    /// or a dropped dispatch would be invisible to the plugin — it only sees
2171    /// `ok: true` — so pin it here.
2172    #[tokio::test]
2173    async fn trampoline_routes_set_editor_text_into_the_mailbox() {
2174        let host = Arc::new(MockHost {
2175            prompt: String::new(),
2176            saw: Mutex::new(Vec::new()),
2177        });
2178        let host_dyn: Arc<dyn RuntimeActionHost> = host;
2179        let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2180        let mailbox = bridge.editor_text_mailbox();
2181        let user_data = bridge.user_data();
2182
2183        let args_ref =
2184            StbStringRef::from_str(r#"{"text":"from voice","mode":"append","autoSendMs":2000}"#);
2185        let mut out = StbString::empty();
2186        let rc = trampoline_runtime_action(
2187            RuntimeActionId::SetEditorText.into(),
2188            args_ref,
2189            &mut out as *mut StbString,
2190            user_data,
2191        );
2192        assert_eq!(rc, 0, "success return code");
2193
2194        // SAFETY: the action wrote a live host-owned output, freed below.
2195        let parsed: serde_json::Value = serde_json::from_str(
2196            &unsafe {
2197                rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2198            }
2199            .to_string_lossy(),
2200        )
2201        .expect("valid json");
2202        assert_eq!(parsed["ok"], serde_json::json!(true));
2203        assert_eq!(parsed["chars"], serde_json::json!(10));
2204
2205        // The queued edit is what the host will apply to the prompt editor.
2206        let edit = mailbox.take_pending().expect("queued edit");
2207        assert_eq!(edit.text, "from voice");
2208        assert_eq!(edit.mode, crate::EditorTextMode::Append);
2209        assert_eq!(edit.auto_send_ms, Some(2000));
2210        assert!(mailbox.take_pending().is_none());
2211    }
2212
2213    #[tokio::test]
2214    async fn trampoline_null_user_data_returns_minus_one() {
2215        let args_ref = StbStringRef::from_str("{}");
2216        let mut out = StbString::empty();
2217        let rc = trampoline_runtime_action(
2218            RuntimeActionId::GetSystemPrompt.into(),
2219            args_ref,
2220            &mut out as *mut StbString,
2221            std::ptr::null_mut(),
2222        );
2223        assert_eq!(rc, -1, "null user_data ⇒ no bridge");
2224    }
2225
2226    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2227    async fn trampoline_intercepts_reload_when_bridge_has_callback() {
2228        // A bridge with a reload callback: the spawn site intercepts Reload and
2229        // runs the callback instead of the host's `reload` method. Proves the
2230        // bridge-level special-casing (the host impl is the fallback only).
2231        use std::sync::atomic::{AtomicUsize, Ordering};
2232        let reload_calls = Arc::new(AtomicUsize::new(0));
2233        let reload_calls_for_cb = Arc::clone(&reload_calls);
2234        let reload: Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync> =
2235            Arc::new(move || {
2236                let c = Arc::clone(&reload_calls_for_cb);
2237                Box::pin(async move {
2238                    c.fetch_add(1, Ordering::SeqCst);
2239                })
2240            });
2241        let host = Arc::new(MockHost {
2242            prompt: String::new(),
2243            saw: Mutex::new(Vec::new()),
2244        });
2245        let host_for_assert = Arc::clone(&host);
2246        let host_dyn: Arc<dyn RuntimeActionHost> = host;
2247        let runtime = tokio::runtime::Handle::current();
2248        let bridge = ActionBridge::with_reload(runtime, host_dyn, reload);
2249        let user_data = bridge.user_data();
2250
2251        let args_ref = StbStringRef::from_str("{}");
2252        let mut out = StbString::empty();
2253        let rc = trampoline_runtime_action(
2254            RuntimeActionId::Reload.into(),
2255            args_ref,
2256            &mut out as *mut StbString,
2257            user_data,
2258        );
2259        assert_eq!(rc, 0);
2260        // The callback ran once; the host's `reload` did NOT.
2261        assert_eq!(reload_calls.load(Ordering::SeqCst), 1);
2262        assert!(host_for_assert.saw.lock().unwrap().is_empty());
2263        // SAFETY: this action returned a live host allocation, not previously freed.
2264        drop(unsafe {
2265            rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2266        });
2267    }
2268
2269    /// B5d: an invalidated bridge rejects `runtime_action` with a stale-bridge
2270    /// error instead of dispatching. A `/reload` calls `invalidate` on the old
2271    /// bridge; an in-flight call that still holds the old pointer must fail
2272    /// fast rather than drive the swapped-out session.
2273    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2274    async fn trampoline_rejects_stale_bridge_with_invalidate() {
2275        let host = Arc::new(MockHost {
2276            prompt: String::new(),
2277            saw: Mutex::new(Vec::new()),
2278        });
2279        let host_for_assert = Arc::clone(&host);
2280        let host_dyn: Arc<dyn RuntimeActionHost> = host;
2281        let runtime = tokio::runtime::Handle::current();
2282        let bridge = ActionBridge::new(runtime, host_dyn);
2283        let user_data = bridge.user_data();
2284
2285        // Invalidate (as a `/reload` would on the old bridge).
2286        bridge.invalidate();
2287        assert!(!bridge.is_active());
2288
2289        let args_ref = StbStringRef::from_str("{}");
2290        let mut out = StbString::empty();
2291        let rc = trampoline_runtime_action(
2292            RuntimeActionId::GetSystemPrompt.into(),
2293            args_ref,
2294            &mut out as *mut StbString,
2295            user_data,
2296        );
2297        // Nonzero (error), and the host method never ran (no dispatch).
2298        assert_eq!(rc, 1, "stale bridge ⇒ error return code");
2299        // SAFETY: the action wrote a live host-owned output, freed below.
2300        let json_text = unsafe {
2301            rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2302        }
2303        .to_string_lossy();
2304        assert!(
2305            json_text.contains("stale"),
2306            "stale-bridge error payload: {json_text}"
2307        );
2308
2309        assert!(
2310            host_for_assert.saw.lock().unwrap().is_empty(),
2311            "host dispatch must NOT run on a stale bridge"
2312        );
2313    }
2314
2315    #[tokio::test]
2316    async fn trampoline_rejects_unknown_numeric_id_without_dispatch() {
2317        let host = Arc::new(MockHost {
2318            prompt: String::new(),
2319            saw: Mutex::new(Vec::new()),
2320        });
2321        let host_for_assert = Arc::clone(&host);
2322        let host_dyn: Arc<dyn RuntimeActionHost> = host;
2323        let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2324        let user_data = bridge.user_data();
2325
2326        let mut out = StbString::empty();
2327        let rc = trampoline_runtime_action(
2328            0xFFFF_FFFE,
2329            StbStringRef::from_str("{}"),
2330            &mut out,
2331            user_data,
2332        );
2333
2334        assert_eq!(rc, 2, "unknown action id must be a protocol error");
2335        let payload: serde_json::Value = serde_json::from_str(
2336            &unsafe {
2337                rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2338            }
2339            .to_string_lossy(),
2340        )
2341        .expect("structured error JSON");
2342        assert_eq!(payload["error"], "unknown runtime action id 4294967294");
2343
2344        assert!(
2345            host_for_assert.saw.lock().unwrap().is_empty(),
2346            "unknown action id must not reach host dispatch"
2347        );
2348    }
2349
2350    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2351    async fn v2_trampoline_accepts_new_action() {
2352        let host = Arc::new(MockHost {
2353            prompt: "v2".to_string(),
2354            saw: Mutex::new(Vec::new()),
2355        });
2356        let host_for_assert = Arc::clone(&host);
2357        let host_dyn: Arc<dyn RuntimeActionHost> = host;
2358        let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host_dyn);
2359        let user_data = bridge.user_data();
2360
2361        let mut v2_out = StbString::empty();
2362        assert_eq!(
2363            trampoline_runtime_action(
2364                RuntimeActionId::GetCliFlag.into(),
2365                StbStringRef::from_str(r#"{"name":"flag"}"#),
2366                &mut v2_out,
2367                user_data,
2368            ),
2369            0
2370        );
2371        // SAFETY: this action returned a live host allocation, not previously freed.
2372        drop(unsafe {
2373            rpi_plugin_sdk::callbacks::OwnedString::from_raw(v2_out, Some(crate::host_free_string))
2374        });
2375
2376        assert_eq!(
2377            *host_for_assert.saw.lock().unwrap(),
2378            vec![RuntimeActionId::GetCliFlag]
2379        );
2380    }
2381
2382    /// `ReloadMailbox` + `reload_callback_from_mailbox` round-trip: signalling
2383    /// fires the installed receiver; an uninstalled mailbox yields `Err` (the
2384    /// host's "not configured" fallback). Exercises the B5d reload-signal path
2385    /// the TUI installs.
2386    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2387    async fn reload_mailbox_signals_installed_receiver() {
2388        let mailbox = ReloadMailbox::new();
2389        // No receiver installed yet ⇒ signal fails.
2390        assert!(matches!(mailbox.signal(), Err(())));
2391
2392        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2393        mailbox.install(tx);
2394        let cb = reload_callback_from_mailbox(mailbox.clone());
2395        cb().await;
2396        assert_eq!(
2397            rx.recv().await,
2398            Some(()),
2399            "installed receiver saw the signal"
2400        );
2401        mailbox.clear();
2402    }
2403
2404    // ---- UiDialogMailbox (runtime action 17 / ask_user) ----
2405
2406    fn open_args(id: &str, tool_call: &str) -> serde_json::Value {
2407        serde_json::json!({
2408            "op": "open",
2409            "requestId": id,
2410            "toolCallId": tool_call,
2411            "ui": {"kind": "selector", "questions": [
2412                {"id": "q1", "question": "Which target?", "options": ["Linux"]}
2413            ]},
2414        })
2415    }
2416
2417    /// Headless hosts (nothing attached) must fail loudly rather than fabricate
2418    /// a user answer.
2419    #[test]
2420    fn ui_dialog_open_requires_an_attached_ui() {
2421        let mailbox = UiDialogMailbox::new();
2422        let error = mailbox.handle(open_args("r1", "c1")).unwrap_err();
2423        assert!(error.contains("interactive UI"), "got: {error}");
2424    }
2425
2426    #[test]
2427    fn ui_dialog_attachment_generation_exhaustion_fails_closed() {
2428        let mailbox = UiDialogMailbox::new();
2429        mailbox
2430            .state
2431            .lock()
2432            .expect("ui dialog mailbox poisoned")
2433            .attachment_generation = u64::MAX;
2434
2435        assert_eq!(mailbox.try_attach_with_generation(), None);
2436        assert_eq!(mailbox.attachment_generation(), Some(u64::MAX));
2437        assert!(!mailbox.is_attached());
2438
2439        // The compatibility attach API also refuses to reuse the terminal
2440        // generation rather than silently reopening the mailbox.
2441        mailbox.attach();
2442        assert!(!mailbox.is_attached());
2443    }
2444
2445    #[test]
2446    fn ui_dialog_attachment_lock_poison_fails_closed_without_panicking() {
2447        let mailbox = UiDialogMailbox::new();
2448        let state = mailbox.state.clone();
2449        assert!(std::thread::spawn(move || {
2450            let _guard = state.lock().unwrap();
2451            panic!("poison synthetic dialog mailbox state");
2452        })
2453        .join()
2454        .is_err());
2455
2456        assert_eq!(mailbox.try_attach_with_generation(), None);
2457        assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2458            // The compatibility API must also refuse rather than panic.
2459            mailbox.attach();
2460        }))
2461        .is_ok());
2462    }
2463
2464    #[test]
2465    fn ui_dialog_observation_lock_poison_fails_closed_without_panicking() {
2466        let mailbox = UiDialogMailbox::new();
2467        let state = mailbox.state.clone();
2468        assert!(std::thread::spawn(move || {
2469            let _guard = state.lock().unwrap();
2470            panic!("poison synthetic dialog observation state");
2471        })
2472        .join()
2473        .is_err());
2474
2475        assert_eq!(mailbox.attachment_generation(), None);
2476        assert!(!mailbox.is_attached());
2477    }
2478
2479    #[test]
2480    fn ui_dialog_detach_generation_lock_poison_fails_closed_without_panicking() {
2481        let mailbox = UiDialogMailbox::new();
2482        let state = mailbox.state.clone();
2483        assert!(std::thread::spawn(move || {
2484            let _guard = state.lock().unwrap();
2485            panic!("poison synthetic dialog retirement state");
2486        })
2487        .join()
2488        .is_err());
2489
2490        assert!(!mailbox.detach_if_generation(1));
2491    }
2492
2493    #[test]
2494    fn ui_dialog_compat_detach_lock_poison_fails_closed_without_panicking() {
2495        let mailbox = UiDialogMailbox::new();
2496        let state = mailbox.state.clone();
2497        assert!(std::thread::spawn(move || {
2498            let _guard = state.lock().unwrap();
2499            panic!("poison synthetic dialog compatibility retirement state");
2500        })
2501        .join()
2502        .is_err());
2503
2504        assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2505            mailbox.detach();
2506        }))
2507        .is_ok());
2508        assert_eq!(mailbox.try_attach_with_generation(), None);
2509    }
2510
2511    #[test]
2512    fn ui_dialog_open_poll_answer_round_trip() {
2513        let mailbox = UiDialogMailbox::new();
2514        mailbox.attach();
2515
2516        let opened = mailbox.handle(open_args("r1", "c1")).unwrap();
2517        assert_eq!(opened["status"], "pending");
2518        assert_eq!(opened["toolCallId"], "c1");
2519
2520        let request = mailbox.take_pending().expect("request visible to TUI");
2521        assert_eq!(request.request_id, "r1");
2522        assert_eq!(request.tool_call_id.as_deref(), Some("c1"));
2523        // A pending poll is non-destructive and remains available.
2524        assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2525        assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2526
2527        mailbox
2528            .respond("r1", serde_json::json!("7890"))
2529            .expect("respond");
2530        let answered = mailbox.poll("r1").unwrap();
2531        assert_eq!(answered["status"], "answered");
2532        assert_eq!(answered["answer"], "7890");
2533        // Polling consumes the terminal entry.
2534        assert!(mailbox.poll("r1").is_err());
2535    }
2536
2537    #[test]
2538    fn ui_dialog_forget_reclaims_terminal_entries_without_stranding_pending_ones() {
2539        let mailbox = UiDialogMailbox::new();
2540        mailbox.attach();
2541
2542        // A live request cannot be forgotten: the UI is still waiting for an
2543        // answer and deleting it would strand the question.
2544        mailbox.handle(open_args("r1", "c1")).unwrap();
2545        assert_eq!(
2546            mailbox.forget("r1"),
2547            Err("UI request `r1` is still pending".to_string())
2548        );
2549        assert_eq!(mailbox.poll("r1").unwrap()["status"], "pending");
2550
2551        // A cancelled request that the plugin will never poll again is
2552        // reclaimed explicitly, so `active` does not grow for the host's life.
2553        mailbox.cancel("r1").unwrap();
2554        assert_eq!(mailbox.forget("r1"), Ok(true));
2555        assert_eq!(mailbox.forget("r1"), Ok(false)); // idempotent
2556        assert!(mailbox.poll("r1").is_err());
2557
2558        // The same works for an answered request, and through the JSON
2559        // `forget` op used across the ABI boundary.
2560        mailbox.handle(open_args("r2", "c2")).unwrap();
2561        mailbox
2562            .respond("r2", serde_json::json!({"values": ["Linux"]}))
2563            .unwrap();
2564        let forgotten = mailbox
2565            .handle(serde_json::json!({"op": "forget", "requestId": "r2"}))
2566            .unwrap();
2567        assert_eq!(forgotten["status"], "forgotten");
2568        assert_eq!(forgotten["removed"], true);
2569        assert!(mailbox.poll("r2").is_err());
2570
2571        // Unknown ids are a no-op, and a forgotten id can be opened again
2572        // without replaying the old terminal state.
2573        assert_eq!(mailbox.forget("missing"), Ok(false));
2574        let reopened = mailbox.handle(open_args("r1", "c1")).unwrap();
2575        assert_eq!(reopened["status"], "pending");
2576    }
2577
2578    #[test]
2579    fn ui_dialog_cancel_is_reported_once() {
2580        let mailbox = UiDialogMailbox::new();
2581        mailbox.attach();
2582        mailbox.handle(open_args("r1", "c1")).unwrap();
2583        mailbox.cancel("r1").unwrap();
2584        let cancelled = mailbox.poll("r1").unwrap();
2585        assert_eq!(cancelled["status"], "cancelled");
2586        assert!(mailbox.poll("r1").is_err());
2587    }
2588
2589    #[test]
2590    fn ui_dialog_tool_cancel_preserves_other_calls_and_rejects_late_questions() {
2591        let mailbox = UiDialogMailbox::new();
2592        mailbox.attach();
2593        mailbox.handle(open_args("r1", "c1")).unwrap();
2594        mailbox.handle(open_args("r2", "c2")).unwrap();
2595        mailbox.cancel_tool_call("c1");
2596        assert_eq!(mailbox.poll("r1").unwrap()["status"], "cancelled");
2597        assert_eq!(mailbox.take_pending().unwrap().request_id, "r2");
2598        assert_eq!(mailbox.poll("r2").unwrap()["status"], "pending");
2599        assert_eq!(
2600            mailbox.handle(open_args("late", "c1")).unwrap()["status"],
2601            "cancelled"
2602        );
2603        assert!(mailbox.take_pending().is_none());
2604    }
2605
2606    #[test]
2607    fn ui_dialog_concurrent_requests_do_not_cross_answers() {
2608        let mailbox = UiDialogMailbox::new();
2609        mailbox.attach();
2610        mailbox.handle(open_args("r1", "c1")).unwrap();
2611        mailbox.handle(open_args("r2", "c2")).unwrap();
2612
2613        let first = mailbox.take_pending().unwrap().request_id;
2614        let second = mailbox.take_pending().unwrap().request_id;
2615        assert_ne!(first, second);
2616
2617        // Answer the SECOND request first; the first must stay pending.
2618        mailbox
2619            .respond(&second, serde_json::json!("second"))
2620            .unwrap();
2621        assert_eq!(mailbox.poll(&first).unwrap()["status"], "pending");
2622        let second_answer = mailbox.poll(&second).unwrap();
2623        assert_eq!(second_answer["answer"], "second");
2624
2625        mailbox.respond(&first, serde_json::json!("first")).unwrap();
2626        assert_eq!(mailbox.poll(&first).unwrap()["answer"], "first");
2627    }
2628
2629    #[test]
2630    fn ui_dialog_detach_cancels_outstanding() {
2631        let mailbox = UiDialogMailbox::new();
2632        mailbox.attach();
2633        mailbox.handle(open_args("r1", "c1")).unwrap();
2634        mailbox.detach();
2635        assert!(!mailbox.is_attached());
2636        assert_eq!(mailbox.pending_len(), 0);
2637        // Re-opening without a consumer is an explicit error again.
2638        assert!(mailbox.handle(open_args("r2", "c2")).is_err());
2639        assert_eq!(mailbox.poll("r1").unwrap()["status"], "cancelled");
2640    }
2641
2642    #[test]
2643    fn ui_dialog_duplicate_open_does_not_reenqueue() {
2644        let mailbox = UiDialogMailbox::new();
2645        mailbox.attach();
2646        mailbox.handle(open_args("r1", "c1")).unwrap();
2647        let again = mailbox.handle(open_args("r1", "c1")).unwrap();
2648        assert_eq!(again["status"], "pending");
2649        assert_eq!(mailbox.pending_len(), 1);
2650        mailbox.take_pending().unwrap();
2651        assert!(mailbox.take_pending().is_none());
2652    }
2653
2654    /// `ListCommands` must route through the trampoline to the host method, and
2655    /// the default implementation must answer with an **empty list** rather than
2656    /// an error — a client has to be able to tell "no commands registered" apart
2657    /// from "this host does not support the action".
2658    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2659    async fn list_commands_routes_to_the_host_and_defaults_to_empty() {
2660        let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2661            prompt: String::new(),
2662            saw: Mutex::new(Vec::new()),
2663        });
2664        let bridge = ActionBridge::with_ui_dialog(
2665            tokio::runtime::Handle::current(),
2666            host,
2667            UiDialogMailbox::new(),
2668        );
2669        let user_data = bridge.user_data();
2670        let mut out = StbString::empty();
2671        let rc = trampoline_runtime_action(
2672            u32::from(RuntimeActionId::ListCommands),
2673            StbStringRef::from_str("{}"),
2674            &mut out,
2675            user_data,
2676        );
2677        assert_eq!(
2678            rc, 0,
2679            "ListCommands must not fail on a host with no registry"
2680        );
2681        let payload: serde_json::Value = serde_json::from_str(
2682            &unsafe {
2683                rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2684            }
2685            .to_string_lossy(),
2686        )
2687        .expect("JSON");
2688        assert_eq!(
2689            payload
2690                .get("commands")
2691                .and_then(|c| c.as_array())
2692                .map(Vec::len),
2693            Some(0),
2694            "an empty registry is an empty list, not an error: {payload}"
2695        );
2696    }
2697
2698    /// The v2 trampoline must route action 17 into the session mailbox rather
2699    /// than rejecting it as unknown, and a detached mailbox must surface the
2700    /// explicit "requires an interactive UI" error (headless contract).
2701    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2702    async fn v2_dispatch_routes_ui_dialog_action_17() {
2703        let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2704            prompt: String::new(),
2705            saw: Mutex::new(Vec::new()),
2706        });
2707        let bridge = ActionBridge::with_ui_dialog(
2708            tokio::runtime::Handle::current(),
2709            host,
2710            UiDialogMailbox::new(),
2711        );
2712        let user_data = bridge.user_data();
2713
2714        let mut out = StbString::empty();
2715        let rc = trampoline_runtime_action(
2716            17,
2717            StbStringRef::from_str(r#"{"op":"open","requestId":"r1","ui":{}}"#),
2718            &mut out,
2719            user_data,
2720        );
2721        assert_eq!(rc, 1);
2722        let payload: serde_json::Value = serde_json::from_str(
2723            &unsafe {
2724                rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2725            }
2726            .to_string_lossy(),
2727        )
2728        .expect("structured error JSON");
2729        assert!(
2730            payload["error"]
2731                .as_str()
2732                .is_some_and(|error| error.contains("interactive UI")),
2733            "unexpected payload: {payload}"
2734        );
2735
2736        // A genuinely unknown id is still rejected (no silent acceptance).
2737        // Derive "one past the highest" from the enum so adding an action does
2738        // not silently turn this into a real dispatch.
2739        let one_past_last = rpi_plugin_sdk::RuntimeActionId::MAX + 1;
2740        let mut out = StbString::empty();
2741        assert_eq!(
2742            trampoline_runtime_action(
2743                one_past_last,
2744                StbStringRef::from_str("{}"),
2745                &mut out,
2746                user_data
2747            ),
2748            2
2749        );
2750        // SAFETY: this action returned a live host allocation, not previously freed.
2751        drop(unsafe {
2752            rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2753        });
2754    }
2755
2756    #[tokio::test(flavor = "current_thread")]
2757    async fn component_bridge_isolates_plugins_and_cleans_up_reload_and_drop() {
2758        let host = Arc::new(MockHost {
2759            prompt: String::new(),
2760            saw: Mutex::new(Vec::new()),
2761        });
2762        let root = ActionBridge::new(tokio::runtime::Handle::current(), host);
2763        let a = root.for_plugin("a");
2764        let b = root.for_plugin("b");
2765        let mailbox = root.extension_status_mailbox();
2766        for plugin in [&a, &b] {
2767            let mut out = StbString::empty();
2768            assert_eq!(
2769                trampoline_runtime_action(
2770                    22,
2771                    StbStringRef::from_str(
2772                        r#"{"op":"register","id":"same","slot":"footer.after"}"#
2773                    ),
2774                    &mut out,
2775                    plugin.user_data()
2776                ),
2777                0
2778            );
2779            // SAFETY: this action returned a live host allocation, not previously freed.
2780            drop(unsafe {
2781                rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2782            });
2783        }
2784        assert_eq!(mailbox.panels().len(), 2);
2785        drop(a);
2786        assert_eq!(mailbox.panels().len(), 1);
2787        root.invalidate();
2788        assert!(mailbox.panels().is_empty());
2789    }
2790
2791    /// Action 28 is mailbox-only, so it must not need a Tokio worker.
2792    ///
2793    /// The route must be off-executor: on a current-thread bridge a spawn-based
2794    /// route parks the only thread able to finish the call. The timeout is the
2795    /// regression.
2796    #[test]
2797    fn relay_ui_dialog_runs_off_the_executor() {
2798        let mailbox = UiDialogMailbox::new();
2799        mailbox.attach();
2800        let out = dispatch_relay_ui_dialog(&mailbox, serde_json::json!({"op":"release"}))
2801            .expect("release is a supported op");
2802        assert_eq!(out["requeued"], serde_json::json!(0));
2803    }
2804
2805    /// Action 18 (`SetStatus`) is bridge-local, like `UiDialog`: it writes the
2806    /// shared registry the TUI polls and never touches the harness.
2807    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2808    async fn v2_dispatch_routes_set_status_action_18() {
2809        let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2810            prompt: String::new(),
2811            saw: Mutex::new(Vec::new()),
2812        });
2813        let status = crate::status::ExtensionStatusMailbox::new();
2814        let bridge = ActionBridge::with_reload_and_ui(
2815            tokio::runtime::Handle::current(),
2816            host,
2817            Arc::new(|| Box::pin(async {})),
2818            UiDialogMailbox::new(),
2819            status.clone(),
2820            crate::editor_text::EditorTextMailbox::new(),
2821        );
2822        let user_data = bridge.user_data();
2823
2824        let mut out = StbString::empty();
2825        let rc = trampoline_runtime_action(
2826            18,
2827            StbStringRef::from_str(r#"{"key":"langfuse","value":"langfuse ✓ (trace sent)"}"#),
2828            &mut out,
2829            user_data,
2830        );
2831        assert_eq!(rc, 0);
2832        assert_eq!(status.text(), "langfuse ✓ (trace sent)");
2833        // SAFETY: this action returned a live host allocation, not previously freed.
2834        drop(unsafe {
2835            rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2836        });
2837
2838        // Clearing through the same action empties the line again.
2839        let mut out = StbString::empty();
2840        assert_eq!(
2841            trampoline_runtime_action(
2842                18,
2843                StbStringRef::from_str(r#"{"key":"langfuse","value":""}"#),
2844                &mut out,
2845                user_data
2846            ),
2847            0
2848        );
2849        assert_eq!(status.text(), "");
2850        // SAFETY: this action returned a live host allocation, not previously freed.
2851        drop(unsafe {
2852            rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2853        });
2854
2855        // A missing key is a host-level error (rc=1), not an unknown action.
2856        let mut out = StbString::empty();
2857        assert_eq!(
2858            trampoline_runtime_action(18, StbStringRef::from_str("{}"), &mut out, user_data),
2859            1
2860        );
2861        // SAFETY: this action returned a live host allocation, not previously freed.
2862        drop(unsafe {
2863            rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2864        });
2865    }
2866    /// The FFI trampoline's ceiling must be exactly the SDK's highest action id.
2867    ///
2868    /// A branch that adds an action but leaves the ceiling behind compiles,
2869    /// keeps every other test green, and quietly makes the newest action
2870    /// un-dispatchable. The ceiling and the enum live in different crates, so
2871    /// nothing but a test can notice the drift.
2872    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2873    async fn trampoline_ceiling_matches_the_highest_defined_action() {
2874        let highest = RuntimeActionId::MAX;
2875        assert_eq!(
2876            highest,
2877            RuntimeActionId::ALL
2878                .iter()
2879                .copied()
2880                .map(u32::from)
2881                .max()
2882                .unwrap(),
2883            "RuntimeActionId::MAX must be the maximum of RuntimeActionId::ALL"
2884        );
2885        let host: Arc<dyn RuntimeActionHost> = Arc::new(MockHost {
2886            prompt: String::new(),
2887            saw: Mutex::new(Vec::new()),
2888        });
2889        let bridge = ActionBridge::with_ui_dialog(
2890            tokio::runtime::Handle::current(),
2891            host,
2892            UiDialogMailbox::new(),
2893        );
2894        let mut out = StbString::empty();
2895        let rc = trampoline_runtime_action(
2896            highest,
2897            StbStringRef::from_str("{}"),
2898            &mut out,
2899            bridge.user_data(),
2900        );
2901        assert_ne!(
2902            rc, 2,
2903            "the highest defined action id ({highest}) must not be rejected as unknown — \
2904             the trampoline ceiling is stale"
2905        );
2906        if rc == 0 {
2907            // SAFETY: success means the trampoline wrote a live host allocation.
2908            drop(unsafe {
2909                rpi_plugin_sdk::callbacks::OwnedString::from_raw(out, Some(crate::host_free_string))
2910            });
2911        }
2912    }
2913}
2914
2915impl Drop for ActionBridge {
2916    fn drop(&mut self) {
2917        bridges()
2918            .lock()
2919            .unwrap_or_else(|e| e.into_inner())
2920            .retain(|_, entry| !std::ptr::eq(entry.bridge.as_ptr(), self));
2921        if self.invocation.is_some() {
2922            return;
2923        }
2924        if let Some((owner, _)) = &self.plugin_identity {
2925            self.ext_status.remove_owner(*owner);
2926            self.host.cancel_child_agents(*owner);
2927            self.host.cancel_side_questions(*owner);
2928        }
2929    }
2930}
2931
2932#[cfg(test)]
2933mod runtime_tests;
2934
2935#[cfg(test)]
2936mod relay_tests {
2937    use super::*;
2938
2939    fn request(id: &str) -> UiDialogRequest {
2940        UiDialogRequest {
2941            request_id: id.to_string(),
2942            tool_call_id: Some(format!("tool-{id}")),
2943            ui: serde_json::json!({"question": "ok?"}),
2944            raw: serde_json::json!({}),
2945        }
2946    }
2947
2948    /// A reserved request must be invisible to the TUI but visible to the plugin
2949    /// that reserved it. Otherwise a remote UI's question pops up in the
2950    /// terminal while the user who can answer it is watching the remote client.
2951    #[test]
2952    fn reserved_requests_are_invisible_to_the_tui() {
2953        let mailbox = UiDialogMailbox::new();
2954        mailbox.attach();
2955        let reserved = format!("{PLUGIN_RESERVED_PREFIX}gate-1");
2956        mailbox
2957            .handle(serde_json::json!({
2958                "op": "open",
2959                "requestId": reserved,
2960                "toolCallId": "t1",
2961                "ui": {}
2962            }))
2963            .unwrap();
2964        mailbox
2965            .handle(serde_json::json!({
2966                "op": "open",
2967                "requestId": "plain-1",
2968                "toolCallId": "t2",
2969                "ui": {}
2970            }))
2971            .unwrap();
2972
2973        // The TUI skips the reserved one and takes the plain one.
2974        let taken = mailbox
2975            .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
2976            .expect("the unreserved request must reach the TUI");
2977        assert_eq!(taken.request_id, "plain-1");
2978
2979        // The plugin still sees its own.
2980        let own = mailbox
2981            .take_pending_filtered(|r| mailbox.is_reserved(&r.request_id))
2982            .expect("the plugin must still see its reserved request");
2983        assert_eq!(own.request_id, reserved);
2984    }
2985
2986    /// Losing the relay consumer must not leave the TUI locked out forever.
2987    #[test]
2988    fn release_or_detach_clears_takeover_and_requeues_unanswered() {
2989        let mailbox = UiDialogMailbox::new();
2990        mailbox.attach();
2991        mailbox
2992            .handle(serde_json::json!({
2993                "op": "open", "requestId": "plain-r", "toolCallId": "t", "ui": {}
2994            }))
2995            .unwrap();
2996
2997        // Relay takes it, then gives up without answering.
2998        mailbox.set_external_takeover(true);
2999        assert_eq!(mailbox.take_all_unreserved().len(), 1);
3000        assert_eq!(mailbox.release_takeover(), 1);
3001        assert!(
3002            !mailbox.external_takeover(),
3003            "release must hand delivery back to the TUI"
3004        );
3005        // The question is visible again instead of being silently lost.
3006        assert_eq!(
3007            mailbox
3008                .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
3009                .map(|r| r.request_id),
3010            Some("plain-r".to_string())
3011        );
3012
3013        // Detach releases ownership too, so a reattached TUI can consume.
3014        mailbox.set_external_takeover(true);
3015        mailbox.detach();
3016        assert!(!mailbox.external_takeover(), "detach must clear takeover");
3017    }
3018
3019    /// Takeover and dequeue share one lock, so a relay cannot claim ownership
3020    /// in the gap and lose the question.
3021    #[test]
3022    fn tui_take_is_atomic_against_takeover() {
3023        let mailbox = UiDialogMailbox::new();
3024        mailbox.attach();
3025        mailbox.set_external_takeover(true);
3026        mailbox
3027            .handle(serde_json::json!({
3028                "op": "open", "requestId": "plain-a", "toolCallId": "t", "ui": {}
3029            }))
3030            .unwrap();
3031        assert!(
3032            mailbox.take_pending_unless_external(|_| true).is_none(),
3033            "the TUI must stand down while a relay owns delivery"
3034        );
3035        // Still queued for the relay.
3036        assert_eq!(mailbox.take_all_unreserved().len(), 1);
3037    }
3038
3039    /// `RelayUiDialog {op:"take"}` hands over everything no plugin reserved and
3040    /// leaves the reserved entries queued.
3041    #[test]
3042    fn relay_take_returns_unreserved_and_keeps_reserved() {
3043        let mailbox = UiDialogMailbox::new();
3044        mailbox.attach();
3045        mailbox
3046            .handle(serde_json::json!({
3047                "op": "open",
3048                "requestId": format!("{PLUGIN_RESERVED_PREFIX}keep"),
3049                "toolCallId": "t1",
3050                "ui": {}
3051            }))
3052            .unwrap();
3053        mailbox
3054            .handle(serde_json::json!({
3055                "op": "open",
3056                "requestId": "relay-1",
3057                "toolCallId": "t2",
3058                "ui": {}
3059            }))
3060            .unwrap();
3061
3062        let taken = mailbox.take_all_unreserved();
3063        assert_eq!(taken.len(), 1);
3064        assert_eq!(taken[0].request_id, "relay-1");
3065        // The reserved one is still there for its owner.
3066        assert_eq!(mailbox.pending_len(), 1);
3067    }
3068
3069    /// A taken request is still answerable — `take` moves it out of `pending`
3070    /// but keeps it in `active`.
3071    #[test]
3072    fn a_relayed_request_can_still_be_answered() {
3073        let mailbox = UiDialogMailbox::new();
3074        mailbox.attach();
3075        mailbox
3076            .handle(serde_json::json!({
3077                "op": "open",
3078                "requestId": "relay-1",
3079                "toolCallId": "t1",
3080                "ui": {}
3081            }))
3082            .unwrap();
3083        let taken = mailbox.take_all_unreserved();
3084        assert_eq!(taken.len(), 1);
3085
3086        mailbox
3087            .handle(serde_json::json!({
3088                "op": "respond",
3089                "requestId": "relay-1",
3090                "answer": {"ok": true}
3091            }))
3092            .unwrap();
3093        // Answered requests are not handed out again.
3094        assert_eq!(
3095            mailbox
3096                .take_pending_filtered(|_| true)
3097                .map(|r| r.request_id),
3098            None,
3099            "an answered request must not resurface"
3100        );
3101    }
3102
3103    /// `take_pending()` (the un-filtered form) still takes everything, so a
3104    /// caller that wants the old behaviour keeps it.
3105    #[test]
3106    fn take_pending_still_takes_reserved_entries() {
3107        let mailbox = UiDialogMailbox::new();
3108        mailbox.attach();
3109        let reserved = format!("{PLUGIN_RESERVED_PREFIX}x");
3110        mailbox
3111            .handle(serde_json::json!({
3112                "op": "open",
3113                "requestId": reserved,
3114                "toolCallId": "t1",
3115                "ui": {}
3116            }))
3117            .unwrap();
3118        assert_eq!(
3119            mailbox.take_pending().map(|r| r.request_id),
3120            Some(format!("{PLUGIN_RESERVED_PREFIX}x"))
3121        );
3122    }
3123
3124    /// External takeover must make the TUI skip taking entirely.
3125    ///
3126    /// The two consumers draw from the same queue, so without an owner whichever
3127    /// polls first wins. A remote client that has taken over must not race a
3128    /// terminal nobody is watching.
3129    #[test]
3130    fn external_takeover_makes_the_tui_stand_down() {
3131        let mailbox = UiDialogMailbox::new();
3132        mailbox.attach();
3133        mailbox
3134            .handle(serde_json::json!({
3135                "op": "open",
3136                "requestId": "plain-1",
3137                "toolCallId": "t1",
3138                "ui": {}
3139            }))
3140            .unwrap();
3141
3142        assert!(!mailbox.external_takeover());
3143        mailbox.set_external_takeover(true);
3144        assert!(mailbox.external_takeover());
3145
3146        // The TUI's take path returns nothing while the external UI owns it…
3147        let tui_take = |m: &UiDialogMailbox| {
3148            if m.external_takeover() {
3149                return None;
3150            }
3151            m.take_pending_filtered(|r| !m.is_reserved(&r.request_id))
3152        };
3153        assert!(
3154            tui_take(&mailbox).is_none(),
3155            "the TUI must not steal a request an external UI owns"
3156        );
3157        // …and the request is still there for the external consumer.
3158        assert_eq!(mailbox.take_all_unreserved().len(), 1);
3159    }
3160
3161    /// Handing ownership back lets the TUI resume.
3162    #[test]
3163    fn clearing_takeover_returns_dialogs_to_the_tui() {
3164        let mailbox = UiDialogMailbox::new();
3165        mailbox.attach();
3166        mailbox.set_external_takeover(true);
3167        mailbox.set_external_takeover(false);
3168        mailbox
3169            .handle(serde_json::json!({
3170                "op": "open",
3171                "requestId": "plain-2",
3172                "toolCallId": "t2",
3173                "ui": {}
3174            }))
3175            .unwrap();
3176        assert_eq!(
3177            mailbox
3178                .take_pending_filtered(|r| !mailbox.is_reserved(&r.request_id))
3179                .map(|r| r.request_id),
3180            Some("plain-2".to_string())
3181        );
3182    }
3183
3184    #[test]
3185    fn request_helper_matches_the_prefix_rule() {
3186        let mailbox = UiDialogMailbox::new();
3187        mailbox.attach();
3188        assert!(mailbox.is_reserved(&request(PLUGIN_RESERVED_PREFIX).request_id));
3189        assert!(!mailbox.is_reserved(&request("plain").request_id));
3190    }
3191}