Skip to main content

rpi_cli/
transcript_view.rs

1//! Transport-agnostic transcript rendering.
2//!
3//! This is the shared render layer behind unification ("only the transport
4//! differs"): both the local interactive TUI (driven by in-process
5//! `AgentEvent`s) and the remote client (driven by wire `RemoteEvent`s) build
6//! their transcript from the **same** `pi-tui` components — an
7//! [`AssistantMessageComponent`] per assistant message, a
8//! [`ToolExecutionComponent`] per tool call, a [`BashExecutionComponent`] per
9//! bash run, and user bubbles. Each side maps its native event stream into the
10//! provider-free [`UiEvent`] enum and feeds it to [`TranscriptView`]; the view
11//! holds the live component maps and updates them in place.
12//!
13//! Keeping this provider-free (only `pi-tui` + `serde_json::Value`) is what lets
14//! the local host and the remote client share it without dragging `rpi_agent`
15//! types into the client.
16
17use std::collections::HashMap;
18use std::sync::atomic::{AtomicU64, Ordering};
19use std::sync::{Arc, Mutex};
20
21use base64::Engine;
22use rpi_tui::{
23    render_diff, AssistantBlock, AssistantMessageComponent, AssistantMessageOptions,
24    BashExecutionComponent, BashTruncation, Container, Spacer, ToolExecutionComponent, ToolStatus,
25    UserMessageComponent,
26};
27use serde_json::Value;
28
29/// A tool call visible in an assistant message snapshot, normalized to plain
30/// data so both the local (`rpi_ai::Content::ToolCall`) and the wire
31/// (`{"type":"toolCall",…}`) shapes map onto it.
32#[derive(Debug, Clone, PartialEq)]
33pub struct UiToolCall {
34    pub id: String,
35    pub name: String,
36    pub args: Value,
37}
38
39/// A normalized transcript event. Both the local `AgentEvent` stream and the
40/// remote `RemoteEvent` stream are projected into this enum before rendering.
41#[derive(Debug, Clone)]
42pub enum UiEvent {
43    /// A run started (no transcript effect; kept for symmetry).
44    AgentStart,
45    /// A run ended: finalize any still-streaming assistant panel.
46    AgentEnd,
47    /// A retry was scheduled — renders as a dim notice line.
48    Retry {
49        attempt: u32,
50        max_retries: u32,
51        delay_ms: u64,
52        error: String,
53    },
54    /// An assistant message began (carries any blocks already present).
55    AssistantStart { blocks: Vec<AssistantBlock> },
56    /// A streaming assistant snapshot: content blocks plus the finalized tool
57    /// calls visible in the snapshot.
58    AssistantUpdate {
59        blocks: Vec<AssistantBlock>,
60        tool_calls: Vec<UiToolCall>,
61    },
62    /// The assistant message finished.
63    AssistantEnd { blocks: Vec<AssistantBlock> },
64    /// A completed message loaded from the saved transcript.
65    SavedAssistant { blocks: Vec<AssistantBlock> },
66    /// Tool lifecycle (args/result carry the stable wire `Value` shape).
67    ToolStart {
68        id: String,
69        name: String,
70        args: Value,
71    },
72    ToolUpdate {
73        id: String,
74        name: String,
75        args: Value,
76        result: Value,
77    },
78    ToolEnd {
79        id: String,
80        name: String,
81        result: Value,
82        is_error: bool,
83    },
84}
85
86/// Shared monotonic allocator for the per-message ids click regions key on.
87///
88/// The host builds a [`TranscriptView`] per event drain, so the allocator must
89/// outlive the view: a per-view counter restarts at `t1` and every live
90/// assistant message would end up sharing the first message's id, making a
91/// click toggle the wrong message. `TuiState` owns one and hands the same
92/// handle to every view it builds for its transcript.
93#[derive(Clone, Default)]
94pub struct MessageIdSeq(Arc<AtomicU64>);
95
96impl MessageIdSeq {
97    /// A fresh allocator; the first id handed out is `t1`.
98    pub fn new() -> Self {
99        Self(Arc::new(AtomicU64::new(1)))
100    }
101
102    /// The next opaque id (`t<seq>`).
103    pub fn next_id(&self) -> String {
104        format!("t{}", self.0.fetch_add(1, Ordering::Relaxed))
105    }
106}
107
108/// The retained transcript: the same component maps the local `TuiState` holds,
109/// so a streaming assistant message and each tool/bash panel are updated in
110/// place rather than rebuilt per event.
111pub struct TranscriptView {
112    show_images: bool,
113    chat: Arc<Container>,
114    panels: Arc<Container>,
115    current_assistant: Arc<Mutex<Option<Arc<AssistantMessageComponent>>>>,
116    tool_components: Arc<Mutex<HashMap<String, Arc<ToolExecutionComponent>>>>,
117    /// Bash executions keyed by `tool_call_id` — kept separate from the generic
118    /// tool map so bash output streams into a [`BashExecutionComponent`] (command
119    /// header + live preview + exit/truncation status).
120    bash_components: Arc<Mutex<HashMap<String, Arc<BashExecutionComponent>>>>,
121    /// When true, thinking blocks collapse to a label (toggled by the host).
122    hide_thinking: Arc<Mutex<bool>>,
123    /// Allocator backing the per-message ids click regions key on. Shared with
124    /// the host so ids stay unique across the views it builds per event.
125    message_seq: MessageIdSeq,
126    /// Global tool-output expansion preference (toggled by the host).
127    expanded: Arc<Mutex<bool>>,
128    /// Optional transformer applied to raw assistant markdown before rendering
129    /// (installed by the local host from plugin `register_markdown_transformer`
130    /// handlers; always `None` on the remote client).
131    markdown_transformer: Arc<Mutex<Option<MarkdownTransformer>>>,
132}
133
134/// A sync `Fn(&str) -> String` applied to raw assistant markdown. Kept as a
135/// trait object so this crate stays free of any plugin types.
136pub type MarkdownTransformer = Arc<dyn Fn(&str) -> String + Send + Sync>;
137
138impl TranscriptView {
139    /// Self-contained view owning fresh maps (the remote client).
140    pub fn new(chat: Arc<Container>) -> Self {
141        Self::with_maps(
142            chat,
143            Arc::new(Mutex::new(None)),
144            Arc::new(Mutex::new(HashMap::new())),
145            Arc::new(Mutex::new(HashMap::new())),
146            Arc::new(Mutex::new(false)),
147            Arc::new(Mutex::new(false)),
148            Arc::new(Mutex::new(None)),
149            MessageIdSeq::new(),
150        )
151    }
152
153    /// Wrap **shared** component maps. The local host keeps direct `Arc` handles
154    /// to these maps for its render-tick, reload and toggle logic, so it hands
155    /// the same handles to the view instead of duplicating them.
156    #[allow(clippy::too_many_arguments)]
157    pub fn with_maps(
158        chat: Arc<Container>,
159        current_assistant: Arc<Mutex<Option<Arc<AssistantMessageComponent>>>>,
160        tool_components: Arc<Mutex<HashMap<String, Arc<ToolExecutionComponent>>>>,
161        bash_components: Arc<Mutex<HashMap<String, Arc<BashExecutionComponent>>>>,
162        hide_thinking: Arc<Mutex<bool>>,
163        expanded: Arc<Mutex<bool>>,
164        markdown_transformer: Arc<Mutex<Option<MarkdownTransformer>>>,
165        message_seq: MessageIdSeq,
166    ) -> Self {
167        Self {
168            show_images: true,
169            panels: chat.clone(),
170            chat,
171            current_assistant,
172            tool_components,
173            bash_components,
174            hide_thinking,
175            expanded,
176            markdown_transformer,
177            message_seq,
178        }
179    }
180
181    pub(crate) fn with_panels(mut self, panels: Arc<Container>) -> Self {
182        self.panels = panels;
183        self
184    }
185
186    /// Configure image visibility for newly created assistant components.
187    pub fn with_show_images(mut self, show: bool) -> Self {
188        self.show_images = show;
189        self
190    }
191
192    /// Append a user prompt bubble.
193    pub fn add_user(&self, text: &str) {
194        self.chat
195            .add_child(Arc::new(UserMessageComponent::new(text.to_string())));
196        self.chat.add_child(Arc::new(Spacer::new(1)));
197    }
198
199    /// Append a dim one-line notice (retry / error / command feedback).
200    pub fn add_notice(&self, text: &str) {
201        self.chat
202            .add_child(Arc::new(rpi_tui::Text::new(format!("· {text}"), 1, 0)));
203        // One convention for every transcript entry: a trailing blank row,
204        // never a leading one — without it the next block would render flush
205        // against the notice.
206        self.chat.add_child(Arc::new(Spacer::new(1)));
207    }
208
209    /// Fold one normalized event into the retained components. `width` is the
210    /// current terminal width, used to render `edit` diffs.
211    pub fn apply(&self, event: &UiEvent, width: usize) {
212        match event {
213            UiEvent::AgentStart => {}
214            UiEvent::AgentEnd => {
215                if let Some(comp) = self.current_assistant.lock().unwrap().take() {
216                    comp.set_streaming(false);
217                }
218            }
219            UiEvent::Retry {
220                attempt,
221                max_retries,
222                delay_ms,
223                error,
224            } => {
225                self.add_notice(&format!(
226                    "retry {attempt}/{max_retries} in {delay_ms}ms: {error}"
227                ));
228            }
229            UiEvent::AssistantStart { blocks } => {
230                self.start_assistant(blocks);
231            }
232            UiEvent::AssistantUpdate { blocks, tool_calls } => {
233                self.ensure_assistant();
234                self.sync_tool_calls(tool_calls);
235                if let Some(comp) = self.current_assistant.lock().unwrap().as_ref() {
236                    comp.update_blocks(blocks);
237                }
238            }
239            UiEvent::AssistantEnd { blocks } => {
240                if let Some(comp) = self.current_assistant.lock().unwrap().take() {
241                    comp.update_blocks(blocks);
242                    comp.set_streaming(false);
243                }
244            }
245            UiEvent::SavedAssistant { blocks } => {
246                self.append_assistant(blocks, false);
247            }
248            UiEvent::ToolStart { id, name, args } => self.tool_start(id, name, args, width),
249            UiEvent::ToolUpdate {
250                id,
251                name,
252                args,
253                result,
254            } => self.tool_update(id, name, args, result, width),
255            UiEvent::ToolEnd {
256                id,
257                name,
258                result,
259                is_error,
260            } => self.tool_end(id, name, result, *is_error, width),
261        }
262    }
263
264    /// Set the global tool-output expansion preference and re-apply it to every
265    /// live panel.
266    pub fn set_expanded(&self, expanded: bool) {
267        *self.expanded.lock().unwrap() = expanded;
268        for child in self.chat.get_children() {
269            if let Some(component) = child.as_any().downcast_ref::<ToolExecutionComponent>() {
270                component.set_expanded(expanded);
271            }
272        }
273        for comp in self.tool_components.lock().unwrap().values() {
274            comp.set_expanded(expanded);
275        }
276        for comp in self.bash_components.lock().unwrap().values() {
277            comp.set_expanded(expanded);
278        }
279    }
280
281    /// Flip the expansion preference; returns the new value.
282    pub fn toggle_expanded(&self) -> bool {
283        let next = !*self.expanded.lock().unwrap();
284        self.set_expanded(next);
285        next
286    }
287
288    /// Whether tool outputs are currently expanded.
289    pub fn expanded(&self) -> bool {
290        *self.expanded.lock().unwrap()
291    }
292
293    /// Hide/show thinking blocks on the in-flight assistant message.
294    pub fn set_hide_thinking(&self, hide: bool) {
295        *self.hide_thinking.lock().unwrap() = hide;
296        if let Some(comp) = self.current_assistant.lock().unwrap().as_ref() {
297            comp.set_hide_thinking(hide);
298        }
299    }
300
301    /// Assign an opaque id to an assistant component so its thinking rows
302    /// carry click-region markers. Every assistant message gets one — the
303    /// marker is zero-width and costs nothing when the host never clicks.
304    fn assign_message_id(&self, comp: &AssistantMessageComponent) -> String {
305        let id = self.message_seq.next_id();
306        comp.set_message_id(&id);
307        id
308    }
309
310    /// Flip one assistant message's thinking between the collapsed label and
311    /// the full body. `None` when `id` is stale (the message scrolled out of
312    /// the live container and its component is gone) — the click is then
313    /// left for the selection tracker.
314    pub fn toggle_message_thinking(&self, id: &str) -> bool {
315        // Toggle semantics: an override-free message expands (against the
316        // global hide); an expanded override collapses back to the global
317        // preference. A forced-collapsed override also expands.
318        // Toggle against what is ACTUALLY visible: with the global preference
319        // showing thinking, a click on an expanded body must collapse it
320        // (Some(false)), not "expand" a message that is already expanded.
321        // `None` is a special case: it means "follow the global preference",
322        // so the target is the inverse of the global hide flag.
323        let global_show = !*self.hide_thinking.lock().unwrap();
324        let toggle = |comp: &AssistantMessageComponent| {
325            let visible = comp.expand_thinking().unwrap_or(global_show);
326            let target = !visible;
327            // When the target equals the global preference, drop the override
328            // entirely so a later global toggle takes effect on this message.
329            let next = (target != global_show).then_some(target);
330            comp.set_expand_thinking(next);
331        };
332        if self.for_each_assistant(|comp| {
333            if comp.message_id().as_deref() == Some(id) {
334                toggle(comp);
335                true
336            } else {
337                false
338            }
339        }) {
340            return true;
341        }
342        // The in-flight message is mounted by `start_assistant` before any
343        // event drains, so this arm only fires for the not-yet-mounted edge
344        // case (a click racing the first frame).
345        let current = self.current_assistant.lock().unwrap().clone();
346        if let Some(comp) = current.filter(|comp| comp.message_id().as_deref() == Some(id)) {
347            toggle(&comp);
348            return true;
349        }
350        false
351    }
352
353    /// Visit every assistant component in the visible transcript, including
354    /// those nested inside history page containers. Stops on the first match.
355    fn for_each_assistant(
356        &self,
357        mut visit: impl FnMut(&AssistantMessageComponent) -> bool,
358    ) -> bool {
359        fn walk(
360            children: Vec<Arc<dyn rpi_tui::Component>>,
361            visit: &mut impl FnMut(&AssistantMessageComponent) -> bool,
362        ) -> bool {
363            for child in children {
364                if let Some(comp) = child.as_any().downcast_ref::<AssistantMessageComponent>() {
365                    if visit(comp) {
366                        return true;
367                    }
368                }
369                if let Some(container) = child.as_any().downcast_ref::<rpi_tui::Container>() {
370                    if walk(container.get_children(), visit) {
371                        return true;
372                    }
373                }
374            }
375            false
376        }
377        walk(self.chat.get_children(), &mut visit)
378    }
379
380    /// The id every NEW assistant message gets, so the host can route a
381    /// click-region hit before knowing which component backs it.
382    pub fn next_message_id(&self) -> String {
383        self.message_seq.next_id()
384    }
385
386    /// Flip the thinking-visibility preference; returns the new value.
387    pub fn toggle_hide_thinking(&self) -> bool {
388        let next = !*self.hide_thinking.lock().unwrap();
389        self.set_hide_thinking(next);
390        next
391    }
392
393    /// Whether thinking blocks are currently hidden.
394    pub fn hide_thinking(&self) -> bool {
395        *self.hide_thinking.lock().unwrap()
396    }
397
398    /// Install (or clear) the assistant-markdown transformer, re-applying it to
399    /// the in-flight assistant message immediately (mirrors the local reload).
400    pub fn set_markdown_transformer(&self, transformer: Option<MarkdownTransformer>) {
401        *self.markdown_transformer.lock().unwrap() = transformer.clone();
402        if let Some(comp) = self.current_assistant.lock().unwrap().as_ref() {
403            comp.set_markdown_transformer(transformer);
404        }
405    }
406
407    /// Finalize any still-streaming assistant panel (used at turn/run end).
408    pub fn finalize_assistant(&self) {
409        if let Some(comp) = self.current_assistant.lock().unwrap().take() {
410            comp.set_streaming(false);
411        }
412    }
413
414    /// Finalize the assistant panel with an authoritative final block list.
415    pub fn finalize_assistant_blocks(&self, blocks: &[AssistantBlock]) {
416        if let Some(comp) = self.current_assistant.lock().unwrap().take() {
417            comp.update_blocks(blocks);
418            comp.set_streaming(false);
419        }
420    }
421
422    /// Whether any tool panel is still running (drives the local render tick).
423    pub fn has_running_tool(&self) -> bool {
424        self.tool_components
425            .lock()
426            .unwrap()
427            .values()
428            .any(|component| component.status() == ToolStatus::Running)
429    }
430
431    /// Whether a bash panel is currently on screen.
432    pub fn has_active_bash(&self) -> bool {
433        !self.bash_components.lock().unwrap().is_empty()
434    }
435
436    fn start_assistant(&self, blocks: &[AssistantBlock]) {
437        let component = self.append_assistant(blocks, true);
438        *self.current_assistant.lock().unwrap() = Some(component);
439    }
440
441    fn append_assistant(
442        &self,
443        blocks: &[AssistantBlock],
444        streaming: bool,
445    ) -> Arc<AssistantMessageComponent> {
446        let comp = Arc::new(AssistantMessageComponent::new(
447            AssistantMessageOptions::default(),
448        ));
449        self.assign_message_id(&comp);
450        comp.set_hide_thinking(*self.hide_thinking.lock().unwrap());
451        comp.set_show_images(self.show_images);
452        comp.set_trailing_spacing(1);
453        if let Some(transformer) = self.markdown_transformer.lock().unwrap().clone() {
454            comp.set_markdown_transformer(Some(transformer));
455        }
456        comp.set_streaming(streaming);
457        comp.update_blocks(blocks);
458        self.chat.add_child(comp.clone());
459        comp
460    }
461
462    /// Create the streaming assistant component if a delta arrives before
463    /// `assistant_start` (the wire does not strictly guarantee ordering).
464    fn ensure_assistant(&self) {
465        let mut current = self.current_assistant.lock().unwrap();
466        if current.is_none() {
467            *current = Some(self.append_assistant(&[], true));
468        }
469    }
470
471    /// Pre-create panels for the tool calls visible in an assistant snapshot. A
472    /// later `tool_start` coalesces onto the same entry.
473    fn sync_tool_calls(&self, calls: &[UiToolCall]) {
474        for call in calls {
475            if matches!(
476                call.name.as_str(),
477                "todo" | "plan_mode_start" | "plan_mode_complete"
478            ) {
479                continue;
480            }
481            if call.name == "bash" {
482                let command = call
483                    .args
484                    .get("command")
485                    .and_then(Value::as_str)
486                    .unwrap_or("");
487                if command.trim().is_empty() {
488                    continue;
489                }
490                let mut bash = self.bash_components.lock().unwrap();
491                if let Some(existing) = bash.get(&call.id) {
492                    existing.set_command(command);
493                } else {
494                    let comp = Arc::new(BashExecutionComponent::new(command));
495                    comp.set_expanded(self.expanded());
496                    self.chat.add_child(comp.clone());
497                    bash.insert(call.id.clone(), comp);
498                }
499                continue;
500            }
501            let ask_user = is_ask_user_tool(&call.name);
502            let display = if ask_user {
503                ask_user_args_display(&call.args)
504            } else {
505                call.args.to_string()
506            };
507            let mut tools = self.tool_components.lock().unwrap();
508            if let Some(existing) = tools.get(&call.id) {
509                if let Some(skill) = skill_tool_name(&call.name, &call.args) {
510                    existing.set_skill_name(skill);
511                }
512                if !display.trim().is_empty() && display.trim() != "{}" {
513                    existing.set_args(&display);
514                }
515            } else {
516                let comp = Arc::new(ToolExecutionComponent::new(&call.name, &display));
517                if ask_user {
518                    comp.set_display_title("ASK USER");
519                }
520                if let Some(skill) = skill_tool_name(&call.name, &call.args) {
521                    comp.set_skill_name(skill);
522                }
523                comp.set_expanded(self.expanded());
524                comp.set_running();
525                self.chat.add_child(comp.clone());
526                tools.insert(call.id.clone(), comp);
527            }
528        }
529    }
530
531    fn tool_start(&self, id: &str, name: &str, args: &Value, _width: usize) {
532        if matches!(name, "todo" | "plan_mode_start" | "plan_mode_complete") {
533            return;
534        }
535        if name.trim().is_empty() {
536            return;
537        }
538        if name == "bash" {
539            let command = args.get("command").and_then(Value::as_str).unwrap_or("");
540            // Arguments can still be `{}` when the lifecycle event races streamed
541            // arg finalization — defer until the command lands.
542            if command.trim().is_empty() {
543                return;
544            }
545            let mut bash = self.bash_components.lock().unwrap();
546            if let Some(existing) = bash.get(id) {
547                existing.set_command(command);
548            } else {
549                let comp = Arc::new(BashExecutionComponent::new(command));
550                comp.set_expanded(self.expanded());
551                self.chat.add_child(comp.clone());
552                bash.insert(id.to_string(), comp);
553            }
554            return;
555        }
556        let ask_user = is_ask_user_tool(name);
557        let display = if ask_user {
558            ask_user_args_display(args)
559        } else {
560            args.to_string()
561        };
562        let mut tools = self.tool_components.lock().unwrap();
563        if let Some(existing) = tools.get(id) {
564            if ask_user {
565                existing.set_display_title("ASK USER");
566            }
567            if let Some(skill) = skill_tool_name(name, args) {
568                existing.set_skill_name(skill);
569            }
570            existing.set_args(&display);
571        } else {
572            let comp = Arc::new(ToolExecutionComponent::new(name, &display));
573            if ask_user {
574                comp.set_display_title("ASK USER");
575            }
576            if let Some(skill) = skill_tool_name(name, args) {
577                comp.set_skill_name(skill);
578            }
579            comp.set_expanded(self.expanded());
580            comp.set_running();
581            self.chat.add_child(comp.clone());
582            tools.insert(id.to_string(), comp);
583        }
584    }
585
586    fn tool_update(&self, id: &str, name: &str, args: &Value, result: &Value, width: usize) {
587        if matches!(name, "todo" | "plan_mode_start" | "plan_mode_complete") {
588            return;
589        }
590        if name.trim().is_empty() {
591            return;
592        }
593        let ask_user = is_ask_user_tool(name);
594        let text = if ask_user {
595            ask_user_progress_text(args, result)
596        } else {
597            tool_result_text(result)
598        };
599        if name == "bash" {
600            if let Some(bash) = self.bash_components.lock().unwrap().get(id) {
601                if let Some(command) = args.get("command").and_then(Value::as_str) {
602                    bash.set_command(command);
603                }
604                if !text.is_empty() {
605                    bash.append_output(&text);
606                }
607            }
608            return;
609        }
610        let existing = self.tool_components.lock().unwrap().get(id).cloned();
611        match existing {
612            Some(comp) => {
613                if let Some(skill) = skill_tool_name(name, args) {
614                    comp.set_skill_name(skill);
615                }
616                if ask_user {
617                    comp.set_display_title("ASK USER");
618                    comp.set_args(&ask_user_args_display(args));
619                } else if !args.is_null() && args != &serde_json::json!({}) {
620                    comp.set_args(&args.to_string());
621                }
622                if tool_update_has_payload(&text, result) {
623                    comp.set_result(&text, false);
624                    if !ask_user {
625                        apply_edit_diff(&comp, name, result.get("details"), width);
626                    }
627                }
628            }
629            None => {
630                // Update before start (fast tool / out-of-order): create the
631                // running panel now so the partial has somewhere to land.
632                if tool_update_has_payload(&text, result) {
633                    let display = if ask_user {
634                        ask_user_args_display(args)
635                    } else {
636                        args.to_string()
637                    };
638                    let comp = Arc::new(ToolExecutionComponent::new(name, &display));
639                    if ask_user {
640                        comp.set_display_title("ASK USER");
641                    }
642                    if let Some(skill) = skill_tool_name(name, args) {
643                        comp.set_skill_name(skill);
644                    }
645                    comp.set_expanded(self.expanded());
646                    comp.set_running();
647                    comp.set_result(&text, false);
648                    if !ask_user {
649                        apply_edit_diff(&comp, name, result.get("details"), width);
650                    }
651                    self.chat.add_child(comp.clone());
652                    self.tool_components
653                        .lock()
654                        .unwrap()
655                        .insert(id.to_string(), comp);
656                }
657            }
658        }
659    }
660
661    fn tool_end(&self, id: &str, name: &str, result: &Value, is_error: bool, width: usize) {
662        if matches!(name, "plan_mode_start" | "plan_mode_complete")
663            && !is_error
664            && update_plan_panel(&self.panels, result)
665        {
666            return;
667        }
668        if name == "todo" && !is_error && update_todo_list(&self.panels, result) {
669            return;
670        }
671        if name.trim().is_empty() {
672            return;
673        }
674        if name == "bash" {
675            let bash = self.bash_components.lock().unwrap().remove(id);
676            match bash {
677                Some(comp) => finalize_bash(&comp, result, is_error),
678                None => {
679                    let command = result
680                        .get("details")
681                        .and_then(|details| details.get("command"))
682                        .and_then(Value::as_str)
683                        .unwrap_or("");
684                    let text = tool_result_text(result);
685                    if command.trim().is_empty() && text.trim().is_empty() {
686                        return;
687                    }
688                    let comp = Arc::new(BashExecutionComponent::new(command));
689                    comp.set_expanded(self.expanded());
690                    if !text.is_empty() {
691                        comp.append_output(&text);
692                    }
693                    finalize_bash(&comp, result, is_error);
694                    self.chat.add_child(comp);
695                }
696            }
697            return;
698        }
699        let ask_user = is_ask_user_tool(name);
700        let text = if ask_user {
701            ask_user_result_text(result)
702        } else {
703            tool_result_text(result)
704        };
705        let details = result.get("details");
706        let existing = self.tool_components.lock().unwrap().remove(id);
707        let comp = match existing {
708            Some(comp) => comp,
709            None => {
710                // Tool ended without a start/update — render a finalized panel.
711                let comp = Arc::new(ToolExecutionComponent::new(name, ""));
712                if ask_user {
713                    comp.set_display_title("ASK USER");
714                }
715                comp.set_expanded(self.expanded());
716                self.chat.add_child(comp.clone());
717                comp
718            }
719        };
720        comp.set_result(&text, is_error);
721        if !ask_user {
722            if tool_result_requests_markdown(details) {
723                comp.set_result_markdown(true);
724            }
725            apply_edit_diff(&comp, name, details, width);
726        }
727    }
728}
729
730/// Tool calls, slash commands, and restored entries share the same current plan.
731pub(crate) fn update_plan_panel(chat: &Arc<Container>, result: &Value) -> bool {
732    let Some(details) = result.get("details") else {
733        return false;
734    };
735    if details.get("kind").and_then(Value::as_str) != Some("plan") || details.get("error").is_some()
736    {
737        return false;
738    }
739    let Some(active) = details.get("active").and_then(Value::as_bool) else {
740        return false;
741    };
742    let plan = match details.get("plan") {
743        None | Some(Value::Null) => String::new(),
744        Some(Value::String(plan)) => plan.clone(),
745        _ => return false,
746    };
747    for child in chat.get_children().into_iter().rev() {
748        if let Some(component) = child.as_any().downcast_ref::<ToolExecutionComponent>() {
749            if component.is_plan_panel() {
750                component.set_plan_state(plan, active);
751                component.set_result("", false);
752                if let Some(expanded) = details.get("expanded").and_then(Value::as_bool) {
753                    component.set_expanded(expanded);
754                }
755                // Keep the panel at the position where planning started. Moving
756                // it to the tail makes all later transcript rows jump above the
757                // completed plan and, in regular mode, turns the reorder into a
758                // native-scrollback rebuild on macOS.
759                return true;
760            }
761        }
762    }
763    let component = Arc::new(ToolExecutionComponent::new("plan_mode_complete", ""));
764    component.set_plan_state(plan, active);
765    component.set_result("", false);
766    component.set_expanded(
767        details
768            .get("expanded")
769            .and_then(Value::as_bool)
770            .unwrap_or(false),
771    );
772    chat.add_child(component);
773    true
774}
775
776/// Keep one visible current task list while retaining every result in session storage.
777pub(crate) fn update_todo_list(chat: &Arc<Container>, result: &Value) -> bool {
778    let Some(details) = result.get("details") else {
779        return false;
780    };
781    if details.get("error").is_some() {
782        return false;
783    }
784    let Some(items) = details.get("todos").and_then(Value::as_array) else {
785        return false;
786    };
787    let rows: Option<Vec<_>> = items
788        .iter()
789        .map(|item| {
790            let text = item.get("text")?.as_str()?.to_owned();
791            let status = if item.get("done").and_then(Value::as_bool) == Some(true) {
792                "completed"
793            } else {
794                item.get("status")
795                    .and_then(Value::as_str)
796                    .unwrap_or("pending")
797            };
798            Some((text, status.to_owned()))
799        })
800        .collect();
801    let Some(rows) = rows else {
802        return false;
803    };
804    let text = tool_result_text(result);
805    for child in chat.get_children().into_iter().rev() {
806        if let Some(component) = child.as_any().downcast_ref::<ToolExecutionComponent>() {
807            if component.is_todo_list() {
808                component.set_todo_state(rows);
809                component.set_result(&text, false);
810                // Keep the panel at the position where the task list first
811                // appeared. Moving it to the tail makes later transcript rows
812                // render above the current task list on every update.
813                return true;
814            }
815        }
816    }
817    let candidate = Arc::new(ToolExecutionComponent::new("todo", ""));
818    candidate.set_todo_state(rows);
819    candidate.set_result(&text, false);
820    chat.add_child(candidate);
821    true
822}
823
824/// Map a wire/local assistant message's content blocks into the provider-free
825/// [`AssistantBlock`] list the shared component renders (text + thinking +
826/// decoded image blocks, in document order).
827pub fn assistant_blocks_from_value(message: &Value) -> Vec<AssistantBlock> {
828    let mut blocks = Vec::new();
829    let Some(content) = message.get("content").and_then(Value::as_array) else {
830        return blocks;
831    };
832    for block in content {
833        match block.get("type").and_then(Value::as_str) {
834            Some("text") => {
835                if let Some(text) = block.get("text").and_then(Value::as_str) {
836                    blocks.push(AssistantBlock::Text(text.to_string()));
837                }
838            }
839            Some("thinking") => {
840                if let Some(text) = block.get("thinking").and_then(Value::as_str) {
841                    blocks.push(AssistantBlock::Thinking(text.to_string()));
842                }
843            }
844            Some("image") => {
845                if let Some(data) = block.get("data").and_then(Value::as_str) {
846                    if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(data) {
847                        if !bytes.is_empty() {
848                            let png = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
849                                Some(bytes)
850                            } else {
851                                rpi_tools::image_processing::process_image(
852                                    &bytes,
853                                    Default::default(),
854                                )
855                                .ok()
856                            };
857                            if let Some(png) = png {
858                                blocks.push(AssistantBlock::Image(png));
859                            }
860                        }
861                    }
862                }
863            }
864            _ => {}
865        }
866    }
867    blocks
868}
869
870/// Extract the finalized tool calls (`type: "toolCall"`) from an assistant
871/// message value, in document order.
872pub fn tool_calls_from_value(message: &Value) -> Vec<UiToolCall> {
873    let mut calls = Vec::new();
874    let Some(content) = message.get("content").and_then(Value::as_array) else {
875        return calls;
876    };
877    for block in content {
878        if block.get("type").and_then(Value::as_str) != Some("toolCall") {
879            continue;
880        }
881        let id = block.get("id").and_then(Value::as_str).unwrap_or("");
882        let name = block.get("name").and_then(Value::as_str).unwrap_or("");
883        if id.is_empty() || name.trim().is_empty() {
884            continue;
885        }
886        calls.push(UiToolCall {
887            id: id.to_string(),
888            name: name.to_string(),
889            args: block.get("arguments").cloned().unwrap_or(Value::Null),
890        });
891    }
892    calls
893}
894
895/// Text out of a wire tool-result payload (`{content:[{type:"text",text}]}`).
896pub fn tool_result_text(result: &Value) -> String {
897    let mut out = String::new();
898    if let Some(blocks) = result.get("content").and_then(Value::as_array) {
899        for block in blocks {
900            if let Some(text) = block.get("text").and_then(Value::as_str) {
901                if !out.is_empty() {
902                    out.push('\n');
903                }
904                out.push_str(text);
905            }
906        }
907    }
908    out
909}
910
911/// Whether a tool result opts into markdown rendering of its body
912/// (`details.markdown = true`).
913pub fn tool_result_requests_markdown(details: Option<&Value>) -> bool {
914    details
915        .and_then(|details| details.get("markdown"))
916        .and_then(Value::as_bool)
917        .unwrap_or(false)
918}
919
920/// The skill name when `tool_name` is a `read` of a `SKILL.md` file (the
921/// `SKILL.md` parent directory's basename), else `None`. A skill read renders
922/// as upstream's `[skill] <name>` box.
923pub fn skill_tool_name(tool_name: &str, args: &Value) -> Option<String> {
924    if tool_name != "read" {
925        return None;
926    }
927    let path = args.get("path").and_then(Value::as_str)?;
928    let normalized = path.replace('\\', "/");
929    let file_name = normalized.rsplit('/').next()?;
930    if !file_name.eq_ignore_ascii_case("SKILL.md") {
931        return None;
932    }
933    normalized
934        .trim_end_matches('/')
935        .rsplit('/')
936        .nth(1)
937        .filter(|name| !name.is_empty())
938        .map(str::to_string)
939}
940
941/// Tool names rendered through the dedicated `ASK USER` panel instead of a
942/// generic tool box. Native `ask_user` plus the JS `ask_user_question` alias.
943fn is_ask_user_tool(tool_name: &str) -> bool {
944    matches!(tool_name, "ask_user" | "ask_user_question")
945}
946
947/// Render ask_user tool-call ARGUMENTS as a readable question. The raw
948/// transport JSON must never leak into the transcript.
949fn ask_user_args_display(args: &Value) -> String {
950    if args.is_null() {
951        return String::new();
952    }
953    if let Some(summary) = args
954        .get("summary")
955        .and_then(Value::as_str)
956        .map(str::trim)
957        .filter(|text| !text.is_empty())
958    {
959        return format!("Confirmation requested: {summary}");
960    }
961
962    let mut lines: Vec<String> = Vec::new();
963    let questions: Vec<&Value> = args
964        .get("questions")
965        .and_then(Value::as_array)
966        .filter(|items| !items.is_empty())
967        .map(|items| items.iter().collect())
968        .unwrap_or_else(|| vec![args]);
969
970    for question in questions {
971        let prompt = question
972            .get("question")
973            .and_then(Value::as_str)
974            .or_else(|| args.get("question").and_then(Value::as_str))
975            .map(str::trim)
976            .unwrap_or_default();
977        if prompt.is_empty() {
978            continue;
979        }
980        if let Some(header) = question
981            .get("header")
982            .and_then(Value::as_str)
983            .map(str::trim)
984            .filter(|text| !text.is_empty())
985        {
986            lines.push(format!("{header}: {prompt}"));
987        } else {
988            lines.push(prompt.to_string());
989        }
990        let context = question
991            .get("context")
992            .and_then(Value::as_str)
993            .or_else(|| args.get("context").and_then(Value::as_str))
994            .map(str::trim)
995            .filter(|text| !text.is_empty());
996        if let Some(context) = context {
997            lines.push(format!("  {context}"));
998        }
999        let options = question
1000            .get("options")
1001            .and_then(Value::as_array)
1002            .or_else(|| args.get("options").and_then(Value::as_array));
1003        if let Some(options) = options {
1004            let labels: Vec<String> = options
1005                .iter()
1006                .filter_map(|option| {
1007                    option
1008                        .get("title")
1009                        .and_then(Value::as_str)
1010                        .or_else(|| option.as_str())
1011                        .map(str::trim)
1012                        .filter(|label| !label.is_empty())
1013                        .map(str::to_string)
1014                })
1015                .collect();
1016            if !labels.is_empty() {
1017                lines.push(format!("Choices: {}", labels.join(", ")));
1018            }
1019        }
1020        if let Some(suggest) = question
1021            .get("suggest")
1022            .and_then(Value::as_str)
1023            .or_else(|| args.get("suggest").and_then(Value::as_str))
1024            .map(str::trim)
1025            .filter(|text| !text.is_empty())
1026        {
1027            lines.push(format!("Suggestions: {suggest}"));
1028        }
1029    }
1030
1031    lines.join("\n")
1032}
1033
1034/// Progress text while an ask_user tool is pending. Prefer the tool's own
1035/// readable `content`, otherwise show the question so the panel is not blank.
1036fn ask_user_progress_text(args: &Value, result: &Value) -> String {
1037    let text = tool_result_text(result);
1038    if !text.trim().is_empty() {
1039        return text;
1040    }
1041    let args_text = ask_user_args_display(args);
1042    if args_text.trim().is_empty() {
1043        "Waiting for your answer…".to_string()
1044    } else {
1045        args_text
1046    }
1047}
1048
1049/// Final text for a completed ask_user tool.
1050fn ask_user_result_text(result: &Value) -> String {
1051    let text = tool_result_text(result);
1052    if text.trim().is_empty() {
1053        "Answer recorded.".to_string()
1054    } else {
1055        text
1056    }
1057}
1058
1059/// Whether a partial tool result carries anything worth rendering.
1060fn tool_update_has_payload(text: &str, result: &Value) -> bool {
1061    !text.trim().is_empty()
1062        || result
1063            .get("details")
1064            .map(|details| !details.is_null())
1065            .unwrap_or(false)
1066}
1067
1068/// Attach a colored diff to an `edit` tool panel. `write` carries no diff and
1069/// stays a plain summary.
1070fn apply_edit_diff(
1071    comp: &Arc<ToolExecutionComponent>,
1072    tool_name: &str,
1073    details: Option<&Value>,
1074    width: usize,
1075) {
1076    if tool_name != "edit" {
1077        return;
1078    }
1079    let Some(diff_text) = details
1080        .and_then(|details| details.get("diff"))
1081        .and_then(Value::as_str)
1082    else {
1083        return;
1084    };
1085    if diff_text.is_empty() {
1086        return;
1087    }
1088    comp.set_diff(render_diff(diff_text, width));
1089}
1090
1091/// Mark a bash panel complete from the wire result payload. The exit code is
1092/// derived from `is_error`; truncation info is read from `details`.
1093fn finalize_bash(comp: &Arc<BashExecutionComponent>, result: &Value, is_error: bool) {
1094    let details = result.get("details");
1095    let exit_code = Some(if is_error { 1 } else { 0 });
1096    let truncated = details
1097        .and_then(|details| details.get("truncation"))
1098        .and_then(|truncation| truncation.get("truncated"))
1099        .and_then(Value::as_bool)
1100        .unwrap_or(false);
1101    let full_output_path = details
1102        .and_then(|details| details.get("full_output_path"))
1103        .and_then(Value::as_str)
1104        .map(str::to_string);
1105    if let Some(command) = details
1106        .and_then(|details| details.get("command"))
1107        .and_then(Value::as_str)
1108    {
1109        comp.set_command(command);
1110    }
1111    comp.set_complete(
1112        exit_code,
1113        false,
1114        BashTruncation {
1115            truncated,
1116            full_output_path,
1117        },
1118    );
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123    use super::*;
1124    use rpi_tui::{strip_ansi, Component};
1125    use serde_json::json;
1126
1127    fn view() -> TranscriptView {
1128        TranscriptView::new(Arc::new(Container::new()))
1129    }
1130
1131    #[test]
1132    fn adjacent_transcript_blocks_separated_by_exactly_one_blank() {
1133        // The seam invariant: any two adjacent transcript blocks — whatever
1134        // their kinds — are separated by exactly one blank line. Every entry
1135        // contributes one trailing blank (assistant trailing spacing, panel
1136        // trailing spacer, host trailing Spacer for user/notice entries), and
1137        // no block opens with a leading spacer, so the gap never depends on
1138        // which kind sits on top. Old behavior: a panel above an assistant
1139        // message gave 0 blanks (thinking glued to the code card) while an
1140        // assistant message above a panel gave 2 (trailing spacing + panel
1141        // top spacer stacking).
1142        //
1143        // Only *truly* empty rows count as a gap: a panel's own padding rows
1144        // carry a background color (non-empty ANSI payload) and belong to the
1145        // panel, not to the seam.
1146        let view = view();
1147        view.add_user("question");
1148        view.apply(
1149            &UiEvent::AssistantStart {
1150                blocks: vec![AssistantBlock::Thinking("reasoning".into())],
1151            },
1152            80,
1153        );
1154        view.apply(
1155            &UiEvent::AssistantUpdate {
1156                blocks: vec![AssistantBlock::Thinking("reasoning".into())],
1157                tool_calls: vec![UiToolCall {
1158                    id: "t1".into(),
1159                    name: "read".into(),
1160                    args: json!({"path": "f.txt"}),
1161                }],
1162            },
1163            80,
1164        );
1165        view.apply(
1166            &UiEvent::ToolEnd {
1167                id: "t1".into(),
1168                name: "read".into(),
1169                result: json!({"content": [{"type": "text", "text": "done"}]}),
1170                is_error: false,
1171            },
1172            80,
1173        );
1174        view.apply(
1175            &UiEvent::AssistantStart {
1176                blocks: vec![AssistantBlock::Text("answer".into())],
1177            },
1178            80,
1179        );
1180        view.apply(
1181            &UiEvent::ToolStart {
1182                id: "b1".into(),
1183                name: "bash".into(),
1184                args: json!({"command": "ls"}),
1185            },
1186            80,
1187        );
1188        view.apply(&UiEvent::AgentEnd, 80);
1189
1190        let lines = view.chat.render(80);
1191        let plain: Vec<String> = lines
1192            .iter()
1193            .map(|l| strip_ansi(l).trim().to_string())
1194            .collect();
1195        // Anchor each block by its LAST content line, so the rows between two
1196        // anchors are exactly the seam between the two blocks.
1197        let find = |needle: &str| {
1198            plain
1199                .iter()
1200                .rposition(|l| l.contains(needle))
1201                .unwrap_or_else(|| panic!("{needle} missing: {plain:?}"))
1202        };
1203        let user = find("question");
1204        let thinking = find("reasoning");
1205        let panel = find("done");
1206        let answer = find("answer");
1207        let bash = find("$ ls");
1208        assert!(user < thinking && thinking < panel && panel < answer);
1209        assert!(answer < bash);
1210        for (top_name, top, bottom_name, bottom) in [
1211            ("user", user, "thinking", thinking),
1212            ("thinking", thinking, "panel", panel),
1213            ("panel", panel, "answer", answer),
1214            ("answer", answer, "bash", bash),
1215        ] {
1216            let gap = lines[top + 1..bottom]
1217                .iter()
1218                .filter(|l| l.is_empty())
1219                .count();
1220            assert_eq!(
1221                gap, 1,
1222                "{top_name}→{bottom_name} seam must be exactly one blank row: {plain:?}"
1223            );
1224        }
1225    }
1226
1227    #[test]
1228    fn retry_notice_ends_with_a_trailing_spacer() {
1229        // A notice is a transcript entry like any other: without its own
1230        // trailing blank it would render flush against the next block.
1231        let view = view();
1232        view.apply(
1233            &UiEvent::Retry {
1234                attempt: 1,
1235                max_retries: 3,
1236                delay_ms: 500,
1237                error: "boom".into(),
1238            },
1239            80,
1240        );
1241        let lines = view.chat.render(80);
1242        let rendered = strip_ansi(&lines.join("\n"));
1243        assert!(rendered.contains("retry 1/3"));
1244        assert_eq!(lines.last(), Some(&String::new()));
1245    }
1246
1247    #[test]
1248    fn empty_assistant_start_and_whitespace_deltas_do_not_move_the_transcript() {
1249        for starts_with_event in [true, false] {
1250            let view = view();
1251            view.add_user("hi");
1252            let before = view.chat.render(80);
1253            if starts_with_event {
1254                view.apply(&UiEvent::AssistantStart { blocks: vec![] }, 80);
1255                assert_eq!(view.chat.render(80), before);
1256            }
1257            for blocks in [
1258                vec![],
1259                vec![AssistantBlock::Text(" ".into())],
1260                vec![AssistantBlock::Thinking("\n".into())],
1261            ] {
1262                view.apply(
1263                    &UiEvent::AssistantUpdate {
1264                        blocks,
1265                        tool_calls: vec![],
1266                    },
1267                    80,
1268                );
1269                assert_eq!(view.chat.render(80), before);
1270            }
1271            view.apply(
1272                &UiEvent::AssistantUpdate {
1273                    blocks: vec![AssistantBlock::Text("hello".into())],
1274                    tool_calls: vec![],
1275                },
1276                80,
1277            );
1278            let visible = view.chat.render(80);
1279            assert!(visible.len() > before.len());
1280            assert!(visible.iter().any(|line| line.contains("hello")));
1281            assert_eq!(visible.last(), Some(&String::new()));
1282            view.apply(&UiEvent::AssistantEnd { blocks: vec![] }, 80);
1283            assert_eq!(view.chat.render(80), before);
1284            view.apply(&UiEvent::AssistantStart { blocks: vec![] }, 80);
1285            assert_eq!(view.chat.render(80), before);
1286        }
1287    }
1288
1289    #[test]
1290    fn saved_assistant_is_rendered_without_replacing_the_live_message() {
1291        let view = view();
1292        view.apply(
1293            &UiEvent::AssistantStart {
1294                blocks: vec![AssistantBlock::Text("pending".into())],
1295            },
1296            80,
1297        );
1298        view.apply(
1299            &UiEvent::SavedAssistant {
1300                blocks: vec![AssistantBlock::Text("previous reply".into())],
1301            },
1302            80,
1303        );
1304        view.apply(
1305            &UiEvent::AssistantEnd {
1306                blocks: vec![AssistantBlock::Text("complete reply".into())],
1307            },
1308            80,
1309        );
1310        let lines = view.chat.render(80);
1311        assert!(lines.iter().any(|line| line.contains("previous reply")));
1312        assert!(lines.iter().any(|line| line.contains("complete reply")));
1313        assert!(lines.iter().all(|line| !line.contains("pending")));
1314    }
1315
1316    #[test]
1317    fn assistant_blocks_follow_content_order() {
1318        let message = json!({
1319            "content": [
1320                {"type": "thinking", "thinking": "why"},
1321                {"type": "text", "text": "hello"},
1322                {"type": "toolCall", "id": "c1", "name": "read", "arguments": {}},
1323            ]
1324        });
1325        assert_eq!(
1326            assistant_blocks_from_value(&message),
1327            vec![
1328                AssistantBlock::Thinking("why".into()),
1329                AssistantBlock::Text("hello".into()),
1330            ]
1331        );
1332    }
1333
1334    #[test]
1335    fn assistant_blocks_decode_images() {
1336        let mut bytes = Vec::new();
1337        {
1338            let mut encoder = png::Encoder::new(&mut bytes, 1, 1);
1339            encoder.set_color(png::ColorType::Rgb);
1340            encoder
1341                .write_header()
1342                .unwrap()
1343                .write_image_data(&[255, 0, 0])
1344                .unwrap();
1345        }
1346        let message = json!({
1347            "content": [{"type": "image", "data": base64::engine::general_purpose::STANDARD.encode(&bytes), "mimeType": "image/png"}]
1348        });
1349        assert_eq!(
1350            assistant_blocks_from_value(&message),
1351            vec![AssistantBlock::Image(bytes.to_vec())]
1352        );
1353        let jpeg = rpi_tools::image_processing::process_image(
1354            &bytes,
1355            rpi_tools::image_processing::ImageProcessingOptions {
1356                format: Some(rpi_tools::image_processing::OutputFormat::Jpeg { quality: 85 }),
1357                ..Default::default()
1358            },
1359        )
1360        .unwrap();
1361        let blocks = assistant_blocks_from_value(&json!({
1362            "content": [{"type": "image", "data": base64::engine::general_purpose::STANDARD.encode(jpeg), "mimeType": "image/jpeg"}]
1363        }));
1364        assert!(
1365            matches!(&blocks[0], AssistantBlock::Image(data) if data.starts_with(b"\x89PNG\r\n\x1a\n"))
1366        );
1367    }
1368
1369    #[test]
1370    fn tool_calls_extract_ids_names_and_args() {
1371        let message = json!({
1372            "content": [
1373                {"type": "text", "text": "x"},
1374                {"type": "toolCall", "id": "b1", "name": "bash", "arguments": {"command": "ls"}},
1375                {"type": "toolCall", "id": "", "name": "read", "arguments": {}},
1376            ]
1377        });
1378        assert_eq!(
1379            tool_calls_from_value(&message),
1380            vec![UiToolCall {
1381                id: "b1".into(),
1382                name: "bash".into(),
1383                args: json!({"command": "ls"}),
1384            }]
1385        );
1386    }
1387
1388    #[test]
1389    fn markdown_flag_is_opt_in() {
1390        assert!(tool_result_requests_markdown(Some(
1391            &json!({"markdown": true})
1392        )));
1393        assert!(!tool_result_requests_markdown(Some(
1394            &json!({"markdown": false})
1395        )));
1396        assert!(!tool_result_requests_markdown(Some(&json!({}))));
1397        assert!(!tool_result_requests_markdown(None));
1398    }
1399
1400    #[test]
1401    fn skill_tool_name_only_matches_skill_reads() {
1402        assert_eq!(
1403            skill_tool_name("read", &json!({"path": "skills/foo/SKILL.md"})),
1404            Some("foo".to_string())
1405        );
1406        assert_eq!(skill_tool_name("read", &json!({"path": "README.md"})), None);
1407        assert_eq!(
1408            skill_tool_name("write", &json!({"path": "skills/foo/SKILL.md"})),
1409            None
1410        );
1411    }
1412
1413    #[test]
1414    fn ask_user_args_display_never_leaks_transport_json() {
1415        let text = ask_user_args_display(&json!({
1416            "question": "你的代理端口是多少?",
1417            "context": "本机",
1418            "options": ["7890", {"title": "7897", "description": "clash"}],
1419            "suggest": "1080"
1420        }));
1421        assert!(text.contains("你的代理端口是多少?"));
1422        assert!(text.contains("本机"));
1423        assert!(text.contains("Choices: 7890, 7897"));
1424        assert!(text.contains("Suggestions: 1080"));
1425        assert!(!text.trim_start().starts_with('{'));
1426        assert_eq!(
1427            ask_user_args_display(&json!({"type": "confirm", "summary": "Deploy?"})),
1428            "Confirmation requested: Deploy?"
1429        );
1430    }
1431
1432    #[test]
1433    fn tool_start_routes_bash_to_its_own_map() {
1434        let view = view();
1435        view.apply(
1436            &UiEvent::ToolStart {
1437                id: "b1".into(),
1438                name: "bash".into(),
1439                args: json!({"command": "ls -la"}),
1440            },
1441            80,
1442        );
1443        view.apply(
1444            &UiEvent::ToolStart {
1445                id: "r1".into(),
1446                name: "read".into(),
1447                args: json!({"path": "a.txt"}),
1448            },
1449            80,
1450        );
1451        assert!(view.bash_components.lock().unwrap().contains_key("b1"));
1452        assert!(view.tool_components.lock().unwrap().contains_key("r1"));
1453        assert!(view.tool_components.lock().unwrap().get("b1").is_none());
1454    }
1455
1456    #[test]
1457    fn bash_start_without_a_command_is_deferred() {
1458        let view = view();
1459        view.apply(
1460            &UiEvent::ToolStart {
1461                id: "b1".into(),
1462                name: "bash".into(),
1463                args: json!({}),
1464            },
1465            80,
1466        );
1467        assert!(view.bash_components.lock().unwrap().is_empty());
1468        assert!(view.tool_components.lock().unwrap().is_empty());
1469    }
1470
1471    #[test]
1472    fn assistant_stream_reuses_one_component() {
1473        let view = view();
1474        view.apply(&UiEvent::AssistantStart { blocks: vec![] }, 80);
1475        view.apply(
1476            &UiEvent::AssistantUpdate {
1477                blocks: vec![AssistantBlock::Text("hi".into())],
1478                tool_calls: vec![],
1479            },
1480            80,
1481        );
1482        assert!(view.current_assistant.lock().unwrap().is_some());
1483    }
1484
1485    #[test]
1486    fn toggle_expanded_round_trips() {
1487        let view = view();
1488        assert!(!view.expanded());
1489        assert!(view.toggle_expanded());
1490        assert!(view.expanded());
1491    }
1492
1493    #[test]
1494    fn todo_updates_share_one_panel_and_preserve_errors() {
1495        let view = view();
1496        for (id, done) in [("a", false), ("b", true)] {
1497            view.sync_tool_calls(&[UiToolCall {
1498                id: id.into(),
1499                name: "todo".into(),
1500                args: json!({"action":"toggle"}),
1501            }]);
1502            view.tool_start(id, "todo", &json!({}), 80);
1503            view.tool_end(id, "todo", &json!({"content":[],"details":{"todos":[{"id":1,"text":"Run tests","done":done}]}}), false, 80);
1504        }
1505        assert_eq!(view.chat.child_count(), 1);
1506        assert!(view.tool_components.lock().unwrap().is_empty());
1507        let children = view.chat.get_children();
1508        let panel = children[0]
1509            .as_any()
1510            .downcast_ref::<ToolExecutionComponent>()
1511            .unwrap();
1512        let rendered = rpi_tui::ansi::strip_ansi(&panel.render(80).join("\n"));
1513        assert!(rendered.contains("1/1 completed"));
1514        assert!(rendered.contains("[✓] Run tests"));
1515        view.tool_end(
1516            "error",
1517            "todo",
1518            &json!({"content":[{"type":"text","text":"invalid task"}]}),
1519            true,
1520            80,
1521        );
1522        assert_eq!(view.chat.child_count(), 2);
1523        view.tool_end("soft-error", "todo", &json!({"content":[{"type":"text","text":"todo not found"}],"details":{"todos":[],"error":"todo not found"}}), false, 80);
1524        assert_eq!(view.chat.child_count(), 3);
1525        assert!(update_todo_list(
1526            &view.chat,
1527            &json!({"details":{"todos":[]}})
1528        ));
1529        assert_eq!(view.chat.child_count(), 3);
1530        assert!(!update_todo_list(
1531            &view.chat,
1532            &json!({"details":{"todos":[{}]}})
1533        ));
1534        assert_eq!(view.chat.child_count(), 3);
1535    }
1536
1537    #[test]
1538    fn completed_plan_keeps_its_transcript_position() {
1539        let view = view();
1540        view.apply(
1541            &UiEvent::AssistantStart {
1542                blocks: vec![AssistantBlock::Text("planning context".into())],
1543            },
1544            80,
1545        );
1546        view.apply(
1547            &UiEvent::AssistantEnd {
1548                blocks: vec![AssistantBlock::Text("planning context".into())],
1549            },
1550            80,
1551        );
1552        view.apply(
1553            &UiEvent::ToolEnd {
1554                id: "start".into(),
1555                name: "plan_mode_start".into(),
1556                result: json!({"details":{"kind":"plan","active":true}}),
1557                is_error: false,
1558            },
1559            80,
1560        );
1561        view.apply(
1562            &UiEvent::AssistantStart {
1563                blocks: vec![AssistantBlock::Text("repository findings".into())],
1564            },
1565            80,
1566        );
1567        view.apply(
1568            &UiEvent::AssistantEnd {
1569                blocks: vec![AssistantBlock::Text("repository findings".into())],
1570            },
1571            80,
1572        );
1573
1574        view.apply(
1575            &UiEvent::ToolEnd {
1576                id: "complete".into(),
1577                name: "plan_mode_complete".into(),
1578                result: json!({
1579                    "details": {
1580                        "kind": "plan",
1581                        "active": false,
1582                        "plan": "1. Keep the plan in place"
1583                    }
1584                }),
1585                is_error: false,
1586            },
1587            80,
1588        );
1589
1590        let lines: Vec<_> = view
1591            .chat
1592            .render(80)
1593            .iter()
1594            .map(|line| strip_ansi(line))
1595            .collect();
1596        let plan = lines
1597            .iter()
1598            .position(|line| line.contains("Plan · Ready"))
1599            .expect("completed plan panel should render");
1600        let findings = lines
1601            .iter()
1602            .position(|line| line.contains("repository findings"))
1603            .expect("later assistant output should render");
1604        assert!(
1605            plan < findings,
1606            "plan completion must not move the plan below later transcript output: {lines:?}"
1607        );
1608    }
1609
1610    #[test]
1611    fn todo_updates_keep_their_transcript_position() {
1612        let view = view();
1613        view.apply(
1614            &UiEvent::AssistantStart {
1615                blocks: vec![AssistantBlock::Text("before tasks".into())],
1616            },
1617            80,
1618        );
1619        view.apply(
1620            &UiEvent::AssistantEnd {
1621                blocks: vec![AssistantBlock::Text("before tasks".into())],
1622            },
1623            80,
1624        );
1625        view.apply(
1626            &UiEvent::ToolEnd {
1627                id: "todo-1".into(),
1628                name: "todo".into(),
1629                result: json!({
1630                    "details": {
1631                        "todos": [{"text": "first task", "done": false}]
1632                    }
1633                }),
1634                is_error: false,
1635            },
1636            80,
1637        );
1638        view.apply(
1639            &UiEvent::AssistantStart {
1640                blocks: vec![AssistantBlock::Text("later output".into())],
1641            },
1642            80,
1643        );
1644        view.apply(
1645            &UiEvent::AssistantEnd {
1646                blocks: vec![AssistantBlock::Text("later output".into())],
1647            },
1648            80,
1649        );
1650        view.apply(
1651            &UiEvent::ToolEnd {
1652                id: "todo-2".into(),
1653                name: "todo".into(),
1654                result: json!({
1655                    "details": {
1656                        "todos": [{"text": "first task", "done": true}]
1657                    }
1658                }),
1659                is_error: false,
1660            },
1661            80,
1662        );
1663
1664        let lines: Vec<_> = view
1665            .chat
1666            .render(80)
1667            .iter()
1668            .map(|line| strip_ansi(line))
1669            .collect();
1670        let tasks = lines
1671            .iter()
1672            .position(|line| line.contains("Tasks  1/1 completed"))
1673            .expect("todo panel should render");
1674        let later = lines
1675            .iter()
1676            .position(|line| line.contains("later output"))
1677            .expect("later transcript output should render");
1678        assert!(
1679            tasks < later,
1680            "todo update must not move the task panel below later output: {lines:?}"
1681        );
1682    }
1683
1684    #[test]
1685    fn plan_tools_and_show_update_one_expandable_panel() {
1686        let view = view();
1687        view.sync_tool_calls(&[UiToolCall {
1688            id: "start".into(),
1689            name: "plan_mode_start".into(),
1690            args: json!({}),
1691        }]);
1692        view.tool_start("start", "plan_mode_start", &json!({}), 80);
1693        view.tool_end(
1694            "start",
1695            "plan_mode_start",
1696            &json!({"details":{"kind":"plan","active":true}}),
1697            false,
1698            80,
1699        );
1700        let body = (1..=30)
1701            .map(|i| format!("{i}. Step {i}"))
1702            .collect::<Vec<_>>()
1703            .join("\n");
1704        view.tool_end(
1705            "complete",
1706            "plan_mode_complete",
1707            &json!({"details":{"kind":"plan","active":false,"plan":body}}),
1708            false,
1709            80,
1710        );
1711        assert_eq!(view.chat.child_count(), 1);
1712        assert!(view.tool_components.lock().unwrap().is_empty());
1713        view.set_expanded(true);
1714        let children = view.chat.get_children();
1715        let panel = children[0]
1716            .as_any()
1717            .downcast_ref::<ToolExecutionComponent>()
1718            .unwrap();
1719        assert!(rpi_tui::ansi::strip_ansi(&panel.render(80).join("\n")).contains("Step 30"));
1720        assert!(update_plan_panel(
1721            &view.chat,
1722            &json!({"kind":"message","details":{"kind":"plan","active":false,"plan":body,"expanded":true}})
1723        ));
1724        assert_eq!(view.chat.child_count(), 1);
1725        view.tool_end(
1726            "error",
1727            "plan_mode_complete",
1728            &json!({"content":[{"type":"text","text":"not active"}]}),
1729            true,
1730            80,
1731        );
1732        assert_eq!(view.chat.child_count(), 2);
1733    }
1734
1735    // ---- Click-to-expand thinking probes (per-message) ----
1736
1737    #[test]
1738    fn transcript_assigns_ids_and_toggles_per_message() {
1739        // Axis: host-side routing. Every streamed assistant message gets an
1740        // id; toggling by id flips only THAT message; the toggle round-trips.
1741        let view = view();
1742        view.set_hide_thinking(true);
1743        view.apply(
1744            &UiEvent::AssistantStart {
1745                blocks: vec![
1746                    AssistantBlock::Thinking("first msg reasoning".into()),
1747                    AssistantBlock::Text("answer one".into()),
1748                ],
1749            },
1750            80,
1751        );
1752        let first = view
1753            .current_assistant
1754            .lock()
1755            .unwrap()
1756            .clone()
1757            .expect("assistant mounted");
1758        let first_id = first.message_id().expect("id assigned");
1759        view.apply(&UiEvent::AgentEnd, 80);
1760
1761        view.apply(
1762            &UiEvent::AssistantStart {
1763                blocks: vec![AssistantBlock::Thinking("second msg reasoning".into())],
1764            },
1765            80,
1766        );
1767        let second = view
1768            .current_assistant
1769            .lock()
1770            .unwrap()
1771            .clone()
1772            .expect("assistant mounted");
1773        let second_id = second.message_id().expect("id assigned");
1774        assert_ne!(first_id, second_id, "ids must be unique per message");
1775
1776        // Toggle the SECOND message only.
1777        assert!(view.toggle_message_thinking(&second_id));
1778        let expanded = strip_ansi(&second.render(80).join("\n"));
1779        assert!(expanded.contains("second msg reasoning"));
1780        let first_render = strip_ansi(&first.render(80).join("\n"));
1781        assert!(
1782            !first_render.contains("first msg reasoning"),
1783            "toggle leaked into another message: {first_render}"
1784        );
1785
1786        // Toggle again collapses back.
1787        assert!(view.toggle_message_thinking(&second_id));
1788        assert!(!strip_ansi(&second.render(80).join("\n")).contains("second msg reasoning"));
1789    }
1790
1791    #[test]
1792    fn toggle_with_stale_id_is_a_noop() {
1793        let view = view();
1794        assert!(!view.toggle_message_thinking("t999"));
1795        view.apply(
1796            &UiEvent::AssistantStart {
1797                blocks: vec![AssistantBlock::Thinking("reasoning".into())],
1798            },
1799            80,
1800        );
1801        // An unknown id must not disturb the live message.
1802        assert!(!view.toggle_message_thinking("h12345"));
1803        let comp = view.current_assistant.lock().unwrap().clone().unwrap();
1804        assert!(!strip_ansi(&comp.render(80).join("\n")).contains("Thinking..."));
1805    }
1806
1807    #[test]
1808    fn global_toggle_keeps_message_level_expansion() {
1809        // Axis: Ctrl+T (global) vs click (per message). A click-expanded
1810        // message stays expanded across a later global toggle, and a globally
1811        // visible transcript still collapses per message.
1812        let view = view();
1813        view.set_hide_thinking(true);
1814        view.apply(
1815            &UiEvent::AssistantStart {
1816                blocks: vec![AssistantBlock::Thinking("sticky reasoning".into())],
1817            },
1818            80,
1819        );
1820        let comp = view.current_assistant.lock().unwrap().clone().unwrap();
1821        let id = comp.message_id().unwrap();
1822        assert!(view.toggle_message_thinking(&id));
1823        assert!(strip_ansi(&comp.render(80).join("\n")).contains("sticky reasoning"));
1824
1825        // Global toggle OFF→ON rebuild: override survives.
1826        view.set_hide_thinking(false);
1827        view.set_hide_thinking(true);
1828        assert!(
1829            strip_ansi(&comp.render(80).join("\n")).contains("sticky reasoning"),
1830            "global toggle wiped the per-message expansion"
1831        );
1832
1833        // The globally-visible case: collapse via toggle, then a global show
1834        // must restore it.
1835        assert!(view.toggle_message_thinking(&id));
1836        view.set_hide_thinking(false);
1837        assert!(strip_ansi(&comp.render(80).join("\n")).contains("sticky reasoning"));
1838    }
1839
1840    #[test]
1841    fn click_reaches_assistant_components_nested_in_history_pages() {
1842        // Self-review probe: a history PAGE is a nested container under the
1843        // chat root, not a direct child of the live slot. A click on one of
1844        // its thinking rows must still resolve to the owning component.
1845        let chat = Arc::new(rpi_tui::Container::new());
1846        let page = Arc::new(rpi_tui::Container::new());
1847        let comp = Arc::new(AssistantMessageComponent::new(AssistantMessageOptions {
1848            hide_thinking: true,
1849            ..Default::default()
1850        }));
1851        comp.set_message_id("h7");
1852        comp.update_blocks(&[
1853            AssistantBlock::Thinking("old reasoning".into()),
1854            AssistantBlock::Text("old answer".into()),
1855        ]);
1856        page.add_child(comp.clone());
1857        chat.add_child(page);
1858        let view = TranscriptView::new(chat);
1859        view.set_hide_thinking(true);
1860        assert!(
1861            view.toggle_message_thinking("h7"),
1862            "click on a nested history page found no component"
1863        );
1864        assert!(strip_ansi(&comp.render(80).join("\n")).contains("old reasoning"));
1865    }
1866
1867    #[test]
1868    fn click_on_globally_visible_thinking_collapses_then_restores() {
1869        // Self-review probe: with Ctrl+T OFF the body is already visible; the
1870        // first click must COLLAPSE that message (not silently "expand" it),
1871        // and the second click must restore it.
1872        let view = view();
1873        view.apply(
1874            &UiEvent::AssistantStart {
1875                blocks: vec![AssistantBlock::Thinking("shown reasoning".into())],
1876            },
1877            80,
1878        );
1879        let comp = view.current_assistant.lock().unwrap().clone().unwrap();
1880        let id = comp.message_id().unwrap();
1881        let visible = || strip_ansi(&comp.render(80).join("\n")).contains("shown reasoning");
1882        assert!(visible());
1883        assert!(view.toggle_message_thinking(&id));
1884        assert!(!visible(), "first click must collapse a visible body");
1885        assert!(view.toggle_message_thinking(&id));
1886        assert!(visible(), "second click must restore the global show");
1887    }
1888}