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