supercode-harness 0.4.4

The optional native Supercode agent and tool harness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! P5-4's three load-bearing interactive handlers — the THIS-MODULE side of
//! the three deferred chains P5-1/P5-2/P5-3 each explicitly left for `tui`:
//!
//! 1. [`TuiApprovalHandler`] implements
//!    [`crate::permissions::PermissionsApprovalHandler`] (P5-1's seam):
//!    installed via [`crate::agent::Agent::set_permissions_approval_handler`].
//! 2. [`TuiElicitationHandler`] implements [`crate::mcp::McpElicitationHandler`]
//!    (P5-2's seam): installed via
//!    [`crate::mcp::McpClient::set_elicitation_handler`].
//! 3. [`TuiChildApprovalHandler`] — also a `PermissionsApprovalHandler`,
//!    installed via the factory
//!    [`crate::agent::Agent::set_child_approval_handler_factory`] (P5-4's
//!    OWN new seam, added specifically to close P5-3's §2.2 C6 "queued,
//!    never-blocking" chain into a genuinely answerable one).
//!
//! All three follow the same shape: push a `Pending*` request (from
//! [`crate::tui::bridge`]) onto a channel the render loop polls, then block
//! (synchronously for the two `PermissionsApprovalHandler`s — `ask` is a
//! sync trait method by design, see that trait's doc comment; via `.await`
//! for the async `McpElicitationHandler`) for the reply. If the reply
//! channel is ever dropped without a reply (the render loop panicked, or
//! the TUI process is shutting down mid-request), every handler here
//! resolves to the FAIL-CLOSED outcome (`Deny`/decline) — never a hang,
//! and never an implicit allow.
//!
//! **Security invariant (repeated at each handler below).** None of these
//! handlers can escalate what the permissions/elicitation engines already
//! decided: [`crate::permissions::approval::resolve_ask`] only ever calls a
//! `PermissionsApprovalHandler::ask` when the rule engine already resolved
//! the call to `Ask` (`Deny` short-circuits before any handler runs;
//! `Allow` never needs one) — a TUI "allow" here can only grant what the
//! policy already routed to a human prompt. Likewise an elicitation answer
//! is exactly what the user typed into the modal — never fabricated,
//! never auto-accepted.

use std::sync::{mpsc, Arc, Mutex};

use async_trait::async_trait;

use crate::mcp::{ElicitationRequest, ElicitationResponse, McpElicitationHandler};
use crate::permissions::{ApprovalOutcome, ApprovalRequest, PermissionsApprovalHandler};
use crate::subagents::QueuedApproval;

use super::bridge::{
    PendingApprovalRequest, PendingChildApproval, PendingElicitation, PendingOAuthDisplay,
};

/// P5-1's interactive ask-UI, closing the deferred chain
/// `crate::permissions::approval`'s module doc comment names. `ask` pushes
/// the request onto `tx` and blocks on a fresh one-shot reply channel;
/// `Self::tx` being closed (the render loop is gone) makes the blocking
/// `recv()` return an `Err`, which resolves to
/// [`ApprovalOutcome::Deny`] — fail-closed, matching the trait's own "no
/// handler ⇒ deny" default posture for the "handler installed but
/// unreachable" case too.
pub struct TuiApprovalHandler {
    tx: mpsc::Sender<PendingApprovalRequest>,
}

impl TuiApprovalHandler {
    /// Construct a handler that feeds `tx` — the matching `Receiver` half
    /// is [`TuiBridge::approval_rx`].
    pub fn new(tx: mpsc::Sender<PendingApprovalRequest>) -> Self {
        TuiApprovalHandler { tx }
    }
}

impl PermissionsApprovalHandler for TuiApprovalHandler {
    fn ask(&self, req: &ApprovalRequest) -> ApprovalOutcome {
        let (reply_tx, reply_rx) = mpsc::channel();
        let pending = PendingApprovalRequest {
            tool: req.tool.to_string(),
            subject: req.subject.map(String::from),
            raw_args: req.raw_args.clone(),
            reply_tx,
        };
        if self.tx.send(pending).is_err() {
            return ApprovalOutcome::Deny;
        }
        reply_rx.recv().unwrap_or(ApprovalOutcome::Deny)
    }
}

/// P5-3's answerable child-approval handler, closing the §2.2 C6 deferred
/// chain — see [`crate::agent::Agent::set_child_approval_handler_factory`]'s
/// doc comment for how this REPLACES (only when installed) the default
/// never-blocking [`crate::subagents::ParentQueueApprovalHandler`]. Also
/// records every request into the shared `queue` (the SAME
/// `Agent::pending_child_approvals` audit trail `ParentQueueApprovalHandler`
/// itself writes to), so [`crate::agent::Agent::pending_child_approvals`]
/// stays a complete audit log regardless of which handler answered a given
/// request.
pub struct TuiChildApprovalHandler {
    child_agent_id: String,
    queue: Arc<Mutex<Vec<QueuedApproval>>>,
    tx: mpsc::Sender<PendingChildApproval>,
}

impl TuiChildApprovalHandler {
    /// Construct a per-child handler — see
    /// `TuiBridge::child_approval_handler_factory` for the usual way one
    /// of these gets built (one per spawn, via
    /// [`crate::agent::Agent::set_child_approval_handler_factory`]).
    pub fn new(
        child_agent_id: String,
        queue: Arc<Mutex<Vec<QueuedApproval>>>,
        tx: mpsc::Sender<PendingChildApproval>,
    ) -> Self {
        TuiChildApprovalHandler {
            child_agent_id,
            queue,
            tx,
        }
    }
}

impl PermissionsApprovalHandler for TuiChildApprovalHandler {
    fn ask(&self, req: &ApprovalRequest) -> ApprovalOutcome {
        if let Ok(mut q) = self.queue.lock() {
            q.push(QueuedApproval {
                child_agent_id: self.child_agent_id.clone(),
                tool: req.tool.to_string(),
                subject: req.subject.map(String::from),
                queued_at_ms: now_ms(),
            });
        }
        let (reply_tx, reply_rx) = mpsc::channel();
        let pending = PendingChildApproval {
            child_agent_id: self.child_agent_id.clone(),
            tool: req.tool.to_string(),
            subject: req.subject.map(String::from),
            raw_args: req.raw_args.clone(),
            reply_tx,
        };
        if self.tx.send(pending).is_err() {
            return ApprovalOutcome::Deny;
        }
        reply_rx.recv().unwrap_or(ApprovalOutcome::Deny)
    }
}

fn now_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

/// P5-2's interactive elicitation UI, closing the deferred chain
/// [`crate::mcp::HeadlessElicitationHandler`]'s doc comment names. `handle`
/// is ASYNC (the MCP trait's own shape), so this uses a `tokio::sync::
/// oneshot` reply rather than blocking a thread — awaiting it yields the
/// executor to other work while the modal is up. A dropped reply sender
/// (render loop gone) resolves to [`crate::mcp::ElicitationAction::Cancel`]
/// (the MCP spec's own "dismissed without a decision" outcome — the
/// honest shape for "nobody answered", distinct from an explicit
/// `Decline`).
pub struct TuiElicitationHandler {
    tx: mpsc::Sender<PendingElicitation>,
}

impl TuiElicitationHandler {
    /// Construct a handler that feeds `tx` — the matching `Receiver` half
    /// is [`TuiBridge::elicitation_rx`].
    pub fn new(tx: mpsc::Sender<PendingElicitation>) -> Self {
        TuiElicitationHandler { tx }
    }
}

#[async_trait]
impl McpElicitationHandler for TuiElicitationHandler {
    async fn handle(&self, request: &ElicitationRequest) -> ElicitationResponse {
        let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
        let pending = PendingElicitation {
            message: request.message.clone(),
            requested_schema: request.requested_schema.clone(),
            reply_tx,
        };
        if self.tx.send(pending).is_err() {
            return ElicitationResponse {
                action: crate::mcp::ElicitationAction::Cancel,
                content: None,
            };
        }
        reply_rx.await.unwrap_or(ElicitationResponse {
            action: crate::mcp::ElicitationAction::Cancel,
            content: None,
        })
    }
}

/// The aggregate wiring point a `crates/cli` embedder uses: constructs
/// every channel pair once, installs the SENDING halves onto the `Agent`/
/// `McpClient`s that need them, and hands the RECEIVING halves to the
/// render loop to poll each frame. See [`crate::tui::should_activate`]'s
/// doc comment for why this is only ever built when the TUI is confirmed
/// active — installing these on an agent that no render loop is draining
/// would hang the first `Ask`-tier prompt or elicitation forever.
pub struct TuiBridge {
    approval_tx: mpsc::Sender<PendingApprovalRequest>,
    /// Poll this each render frame (`try_recv`) for a new top-level
    /// approval prompt to show.
    pub approval_rx: mpsc::Receiver<PendingApprovalRequest>,
    child_approval_tx: mpsc::Sender<PendingChildApproval>,
    /// Poll this each render frame for a new child-approval prompt.
    pub child_approval_rx: mpsc::Receiver<PendingChildApproval>,
    elicitation_tx: mpsc::Sender<PendingElicitation>,
    /// Poll this each render frame for a new elicitation prompt.
    pub elicitation_rx: mpsc::Receiver<PendingElicitation>,
    oauth_tx: mpsc::Sender<PendingOAuthDisplay>,
    /// Poll this each render frame for a new OAuth device-code display.
    pub oauth_rx: mpsc::Receiver<PendingOAuthDisplay>,
}

impl Default for TuiBridge {
    fn default() -> Self {
        Self::new()
    }
}

impl TuiBridge {
    /// Build a fresh bridge — four independent channel pairs, all cheap
    /// (unbounded `mpsc`, no background threads spawned here).
    pub fn new() -> Self {
        let (approval_tx, approval_rx) = mpsc::channel();
        let (child_approval_tx, child_approval_rx) = mpsc::channel();
        let (elicitation_tx, elicitation_rx) = mpsc::channel();
        let (oauth_tx, oauth_rx) = mpsc::channel();
        TuiBridge {
            approval_tx,
            approval_rx,
            child_approval_tx,
            child_approval_rx,
            elicitation_tx,
            elicitation_rx,
            oauth_tx,
            oauth_rx,
        }
    }

    /// Install this bridge's top-level-approval and child-approval-factory
    /// handlers onto `agent`. Does NOT touch MCP elicitation — an
    /// `McpClient` needs [`Self::elicitation_handler`] installed on IT
    /// directly (before the client is consumed into tool registration),
    /// which is why that's a separate method the caller invokes per
    /// client, earlier in its own connect sequence.
    pub fn install_on(&self, agent: &mut crate::agent::Agent) {
        agent.set_permissions_approval_handler(TuiApprovalHandler::new(self.approval_tx.clone()));
        agent.set_child_approval_handler_factory({
            let tx = self.child_approval_tx.clone();
            move |child_id, queue| {
                Arc::new(TuiChildApprovalHandler::new(child_id, queue, tx.clone()))
                    as Arc<dyn PermissionsApprovalHandler>
            }
        });
    }

    /// A fresh [`TuiElicitationHandler`] wired to this bridge — install on
    /// each `McpClient` via
    /// [`crate::mcp::McpClient::set_elicitation_handler`] before that
    /// client is consumed into tool registration.
    pub fn elicitation_handler(&self) -> Arc<dyn McpElicitationHandler> {
        Arc::new(TuiElicitationHandler::new(self.elicitation_tx.clone()))
    }

    /// The sender half for a one-shot OAuth device-code display push (P5-2
    /// device flow's `on_prompt` callback) — see `crates/cli`'s OAuth login
    /// wiring for the call site.
    pub fn oauth_sender(&self) -> mpsc::Sender<PendingOAuthDisplay> {
        self.oauth_tx.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::permissions::approval::resolve_ask;
    use crate::permissions::ApprovalCache;

    // ---- P5-1 chain: ask → modal → allow-for-session → cache ----

    #[test]
    fn approval_ask_blocks_until_render_loop_replies_allow_for_session_and_cache_then_skips_handler(
    ) {
        let (tx, rx) = mpsc::channel::<PendingApprovalRequest>();
        let handler = Arc::new(TuiApprovalHandler::new(tx));
        let cache = Arc::new(ApprovalCache::new());

        // First call: spawn a thread that calls `resolve_ask` (which
        // blocks inside `ask` until we reply below).
        let h = handler.clone();
        let c = cache.clone();
        let worker = std::thread::spawn(move || {
            let args = serde_json::json!({});
            let req = ApprovalRequest {
                tool: "bash",
                subject: Some("ls -la"),
                raw_args: &args,
            };
            resolve_ask(&c, Some(h.as_ref()), &req)
        });

        // Act as the render loop: receive the pending request, verify its
        // shape, and reply "allow for session".
        let pending = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
        assert_eq!(pending.tool, "bash");
        assert_eq!(pending.subject.as_deref(), Some("ls -la"));
        pending
            .reply_tx
            .send(ApprovalOutcome::AllowForSession)
            .unwrap();

        let approved = worker.join().unwrap();
        assert!(approved, "first Ask must be approved via the modal");

        // Second, IDENTICAL call: the cache must short-circuit — no
        // request should reach the handler's channel this time, proving
        // "approve for session" was actually recorded.
        let args = serde_json::json!({});
        let req2 = ApprovalRequest {
            tool: "bash",
            subject: Some("ls -la"),
            raw_args: &args,
        };
        let approved2 = resolve_ask(&cache, Some(handler.as_ref()), &req2);
        assert!(approved2);
        assert!(
            rx.try_recv().is_err(),
            "a cached AllowForSession must skip the handler entirely"
        );
    }

    #[test]
    fn approval_ask_deny_is_not_cached() {
        let (tx, rx) = mpsc::channel::<PendingApprovalRequest>();
        let handler = Arc::new(TuiApprovalHandler::new(tx));
        let cache = Arc::new(ApprovalCache::new());
        let h = handler.clone();
        let c = cache.clone();
        let worker = std::thread::spawn(move || {
            let args = serde_json::json!({});
            let req = ApprovalRequest {
                tool: "bash",
                subject: Some("curl evil.example"),
                raw_args: &args,
            };
            resolve_ask(&c, Some(h.as_ref()), &req)
        });
        let pending = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
        pending.reply_tx.send(ApprovalOutcome::Deny).unwrap();
        let approved = worker.join().unwrap();
        assert!(!approved);
        assert!(!cache.is_approved(&ApprovalCache::key("bash", Some("curl evil.example"))));
    }

    #[test]
    fn approval_ask_fails_closed_when_render_loop_is_gone() {
        let (tx, rx) = mpsc::channel::<PendingApprovalRequest>();
        let handler = TuiApprovalHandler::new(tx);
        drop(rx); // "render loop" gone before any request is sent
        let args = serde_json::json!({});
        let req = ApprovalRequest {
            tool: "bash",
            subject: None,
            raw_args: &args,
        };
        assert_eq!(handler.ask(&req), ApprovalOutcome::Deny);
    }

    #[test]
    fn approval_ask_fails_closed_when_reply_sender_is_dropped_without_replying() {
        let (tx, rx) = mpsc::channel::<PendingApprovalRequest>();
        let handler = Arc::new(TuiApprovalHandler::new(tx));
        let h = handler.clone();
        let worker = std::thread::spawn(move || {
            let args = serde_json::json!({});
            let req = ApprovalRequest {
                tool: "bash",
                subject: None,
                raw_args: &args,
            };
            h.ask(&req)
        });
        let pending = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
        drop(pending.reply_tx); // render loop drops the request without answering
        assert_eq!(worker.join().unwrap(), ApprovalOutcome::Deny);
    }

    // ---- P5-1's escalation-floor invariant: `ask` is never called at all
    // for a `Deny`/`Allow` decision — `resolve_ask`/`decision_to_approved`
    // already enforce this (P5-1's own tests cover it); this just proves
    // the TUI handler doesn't change that wiring.

    #[test]
    fn approval_handler_never_consulted_when_rule_engine_already_denies() {
        use crate::permissions::approval::decision_to_approved;
        use crate::permissions::rules::Decision;
        let (tx, rx) = mpsc::channel::<PendingApprovalRequest>();
        let handler = TuiApprovalHandler::new(tx);
        // `decision_to_approved` never even calls the closure for `Deny` —
        // if it did, `handler.ask` would block forever (nothing ever
        // drains `rx`) and this test would hang/timeout instead of
        // passing, so a passing test IS the proof.
        let approved = decision_to_approved(Decision::Deny, || {
            handler.ask(&ApprovalRequest {
                tool: "bash",
                subject: None,
                raw_args: &serde_json::json!({}),
            }) == ApprovalOutcome::Allow
        });
        assert!(!approved);
        assert!(rx.try_recv().is_err(), "handler must never have been asked");
    }

    // ---- P5-3 chain: child ask → modal → allow → answered, not immediate-deny ----

    #[test]
    fn child_approval_handler_blocks_for_an_answer_instead_of_immediate_deny() {
        let (tx, rx) = mpsc::channel::<PendingChildApproval>();
        let queue = Arc::new(Mutex::new(Vec::new()));
        let handler = Arc::new(TuiChildApprovalHandler::new(
            "agent-bg-7".to_string(),
            queue.clone(),
            tx,
        ));
        let h = handler.clone();
        let worker = std::thread::spawn(move || {
            let args = serde_json::json!({});
            let subject = "/workspace/out.txt".to_string();
            let req = ApprovalRequest {
                tool: "write_file",
                subject: Some(subject.as_str()),
                raw_args: &args,
            };
            h.ask(&req)
        });
        let pending = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
        assert_eq!(pending.child_agent_id, "agent-bg-7");
        assert_eq!(pending.tool, "write_file");
        pending.reply_tx.send(ApprovalOutcome::Allow).unwrap();
        assert_eq!(worker.join().unwrap(), ApprovalOutcome::Allow);

        // Still recorded in the shared audit queue, same as the default
        // `ParentQueueApprovalHandler` would.
        let recorded = queue.lock().unwrap();
        assert_eq!(recorded.len(), 1);
        assert_eq!(recorded[0].child_agent_id, "agent-bg-7");
    }

    #[test]
    fn child_approval_handler_fails_closed_when_nobody_answers() {
        let (tx, rx) = mpsc::channel::<PendingChildApproval>();
        let queue = Arc::new(Mutex::new(Vec::new()));
        let handler = Arc::new(TuiChildApprovalHandler::new(
            "agent-bg-8".to_string(),
            queue,
            tx,
        ));
        let h = handler.clone();
        let worker = std::thread::spawn(move || {
            let args = serde_json::json!({});
            let req = ApprovalRequest {
                tool: "bash",
                subject: None,
                raw_args: &args,
            };
            h.ask(&req)
        });
        let pending = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
        drop(pending); // dropped without a reply
        assert_eq!(worker.join().unwrap(), ApprovalOutcome::Deny);
    }

    // ---- P5-2 chain: elicitation request → modal → answer ----

    #[tokio::test]
    async fn elicitation_handler_returns_the_modals_accept_answer() {
        let (tx, rx) = mpsc::channel::<PendingElicitation>();
        let handler = TuiElicitationHandler::new(tx);
        let request = ElicitationRequest {
            message: "What's the deploy tag?".to_string(),
            requested_schema: serde_json::json!({"properties": {"tag": {"type": "string"}}}),
        };

        let handle_fut = handler.handle(&request);
        // Poll the channel from a blocking thread (mpsc::Receiver::recv is
        // sync) concurrently with the future above via `tokio::join!`.
        let reply_task = tokio::task::spawn_blocking(move || {
            let pending = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
            assert_eq!(pending.message, "What's the deploy tag?");
            pending
                .reply_tx
                .send(ElicitationResponse {
                    action: crate::mcp::ElicitationAction::Accept,
                    content: Some(serde_json::json!({"tag": "v1.2.3"})),
                })
                .unwrap();
        });

        let (resp, _) = tokio::join!(handle_fut, reply_task);
        assert_eq!(resp.action, crate::mcp::ElicitationAction::Accept);
        assert_eq!(resp.content, Some(serde_json::json!({"tag": "v1.2.3"})));
    }

    #[tokio::test]
    async fn elicitation_handler_cancels_when_render_loop_is_gone() {
        let (tx, rx) = mpsc::channel::<PendingElicitation>();
        let handler = TuiElicitationHandler::new(tx);
        drop(rx);
        let request = ElicitationRequest {
            message: "".to_string(),
            requested_schema: serde_json::json!({}),
        };
        let resp = handler.handle(&request).await;
        assert_eq!(resp.action, crate::mcp::ElicitationAction::Cancel);
        assert_eq!(resp.content, None);
    }

    #[tokio::test]
    async fn elicitation_handler_cancels_when_reply_sender_dropped_without_replying() {
        let (tx, rx) = mpsc::channel::<PendingElicitation>();
        let handler = TuiElicitationHandler::new(tx);
        let request = ElicitationRequest {
            message: "".to_string(),
            requested_schema: serde_json::json!({}),
        };
        let handle_fut = handler.handle(&request);
        let drop_task = tokio::task::spawn_blocking(move || {
            let pending = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
            drop(pending); // drops reply_tx without sending
        });
        let (resp, _) = tokio::join!(handle_fut, drop_task);
        assert_eq!(resp.action, crate::mcp::ElicitationAction::Cancel);
    }

    // ---- TuiBridge wiring smoke tests ----

    #[test]
    fn bridge_install_on_wires_a_working_approval_handler() {
        let bridge = TuiBridge::new();
        let mut agent = crate::agent::Agent::new(
            crate::Config::builder()
                .model("test/model")
                .api_key("test-key")
                .build(),
        )
        .expect("agent construction");
        bridge.install_on(&mut agent);
        // No direct accessor for the installed handler (by design — it's
        // `Agent`-private); this just proves `install_on` doesn't panic
        // and the bridge's receivers are still usable afterward.
        assert!(bridge.approval_rx.try_recv().is_err());
        assert!(bridge.child_approval_rx.try_recv().is_err());
    }

    #[test]
    fn bridge_elicitation_handler_feeds_the_bridges_receiver() {
        let bridge = TuiBridge::new();
        let handler = bridge.elicitation_handler();
        let h = handler.clone();
        let worker = std::thread::spawn(move || {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();
            rt.block_on(async {
                let req = ElicitationRequest {
                    message: "hi".to_string(),
                    requested_schema: serde_json::json!({}),
                };
                h.handle(&req).await
            })
        });
        let pending = bridge
            .elicitation_rx
            .recv_timeout(std::time::Duration::from_secs(5))
            .unwrap();
        pending
            .reply_tx
            .send(ElicitationResponse {
                action: crate::mcp::ElicitationAction::Decline,
                content: None,
            })
            .unwrap();
        let resp = worker.join().unwrap();
        assert_eq!(resp.action, crate::mcp::ElicitationAction::Decline);
    }
}