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