Skip to main content

rpi_cli/
session_driver.rs

1//! Transport-agnostic **session driver** — the "only the transport differs"
2//! boundary.
3//!
4//! A driver bundles the two things a TUI needs from its backend:
5//!
6//! 1. a **stream** of normalized events ([`DriverEvent`] / [`UiEvent`]), and
7//! 2. a **command** sink ([`DriverCommand`]).
8//!
9//! The remote client ([`RemoteDriver`]) implements this over TCP JSON-RPC. The
10//! local interactive host drives the same rendering path via
11//! [`map_agent_event`] (its own in-process `AgentEvent` stream → [`UiEvent`]).
12//! Because both sides speak [`UiEvent`], they render through the same
13//! [`crate::transcript_view::TranscriptView`].
14//!
15//! [`UiEvent`]: crate::transcript_view::UiEvent
16
17use std::sync::atomic::{AtomicU64, Ordering};
18use std::sync::{Arc, Mutex as StdMutex};
19
20use async_trait::async_trait;
21use base64::Engine;
22use serde_json::{json, Value};
23use tokio::sync::{broadcast, mpsc};
24
25use rpi_agent::{AgentEvent, AgentMessage};
26use rpi_ai::types::{AssistantMessage, Content, ThinkingLevel};
27use rpi_harness::agent_harness::AgentLane;
28use rpi_tui::AssistantBlock;
29
30use crate::remote::client::RemoteClient;
31use crate::remote::protocol::{RemoteCommand, RemoteEvent};
32use crate::remote::session::RemoteSession;
33use crate::transcript_view::{UiEvent, UiToolCall};
34
35/// A command the TUI sends to its backend.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum DriverCommand {
38    /// Answer or cancel a remote question by request id.
39    UiDialogResponse {
40        request_id: String,
41        answer: Option<Value>,
42    },
43    /// Run a prompt on the backend's main lane.
44    Prompt(String),
45    /// Interrupt the in-flight run.
46    Abort,
47    /// Re-query the backend's session state (model / thinking / tools).
48    RefreshState,
49    /// Switch the active model by id.
50    SetModel(String),
51    /// Set the thinking level (`off`…`max`).
52    SetThinkingLevel(String),
53    /// Replace the active tool set.
54    SetActiveTools(Vec<String>),
55}
56
57/// A snapshot of backend session state for the chrome (header / footer / retry).
58#[derive(Debug, Clone, Default, PartialEq)]
59pub struct DriverStatus {
60    pub ready: bool,
61    pub streaming: bool,
62    pub model: Option<String>,
63    pub thinking: Option<String>,
64    pub active_tools: Vec<String>,
65    /// `(attempt, max, delay_ms)` while a retry is pending.
66    pub retry: Option<(u32, u32, u64)>,
67}
68
69/// An item pushed from a driver to the TUI.
70#[derive(Debug, Clone)]
71pub enum DriverEvent {
72    UiDialog(rpi_extensions::UiDialogRequest),
73    UiDialogClosed(String),
74    /// A transcript event.
75    Ui(UiEvent),
76    /// A fresh session-state snapshot.
77    Status(DriverStatus),
78    /// A local notice line (error / connection message).
79    Notice(String),
80    /// The backend stream ended.
81    Ended,
82}
83
84/// A backend the TUI can drive: it yields [`DriverEvent`]s and accepts
85/// [`DriverCommand`]s. Both the in-process host and the remote client
86/// implement it, so the transcript render layer above is transport-agnostic.
87#[async_trait]
88pub trait SessionDriver: Send + Sync {
89    /// Take the driver's event receiver. Returns `Some` exactly once; later
90    /// calls return `None`.
91    fn events(&self) -> Option<mpsc::UnboundedReceiver<DriverEvent>>;
92
93    /// Send a command to the backend.
94    async fn send(&self, command: DriverCommand) -> Result<(), String>;
95}
96
97// ---------------------------------------------------------------------------
98// Local projection: in-process `AgentEvent` → normalized `UiEvent`
99// ---------------------------------------------------------------------------
100
101/// Project an in-process [`AgentEvent`] into the shared [`UiEvent`]. Returns
102/// `None` for events with no transcript effect.
103pub fn map_agent_event(event: &AgentEvent) -> Option<UiEvent> {
104    match event {
105        AgentEvent::AgentStart => Some(UiEvent::AgentStart),
106        AgentEvent::AgentEnd { .. } => Some(UiEvent::AgentEnd),
107        AgentEvent::RetryScheduled {
108            attempt,
109            max_retries,
110            delay_ms,
111            error,
112        } => Some(UiEvent::Retry {
113            attempt: *attempt,
114            max_retries: *max_retries,
115            delay_ms: *delay_ms,
116            error: error.clone(),
117        }),
118        AgentEvent::TurnStart | AgentEvent::TurnEnd { .. } => None,
119        AgentEvent::MessageStart { message, .. } => match message {
120            AgentMessage::Assistant(a) => Some(UiEvent::AssistantStart {
121                blocks: assistant_blocks(a),
122            }),
123            _ => None,
124        },
125        AgentEvent::MessageUpdate { message, .. } => Some(UiEvent::AssistantUpdate {
126            blocks: assistant_blocks(message),
127            tool_calls: assistant_tool_calls(message),
128        }),
129        AgentEvent::MessageEnd { message, .. } => match message {
130            AgentMessage::Assistant(a) => Some(UiEvent::AssistantEnd {
131                blocks: assistant_blocks(a),
132            }),
133            _ => None,
134        },
135        AgentEvent::ToolExecutionStart {
136            tool_call_id,
137            tool_name,
138            args,
139        } => Some(UiEvent::ToolStart {
140            id: tool_call_id.clone(),
141            name: tool_name.clone(),
142            args: args.clone(),
143        }),
144        AgentEvent::ToolExecutionUpdate {
145            tool_call_id,
146            tool_name,
147            args,
148            partial_result,
149        } => Some(UiEvent::ToolUpdate {
150            id: tool_call_id.clone(),
151            name: tool_name.clone(),
152            args: args.clone(),
153            result: crate::remote::protocol::tool_result_json(partial_result),
154        }),
155        AgentEvent::ToolExecutionEnd {
156            tool_call_id,
157            tool_name,
158            result,
159            is_error,
160        } => Some(UiEvent::ToolEnd {
161            id: tool_call_id.clone(),
162            name: tool_name.clone(),
163            result: crate::remote::protocol::tool_result_json(result),
164            is_error: *is_error,
165        }),
166    }
167}
168
169/// Provider-free assistant block projection (text / thinking / decoded image),
170/// in document order.
171pub fn assistant_blocks(msg: &AssistantMessage) -> Vec<AssistantBlock> {
172    msg.content
173        .iter()
174        .filter_map(|c| match c {
175            Content::Text(t) => Some(AssistantBlock::Text(t.text.clone())),
176            Content::Thinking(t) => Some(AssistantBlock::Thinking(t.thinking.clone())),
177            Content::Image(image) => base64::engine::general_purpose::STANDARD
178                .decode(&*image.data)
179                .ok()
180                .filter(|data| !data.is_empty())
181                .map(AssistantBlock::Image),
182            _ => None,
183        })
184        .collect()
185}
186
187/// Finalized tool calls in an assistant message (placeholder calls with an
188/// empty name are skipped).
189pub fn assistant_tool_calls(msg: &AssistantMessage) -> Vec<UiToolCall> {
190    msg.content
191        .iter()
192        .filter_map(|c| match c {
193            Content::ToolCall(tc) if !tc.name.trim().is_empty() => Some(UiToolCall {
194                id: tc.id.clone(),
195                name: tc.name.clone(),
196                args: tc.arguments.clone(),
197            }),
198            _ => None,
199        })
200        .collect()
201}
202
203// ---------------------------------------------------------------------------
204// Remote driver
205// ---------------------------------------------------------------------------
206
207/// A [`SessionDriver`] backed by a remote `rpi --server` over TCP JSON-RPC.
208pub struct RemoteDriver {
209    client: tokio::sync::Mutex<RemoteClient>,
210    session_id: String,
211    next_id: AtomicU64,
212    events: StdMutex<Option<mpsc::UnboundedReceiver<DriverEvent>>>,
213}
214
215impl RemoteDriver {
216    /// Connect, authenticate, start a remote session, subscribe, and spawn the
217    /// event pump that folds the wire stream into [`DriverEvent`]s.
218    pub async fn connect(addr: &str, token: Option<&str>) -> Result<Self, String> {
219        let mut client = RemoteClient::connect(addr).await?;
220        client
221            .authenticate(token.unwrap_or(""))
222            .await
223            .map_err(auth_hint)?;
224
225        let started = client
226            .call("start_session", json!({}))
227            .await
228            .map_err(auth_hint)?;
229        let session_id = started
230            .get("sessionId")
231            .and_then(Value::as_str)
232            .ok_or("server did not return a sessionId")?
233            .to_string();
234
235        let subscribed = client
236            .call("subscribe", json!({"sessionId": session_id}))
237            .await?;
238        let subscription_id = subscribed
239            .get("subscriptionId")
240            .and_then(Value::as_u64)
241            .ok_or("server did not return a subscriptionId")?;
242
243        let mut lines = client.start_event_pump(subscription_id);
244        let (tx, rx) = mpsc::unbounded_channel();
245        tokio::spawn(async move {
246            let mut mapper = RemoteEventMapper::default();
247            while let Some(line) = lines.recv().await {
248                if !mapper.forward(line, &tx) {
249                    break;
250                }
251            }
252            let _ = tx.send(DriverEvent::Ended);
253        });
254
255        let driver = Self {
256            client: tokio::sync::Mutex::new(client),
257            session_id,
258            next_id: AtomicU64::new(1),
259            events: StdMutex::new(Some(rx)),
260        };
261        // Seed the state (model / thinking / tools) for the chrome.
262        let _ = driver.send(DriverCommand::RefreshState).await;
263        Ok(driver)
264    }
265
266    /// Best-effort session teardown.
267    pub async fn shutdown(&self) {
268        let mut client = self.client.lock().await;
269        client.stop_session(&self.session_id).await;
270    }
271}
272
273#[async_trait]
274impl SessionDriver for RemoteDriver {
275    fn events(&self) -> Option<mpsc::UnboundedReceiver<DriverEvent>> {
276        self.events.lock().unwrap().take()
277    }
278
279    async fn send(&self, command: DriverCommand) -> Result<(), String> {
280        let remote = RemoteCommand::from(command);
281        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
282        let mut client = self.client.lock().await;
283        client
284            .send_command(&self.session_id, remote.with_id(id))
285            .await
286    }
287}
288
289impl From<DriverCommand> for RemoteCommand {
290    fn from(command: DriverCommand) -> Self {
291        match command {
292            DriverCommand::UiDialogResponse { request_id, answer } => {
293                RemoteCommand::UiDialogResponse {
294                    request_id,
295                    cancelled: answer.is_none(),
296                    answer,
297                }
298            }
299            DriverCommand::Prompt(content) => RemoteCommand::Prompt { content },
300            DriverCommand::Abort => RemoteCommand::Abort,
301            DriverCommand::RefreshState => RemoteCommand::GetState,
302            DriverCommand::SetModel(model) => RemoteCommand::SetModel { model },
303            DriverCommand::SetThinkingLevel(level) => RemoteCommand::SetThinkingLevel { level },
304            DriverCommand::SetActiveTools(tools) => RemoteCommand::SetActiveTools { tools },
305        }
306    }
307}
308
309/// Snapshot the foldable parts of a [`RemoteSession`] the chrome needs.
310fn status_of(session: &RemoteSession) -> DriverStatus {
311    DriverStatus {
312        ready: session.ready,
313        streaming: session.streaming,
314        model: session.state.model.clone(),
315        thinking: session
316            .state
317            .thinking_level
318            .as_ref()
319            .and_then(Value::as_str)
320            .map(str::to_string),
321        active_tools: session.state.active_tools.clone(),
322        retry: session
323            .retry_attempt
324            .map(|(attempt, max)| (attempt, max, session.retry_delay_ms.unwrap_or(1000))),
325    }
326}
327
328/// Stateful wire-to-UI adapter used by the actual remote event pump. Keep the
329/// stateless projection below available for callers with complete snapshots.
330pub(crate) struct RemoteEventMapper {
331    messages: crate::remote::message_accumulator::MessageAccumulator,
332    session: RemoteSession,
333    last_error: Option<String>,
334}
335
336impl Default for RemoteEventMapper {
337    fn default() -> Self {
338        Self {
339            messages: Default::default(),
340            session: RemoteSession::new(),
341            last_error: None,
342        }
343    }
344}
345
346impl RemoteEventMapper {
347    pub(crate) fn forward(&mut self, line: Value, tx: &mpsc::UnboundedSender<DriverEvent>) -> bool {
348        self.session.apply_line(&line);
349        if tx
350            .send(DriverEvent::Status(status_of(&self.session)))
351            .is_err()
352        {
353            return false;
354        }
355        if self.session.last_error != self.last_error {
356            self.last_error.clone_from(&self.session.last_error);
357            if let Some(error) = &self.last_error {
358                let _ = tx.send(DriverEvent::Notice(format!("error: {error}")));
359            }
360        }
361        if let Ok(event) = serde_json::from_value::<RemoteEvent>(line) {
362            if let Some(event) = self.map(&event) {
363                let _ = tx.send(event);
364            }
365        }
366        true
367    }
368
369    fn map(&mut self, event: &RemoteEvent) -> Option<DriverEvent> {
370        map_remote_driver_event(&self.messages.apply(event))
371    }
372}
373
374/// Preserve dialog messages alongside transcript events; they are not part
375/// of the transcript and must reach the shell's modal input slot.
376fn map_remote_driver_event(event: &RemoteEvent) -> Option<DriverEvent> {
377    match event {
378        RemoteEvent::UiDialogRequest {
379            request_id,
380            tool_call_id,
381            ui,
382        } => Some(DriverEvent::UiDialog(rpi_extensions::UiDialogRequest {
383            request_id: request_id.clone(),
384            tool_call_id: tool_call_id.clone(),
385            ui: ui.clone(),
386            raw: serde_json::to_value(event).unwrap_or(Value::Null),
387        })),
388        RemoteEvent::UiDialogClosed { request_id } => {
389            Some(DriverEvent::UiDialogClosed(request_id.clone()))
390        }
391        RemoteEvent::ExtensionUiRequest {
392            method,
393            message,
394            notify_type,
395            ..
396        } if method == "notify" => Some(DriverEvent::Notice(
397            crate::remote::session::notification_text(message, *notify_type),
398        )),
399        _ => map_remote_event(event).map(DriverEvent::Ui),
400    }
401}
402
403/// Project a wire [`RemoteEvent`] into the shared [`UiEvent`].
404pub fn map_remote_event(event: &RemoteEvent) -> Option<UiEvent> {
405    use crate::remote::session::message_role;
406    use crate::transcript_view::{assistant_blocks_from_value, tool_calls_from_value};
407
408    match event {
409        RemoteEvent::UiDialogRequest { .. }
410        | RemoteEvent::UiDialogClosed { .. }
411        | RemoteEvent::ExtensionUiRequest { .. } => None,
412        RemoteEvent::AgentStart => Some(UiEvent::AgentStart),
413        RemoteEvent::AgentEnd { .. } => Some(UiEvent::AgentEnd),
414        RemoteEvent::RetryScheduled {
415            attempt,
416            max_retries,
417            delay_ms,
418            error,
419        } => Some(UiEvent::Retry {
420            attempt: *attempt,
421            max_retries: *max_retries,
422            delay_ms: *delay_ms,
423            error: error.clone(),
424        }),
425        RemoteEvent::MessageStart { message, .. } => {
426            if message_role(message) != "assistant" {
427                return None;
428            }
429            Some(UiEvent::AssistantStart {
430                blocks: assistant_blocks_from_value(message),
431            })
432        }
433        RemoteEvent::MessageUpdate { message, .. } => {
434            if !message.is_object() {
435                return None;
436            }
437            Some(UiEvent::AssistantUpdate {
438                blocks: assistant_blocks_from_value(message),
439                tool_calls: tool_calls_from_value(message),
440            })
441        }
442        RemoteEvent::MessageEnd { message, .. } => {
443            if message_role(message) != "assistant" {
444                return None;
445            }
446            Some(UiEvent::AssistantEnd {
447                blocks: assistant_blocks_from_value(message),
448            })
449        }
450        RemoteEvent::ToolExecutionStart {
451            tool_call_id,
452            tool_name,
453            args,
454        } => Some(UiEvent::ToolStart {
455            id: tool_call_id.clone(),
456            name: tool_name.clone(),
457            args: args.clone(),
458        }),
459        RemoteEvent::ToolExecutionUpdate {
460            tool_call_id,
461            tool_name,
462            args,
463            partial_result,
464        } => Some(UiEvent::ToolUpdate {
465            id: tool_call_id.clone(),
466            name: tool_name.clone(),
467            args: args.clone(),
468            result: partial_result.clone(),
469        }),
470        RemoteEvent::ToolExecutionEnd {
471            tool_call_id,
472            tool_name,
473            result,
474            is_error,
475        } => Some(UiEvent::ToolEnd {
476            id: tool_call_id.clone(),
477            name: tool_name.clone(),
478            result: result.clone(),
479            is_error: *is_error,
480        }),
481        RemoteEvent::TurnStart | RemoteEvent::TurnEnd { .. } => None,
482    }
483}
484
485/// Append a `--token` hint when the server rejected us for authentication.
486fn auth_hint(error: String) -> String {
487    let lower = error.to_lowercase();
488    if lower.contains("authentication") || lower.contains("token") {
489        format!("{error} (retrieve the token printed by `rpi --server` and pass `--token <token>`)")
490    } else {
491        error
492    }
493}
494
495// ---------------------------------------------------------------------------
496// Local driver
497// ---------------------------------------------------------------------------
498
499/// A [`SessionDriver`] backed by an in-process harness lane: it turns the
500/// lane's `broadcast::Receiver<AgentEvent>` into [`DriverEvent`]s and maps
501/// [`DriverCommand`]s onto the lane. Additive — the interactive TUI can adopt
502/// it without changing the rich local operations it performs through the lane
503/// directly.
504///
505/// Model switching is **not** exposed through the driver: `AgentLane::set_model`
506/// takes a resolved `Model`, while the driver only carries an id. The local TUI
507/// keeps using its own model catalog for `/model`.
508pub struct LocalDriver {
509    lane: Arc<dyn AgentLane>,
510    status_tx: mpsc::UnboundedSender<DriverEvent>,
511    events: StdMutex<Option<mpsc::UnboundedReceiver<DriverEvent>>>,
512}
513
514impl LocalDriver {
515    /// Wrap a lane plus its live event receiver.
516    pub fn new(lane: Arc<dyn AgentLane>, events: broadcast::Receiver<AgentEvent>) -> Self {
517        let (tx, rx) = mpsc::unbounded_channel();
518        let status_tx = tx.clone();
519        tokio::spawn(pump_agent_events(lane.clone(), events, tx));
520        Self {
521            lane,
522            status_tx,
523            events: StdMutex::new(Some(rx)),
524        }
525    }
526}
527
528#[async_trait]
529impl SessionDriver for LocalDriver {
530    fn events(&self) -> Option<mpsc::UnboundedReceiver<DriverEvent>> {
531        self.events.lock().unwrap().take()
532    }
533
534    async fn send(&self, command: DriverCommand) -> Result<(), String> {
535        match command {
536            DriverCommand::UiDialogResponse { .. } => {
537                Err("local driver has no dialog mailbox".to_string())
538            }
539            DriverCommand::Prompt(text) => {
540                // Drive the run on a background task: `prompt_text` only returns
541                // once the run completes, but a driver `send` must not block the
542                // TUI loop on the whole agent turn.
543                let lane = self.lane.clone();
544                let tx = self.status_tx.clone();
545                tokio::spawn(async move {
546                    if let Err(error) = lane.prompt_text(&text, Vec::new()).await {
547                        let _ = tx.send(DriverEvent::Notice(format!("error: {error}")));
548                    }
549                });
550                Ok(())
551            }
552            DriverCommand::Abort => self
553                .lane
554                .abort()
555                .await
556                .map(|_| ())
557                .map_err(|e| e.to_string()),
558            DriverCommand::RefreshState => {
559                let status = query_status(&self.lane, false).await;
560                let _ = self.status_tx.send(DriverEvent::Status(status));
561                Ok(())
562            }
563            DriverCommand::SetThinkingLevel(level) => {
564                let parsed = parse_thinking_level_name(&level)
565                    .ok_or_else(|| format!("unknown thinking level: {level}"))?;
566                self.lane
567                    .set_thinking_level(parsed)
568                    .await
569                    .map_err(|e| e.to_string())
570            }
571            DriverCommand::SetActiveTools(tools) => self
572                .lane
573                .set_active_tools(tools)
574                .await
575                .map_err(|e| e.to_string()),
576            DriverCommand::SetModel(_) => Err(
577                "model switching is not available through the local driver (use /model)"
578                    .to_string(),
579            ),
580        }
581    }
582}
583
584/// Forward the lane's `AgentEvent` stream as [`DriverEvent`]s, emitting a fresh
585/// [`DriverStatus`] on each run boundary.
586async fn pump_agent_events(
587    lane: Arc<dyn AgentLane>,
588    mut rx: broadcast::Receiver<AgentEvent>,
589    tx: mpsc::UnboundedSender<DriverEvent>,
590) {
591    let mut streaming = false;
592    loop {
593        match rx.recv().await {
594            Ok(event) => {
595                match &event {
596                    AgentEvent::AgentStart => streaming = true,
597                    AgentEvent::AgentEnd { .. } => streaming = false,
598                    _ => {}
599                }
600                if let Some(ui) = map_agent_event(&event) {
601                    if tx.send(DriverEvent::Ui(ui)).is_err() {
602                        return;
603                    }
604                }
605                if matches!(
606                    &event,
607                    AgentEvent::AgentStart
608                        | AgentEvent::AgentEnd { .. }
609                        | AgentEvent::RetryScheduled { .. }
610                ) {
611                    let status = query_status(&lane, streaming).await;
612                    if tx.send(DriverEvent::Status(status)).is_err() {
613                        return;
614                    }
615                }
616            }
617            Err(broadcast::error::RecvError::Lagged(_)) => continue,
618            Err(broadcast::error::RecvError::Closed) => break,
619        }
620    }
621    let _ = tx.send(DriverEvent::Ended);
622}
623
624/// Query the lane for a status snapshot.
625async fn query_status(lane: &Arc<dyn AgentLane>, streaming: bool) -> DriverStatus {
626    DriverStatus {
627        ready: true,
628        streaming,
629        model: lane.get_model().await.ok().map(|model| model.id),
630        thinking: lane
631            .get_thinking_level()
632            .await
633            .ok()
634            .map(thinking_level_name)
635            .map(str::to_string),
636        active_tools: lane.get_active_tools().await.unwrap_or_default(),
637        retry: None,
638    }
639}
640
641/// The wire/display name of a thinking level.
642fn thinking_level_name(level: ThinkingLevel) -> &'static str {
643    use ThinkingLevel::*;
644    match level {
645        Off => "off",
646        Minimal => "minimal",
647        Low => "low",
648        Medium => "medium",
649        High => "high",
650        Xhigh => "xhigh",
651        Max => "max",
652    }
653}
654
655/// Parse a thinking-level name (case-insensitive); `None` for an unknown name.
656fn parse_thinking_level_name(name: &str) -> Option<ThinkingLevel> {
657    match name.trim().to_ascii_lowercase().as_str() {
658        "off" => Some(ThinkingLevel::Off),
659        "minimal" => Some(ThinkingLevel::Minimal),
660        "low" => Some(ThinkingLevel::Low),
661        "medium" => Some(ThinkingLevel::Medium),
662        "high" => Some(ThinkingLevel::High),
663        "xhigh" => Some(ThinkingLevel::Xhigh),
664        "max" => Some(ThinkingLevel::Max),
665        _ => None,
666    }
667}
668
669#[cfg(test)]
670#[path = "remote/compatibility_tests.rs"]
671mod compact_compatibility_tests;
672
673#[cfg(test)]
674mod tests {
675    use super::*;
676    use serde_json::json;
677
678    #[test]
679    fn remote_dialogs_are_forwarded_as_modal_events() {
680        let request: RemoteEvent = serde_json::from_value(json!({
681            "type":"ui_dialog_request", "requestId":"q1", "toolCallId":"c1", "ui":{"question":"Allow?"},
682        })).unwrap();
683        let Some(DriverEvent::UiDialog(request)) = map_remote_driver_event(&request) else {
684            panic!("dialog was dropped")
685        };
686        assert_eq!(request.request_id, "q1");
687        assert_eq!(request.tool_call_id.as_deref(), Some("c1"));
688        assert_eq!(request.ui["question"], "Allow?");
689        assert!(
690            matches!(map_remote_driver_event(&RemoteEvent::UiDialogClosed { request_id: "q1".into() }),
691            Some(DriverEvent::UiDialogClosed(id)) if id == "q1")
692        );
693    }
694
695    #[test]
696    fn map_remote_event_ignores_non_assistant_messages() {
697        let event = serde_json::from_value::<RemoteEvent>(json!({
698            "type": "message_start",
699            "message": {"kind": "user", "content": []}
700        }))
701        .unwrap();
702        assert!(map_remote_event(&event).is_none());
703    }
704
705    #[test]
706    fn map_remote_event_projects_assistant_update() {
707        let event = serde_json::from_value::<RemoteEvent>(json!({
708            "type": "message_update",
709            "message": {"kind": "assistant", "content": [{"type": "text", "text": "hi"}]}
710        }))
711        .unwrap();
712        match map_remote_event(&event) {
713            Some(UiEvent::AssistantUpdate { blocks, tool_calls }) => {
714                assert_eq!(blocks, vec![AssistantBlock::Text("hi".into())]);
715                assert!(tool_calls.is_empty());
716            }
717            other => panic!("expected AssistantUpdate, got {other:?}"),
718        }
719    }
720
721    #[test]
722    fn map_remote_event_projects_tool_end() {
723        let event = serde_json::from_value::<RemoteEvent>(json!({
724            "type": "tool_execution_end",
725            "toolCallId": "c1",
726            "toolName": "read",
727            "isError": true,
728            "result": {"content": [{"type": "text", "text": "nope"}]}
729        }))
730        .unwrap();
731        match map_remote_event(&event) {
732            Some(UiEvent::ToolEnd {
733                id, name, is_error, ..
734            }) => {
735                assert_eq!(id, "c1");
736                assert_eq!(name, "read");
737                assert!(is_error);
738            }
739            other => panic!("expected ToolEnd, got {other:?}"),
740        }
741    }
742
743    #[test]
744    fn auth_hint_mentions_the_token_flag() {
745        assert!(auth_hint("authentication required".to_string()).contains("--token"));
746        assert_eq!(auth_hint("boom".to_string()), "boom");
747    }
748
749    #[test]
750    fn thinking_level_name_round_trips() {
751        for name in ["off", "minimal", "low", "medium", "high", "xhigh", "max"] {
752            let level = parse_thinking_level_name(name).unwrap();
753            assert_eq!(thinking_level_name(level), name);
754        }
755        assert_eq!(parse_thinking_level_name("HIGH"), Some(ThinkingLevel::High));
756        assert_eq!(parse_thinking_level_name("bogus"), None);
757    }
758}