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