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, Component, Container, Spacer, ToolExecutionComponent,
25    ToolStatus, 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    restored_page: Option<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            chat,
170            restored_page: None,
171            current_assistant,
172            tool_components,
173            bash_components,
174            hide_thinking,
175            expanded,
176            markdown_transformer,
177            message_seq,
178        }
179    }
180
181    /// Configure image visibility for newly created assistant components.
182    pub fn with_show_images(mut self, show: bool) -> Self {
183        self.show_images = show;
184        self
185    }
186
187    pub(crate) fn with_restored_page(mut self, page: Option<Arc<Container>>) -> Self {
188        self.restored_page = page;
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.chat, self.restored_page.as_deref(), result)
665        {
666            return;
667        }
668        if name == "todo"
669            && !is_error
670            && update_todo_list(&self.chat, self.restored_page.as_deref(), result)
671        {
672            return;
673        }
674        if name.trim().is_empty() {
675            return;
676        }
677        if name == "bash" {
678            let bash = self.bash_components.lock().unwrap().remove(id);
679            match bash {
680                Some(comp) => finalize_bash(&comp, result, is_error),
681                None => {
682                    let command = result
683                        .get("details")
684                        .and_then(|details| details.get("command"))
685                        .and_then(Value::as_str)
686                        .unwrap_or("");
687                    let text = tool_result_text(result);
688                    if command.trim().is_empty() && text.trim().is_empty() {
689                        return;
690                    }
691                    let comp = Arc::new(BashExecutionComponent::new(command));
692                    comp.set_expanded(self.expanded());
693                    if !text.is_empty() {
694                        comp.append_output(&text);
695                    }
696                    finalize_bash(&comp, result, is_error);
697                    self.chat.add_child(comp);
698                }
699            }
700            return;
701        }
702        let ask_user = is_ask_user_tool(name);
703        let text = if ask_user {
704            ask_user_result_text(result)
705        } else {
706            tool_result_text(result)
707        };
708        let details = result.get("details");
709        let existing = self.tool_components.lock().unwrap().remove(id);
710        let comp = match existing {
711            Some(comp) => comp,
712            None => {
713                // Tool ended without a start/update — render a finalized panel.
714                let comp = Arc::new(ToolExecutionComponent::new(name, ""));
715                if ask_user {
716                    comp.set_display_title("ASK USER");
717                }
718                comp.set_expanded(self.expanded());
719                self.chat.add_child(comp.clone());
720                comp
721            }
722        };
723        comp.set_result(&text, is_error);
724        if !ask_user {
725            if tool_result_requests_markdown(details) {
726                comp.set_result_markdown(true);
727            }
728            apply_edit_diff(&comp, name, details, width);
729        }
730    }
731}
732
733fn update_transcript_panel(
734    chat: &Container,
735    restored_page: Option<&Container>,
736    name: &str,
737    matches: fn(&ToolExecutionComponent) -> bool,
738    update: impl FnOnce(&ToolExecutionComponent),
739) {
740    for owner in std::iter::once(chat).chain(restored_page) {
741        for child in owner.get_children().into_iter().rev() {
742            if let Some(panel) = child.as_any().downcast_ref::<ToolExecutionComponent>() {
743                if matches(panel) {
744                    update(panel);
745                    return;
746                }
747            }
748        }
749    }
750    let panel = Arc::new(ToolExecutionComponent::new(name, ""));
751    update(&panel);
752    chat.add_child(panel);
753}
754
755/// Move a newer live panel into the restored row when returning to the latest page.
756pub(crate) fn merge_transcript_panels(page: &Container, live: &Container) {
757    let mut rows = page.get_children();
758    let live_rows = live.get_children();
759    for matches in [
760        ToolExecutionComponent::is_plan_panel as fn(&ToolExecutionComponent) -> bool,
761        ToolExecutionComponent::is_todo_list,
762    ] {
763        let is_panel = |row: &Arc<dyn Component>| {
764            row.as_any()
765                .downcast_ref::<ToolExecutionComponent>()
766                .is_some_and(matches)
767        };
768        if let (Some(row), Some(live_row)) = (
769            rows.iter_mut().find(|row| is_panel(row)),
770            live_rows.iter().rev().find(|row| is_panel(row)),
771        ) {
772            *row = live_row.clone();
773            live.remove_child(live_row);
774        }
775    }
776    page.replace_children(rows);
777}
778
779/// Tool calls, slash commands, and restored entries share the same current plan.
780pub(crate) fn update_plan_panel(
781    chat: &Container,
782    restored_page: Option<&Container>,
783    result: &Value,
784) -> bool {
785    let Some(details) = result.get("details") else {
786        return false;
787    };
788    if details.get("kind").and_then(Value::as_str) != Some("plan") || details.get("error").is_some()
789    {
790        return false;
791    }
792    let Some(active) = details.get("active").and_then(Value::as_bool) else {
793        return false;
794    };
795    let plan = match details.get("plan") {
796        None | Some(Value::Null) => String::new(),
797        Some(Value::String(plan)) => plan.clone(),
798        _ => return false,
799    };
800    let expanded = details.get("expanded").and_then(Value::as_bool);
801    update_transcript_panel(
802        chat,
803        restored_page,
804        "plan_mode_complete",
805        ToolExecutionComponent::is_plan_panel,
806        |panel| {
807            panel.set_plan_state(plan, active);
808            panel.set_result("", false);
809            if let Some(expanded) = expanded {
810                panel.set_expanded(expanded);
811            }
812        },
813    );
814    true
815}
816
817/// Keep one visible current task list while retaining every result in session storage.
818pub(crate) fn update_todo_list(
819    chat: &Container,
820    restored_page: Option<&Container>,
821    result: &Value,
822) -> bool {
823    let Some(details) = result.get("details") else {
824        return false;
825    };
826    if details.get("error").is_some() {
827        return false;
828    }
829    let Some(items) = details.get("todos").and_then(Value::as_array) else {
830        return false;
831    };
832    let rows: Option<Vec<_>> = items
833        .iter()
834        .map(|item| {
835            let text = item.get("text")?.as_str()?.to_owned();
836            let status = if item.get("done").and_then(Value::as_bool) == Some(true) {
837                "completed"
838            } else {
839                item.get("status")
840                    .and_then(Value::as_str)
841                    .unwrap_or("pending")
842            };
843            Some((text, status.to_owned()))
844        })
845        .collect();
846    let Some(rows) = rows else {
847        return false;
848    };
849    let text = tool_result_text(result);
850    update_transcript_panel(
851        chat,
852        restored_page,
853        "todo",
854        ToolExecutionComponent::is_todo_list,
855        |panel| {
856            panel.set_todo_state(rows);
857            panel.set_result(&text, false);
858        },
859    );
860    true
861}
862
863/// Map a wire/local assistant message's content blocks into the provider-free
864/// [`AssistantBlock`] list the shared component renders (text + thinking +
865/// decoded image blocks, in document order).
866pub fn assistant_blocks_from_value(message: &Value) -> Vec<AssistantBlock> {
867    let mut blocks = Vec::new();
868    let Some(content) = message.get("content").and_then(Value::as_array) else {
869        return blocks;
870    };
871    for block in content {
872        match block.get("type").and_then(Value::as_str) {
873            Some("text") => {
874                if let Some(text) = block.get("text").and_then(Value::as_str) {
875                    blocks.push(AssistantBlock::Text(text.to_string()));
876                }
877            }
878            Some("thinking") => {
879                if let Some(text) = block.get("thinking").and_then(Value::as_str) {
880                    blocks.push(AssistantBlock::Thinking(text.to_string()));
881                }
882            }
883            Some("image") => {
884                if let Some(data) = block.get("data").and_then(Value::as_str) {
885                    if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(data) {
886                        if !bytes.is_empty() {
887                            let png = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
888                                Some(bytes)
889                            } else {
890                                rpi_tools::image_processing::process_image(
891                                    &bytes,
892                                    Default::default(),
893                                )
894                                .ok()
895                            };
896                            if let Some(png) = png {
897                                blocks.push(AssistantBlock::Image(png));
898                            }
899                        }
900                    }
901                }
902            }
903            _ => {}
904        }
905    }
906    blocks
907}
908
909/// Extract the finalized tool calls (`type: "toolCall"`) from an assistant
910/// message value, in document order.
911pub fn tool_calls_from_value(message: &Value) -> Vec<UiToolCall> {
912    let mut calls = Vec::new();
913    let Some(content) = message.get("content").and_then(Value::as_array) else {
914        return calls;
915    };
916    for block in content {
917        if block.get("type").and_then(Value::as_str) != Some("toolCall") {
918            continue;
919        }
920        let id = block.get("id").and_then(Value::as_str).unwrap_or("");
921        let name = block.get("name").and_then(Value::as_str).unwrap_or("");
922        if id.is_empty() || name.trim().is_empty() {
923            continue;
924        }
925        calls.push(UiToolCall {
926            id: id.to_string(),
927            name: name.to_string(),
928            args: block.get("arguments").cloned().unwrap_or(Value::Null),
929        });
930    }
931    calls
932}
933
934/// Text out of a wire tool-result payload (`{content:[{type:"text",text}]}`).
935pub fn tool_result_text(result: &Value) -> String {
936    let mut out = String::new();
937    if let Some(blocks) = result.get("content").and_then(Value::as_array) {
938        for block in blocks {
939            if let Some(text) = block.get("text").and_then(Value::as_str) {
940                if !out.is_empty() {
941                    out.push('\n');
942                }
943                out.push_str(text);
944            }
945        }
946    }
947    out
948}
949
950/// Whether a tool result opts into markdown rendering of its body
951/// (`details.markdown = true`).
952pub fn tool_result_requests_markdown(details: Option<&Value>) -> bool {
953    details
954        .and_then(|details| details.get("markdown"))
955        .and_then(Value::as_bool)
956        .unwrap_or(false)
957}
958
959/// The skill name when `tool_name` is a `read` of a `SKILL.md` file (the
960/// `SKILL.md` parent directory's basename), else `None`. A skill read renders
961/// as upstream's `[skill] <name>` box.
962pub fn skill_tool_name(tool_name: &str, args: &Value) -> Option<String> {
963    if tool_name != "read" {
964        return None;
965    }
966    let path = args.get("path").and_then(Value::as_str)?;
967    let normalized = path.replace('\\', "/");
968    let file_name = normalized.rsplit('/').next()?;
969    if !file_name.eq_ignore_ascii_case("SKILL.md") {
970        return None;
971    }
972    normalized
973        .trim_end_matches('/')
974        .rsplit('/')
975        .nth(1)
976        .filter(|name| !name.is_empty())
977        .map(str::to_string)
978}
979
980/// Tool names rendered through the dedicated `ASK USER` panel instead of a
981/// generic tool box. Native `ask_user` plus the JS `ask_user_question` alias.
982fn is_ask_user_tool(tool_name: &str) -> bool {
983    matches!(tool_name, "ask_user" | "ask_user_question")
984}
985
986/// Render ask_user tool-call ARGUMENTS as a readable question. The raw
987/// transport JSON must never leak into the transcript.
988fn ask_user_args_display(args: &Value) -> String {
989    if args.is_null() {
990        return String::new();
991    }
992    if let Some(summary) = args
993        .get("summary")
994        .and_then(Value::as_str)
995        .map(str::trim)
996        .filter(|text| !text.is_empty())
997    {
998        return format!("Confirmation requested: {summary}");
999    }
1000
1001    let mut lines: Vec<String> = Vec::new();
1002    let questions: Vec<&Value> = args
1003        .get("questions")
1004        .and_then(Value::as_array)
1005        .filter(|items| !items.is_empty())
1006        .map(|items| items.iter().collect())
1007        .unwrap_or_else(|| vec![args]);
1008
1009    for question in questions {
1010        let prompt = question
1011            .get("question")
1012            .and_then(Value::as_str)
1013            .or_else(|| args.get("question").and_then(Value::as_str))
1014            .map(str::trim)
1015            .unwrap_or_default();
1016        if prompt.is_empty() {
1017            continue;
1018        }
1019        if let Some(header) = question
1020            .get("header")
1021            .and_then(Value::as_str)
1022            .map(str::trim)
1023            .filter(|text| !text.is_empty())
1024        {
1025            lines.push(format!("{header}: {prompt}"));
1026        } else {
1027            lines.push(prompt.to_string());
1028        }
1029        let context = question
1030            .get("context")
1031            .and_then(Value::as_str)
1032            .or_else(|| args.get("context").and_then(Value::as_str))
1033            .map(str::trim)
1034            .filter(|text| !text.is_empty());
1035        if let Some(context) = context {
1036            lines.push(format!("  {context}"));
1037        }
1038        let options = question
1039            .get("options")
1040            .and_then(Value::as_array)
1041            .or_else(|| args.get("options").and_then(Value::as_array));
1042        if let Some(options) = options {
1043            let labels: Vec<String> = options
1044                .iter()
1045                .filter_map(|option| {
1046                    option
1047                        .get("title")
1048                        .and_then(Value::as_str)
1049                        .or_else(|| option.as_str())
1050                        .map(str::trim)
1051                        .filter(|label| !label.is_empty())
1052                        .map(str::to_string)
1053                })
1054                .collect();
1055            if !labels.is_empty() {
1056                lines.push(format!("Choices: {}", labels.join(", ")));
1057            }
1058        }
1059        if let Some(suggest) = question
1060            .get("suggest")
1061            .and_then(Value::as_str)
1062            .or_else(|| args.get("suggest").and_then(Value::as_str))
1063            .map(str::trim)
1064            .filter(|text| !text.is_empty())
1065        {
1066            lines.push(format!("Suggestions: {suggest}"));
1067        }
1068    }
1069
1070    lines.join("\n")
1071}
1072
1073/// Progress text while an ask_user tool is pending. Prefer the tool's own
1074/// readable `content`, otherwise show the question so the panel is not blank.
1075fn ask_user_progress_text(args: &Value, result: &Value) -> String {
1076    let text = tool_result_text(result);
1077    if !text.trim().is_empty() {
1078        return text;
1079    }
1080    let args_text = ask_user_args_display(args);
1081    if args_text.trim().is_empty() {
1082        "Waiting for your answer…".to_string()
1083    } else {
1084        args_text
1085    }
1086}
1087
1088/// Final text for a completed ask_user tool.
1089fn ask_user_result_text(result: &Value) -> String {
1090    let text = tool_result_text(result);
1091    if text.trim().is_empty() {
1092        "Answer recorded.".to_string()
1093    } else {
1094        text
1095    }
1096}
1097
1098/// Whether a partial tool result carries anything worth rendering.
1099fn tool_update_has_payload(text: &str, result: &Value) -> bool {
1100    !text.trim().is_empty()
1101        || result
1102            .get("details")
1103            .map(|details| !details.is_null())
1104            .unwrap_or(false)
1105}
1106
1107/// Attach a colored diff to an `edit` tool panel. `write` carries no diff and
1108/// stays a plain summary.
1109fn apply_edit_diff(
1110    comp: &Arc<ToolExecutionComponent>,
1111    tool_name: &str,
1112    details: Option<&Value>,
1113    width: usize,
1114) {
1115    if tool_name != "edit" {
1116        return;
1117    }
1118    let Some(diff_text) = details
1119        .and_then(|details| details.get("diff"))
1120        .and_then(Value::as_str)
1121    else {
1122        return;
1123    };
1124    if diff_text.is_empty() {
1125        return;
1126    }
1127    comp.set_diff(render_diff(diff_text, width));
1128}
1129
1130/// Mark a bash panel complete from the wire result payload. The exit code is
1131/// derived from `is_error`; truncation info is read from `details`.
1132fn finalize_bash(comp: &Arc<BashExecutionComponent>, result: &Value, is_error: bool) {
1133    let details = result.get("details");
1134    let exit_code = Some(if is_error { 1 } else { 0 });
1135    let truncated = details
1136        .and_then(|details| details.get("truncation"))
1137        .and_then(|truncation| truncation.get("truncated"))
1138        .and_then(Value::as_bool)
1139        .unwrap_or(false);
1140    let full_output_path = details
1141        .and_then(|details| details.get("full_output_path"))
1142        .and_then(Value::as_str)
1143        .map(str::to_string);
1144    if let Some(command) = details
1145        .and_then(|details| details.get("command"))
1146        .and_then(Value::as_str)
1147    {
1148        comp.set_command(command);
1149    }
1150    comp.set_complete(
1151        exit_code,
1152        false,
1153        BashTruncation {
1154            truncated,
1155            full_output_path,
1156        },
1157    );
1158}
1159
1160#[cfg(test)]
1161mod tests {
1162    use super::*;
1163    use rpi_tui::{strip_ansi, Component};
1164    use serde_json::json;
1165
1166    fn view() -> TranscriptView {
1167        TranscriptView::new(Arc::new(Container::new()))
1168    }
1169
1170    #[test]
1171    fn adjacent_transcript_blocks_separated_by_exactly_one_blank() {
1172        // The seam invariant: any two adjacent transcript blocks — whatever
1173        // their kinds — are separated by exactly one blank line. Every entry
1174        // contributes one trailing blank (assistant trailing spacing, panel
1175        // trailing spacer, host trailing Spacer for user/notice entries), and
1176        // no block opens with a leading spacer, so the gap never depends on
1177        // which kind sits on top. Old behavior: a panel above an assistant
1178        // message gave 0 blanks (thinking glued to the code card) while an
1179        // assistant message above a panel gave 2 (trailing spacing + panel
1180        // top spacer stacking).
1181        //
1182        // Only *truly* empty rows count as a gap: a panel's own padding rows
1183        // carry a background color (non-empty ANSI payload) and belong to the
1184        // panel, not to the seam.
1185        let view = view();
1186        view.add_user("question");
1187        view.apply(
1188            &UiEvent::AssistantStart {
1189                blocks: vec![AssistantBlock::Thinking("reasoning".into())],
1190            },
1191            80,
1192        );
1193        view.apply(
1194            &UiEvent::AssistantUpdate {
1195                blocks: vec![AssistantBlock::Thinking("reasoning".into())],
1196                tool_calls: vec![UiToolCall {
1197                    id: "t1".into(),
1198                    name: "read".into(),
1199                    args: json!({"path": "f.txt"}),
1200                }],
1201            },
1202            80,
1203        );
1204        view.apply(
1205            &UiEvent::ToolEnd {
1206                id: "t1".into(),
1207                name: "read".into(),
1208                result: json!({"content": [{"type": "text", "text": "done"}]}),
1209                is_error: false,
1210            },
1211            80,
1212        );
1213        view.apply(
1214            &UiEvent::AssistantStart {
1215                blocks: vec![AssistantBlock::Text("answer".into())],
1216            },
1217            80,
1218        );
1219        view.apply(
1220            &UiEvent::ToolStart {
1221                id: "b1".into(),
1222                name: "bash".into(),
1223                args: json!({"command": "ls"}),
1224            },
1225            80,
1226        );
1227        view.apply(&UiEvent::AgentEnd, 80);
1228
1229        let lines = view.chat.render(80);
1230        let plain: Vec<String> = lines
1231            .iter()
1232            .map(|l| strip_ansi(l).trim().to_string())
1233            .collect();
1234        // Anchor each block by its LAST content line, so the rows between two
1235        // anchors are exactly the seam between the two blocks.
1236        let find = |needle: &str| {
1237            plain
1238                .iter()
1239                .rposition(|l| l.contains(needle))
1240                .unwrap_or_else(|| panic!("{needle} missing: {plain:?}"))
1241        };
1242        let user = find("question");
1243        let thinking = find("reasoning");
1244        let panel = find("done");
1245        let answer = find("answer");
1246        let bash = find("$ ls");
1247        assert!(user < thinking && thinking < panel && panel < answer);
1248        assert!(answer < bash);
1249        for (top_name, top, bottom_name, bottom) in [
1250            ("user", user, "thinking", thinking),
1251            ("thinking", thinking, "panel", panel),
1252            ("panel", panel, "answer", answer),
1253            ("answer", answer, "bash", bash),
1254        ] {
1255            let gap = lines[top + 1..bottom]
1256                .iter()
1257                .filter(|l| l.is_empty())
1258                .count();
1259            assert_eq!(
1260                gap, 1,
1261                "{top_name}→{bottom_name} seam must be exactly one blank row: {plain:?}"
1262            );
1263        }
1264    }
1265
1266    #[test]
1267    fn retry_notice_ends_with_a_trailing_spacer() {
1268        // A notice is a transcript entry like any other: without its own
1269        // trailing blank it would render flush against the next block.
1270        let view = view();
1271        view.apply(
1272            &UiEvent::Retry {
1273                attempt: 1,
1274                max_retries: 3,
1275                delay_ms: 500,
1276                error: "boom".into(),
1277            },
1278            80,
1279        );
1280        let lines = view.chat.render(80);
1281        let rendered = strip_ansi(&lines.join("\n"));
1282        assert!(rendered.contains("retry 1/3"));
1283        assert_eq!(lines.last(), Some(&String::new()));
1284    }
1285
1286    #[test]
1287    fn empty_assistant_start_and_whitespace_deltas_do_not_move_the_transcript() {
1288        for starts_with_event in [true, false] {
1289            let view = view();
1290            view.add_user("hi");
1291            let before = view.chat.render(80);
1292            if starts_with_event {
1293                view.apply(&UiEvent::AssistantStart { blocks: vec![] }, 80);
1294                assert_eq!(view.chat.render(80), before);
1295            }
1296            for blocks in [
1297                vec![],
1298                vec![AssistantBlock::Text(" ".into())],
1299                vec![AssistantBlock::Thinking("\n".into())],
1300            ] {
1301                view.apply(
1302                    &UiEvent::AssistantUpdate {
1303                        blocks,
1304                        tool_calls: vec![],
1305                    },
1306                    80,
1307                );
1308                assert_eq!(view.chat.render(80), before);
1309            }
1310            view.apply(
1311                &UiEvent::AssistantUpdate {
1312                    blocks: vec![AssistantBlock::Text("hello".into())],
1313                    tool_calls: vec![],
1314                },
1315                80,
1316            );
1317            let visible = view.chat.render(80);
1318            assert!(visible.len() > before.len());
1319            assert!(visible.iter().any(|line| line.contains("hello")));
1320            assert_eq!(visible.last(), Some(&String::new()));
1321            view.apply(&UiEvent::AssistantEnd { blocks: vec![] }, 80);
1322            assert_eq!(view.chat.render(80), before);
1323            view.apply(&UiEvent::AssistantStart { blocks: vec![] }, 80);
1324            assert_eq!(view.chat.render(80), before);
1325        }
1326    }
1327
1328    #[test]
1329    fn saved_assistant_is_rendered_without_replacing_the_live_message() {
1330        let view = view();
1331        view.apply(
1332            &UiEvent::AssistantStart {
1333                blocks: vec![AssistantBlock::Text("pending".into())],
1334            },
1335            80,
1336        );
1337        view.apply(
1338            &UiEvent::SavedAssistant {
1339                blocks: vec![AssistantBlock::Text("previous reply".into())],
1340            },
1341            80,
1342        );
1343        view.apply(
1344            &UiEvent::AssistantEnd {
1345                blocks: vec![AssistantBlock::Text("complete reply".into())],
1346            },
1347            80,
1348        );
1349        let lines = view.chat.render(80);
1350        assert!(lines.iter().any(|line| line.contains("previous reply")));
1351        assert!(lines.iter().any(|line| line.contains("complete reply")));
1352        assert!(lines.iter().all(|line| !line.contains("pending")));
1353    }
1354
1355    #[test]
1356    fn assistant_blocks_follow_content_order() {
1357        let message = json!({
1358            "content": [
1359                {"type": "thinking", "thinking": "why"},
1360                {"type": "text", "text": "hello"},
1361                {"type": "toolCall", "id": "c1", "name": "read", "arguments": {}},
1362            ]
1363        });
1364        assert_eq!(
1365            assistant_blocks_from_value(&message),
1366            vec![
1367                AssistantBlock::Thinking("why".into()),
1368                AssistantBlock::Text("hello".into()),
1369            ]
1370        );
1371    }
1372
1373    #[test]
1374    fn assistant_blocks_decode_images() {
1375        let mut bytes = Vec::new();
1376        {
1377            let mut encoder = png::Encoder::new(&mut bytes, 1, 1);
1378            encoder.set_color(png::ColorType::Rgb);
1379            encoder
1380                .write_header()
1381                .unwrap()
1382                .write_image_data(&[255, 0, 0])
1383                .unwrap();
1384        }
1385        let message = json!({
1386            "content": [{"type": "image", "data": base64::engine::general_purpose::STANDARD.encode(&bytes), "mimeType": "image/png"}]
1387        });
1388        assert_eq!(
1389            assistant_blocks_from_value(&message),
1390            vec![AssistantBlock::Image(bytes.to_vec())]
1391        );
1392        let jpeg = rpi_tools::image_processing::process_image(
1393            &bytes,
1394            rpi_tools::image_processing::ImageProcessingOptions {
1395                format: Some(rpi_tools::image_processing::OutputFormat::Jpeg { quality: 85 }),
1396                ..Default::default()
1397            },
1398        )
1399        .unwrap();
1400        let blocks = assistant_blocks_from_value(&json!({
1401            "content": [{"type": "image", "data": base64::engine::general_purpose::STANDARD.encode(jpeg), "mimeType": "image/jpeg"}]
1402        }));
1403        assert!(
1404            matches!(&blocks[0], AssistantBlock::Image(data) if data.starts_with(b"\x89PNG\r\n\x1a\n"))
1405        );
1406    }
1407
1408    #[test]
1409    fn tool_calls_extract_ids_names_and_args() {
1410        let message = json!({
1411            "content": [
1412                {"type": "text", "text": "x"},
1413                {"type": "toolCall", "id": "b1", "name": "bash", "arguments": {"command": "ls"}},
1414                {"type": "toolCall", "id": "", "name": "read", "arguments": {}},
1415            ]
1416        });
1417        assert_eq!(
1418            tool_calls_from_value(&message),
1419            vec![UiToolCall {
1420                id: "b1".into(),
1421                name: "bash".into(),
1422                args: json!({"command": "ls"}),
1423            }]
1424        );
1425    }
1426
1427    #[test]
1428    fn markdown_flag_is_opt_in() {
1429        assert!(tool_result_requests_markdown(Some(
1430            &json!({"markdown": true})
1431        )));
1432        assert!(!tool_result_requests_markdown(Some(
1433            &json!({"markdown": false})
1434        )));
1435        assert!(!tool_result_requests_markdown(Some(&json!({}))));
1436        assert!(!tool_result_requests_markdown(None));
1437    }
1438
1439    #[test]
1440    fn skill_tool_name_only_matches_skill_reads() {
1441        assert_eq!(
1442            skill_tool_name("read", &json!({"path": "skills/foo/SKILL.md"})),
1443            Some("foo".to_string())
1444        );
1445        assert_eq!(skill_tool_name("read", &json!({"path": "README.md"})), None);
1446        assert_eq!(
1447            skill_tool_name("write", &json!({"path": "skills/foo/SKILL.md"})),
1448            None
1449        );
1450    }
1451
1452    #[test]
1453    fn ask_user_args_display_never_leaks_transport_json() {
1454        let text = ask_user_args_display(&json!({
1455            "question": "你的代理端口是多少?",
1456            "context": "本机",
1457            "options": ["7890", {"title": "7897", "description": "clash"}],
1458            "suggest": "1080"
1459        }));
1460        assert!(text.contains("你的代理端口是多少?"));
1461        assert!(text.contains("本机"));
1462        assert!(text.contains("Choices: 7890, 7897"));
1463        assert!(text.contains("Suggestions: 1080"));
1464        assert!(!text.trim_start().starts_with('{'));
1465        assert_eq!(
1466            ask_user_args_display(&json!({"type": "confirm", "summary": "Deploy?"})),
1467            "Confirmation requested: Deploy?"
1468        );
1469    }
1470
1471    #[test]
1472    fn tool_start_routes_bash_to_its_own_map() {
1473        let view = view();
1474        view.apply(
1475            &UiEvent::ToolStart {
1476                id: "b1".into(),
1477                name: "bash".into(),
1478                args: json!({"command": "ls -la"}),
1479            },
1480            80,
1481        );
1482        view.apply(
1483            &UiEvent::ToolStart {
1484                id: "r1".into(),
1485                name: "read".into(),
1486                args: json!({"path": "a.txt"}),
1487            },
1488            80,
1489        );
1490        assert!(view.bash_components.lock().unwrap().contains_key("b1"));
1491        assert!(view.tool_components.lock().unwrap().contains_key("r1"));
1492        assert!(view.tool_components.lock().unwrap().get("b1").is_none());
1493    }
1494
1495    #[test]
1496    fn bash_start_without_a_command_is_deferred() {
1497        let view = view();
1498        view.apply(
1499            &UiEvent::ToolStart {
1500                id: "b1".into(),
1501                name: "bash".into(),
1502                args: json!({}),
1503            },
1504            80,
1505        );
1506        assert!(view.bash_components.lock().unwrap().is_empty());
1507        assert!(view.tool_components.lock().unwrap().is_empty());
1508    }
1509
1510    #[test]
1511    fn assistant_stream_reuses_one_component() {
1512        let view = view();
1513        view.apply(&UiEvent::AssistantStart { blocks: vec![] }, 80);
1514        view.apply(
1515            &UiEvent::AssistantUpdate {
1516                blocks: vec![AssistantBlock::Text("hi".into())],
1517                tool_calls: vec![],
1518            },
1519            80,
1520        );
1521        assert!(view.current_assistant.lock().unwrap().is_some());
1522    }
1523
1524    #[test]
1525    fn toggle_expanded_round_trips() {
1526        let view = view();
1527        assert!(!view.expanded());
1528        assert!(view.toggle_expanded());
1529        assert!(view.expanded());
1530    }
1531
1532    #[test]
1533    fn todo_updates_share_one_panel_and_preserve_errors() {
1534        let view = view();
1535        for (id, done) in [("a", false), ("b", true)] {
1536            view.sync_tool_calls(&[UiToolCall {
1537                id: id.into(),
1538                name: "todo".into(),
1539                args: json!({"action":"toggle"}),
1540            }]);
1541            view.tool_start(id, "todo", &json!({}), 80);
1542            view.tool_end(id, "todo", &json!({"content":[],"details":{"todos":[{"id":1,"text":"Run tests","done":done}]}}), false, 80);
1543        }
1544        assert_eq!(view.chat.child_count(), 1);
1545        assert!(view.tool_components.lock().unwrap().is_empty());
1546        let children = view.chat.get_children();
1547        let panel = children[0]
1548            .as_any()
1549            .downcast_ref::<ToolExecutionComponent>()
1550            .unwrap();
1551        let rendered = rpi_tui::ansi::strip_ansi(&panel.render(80).join("\n"));
1552        assert!(rendered.contains("1/1 completed"));
1553        assert!(rendered.contains("[✓] Run tests"));
1554        view.tool_end(
1555            "error",
1556            "todo",
1557            &json!({"content":[{"type":"text","text":"invalid task"}]}),
1558            true,
1559            80,
1560        );
1561        assert_eq!(view.chat.child_count(), 2);
1562        view.tool_end("soft-error", "todo", &json!({"content":[{"type":"text","text":"todo not found"}],"details":{"todos":[],"error":"todo not found"}}), false, 80);
1563        assert_eq!(view.chat.child_count(), 3);
1564        assert!(update_todo_list(
1565            &view.chat,
1566            None,
1567            &json!({"details":{"todos":[]}})
1568        ));
1569        assert_eq!(view.chat.child_count(), 3);
1570        assert!(!update_todo_list(
1571            &view.chat,
1572            None,
1573            &json!({"details":{"todos":[{}]}})
1574        ));
1575        assert_eq!(view.chat.child_count(), 3);
1576    }
1577
1578    #[test]
1579    fn completed_plan_keeps_its_transcript_position() {
1580        let view = view();
1581        view.apply(
1582            &UiEvent::AssistantStart {
1583                blocks: vec![AssistantBlock::Text("planning context".into())],
1584            },
1585            80,
1586        );
1587        view.apply(
1588            &UiEvent::AssistantEnd {
1589                blocks: vec![AssistantBlock::Text("planning context".into())],
1590            },
1591            80,
1592        );
1593        view.apply(
1594            &UiEvent::ToolEnd {
1595                id: "start".into(),
1596                name: "plan_mode_start".into(),
1597                result: json!({"details":{"kind":"plan","active":true}}),
1598                is_error: false,
1599            },
1600            80,
1601        );
1602        view.apply(
1603            &UiEvent::AssistantStart {
1604                blocks: vec![AssistantBlock::Text("repository findings".into())],
1605            },
1606            80,
1607        );
1608        view.apply(
1609            &UiEvent::AssistantEnd {
1610                blocks: vec![AssistantBlock::Text("repository findings".into())],
1611            },
1612            80,
1613        );
1614
1615        view.apply(
1616            &UiEvent::ToolEnd {
1617                id: "complete".into(),
1618                name: "plan_mode_complete".into(),
1619                result: json!({
1620                    "details": {
1621                        "kind": "plan",
1622                        "active": false,
1623                        "plan": "1. Keep the plan in place"
1624                    }
1625                }),
1626                is_error: false,
1627            },
1628            80,
1629        );
1630
1631        let lines: Vec<_> = view
1632            .chat
1633            .render(80)
1634            .iter()
1635            .map(|line| strip_ansi(line))
1636            .collect();
1637        let plan = lines
1638            .iter()
1639            .position(|line| line.contains("Plan · Ready"))
1640            .expect("completed plan panel should render");
1641        let findings = lines
1642            .iter()
1643            .position(|line| line.contains("repository findings"))
1644            .expect("later assistant output should render");
1645        assert!(
1646            plan < findings,
1647            "plan completion must not move the plan below later transcript output: {lines:?}"
1648        );
1649    }
1650
1651    #[test]
1652    fn todo_updates_keep_their_transcript_position() {
1653        let view = view();
1654        view.apply(
1655            &UiEvent::AssistantStart {
1656                blocks: vec![AssistantBlock::Text("before tasks".into())],
1657            },
1658            80,
1659        );
1660        view.apply(
1661            &UiEvent::AssistantEnd {
1662                blocks: vec![AssistantBlock::Text("before tasks".into())],
1663            },
1664            80,
1665        );
1666        view.apply(
1667            &UiEvent::ToolEnd {
1668                id: "todo-1".into(),
1669                name: "todo".into(),
1670                result: json!({
1671                    "details": {
1672                        "todos": [{"text": "first task", "done": false}]
1673                    }
1674                }),
1675                is_error: false,
1676            },
1677            80,
1678        );
1679        view.apply(
1680            &UiEvent::AssistantStart {
1681                blocks: vec![AssistantBlock::Text("later output".into())],
1682            },
1683            80,
1684        );
1685        view.apply(
1686            &UiEvent::AssistantEnd {
1687                blocks: vec![AssistantBlock::Text("later output".into())],
1688            },
1689            80,
1690        );
1691        view.apply(
1692            &UiEvent::ToolEnd {
1693                id: "todo-2".into(),
1694                name: "todo".into(),
1695                result: json!({
1696                    "details": {
1697                        "todos": [{"text": "first task", "done": true}]
1698                    }
1699                }),
1700                is_error: false,
1701            },
1702            80,
1703        );
1704
1705        let lines: Vec<_> = view
1706            .chat
1707            .render(80)
1708            .iter()
1709            .map(|line| strip_ansi(line))
1710            .collect();
1711        let tasks = lines
1712            .iter()
1713            .position(|line| line.contains("Tasks  1/1 completed"))
1714            .expect("todo panel should render");
1715        let later = lines
1716            .iter()
1717            .position(|line| line.contains("later output"))
1718            .expect("later transcript output should render");
1719        assert!(
1720            tasks < later,
1721            "todo update must not move the task panel below later output: {lines:?}"
1722        );
1723    }
1724
1725    #[test]
1726    fn plan_tools_and_show_update_one_expandable_panel() {
1727        let view = view();
1728        view.sync_tool_calls(&[UiToolCall {
1729            id: "start".into(),
1730            name: "plan_mode_start".into(),
1731            args: json!({}),
1732        }]);
1733        view.tool_start("start", "plan_mode_start", &json!({}), 80);
1734        view.tool_end(
1735            "start",
1736            "plan_mode_start",
1737            &json!({"details":{"kind":"plan","active":true}}),
1738            false,
1739            80,
1740        );
1741        let body = (1..=30)
1742            .map(|i| format!("{i}. Step {i}"))
1743            .collect::<Vec<_>>()
1744            .join("\n");
1745        view.tool_end(
1746            "complete",
1747            "plan_mode_complete",
1748            &json!({"details":{"kind":"plan","active":false,"plan":body}}),
1749            false,
1750            80,
1751        );
1752        assert_eq!(view.chat.child_count(), 1);
1753        assert!(view.tool_components.lock().unwrap().is_empty());
1754        view.set_expanded(true);
1755        let children = view.chat.get_children();
1756        let panel = children[0]
1757            .as_any()
1758            .downcast_ref::<ToolExecutionComponent>()
1759            .unwrap();
1760        assert!(rpi_tui::ansi::strip_ansi(&panel.render(80).join("\n")).contains("Step 30"));
1761        assert!(update_plan_panel(
1762            &view.chat,
1763            None,
1764            &json!({"kind":"message","details":{"kind":"plan","active":false,"plan":body,"expanded":true}})
1765        ));
1766        assert_eq!(view.chat.child_count(), 1);
1767        view.tool_end(
1768            "error",
1769            "plan_mode_complete",
1770            &json!({"content":[{"type":"text","text":"not active"}]}),
1771            true,
1772            80,
1773        );
1774        assert_eq!(view.chat.child_count(), 2);
1775    }
1776
1777    // ---- Click-to-expand thinking probes (per-message) ----
1778
1779    #[test]
1780    fn transcript_assigns_ids_and_toggles_per_message() {
1781        // Axis: host-side routing. Every streamed assistant message gets an
1782        // id; toggling by id flips only THAT message; the toggle round-trips.
1783        let view = view();
1784        view.set_hide_thinking(true);
1785        view.apply(
1786            &UiEvent::AssistantStart {
1787                blocks: vec![
1788                    AssistantBlock::Thinking("first msg reasoning".into()),
1789                    AssistantBlock::Text("answer one".into()),
1790                ],
1791            },
1792            80,
1793        );
1794        let first = view
1795            .current_assistant
1796            .lock()
1797            .unwrap()
1798            .clone()
1799            .expect("assistant mounted");
1800        let first_id = first.message_id().expect("id assigned");
1801        view.apply(&UiEvent::AgentEnd, 80);
1802
1803        view.apply(
1804            &UiEvent::AssistantStart {
1805                blocks: vec![AssistantBlock::Thinking("second msg reasoning".into())],
1806            },
1807            80,
1808        );
1809        let second = view
1810            .current_assistant
1811            .lock()
1812            .unwrap()
1813            .clone()
1814            .expect("assistant mounted");
1815        let second_id = second.message_id().expect("id assigned");
1816        assert_ne!(first_id, second_id, "ids must be unique per message");
1817
1818        // Toggle the SECOND message only.
1819        assert!(view.toggle_message_thinking(&second_id));
1820        let expanded = strip_ansi(&second.render(80).join("\n"));
1821        assert!(expanded.contains("second msg reasoning"));
1822        let first_render = strip_ansi(&first.render(80).join("\n"));
1823        assert!(
1824            !first_render.contains("first msg reasoning"),
1825            "toggle leaked into another message: {first_render}"
1826        );
1827
1828        // Toggle again collapses back.
1829        assert!(view.toggle_message_thinking(&second_id));
1830        assert!(!strip_ansi(&second.render(80).join("\n")).contains("second msg reasoning"));
1831    }
1832
1833    #[test]
1834    fn toggle_with_stale_id_is_a_noop() {
1835        let view = view();
1836        assert!(!view.toggle_message_thinking("t999"));
1837        view.apply(
1838            &UiEvent::AssistantStart {
1839                blocks: vec![AssistantBlock::Thinking("reasoning".into())],
1840            },
1841            80,
1842        );
1843        // An unknown id must not disturb the live message.
1844        assert!(!view.toggle_message_thinking("h12345"));
1845        let comp = view.current_assistant.lock().unwrap().clone().unwrap();
1846        assert!(!strip_ansi(&comp.render(80).join("\n")).contains("Thinking..."));
1847    }
1848
1849    #[test]
1850    fn global_toggle_keeps_message_level_expansion() {
1851        // Axis: Ctrl+T (global) vs click (per message). A click-expanded
1852        // message stays expanded across a later global toggle, and a globally
1853        // visible transcript still collapses per message.
1854        let view = view();
1855        view.set_hide_thinking(true);
1856        view.apply(
1857            &UiEvent::AssistantStart {
1858                blocks: vec![AssistantBlock::Thinking("sticky reasoning".into())],
1859            },
1860            80,
1861        );
1862        let comp = view.current_assistant.lock().unwrap().clone().unwrap();
1863        let id = comp.message_id().unwrap();
1864        assert!(view.toggle_message_thinking(&id));
1865        assert!(strip_ansi(&comp.render(80).join("\n")).contains("sticky reasoning"));
1866
1867        // Global toggle OFF→ON rebuild: override survives.
1868        view.set_hide_thinking(false);
1869        view.set_hide_thinking(true);
1870        assert!(
1871            strip_ansi(&comp.render(80).join("\n")).contains("sticky reasoning"),
1872            "global toggle wiped the per-message expansion"
1873        );
1874
1875        // The globally-visible case: collapse via toggle, then a global show
1876        // must restore it.
1877        assert!(view.toggle_message_thinking(&id));
1878        view.set_hide_thinking(false);
1879        assert!(strip_ansi(&comp.render(80).join("\n")).contains("sticky reasoning"));
1880    }
1881
1882    #[test]
1883    fn click_reaches_assistant_components_nested_in_history_pages() {
1884        // Self-review probe: a history PAGE is a nested container under the
1885        // chat root, not a direct child of the live slot. A click on one of
1886        // its thinking rows must still resolve to the owning component.
1887        let chat = Arc::new(rpi_tui::Container::new());
1888        let page = Arc::new(rpi_tui::Container::new());
1889        let comp = Arc::new(AssistantMessageComponent::new(AssistantMessageOptions {
1890            hide_thinking: true,
1891            ..Default::default()
1892        }));
1893        comp.set_message_id("h7");
1894        comp.update_blocks(&[
1895            AssistantBlock::Thinking("old reasoning".into()),
1896            AssistantBlock::Text("old answer".into()),
1897        ]);
1898        page.add_child(comp.clone());
1899        chat.add_child(page);
1900        let view = TranscriptView::new(chat);
1901        view.set_hide_thinking(true);
1902        assert!(
1903            view.toggle_message_thinking("h7"),
1904            "click on a nested history page found no component"
1905        );
1906        assert!(strip_ansi(&comp.render(80).join("\n")).contains("old reasoning"));
1907    }
1908
1909    #[test]
1910    fn click_on_globally_visible_thinking_collapses_then_restores() {
1911        // Self-review probe: with Ctrl+T OFF the body is already visible; the
1912        // first click must COLLAPSE that message (not silently "expand" it),
1913        // and the second click must restore it.
1914        let view = view();
1915        view.apply(
1916            &UiEvent::AssistantStart {
1917                blocks: vec![AssistantBlock::Thinking("shown reasoning".into())],
1918            },
1919            80,
1920        );
1921        let comp = view.current_assistant.lock().unwrap().clone().unwrap();
1922        let id = comp.message_id().unwrap();
1923        let visible = || strip_ansi(&comp.render(80).join("\n")).contains("shown reasoning");
1924        assert!(visible());
1925        assert!(view.toggle_message_thinking(&id));
1926        assert!(!visible(), "first click must collapse a visible body");
1927        assert!(view.toggle_message_thinking(&id));
1928        assert!(visible(), "second click must restore the global show");
1929    }
1930}