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