1use 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#[derive(Debug, Clone, PartialEq)]
33pub struct UiToolCall {
34 pub id: String,
35 pub name: String,
36 pub args: Value,
37}
38
39#[derive(Debug, Clone)]
42pub enum UiEvent {
43 AgentStart,
45 AgentEnd,
47 Retry {
49 attempt: u32,
50 max_retries: u32,
51 delay_ms: u64,
52 error: String,
53 },
54 AssistantStart { blocks: Vec<AssistantBlock> },
56 AssistantUpdate {
59 blocks: Vec<AssistantBlock>,
60 tool_calls: Vec<UiToolCall>,
61 },
62 AssistantEnd { blocks: Vec<AssistantBlock> },
64 SavedAssistant { blocks: Vec<AssistantBlock> },
66 ToolStart {
68 id: String,
69 name: String,
70 args: Value,
71 },
72 ToolUpdate {
73 id: String,
74 name: String,
75 args: Value,
76 result: Value,
77 },
78 ToolEnd {
79 id: String,
80 name: String,
81 result: Value,
82 is_error: bool,
83 },
84}
85
86#[derive(Clone, Default)]
94pub struct MessageIdSeq(Arc<AtomicU64>);
95
96impl MessageIdSeq {
97 pub fn new() -> Self {
99 Self(Arc::new(AtomicU64::new(1)))
100 }
101
102 pub fn next_id(&self) -> String {
104 format!("t{}", self.0.fetch_add(1, Ordering::Relaxed))
105 }
106}
107
108pub struct TranscriptView {
112 show_images: bool,
113 chat: Arc<Container>,
114 panels: Arc<Container>,
115 current_assistant: Arc<Mutex<Option<Arc<AssistantMessageComponent>>>>,
116 tool_components: Arc<Mutex<HashMap<String, Arc<ToolExecutionComponent>>>>,
117 bash_components: Arc<Mutex<HashMap<String, Arc<BashExecutionComponent>>>>,
121 hide_thinking: Arc<Mutex<bool>>,
123 message_seq: MessageIdSeq,
126 expanded: Arc<Mutex<bool>>,
128 markdown_transformer: Arc<Mutex<Option<MarkdownTransformer>>>,
132}
133
134pub type MarkdownTransformer = Arc<dyn Fn(&str) -> String + Send + Sync>;
137
138impl TranscriptView {
139 pub fn new(chat: Arc<Container>) -> Self {
141 Self::with_maps(
142 chat,
143 Arc::new(Mutex::new(None)),
144 Arc::new(Mutex::new(HashMap::new())),
145 Arc::new(Mutex::new(HashMap::new())),
146 Arc::new(Mutex::new(false)),
147 Arc::new(Mutex::new(false)),
148 Arc::new(Mutex::new(None)),
149 MessageIdSeq::new(),
150 )
151 }
152
153 #[allow(clippy::too_many_arguments)]
157 pub fn with_maps(
158 chat: Arc<Container>,
159 current_assistant: Arc<Mutex<Option<Arc<AssistantMessageComponent>>>>,
160 tool_components: Arc<Mutex<HashMap<String, Arc<ToolExecutionComponent>>>>,
161 bash_components: Arc<Mutex<HashMap<String, Arc<BashExecutionComponent>>>>,
162 hide_thinking: Arc<Mutex<bool>>,
163 expanded: Arc<Mutex<bool>>,
164 markdown_transformer: Arc<Mutex<Option<MarkdownTransformer>>>,
165 message_seq: MessageIdSeq,
166 ) -> Self {
167 Self {
168 show_images: true,
169 panels: chat.clone(),
170 chat,
171 current_assistant,
172 tool_components,
173 bash_components,
174 hide_thinking,
175 expanded,
176 markdown_transformer,
177 message_seq,
178 }
179 }
180
181 pub(crate) fn with_panels(mut self, panels: Arc<Container>) -> Self {
182 self.panels = panels;
183 self
184 }
185
186 pub fn with_show_images(mut self, show: bool) -> Self {
188 self.show_images = show;
189 self
190 }
191
192 pub fn add_user(&self, text: &str) {
194 self.chat
195 .add_child(Arc::new(UserMessageComponent::new(text.to_string())));
196 self.chat.add_child(Arc::new(Spacer::new(1)));
197 }
198
199 pub fn add_notice(&self, text: &str) {
201 self.chat
202 .add_child(Arc::new(rpi_tui::Text::new(format!("· {text}"), 1, 0)));
203 self.chat.add_child(Arc::new(Spacer::new(1)));
207 }
208
209 pub fn apply(&self, event: &UiEvent, width: usize) {
212 match event {
213 UiEvent::AgentStart => {}
214 UiEvent::AgentEnd => {
215 if let Some(comp) = self.current_assistant.lock().unwrap().take() {
216 comp.set_streaming(false);
217 }
218 }
219 UiEvent::Retry {
220 attempt,
221 max_retries,
222 delay_ms,
223 error,
224 } => {
225 self.add_notice(&format!(
226 "retry {attempt}/{max_retries} in {delay_ms}ms: {error}"
227 ));
228 }
229 UiEvent::AssistantStart { blocks } => {
230 self.start_assistant(blocks);
231 }
232 UiEvent::AssistantUpdate { blocks, tool_calls } => {
233 self.ensure_assistant();
234 self.sync_tool_calls(tool_calls);
235 if let Some(comp) = self.current_assistant.lock().unwrap().as_ref() {
236 comp.update_blocks(blocks);
237 }
238 }
239 UiEvent::AssistantEnd { blocks } => {
240 if let Some(comp) = self.current_assistant.lock().unwrap().take() {
241 comp.update_blocks(blocks);
242 comp.set_streaming(false);
243 }
244 }
245 UiEvent::SavedAssistant { blocks } => {
246 self.append_assistant(blocks, false);
247 }
248 UiEvent::ToolStart { id, name, args } => self.tool_start(id, name, args, width),
249 UiEvent::ToolUpdate {
250 id,
251 name,
252 args,
253 result,
254 } => self.tool_update(id, name, args, result, width),
255 UiEvent::ToolEnd {
256 id,
257 name,
258 result,
259 is_error,
260 } => self.tool_end(id, name, result, *is_error, width),
261 }
262 }
263
264 pub fn set_expanded(&self, expanded: bool) {
267 *self.expanded.lock().unwrap() = expanded;
268 for child in self.chat.get_children() {
269 if let Some(component) = child.as_any().downcast_ref::<ToolExecutionComponent>() {
270 component.set_expanded(expanded);
271 }
272 }
273 for comp in self.tool_components.lock().unwrap().values() {
274 comp.set_expanded(expanded);
275 }
276 for comp in self.bash_components.lock().unwrap().values() {
277 comp.set_expanded(expanded);
278 }
279 }
280
281 pub fn toggle_expanded(&self) -> bool {
283 let next = !*self.expanded.lock().unwrap();
284 self.set_expanded(next);
285 next
286 }
287
288 pub fn expanded(&self) -> bool {
290 *self.expanded.lock().unwrap()
291 }
292
293 pub fn set_hide_thinking(&self, hide: bool) {
295 *self.hide_thinking.lock().unwrap() = hide;
296 if let Some(comp) = self.current_assistant.lock().unwrap().as_ref() {
297 comp.set_hide_thinking(hide);
298 }
299 }
300
301 fn assign_message_id(&self, comp: &AssistantMessageComponent) -> String {
305 let id = self.message_seq.next_id();
306 comp.set_message_id(&id);
307 id
308 }
309
310 pub fn toggle_message_thinking(&self, id: &str) -> bool {
315 let global_show = !*self.hide_thinking.lock().unwrap();
324 let toggle = |comp: &AssistantMessageComponent| {
325 let visible = comp.expand_thinking().unwrap_or(global_show);
326 let target = !visible;
327 let next = (target != global_show).then_some(target);
330 comp.set_expand_thinking(next);
331 };
332 if self.for_each_assistant(|comp| {
333 if comp.message_id().as_deref() == Some(id) {
334 toggle(comp);
335 true
336 } else {
337 false
338 }
339 }) {
340 return true;
341 }
342 let current = self.current_assistant.lock().unwrap().clone();
346 if let Some(comp) = current.filter(|comp| comp.message_id().as_deref() == Some(id)) {
347 toggle(&comp);
348 return true;
349 }
350 false
351 }
352
353 fn for_each_assistant(
356 &self,
357 mut visit: impl FnMut(&AssistantMessageComponent) -> bool,
358 ) -> bool {
359 fn walk(
360 children: Vec<Arc<dyn rpi_tui::Component>>,
361 visit: &mut impl FnMut(&AssistantMessageComponent) -> bool,
362 ) -> bool {
363 for child in children {
364 if let Some(comp) = child.as_any().downcast_ref::<AssistantMessageComponent>() {
365 if visit(comp) {
366 return true;
367 }
368 }
369 if let Some(container) = child.as_any().downcast_ref::<rpi_tui::Container>() {
370 if walk(container.get_children(), visit) {
371 return true;
372 }
373 }
374 }
375 false
376 }
377 walk(self.chat.get_children(), &mut visit)
378 }
379
380 pub fn next_message_id(&self) -> String {
383 self.message_seq.next_id()
384 }
385
386 pub fn toggle_hide_thinking(&self) -> bool {
388 let next = !*self.hide_thinking.lock().unwrap();
389 self.set_hide_thinking(next);
390 next
391 }
392
393 pub fn hide_thinking(&self) -> bool {
395 *self.hide_thinking.lock().unwrap()
396 }
397
398 pub fn set_markdown_transformer(&self, transformer: Option<MarkdownTransformer>) {
401 *self.markdown_transformer.lock().unwrap() = transformer.clone();
402 if let Some(comp) = self.current_assistant.lock().unwrap().as_ref() {
403 comp.set_markdown_transformer(transformer);
404 }
405 }
406
407 pub fn finalize_assistant(&self) {
409 if let Some(comp) = self.current_assistant.lock().unwrap().take() {
410 comp.set_streaming(false);
411 }
412 }
413
414 pub fn finalize_assistant_blocks(&self, blocks: &[AssistantBlock]) {
416 if let Some(comp) = self.current_assistant.lock().unwrap().take() {
417 comp.update_blocks(blocks);
418 comp.set_streaming(false);
419 }
420 }
421
422 pub fn has_running_tool(&self) -> bool {
424 self.tool_components
425 .lock()
426 .unwrap()
427 .values()
428 .any(|component| component.status() == ToolStatus::Running)
429 }
430
431 pub fn has_active_bash(&self) -> bool {
433 !self.bash_components.lock().unwrap().is_empty()
434 }
435
436 fn start_assistant(&self, blocks: &[AssistantBlock]) {
437 let component = self.append_assistant(blocks, true);
438 *self.current_assistant.lock().unwrap() = Some(component);
439 }
440
441 fn append_assistant(
442 &self,
443 blocks: &[AssistantBlock],
444 streaming: bool,
445 ) -> Arc<AssistantMessageComponent> {
446 let comp = Arc::new(AssistantMessageComponent::new(
447 AssistantMessageOptions::default(),
448 ));
449 self.assign_message_id(&comp);
450 comp.set_hide_thinking(*self.hide_thinking.lock().unwrap());
451 comp.set_show_images(self.show_images);
452 comp.set_trailing_spacing(1);
453 if let Some(transformer) = self.markdown_transformer.lock().unwrap().clone() {
454 comp.set_markdown_transformer(Some(transformer));
455 }
456 comp.set_streaming(streaming);
457 comp.update_blocks(blocks);
458 self.chat.add_child(comp.clone());
459 comp
460 }
461
462 fn ensure_assistant(&self) {
465 let mut current = self.current_assistant.lock().unwrap();
466 if current.is_none() {
467 *current = Some(self.append_assistant(&[], true));
468 }
469 }
470
471 fn sync_tool_calls(&self, calls: &[UiToolCall]) {
474 for call in calls {
475 if matches!(
476 call.name.as_str(),
477 "todo" | "plan_mode_start" | "plan_mode_complete"
478 ) {
479 continue;
480 }
481 if call.name == "bash" {
482 let command = call
483 .args
484 .get("command")
485 .and_then(Value::as_str)
486 .unwrap_or("");
487 if command.trim().is_empty() {
488 continue;
489 }
490 let mut bash = self.bash_components.lock().unwrap();
491 if let Some(existing) = bash.get(&call.id) {
492 existing.set_command(command);
493 } else {
494 let comp = Arc::new(BashExecutionComponent::new(command));
495 comp.set_expanded(self.expanded());
496 self.chat.add_child(comp.clone());
497 bash.insert(call.id.clone(), comp);
498 }
499 continue;
500 }
501 let ask_user = is_ask_user_tool(&call.name);
502 let display = if ask_user {
503 ask_user_args_display(&call.args)
504 } else {
505 call.args.to_string()
506 };
507 let mut tools = self.tool_components.lock().unwrap();
508 if let Some(existing) = tools.get(&call.id) {
509 if let Some(skill) = skill_tool_name(&call.name, &call.args) {
510 existing.set_skill_name(skill);
511 }
512 if !display.trim().is_empty() && display.trim() != "{}" {
513 existing.set_args(&display);
514 }
515 } else {
516 let comp = Arc::new(ToolExecutionComponent::new(&call.name, &display));
517 if ask_user {
518 comp.set_display_title("ASK USER");
519 }
520 if let Some(skill) = skill_tool_name(&call.name, &call.args) {
521 comp.set_skill_name(skill);
522 }
523 comp.set_expanded(self.expanded());
524 comp.set_running();
525 self.chat.add_child(comp.clone());
526 tools.insert(call.id.clone(), comp);
527 }
528 }
529 }
530
531 fn tool_start(&self, id: &str, name: &str, args: &Value, _width: usize) {
532 if matches!(name, "todo" | "plan_mode_start" | "plan_mode_complete") {
533 return;
534 }
535 if name.trim().is_empty() {
536 return;
537 }
538 if name == "bash" {
539 let command = args.get("command").and_then(Value::as_str).unwrap_or("");
540 if command.trim().is_empty() {
543 return;
544 }
545 let mut bash = self.bash_components.lock().unwrap();
546 if let Some(existing) = bash.get(id) {
547 existing.set_command(command);
548 } else {
549 let comp = Arc::new(BashExecutionComponent::new(command));
550 comp.set_expanded(self.expanded());
551 self.chat.add_child(comp.clone());
552 bash.insert(id.to_string(), comp);
553 }
554 return;
555 }
556 let ask_user = is_ask_user_tool(name);
557 let display = if ask_user {
558 ask_user_args_display(args)
559 } else {
560 args.to_string()
561 };
562 let mut tools = self.tool_components.lock().unwrap();
563 if let Some(existing) = tools.get(id) {
564 if ask_user {
565 existing.set_display_title("ASK USER");
566 }
567 if let Some(skill) = skill_tool_name(name, args) {
568 existing.set_skill_name(skill);
569 }
570 existing.set_args(&display);
571 } else {
572 let comp = Arc::new(ToolExecutionComponent::new(name, &display));
573 if ask_user {
574 comp.set_display_title("ASK USER");
575 }
576 if let Some(skill) = skill_tool_name(name, args) {
577 comp.set_skill_name(skill);
578 }
579 comp.set_expanded(self.expanded());
580 comp.set_running();
581 self.chat.add_child(comp.clone());
582 tools.insert(id.to_string(), comp);
583 }
584 }
585
586 fn tool_update(&self, id: &str, name: &str, args: &Value, result: &Value, width: usize) {
587 if matches!(name, "todo" | "plan_mode_start" | "plan_mode_complete") {
588 return;
589 }
590 if name.trim().is_empty() {
591 return;
592 }
593 let ask_user = is_ask_user_tool(name);
594 let text = if ask_user {
595 ask_user_progress_text(args, result)
596 } else {
597 tool_result_text(result)
598 };
599 if name == "bash" {
600 if let Some(bash) = self.bash_components.lock().unwrap().get(id) {
601 if let Some(command) = args.get("command").and_then(Value::as_str) {
602 bash.set_command(command);
603 }
604 if !text.is_empty() {
605 bash.append_output(&text);
606 }
607 }
608 return;
609 }
610 let existing = self.tool_components.lock().unwrap().get(id).cloned();
611 match existing {
612 Some(comp) => {
613 if let Some(skill) = skill_tool_name(name, args) {
614 comp.set_skill_name(skill);
615 }
616 if ask_user {
617 comp.set_display_title("ASK USER");
618 comp.set_args(&ask_user_args_display(args));
619 } else if !args.is_null() && args != &serde_json::json!({}) {
620 comp.set_args(&args.to_string());
621 }
622 if tool_update_has_payload(&text, result) {
623 comp.set_result(&text, false);
624 if !ask_user {
625 apply_edit_diff(&comp, name, result.get("details"), width);
626 }
627 }
628 }
629 None => {
630 if tool_update_has_payload(&text, result) {
633 let display = if ask_user {
634 ask_user_args_display(args)
635 } else {
636 args.to_string()
637 };
638 let comp = Arc::new(ToolExecutionComponent::new(name, &display));
639 if ask_user {
640 comp.set_display_title("ASK USER");
641 }
642 if let Some(skill) = skill_tool_name(name, args) {
643 comp.set_skill_name(skill);
644 }
645 comp.set_expanded(self.expanded());
646 comp.set_running();
647 comp.set_result(&text, false);
648 if !ask_user {
649 apply_edit_diff(&comp, name, result.get("details"), width);
650 }
651 self.chat.add_child(comp.clone());
652 self.tool_components
653 .lock()
654 .unwrap()
655 .insert(id.to_string(), comp);
656 }
657 }
658 }
659 }
660
661 fn tool_end(&self, id: &str, name: &str, result: &Value, is_error: bool, width: usize) {
662 if matches!(name, "plan_mode_start" | "plan_mode_complete")
663 && !is_error
664 && update_plan_panel(&self.panels, result)
665 {
666 return;
667 }
668 if name == "todo" && !is_error && update_todo_list(&self.panels, result) {
669 return;
670 }
671 if name.trim().is_empty() {
672 return;
673 }
674 if name == "bash" {
675 let bash = self.bash_components.lock().unwrap().remove(id);
676 match bash {
677 Some(comp) => finalize_bash(&comp, result, is_error),
678 None => {
679 let command = result
680 .get("details")
681 .and_then(|details| details.get("command"))
682 .and_then(Value::as_str)
683 .unwrap_or("");
684 let text = tool_result_text(result);
685 if command.trim().is_empty() && text.trim().is_empty() {
686 return;
687 }
688 let comp = Arc::new(BashExecutionComponent::new(command));
689 comp.set_expanded(self.expanded());
690 if !text.is_empty() {
691 comp.append_output(&text);
692 }
693 finalize_bash(&comp, result, is_error);
694 self.chat.add_child(comp);
695 }
696 }
697 return;
698 }
699 let ask_user = is_ask_user_tool(name);
700 let text = if ask_user {
701 ask_user_result_text(result)
702 } else {
703 tool_result_text(result)
704 };
705 let details = result.get("details");
706 let existing = self.tool_components.lock().unwrap().remove(id);
707 let comp = match existing {
708 Some(comp) => comp,
709 None => {
710 let comp = Arc::new(ToolExecutionComponent::new(name, ""));
712 if ask_user {
713 comp.set_display_title("ASK USER");
714 }
715 comp.set_expanded(self.expanded());
716 self.chat.add_child(comp.clone());
717 comp
718 }
719 };
720 comp.set_result(&text, is_error);
721 if !ask_user {
722 if tool_result_requests_markdown(details) {
723 comp.set_result_markdown(true);
724 }
725 apply_edit_diff(&comp, name, details, width);
726 }
727 }
728}
729
730pub(crate) fn update_plan_panel(chat: &Arc<Container>, result: &Value) -> bool {
732 let Some(details) = result.get("details") else {
733 return false;
734 };
735 if details.get("kind").and_then(Value::as_str) != Some("plan") || details.get("error").is_some()
736 {
737 return false;
738 }
739 let Some(active) = details.get("active").and_then(Value::as_bool) else {
740 return false;
741 };
742 let plan = match details.get("plan") {
743 None | Some(Value::Null) => String::new(),
744 Some(Value::String(plan)) => plan.clone(),
745 _ => return false,
746 };
747 for child in chat.get_children().into_iter().rev() {
748 if let Some(component) = child.as_any().downcast_ref::<ToolExecutionComponent>() {
749 if component.is_plan_panel() {
750 component.set_plan_state(plan, active);
751 component.set_result("", false);
752 if let Some(expanded) = details.get("expanded").and_then(Value::as_bool) {
753 component.set_expanded(expanded);
754 }
755 return true;
760 }
761 }
762 }
763 let component = Arc::new(ToolExecutionComponent::new("plan_mode_complete", ""));
764 component.set_plan_state(plan, active);
765 component.set_result("", false);
766 component.set_expanded(
767 details
768 .get("expanded")
769 .and_then(Value::as_bool)
770 .unwrap_or(false),
771 );
772 chat.add_child(component);
773 true
774}
775
776pub(crate) fn update_todo_list(chat: &Arc<Container>, result: &Value) -> bool {
778 let Some(details) = result.get("details") else {
779 return false;
780 };
781 if details.get("error").is_some() {
782 return false;
783 }
784 let Some(items) = details.get("todos").and_then(Value::as_array) else {
785 return false;
786 };
787 let rows: Option<Vec<_>> = items
788 .iter()
789 .map(|item| {
790 let text = item.get("text")?.as_str()?.to_owned();
791 let status = if item.get("done").and_then(Value::as_bool) == Some(true) {
792 "completed"
793 } else {
794 item.get("status")
795 .and_then(Value::as_str)
796 .unwrap_or("pending")
797 };
798 Some((text, status.to_owned()))
799 })
800 .collect();
801 let Some(rows) = rows else {
802 return false;
803 };
804 let text = tool_result_text(result);
805 for child in chat.get_children().into_iter().rev() {
806 if let Some(component) = child.as_any().downcast_ref::<ToolExecutionComponent>() {
807 if component.is_todo_list() {
808 component.set_todo_state(rows);
809 component.set_result(&text, false);
810 return true;
814 }
815 }
816 }
817 let candidate = Arc::new(ToolExecutionComponent::new("todo", ""));
818 candidate.set_todo_state(rows);
819 candidate.set_result(&text, false);
820 chat.add_child(candidate);
821 true
822}
823
824pub fn assistant_blocks_from_value(message: &Value) -> Vec<AssistantBlock> {
828 let mut blocks = Vec::new();
829 let Some(content) = message.get("content").and_then(Value::as_array) else {
830 return blocks;
831 };
832 for block in content {
833 match block.get("type").and_then(Value::as_str) {
834 Some("text") => {
835 if let Some(text) = block.get("text").and_then(Value::as_str) {
836 blocks.push(AssistantBlock::Text(text.to_string()));
837 }
838 }
839 Some("thinking") => {
840 if let Some(text) = block.get("thinking").and_then(Value::as_str) {
841 blocks.push(AssistantBlock::Thinking(text.to_string()));
842 }
843 }
844 Some("image") => {
845 if let Some(data) = block.get("data").and_then(Value::as_str) {
846 if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(data) {
847 if !bytes.is_empty() {
848 let png = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
849 Some(bytes)
850 } else {
851 rpi_tools::image_processing::process_image(
852 &bytes,
853 Default::default(),
854 )
855 .ok()
856 };
857 if let Some(png) = png {
858 blocks.push(AssistantBlock::Image(png));
859 }
860 }
861 }
862 }
863 }
864 _ => {}
865 }
866 }
867 blocks
868}
869
870pub fn tool_calls_from_value(message: &Value) -> Vec<UiToolCall> {
873 let mut calls = Vec::new();
874 let Some(content) = message.get("content").and_then(Value::as_array) else {
875 return calls;
876 };
877 for block in content {
878 if block.get("type").and_then(Value::as_str) != Some("toolCall") {
879 continue;
880 }
881 let id = block.get("id").and_then(Value::as_str).unwrap_or("");
882 let name = block.get("name").and_then(Value::as_str).unwrap_or("");
883 if id.is_empty() || name.trim().is_empty() {
884 continue;
885 }
886 calls.push(UiToolCall {
887 id: id.to_string(),
888 name: name.to_string(),
889 args: block.get("arguments").cloned().unwrap_or(Value::Null),
890 });
891 }
892 calls
893}
894
895pub fn tool_result_text(result: &Value) -> String {
897 let mut out = String::new();
898 if let Some(blocks) = result.get("content").and_then(Value::as_array) {
899 for block in blocks {
900 if let Some(text) = block.get("text").and_then(Value::as_str) {
901 if !out.is_empty() {
902 out.push('\n');
903 }
904 out.push_str(text);
905 }
906 }
907 }
908 out
909}
910
911pub fn tool_result_requests_markdown(details: Option<&Value>) -> bool {
914 details
915 .and_then(|details| details.get("markdown"))
916 .and_then(Value::as_bool)
917 .unwrap_or(false)
918}
919
920pub fn skill_tool_name(tool_name: &str, args: &Value) -> Option<String> {
924 if tool_name != "read" {
925 return None;
926 }
927 let path = args.get("path").and_then(Value::as_str)?;
928 let normalized = path.replace('\\', "/");
929 let file_name = normalized.rsplit('/').next()?;
930 if !file_name.eq_ignore_ascii_case("SKILL.md") {
931 return None;
932 }
933 normalized
934 .trim_end_matches('/')
935 .rsplit('/')
936 .nth(1)
937 .filter(|name| !name.is_empty())
938 .map(str::to_string)
939}
940
941fn is_ask_user_tool(tool_name: &str) -> bool {
944 matches!(tool_name, "ask_user" | "ask_user_question")
945}
946
947fn ask_user_args_display(args: &Value) -> String {
950 if args.is_null() {
951 return String::new();
952 }
953 if let Some(summary) = args
954 .get("summary")
955 .and_then(Value::as_str)
956 .map(str::trim)
957 .filter(|text| !text.is_empty())
958 {
959 return format!("Confirmation requested: {summary}");
960 }
961
962 let mut lines: Vec<String> = Vec::new();
963 let questions: Vec<&Value> = args
964 .get("questions")
965 .and_then(Value::as_array)
966 .filter(|items| !items.is_empty())
967 .map(|items| items.iter().collect())
968 .unwrap_or_else(|| vec![args]);
969
970 for question in questions {
971 let prompt = question
972 .get("question")
973 .and_then(Value::as_str)
974 .or_else(|| args.get("question").and_then(Value::as_str))
975 .map(str::trim)
976 .unwrap_or_default();
977 if prompt.is_empty() {
978 continue;
979 }
980 if let Some(header) = question
981 .get("header")
982 .and_then(Value::as_str)
983 .map(str::trim)
984 .filter(|text| !text.is_empty())
985 {
986 lines.push(format!("{header}: {prompt}"));
987 } else {
988 lines.push(prompt.to_string());
989 }
990 let context = question
991 .get("context")
992 .and_then(Value::as_str)
993 .or_else(|| args.get("context").and_then(Value::as_str))
994 .map(str::trim)
995 .filter(|text| !text.is_empty());
996 if let Some(context) = context {
997 lines.push(format!(" {context}"));
998 }
999 let options = question
1000 .get("options")
1001 .and_then(Value::as_array)
1002 .or_else(|| args.get("options").and_then(Value::as_array));
1003 if let Some(options) = options {
1004 let labels: Vec<String> = options
1005 .iter()
1006 .filter_map(|option| {
1007 option
1008 .get("title")
1009 .and_then(Value::as_str)
1010 .or_else(|| option.as_str())
1011 .map(str::trim)
1012 .filter(|label| !label.is_empty())
1013 .map(str::to_string)
1014 })
1015 .collect();
1016 if !labels.is_empty() {
1017 lines.push(format!("Choices: {}", labels.join(", ")));
1018 }
1019 }
1020 if let Some(suggest) = question
1021 .get("suggest")
1022 .and_then(Value::as_str)
1023 .or_else(|| args.get("suggest").and_then(Value::as_str))
1024 .map(str::trim)
1025 .filter(|text| !text.is_empty())
1026 {
1027 lines.push(format!("Suggestions: {suggest}"));
1028 }
1029 }
1030
1031 lines.join("\n")
1032}
1033
1034fn ask_user_progress_text(args: &Value, result: &Value) -> String {
1037 let text = tool_result_text(result);
1038 if !text.trim().is_empty() {
1039 return text;
1040 }
1041 let args_text = ask_user_args_display(args);
1042 if args_text.trim().is_empty() {
1043 "Waiting for your answer…".to_string()
1044 } else {
1045 args_text
1046 }
1047}
1048
1049fn ask_user_result_text(result: &Value) -> String {
1051 let text = tool_result_text(result);
1052 if text.trim().is_empty() {
1053 "Answer recorded.".to_string()
1054 } else {
1055 text
1056 }
1057}
1058
1059fn tool_update_has_payload(text: &str, result: &Value) -> bool {
1061 !text.trim().is_empty()
1062 || result
1063 .get("details")
1064 .map(|details| !details.is_null())
1065 .unwrap_or(false)
1066}
1067
1068fn apply_edit_diff(
1071 comp: &Arc<ToolExecutionComponent>,
1072 tool_name: &str,
1073 details: Option<&Value>,
1074 width: usize,
1075) {
1076 if tool_name != "edit" {
1077 return;
1078 }
1079 let Some(diff_text) = details
1080 .and_then(|details| details.get("diff"))
1081 .and_then(Value::as_str)
1082 else {
1083 return;
1084 };
1085 if diff_text.is_empty() {
1086 return;
1087 }
1088 comp.set_diff(render_diff(diff_text, width));
1089}
1090
1091fn finalize_bash(comp: &Arc<BashExecutionComponent>, result: &Value, is_error: bool) {
1094 let details = result.get("details");
1095 let exit_code = Some(if is_error { 1 } else { 0 });
1096 let truncated = details
1097 .and_then(|details| details.get("truncation"))
1098 .and_then(|truncation| truncation.get("truncated"))
1099 .and_then(Value::as_bool)
1100 .unwrap_or(false);
1101 let full_output_path = details
1102 .and_then(|details| details.get("full_output_path"))
1103 .and_then(Value::as_str)
1104 .map(str::to_string);
1105 if let Some(command) = details
1106 .and_then(|details| details.get("command"))
1107 .and_then(Value::as_str)
1108 {
1109 comp.set_command(command);
1110 }
1111 comp.set_complete(
1112 exit_code,
1113 false,
1114 BashTruncation {
1115 truncated,
1116 full_output_path,
1117 },
1118 );
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123 use super::*;
1124 use rpi_tui::{strip_ansi, Component};
1125 use serde_json::json;
1126
1127 fn view() -> TranscriptView {
1128 TranscriptView::new(Arc::new(Container::new()))
1129 }
1130
1131 #[test]
1132 fn adjacent_transcript_blocks_separated_by_exactly_one_blank() {
1133 let view = view();
1147 view.add_user("question");
1148 view.apply(
1149 &UiEvent::AssistantStart {
1150 blocks: vec![AssistantBlock::Thinking("reasoning".into())],
1151 },
1152 80,
1153 );
1154 view.apply(
1155 &UiEvent::AssistantUpdate {
1156 blocks: vec![AssistantBlock::Thinking("reasoning".into())],
1157 tool_calls: vec![UiToolCall {
1158 id: "t1".into(),
1159 name: "read".into(),
1160 args: json!({"path": "f.txt"}),
1161 }],
1162 },
1163 80,
1164 );
1165 view.apply(
1166 &UiEvent::ToolEnd {
1167 id: "t1".into(),
1168 name: "read".into(),
1169 result: json!({"content": [{"type": "text", "text": "done"}]}),
1170 is_error: false,
1171 },
1172 80,
1173 );
1174 view.apply(
1175 &UiEvent::AssistantStart {
1176 blocks: vec![AssistantBlock::Text("answer".into())],
1177 },
1178 80,
1179 );
1180 view.apply(
1181 &UiEvent::ToolStart {
1182 id: "b1".into(),
1183 name: "bash".into(),
1184 args: json!({"command": "ls"}),
1185 },
1186 80,
1187 );
1188 view.apply(&UiEvent::AgentEnd, 80);
1189
1190 let lines = view.chat.render(80);
1191 let plain: Vec<String> = lines
1192 .iter()
1193 .map(|l| strip_ansi(l).trim().to_string())
1194 .collect();
1195 let find = |needle: &str| {
1198 plain
1199 .iter()
1200 .rposition(|l| l.contains(needle))
1201 .unwrap_or_else(|| panic!("{needle} missing: {plain:?}"))
1202 };
1203 let user = find("question");
1204 let thinking = find("reasoning");
1205 let panel = find("done");
1206 let answer = find("answer");
1207 let bash = find("$ ls");
1208 assert!(user < thinking && thinking < panel && panel < answer);
1209 assert!(answer < bash);
1210 for (top_name, top, bottom_name, bottom) in [
1211 ("user", user, "thinking", thinking),
1212 ("thinking", thinking, "panel", panel),
1213 ("panel", panel, "answer", answer),
1214 ("answer", answer, "bash", bash),
1215 ] {
1216 let gap = lines[top + 1..bottom]
1217 .iter()
1218 .filter(|l| l.is_empty())
1219 .count();
1220 assert_eq!(
1221 gap, 1,
1222 "{top_name}→{bottom_name} seam must be exactly one blank row: {plain:?}"
1223 );
1224 }
1225 }
1226
1227 #[test]
1228 fn retry_notice_ends_with_a_trailing_spacer() {
1229 let view = view();
1232 view.apply(
1233 &UiEvent::Retry {
1234 attempt: 1,
1235 max_retries: 3,
1236 delay_ms: 500,
1237 error: "boom".into(),
1238 },
1239 80,
1240 );
1241 let lines = view.chat.render(80);
1242 let rendered = strip_ansi(&lines.join("\n"));
1243 assert!(rendered.contains("retry 1/3"));
1244 assert_eq!(lines.last(), Some(&String::new()));
1245 }
1246
1247 #[test]
1248 fn empty_assistant_start_and_whitespace_deltas_do_not_move_the_transcript() {
1249 for starts_with_event in [true, false] {
1250 let view = view();
1251 view.add_user("hi");
1252 let before = view.chat.render(80);
1253 if starts_with_event {
1254 view.apply(&UiEvent::AssistantStart { blocks: vec![] }, 80);
1255 assert_eq!(view.chat.render(80), before);
1256 }
1257 for blocks in [
1258 vec![],
1259 vec![AssistantBlock::Text(" ".into())],
1260 vec![AssistantBlock::Thinking("\n".into())],
1261 ] {
1262 view.apply(
1263 &UiEvent::AssistantUpdate {
1264 blocks,
1265 tool_calls: vec![],
1266 },
1267 80,
1268 );
1269 assert_eq!(view.chat.render(80), before);
1270 }
1271 view.apply(
1272 &UiEvent::AssistantUpdate {
1273 blocks: vec![AssistantBlock::Text("hello".into())],
1274 tool_calls: vec![],
1275 },
1276 80,
1277 );
1278 let visible = view.chat.render(80);
1279 assert!(visible.len() > before.len());
1280 assert!(visible.iter().any(|line| line.contains("hello")));
1281 assert_eq!(visible.last(), Some(&String::new()));
1282 view.apply(&UiEvent::AssistantEnd { blocks: vec![] }, 80);
1283 assert_eq!(view.chat.render(80), before);
1284 view.apply(&UiEvent::AssistantStart { blocks: vec![] }, 80);
1285 assert_eq!(view.chat.render(80), before);
1286 }
1287 }
1288
1289 #[test]
1290 fn saved_assistant_is_rendered_without_replacing_the_live_message() {
1291 let view = view();
1292 view.apply(
1293 &UiEvent::AssistantStart {
1294 blocks: vec![AssistantBlock::Text("pending".into())],
1295 },
1296 80,
1297 );
1298 view.apply(
1299 &UiEvent::SavedAssistant {
1300 blocks: vec![AssistantBlock::Text("previous reply".into())],
1301 },
1302 80,
1303 );
1304 view.apply(
1305 &UiEvent::AssistantEnd {
1306 blocks: vec![AssistantBlock::Text("complete reply".into())],
1307 },
1308 80,
1309 );
1310 let lines = view.chat.render(80);
1311 assert!(lines.iter().any(|line| line.contains("previous reply")));
1312 assert!(lines.iter().any(|line| line.contains("complete reply")));
1313 assert!(lines.iter().all(|line| !line.contains("pending")));
1314 }
1315
1316 #[test]
1317 fn assistant_blocks_follow_content_order() {
1318 let message = json!({
1319 "content": [
1320 {"type": "thinking", "thinking": "why"},
1321 {"type": "text", "text": "hello"},
1322 {"type": "toolCall", "id": "c1", "name": "read", "arguments": {}},
1323 ]
1324 });
1325 assert_eq!(
1326 assistant_blocks_from_value(&message),
1327 vec![
1328 AssistantBlock::Thinking("why".into()),
1329 AssistantBlock::Text("hello".into()),
1330 ]
1331 );
1332 }
1333
1334 #[test]
1335 fn assistant_blocks_decode_images() {
1336 let mut bytes = Vec::new();
1337 {
1338 let mut encoder = png::Encoder::new(&mut bytes, 1, 1);
1339 encoder.set_color(png::ColorType::Rgb);
1340 encoder
1341 .write_header()
1342 .unwrap()
1343 .write_image_data(&[255, 0, 0])
1344 .unwrap();
1345 }
1346 let message = json!({
1347 "content": [{"type": "image", "data": base64::engine::general_purpose::STANDARD.encode(&bytes), "mimeType": "image/png"}]
1348 });
1349 assert_eq!(
1350 assistant_blocks_from_value(&message),
1351 vec![AssistantBlock::Image(bytes.to_vec())]
1352 );
1353 let jpeg = rpi_tools::image_processing::process_image(
1354 &bytes,
1355 rpi_tools::image_processing::ImageProcessingOptions {
1356 format: Some(rpi_tools::image_processing::OutputFormat::Jpeg { quality: 85 }),
1357 ..Default::default()
1358 },
1359 )
1360 .unwrap();
1361 let blocks = assistant_blocks_from_value(&json!({
1362 "content": [{"type": "image", "data": base64::engine::general_purpose::STANDARD.encode(jpeg), "mimeType": "image/jpeg"}]
1363 }));
1364 assert!(
1365 matches!(&blocks[0], AssistantBlock::Image(data) if data.starts_with(b"\x89PNG\r\n\x1a\n"))
1366 );
1367 }
1368
1369 #[test]
1370 fn tool_calls_extract_ids_names_and_args() {
1371 let message = json!({
1372 "content": [
1373 {"type": "text", "text": "x"},
1374 {"type": "toolCall", "id": "b1", "name": "bash", "arguments": {"command": "ls"}},
1375 {"type": "toolCall", "id": "", "name": "read", "arguments": {}},
1376 ]
1377 });
1378 assert_eq!(
1379 tool_calls_from_value(&message),
1380 vec![UiToolCall {
1381 id: "b1".into(),
1382 name: "bash".into(),
1383 args: json!({"command": "ls"}),
1384 }]
1385 );
1386 }
1387
1388 #[test]
1389 fn markdown_flag_is_opt_in() {
1390 assert!(tool_result_requests_markdown(Some(
1391 &json!({"markdown": true})
1392 )));
1393 assert!(!tool_result_requests_markdown(Some(
1394 &json!({"markdown": false})
1395 )));
1396 assert!(!tool_result_requests_markdown(Some(&json!({}))));
1397 assert!(!tool_result_requests_markdown(None));
1398 }
1399
1400 #[test]
1401 fn skill_tool_name_only_matches_skill_reads() {
1402 assert_eq!(
1403 skill_tool_name("read", &json!({"path": "skills/foo/SKILL.md"})),
1404 Some("foo".to_string())
1405 );
1406 assert_eq!(skill_tool_name("read", &json!({"path": "README.md"})), None);
1407 assert_eq!(
1408 skill_tool_name("write", &json!({"path": "skills/foo/SKILL.md"})),
1409 None
1410 );
1411 }
1412
1413 #[test]
1414 fn ask_user_args_display_never_leaks_transport_json() {
1415 let text = ask_user_args_display(&json!({
1416 "question": "你的代理端口是多少?",
1417 "context": "本机",
1418 "options": ["7890", {"title": "7897", "description": "clash"}],
1419 "suggest": "1080"
1420 }));
1421 assert!(text.contains("你的代理端口是多少?"));
1422 assert!(text.contains("本机"));
1423 assert!(text.contains("Choices: 7890, 7897"));
1424 assert!(text.contains("Suggestions: 1080"));
1425 assert!(!text.trim_start().starts_with('{'));
1426 assert_eq!(
1427 ask_user_args_display(&json!({"type": "confirm", "summary": "Deploy?"})),
1428 "Confirmation requested: Deploy?"
1429 );
1430 }
1431
1432 #[test]
1433 fn tool_start_routes_bash_to_its_own_map() {
1434 let view = view();
1435 view.apply(
1436 &UiEvent::ToolStart {
1437 id: "b1".into(),
1438 name: "bash".into(),
1439 args: json!({"command": "ls -la"}),
1440 },
1441 80,
1442 );
1443 view.apply(
1444 &UiEvent::ToolStart {
1445 id: "r1".into(),
1446 name: "read".into(),
1447 args: json!({"path": "a.txt"}),
1448 },
1449 80,
1450 );
1451 assert!(view.bash_components.lock().unwrap().contains_key("b1"));
1452 assert!(view.tool_components.lock().unwrap().contains_key("r1"));
1453 assert!(view.tool_components.lock().unwrap().get("b1").is_none());
1454 }
1455
1456 #[test]
1457 fn bash_start_without_a_command_is_deferred() {
1458 let view = view();
1459 view.apply(
1460 &UiEvent::ToolStart {
1461 id: "b1".into(),
1462 name: "bash".into(),
1463 args: json!({}),
1464 },
1465 80,
1466 );
1467 assert!(view.bash_components.lock().unwrap().is_empty());
1468 assert!(view.tool_components.lock().unwrap().is_empty());
1469 }
1470
1471 #[test]
1472 fn assistant_stream_reuses_one_component() {
1473 let view = view();
1474 view.apply(&UiEvent::AssistantStart { blocks: vec![] }, 80);
1475 view.apply(
1476 &UiEvent::AssistantUpdate {
1477 blocks: vec![AssistantBlock::Text("hi".into())],
1478 tool_calls: vec![],
1479 },
1480 80,
1481 );
1482 assert!(view.current_assistant.lock().unwrap().is_some());
1483 }
1484
1485 #[test]
1486 fn toggle_expanded_round_trips() {
1487 let view = view();
1488 assert!(!view.expanded());
1489 assert!(view.toggle_expanded());
1490 assert!(view.expanded());
1491 }
1492
1493 #[test]
1494 fn todo_updates_share_one_panel_and_preserve_errors() {
1495 let view = view();
1496 for (id, done) in [("a", false), ("b", true)] {
1497 view.sync_tool_calls(&[UiToolCall {
1498 id: id.into(),
1499 name: "todo".into(),
1500 args: json!({"action":"toggle"}),
1501 }]);
1502 view.tool_start(id, "todo", &json!({}), 80);
1503 view.tool_end(id, "todo", &json!({"content":[],"details":{"todos":[{"id":1,"text":"Run tests","done":done}]}}), false, 80);
1504 }
1505 assert_eq!(view.chat.child_count(), 1);
1506 assert!(view.tool_components.lock().unwrap().is_empty());
1507 let children = view.chat.get_children();
1508 let panel = children[0]
1509 .as_any()
1510 .downcast_ref::<ToolExecutionComponent>()
1511 .unwrap();
1512 let rendered = rpi_tui::ansi::strip_ansi(&panel.render(80).join("\n"));
1513 assert!(rendered.contains("1/1 completed"));
1514 assert!(rendered.contains("[✓] Run tests"));
1515 view.tool_end(
1516 "error",
1517 "todo",
1518 &json!({"content":[{"type":"text","text":"invalid task"}]}),
1519 true,
1520 80,
1521 );
1522 assert_eq!(view.chat.child_count(), 2);
1523 view.tool_end("soft-error", "todo", &json!({"content":[{"type":"text","text":"todo not found"}],"details":{"todos":[],"error":"todo not found"}}), false, 80);
1524 assert_eq!(view.chat.child_count(), 3);
1525 assert!(update_todo_list(
1526 &view.chat,
1527 &json!({"details":{"todos":[]}})
1528 ));
1529 assert_eq!(view.chat.child_count(), 3);
1530 assert!(!update_todo_list(
1531 &view.chat,
1532 &json!({"details":{"todos":[{}]}})
1533 ));
1534 assert_eq!(view.chat.child_count(), 3);
1535 }
1536
1537 #[test]
1538 fn completed_plan_keeps_its_transcript_position() {
1539 let view = view();
1540 view.apply(
1541 &UiEvent::AssistantStart {
1542 blocks: vec![AssistantBlock::Text("planning context".into())],
1543 },
1544 80,
1545 );
1546 view.apply(
1547 &UiEvent::AssistantEnd {
1548 blocks: vec![AssistantBlock::Text("planning context".into())],
1549 },
1550 80,
1551 );
1552 view.apply(
1553 &UiEvent::ToolEnd {
1554 id: "start".into(),
1555 name: "plan_mode_start".into(),
1556 result: json!({"details":{"kind":"plan","active":true}}),
1557 is_error: false,
1558 },
1559 80,
1560 );
1561 view.apply(
1562 &UiEvent::AssistantStart {
1563 blocks: vec![AssistantBlock::Text("repository findings".into())],
1564 },
1565 80,
1566 );
1567 view.apply(
1568 &UiEvent::AssistantEnd {
1569 blocks: vec![AssistantBlock::Text("repository findings".into())],
1570 },
1571 80,
1572 );
1573
1574 view.apply(
1575 &UiEvent::ToolEnd {
1576 id: "complete".into(),
1577 name: "plan_mode_complete".into(),
1578 result: json!({
1579 "details": {
1580 "kind": "plan",
1581 "active": false,
1582 "plan": "1. Keep the plan in place"
1583 }
1584 }),
1585 is_error: false,
1586 },
1587 80,
1588 );
1589
1590 let lines: Vec<_> = view
1591 .chat
1592 .render(80)
1593 .iter()
1594 .map(|line| strip_ansi(line))
1595 .collect();
1596 let plan = lines
1597 .iter()
1598 .position(|line| line.contains("Plan · Ready"))
1599 .expect("completed plan panel should render");
1600 let findings = lines
1601 .iter()
1602 .position(|line| line.contains("repository findings"))
1603 .expect("later assistant output should render");
1604 assert!(
1605 plan < findings,
1606 "plan completion must not move the plan below later transcript output: {lines:?}"
1607 );
1608 }
1609
1610 #[test]
1611 fn todo_updates_keep_their_transcript_position() {
1612 let view = view();
1613 view.apply(
1614 &UiEvent::AssistantStart {
1615 blocks: vec![AssistantBlock::Text("before tasks".into())],
1616 },
1617 80,
1618 );
1619 view.apply(
1620 &UiEvent::AssistantEnd {
1621 blocks: vec![AssistantBlock::Text("before tasks".into())],
1622 },
1623 80,
1624 );
1625 view.apply(
1626 &UiEvent::ToolEnd {
1627 id: "todo-1".into(),
1628 name: "todo".into(),
1629 result: json!({
1630 "details": {
1631 "todos": [{"text": "first task", "done": false}]
1632 }
1633 }),
1634 is_error: false,
1635 },
1636 80,
1637 );
1638 view.apply(
1639 &UiEvent::AssistantStart {
1640 blocks: vec![AssistantBlock::Text("later output".into())],
1641 },
1642 80,
1643 );
1644 view.apply(
1645 &UiEvent::AssistantEnd {
1646 blocks: vec![AssistantBlock::Text("later output".into())],
1647 },
1648 80,
1649 );
1650 view.apply(
1651 &UiEvent::ToolEnd {
1652 id: "todo-2".into(),
1653 name: "todo".into(),
1654 result: json!({
1655 "details": {
1656 "todos": [{"text": "first task", "done": true}]
1657 }
1658 }),
1659 is_error: false,
1660 },
1661 80,
1662 );
1663
1664 let lines: Vec<_> = view
1665 .chat
1666 .render(80)
1667 .iter()
1668 .map(|line| strip_ansi(line))
1669 .collect();
1670 let tasks = lines
1671 .iter()
1672 .position(|line| line.contains("Tasks 1/1 completed"))
1673 .expect("todo panel should render");
1674 let later = lines
1675 .iter()
1676 .position(|line| line.contains("later output"))
1677 .expect("later transcript output should render");
1678 assert!(
1679 tasks < later,
1680 "todo update must not move the task panel below later output: {lines:?}"
1681 );
1682 }
1683
1684 #[test]
1685 fn plan_tools_and_show_update_one_expandable_panel() {
1686 let view = view();
1687 view.sync_tool_calls(&[UiToolCall {
1688 id: "start".into(),
1689 name: "plan_mode_start".into(),
1690 args: json!({}),
1691 }]);
1692 view.tool_start("start", "plan_mode_start", &json!({}), 80);
1693 view.tool_end(
1694 "start",
1695 "plan_mode_start",
1696 &json!({"details":{"kind":"plan","active":true}}),
1697 false,
1698 80,
1699 );
1700 let body = (1..=30)
1701 .map(|i| format!("{i}. Step {i}"))
1702 .collect::<Vec<_>>()
1703 .join("\n");
1704 view.tool_end(
1705 "complete",
1706 "plan_mode_complete",
1707 &json!({"details":{"kind":"plan","active":false,"plan":body}}),
1708 false,
1709 80,
1710 );
1711 assert_eq!(view.chat.child_count(), 1);
1712 assert!(view.tool_components.lock().unwrap().is_empty());
1713 view.set_expanded(true);
1714 let children = view.chat.get_children();
1715 let panel = children[0]
1716 .as_any()
1717 .downcast_ref::<ToolExecutionComponent>()
1718 .unwrap();
1719 assert!(rpi_tui::ansi::strip_ansi(&panel.render(80).join("\n")).contains("Step 30"));
1720 assert!(update_plan_panel(
1721 &view.chat,
1722 &json!({"kind":"message","details":{"kind":"plan","active":false,"plan":body,"expanded":true}})
1723 ));
1724 assert_eq!(view.chat.child_count(), 1);
1725 view.tool_end(
1726 "error",
1727 "plan_mode_complete",
1728 &json!({"content":[{"type":"text","text":"not active"}]}),
1729 true,
1730 80,
1731 );
1732 assert_eq!(view.chat.child_count(), 2);
1733 }
1734
1735 #[test]
1738 fn transcript_assigns_ids_and_toggles_per_message() {
1739 let view = view();
1742 view.set_hide_thinking(true);
1743 view.apply(
1744 &UiEvent::AssistantStart {
1745 blocks: vec![
1746 AssistantBlock::Thinking("first msg reasoning".into()),
1747 AssistantBlock::Text("answer one".into()),
1748 ],
1749 },
1750 80,
1751 );
1752 let first = view
1753 .current_assistant
1754 .lock()
1755 .unwrap()
1756 .clone()
1757 .expect("assistant mounted");
1758 let first_id = first.message_id().expect("id assigned");
1759 view.apply(&UiEvent::AgentEnd, 80);
1760
1761 view.apply(
1762 &UiEvent::AssistantStart {
1763 blocks: vec![AssistantBlock::Thinking("second msg reasoning".into())],
1764 },
1765 80,
1766 );
1767 let second = view
1768 .current_assistant
1769 .lock()
1770 .unwrap()
1771 .clone()
1772 .expect("assistant mounted");
1773 let second_id = second.message_id().expect("id assigned");
1774 assert_ne!(first_id, second_id, "ids must be unique per message");
1775
1776 assert!(view.toggle_message_thinking(&second_id));
1778 let expanded = strip_ansi(&second.render(80).join("\n"));
1779 assert!(expanded.contains("second msg reasoning"));
1780 let first_render = strip_ansi(&first.render(80).join("\n"));
1781 assert!(
1782 !first_render.contains("first msg reasoning"),
1783 "toggle leaked into another message: {first_render}"
1784 );
1785
1786 assert!(view.toggle_message_thinking(&second_id));
1788 assert!(!strip_ansi(&second.render(80).join("\n")).contains("second msg reasoning"));
1789 }
1790
1791 #[test]
1792 fn toggle_with_stale_id_is_a_noop() {
1793 let view = view();
1794 assert!(!view.toggle_message_thinking("t999"));
1795 view.apply(
1796 &UiEvent::AssistantStart {
1797 blocks: vec![AssistantBlock::Thinking("reasoning".into())],
1798 },
1799 80,
1800 );
1801 assert!(!view.toggle_message_thinking("h12345"));
1803 let comp = view.current_assistant.lock().unwrap().clone().unwrap();
1804 assert!(!strip_ansi(&comp.render(80).join("\n")).contains("Thinking..."));
1805 }
1806
1807 #[test]
1808 fn global_toggle_keeps_message_level_expansion() {
1809 let view = view();
1813 view.set_hide_thinking(true);
1814 view.apply(
1815 &UiEvent::AssistantStart {
1816 blocks: vec![AssistantBlock::Thinking("sticky reasoning".into())],
1817 },
1818 80,
1819 );
1820 let comp = view.current_assistant.lock().unwrap().clone().unwrap();
1821 let id = comp.message_id().unwrap();
1822 assert!(view.toggle_message_thinking(&id));
1823 assert!(strip_ansi(&comp.render(80).join("\n")).contains("sticky reasoning"));
1824
1825 view.set_hide_thinking(false);
1827 view.set_hide_thinking(true);
1828 assert!(
1829 strip_ansi(&comp.render(80).join("\n")).contains("sticky reasoning"),
1830 "global toggle wiped the per-message expansion"
1831 );
1832
1833 assert!(view.toggle_message_thinking(&id));
1836 view.set_hide_thinking(false);
1837 assert!(strip_ansi(&comp.render(80).join("\n")).contains("sticky reasoning"));
1838 }
1839
1840 #[test]
1841 fn click_reaches_assistant_components_nested_in_history_pages() {
1842 let chat = Arc::new(rpi_tui::Container::new());
1846 let page = Arc::new(rpi_tui::Container::new());
1847 let comp = Arc::new(AssistantMessageComponent::new(AssistantMessageOptions {
1848 hide_thinking: true,
1849 ..Default::default()
1850 }));
1851 comp.set_message_id("h7");
1852 comp.update_blocks(&[
1853 AssistantBlock::Thinking("old reasoning".into()),
1854 AssistantBlock::Text("old answer".into()),
1855 ]);
1856 page.add_child(comp.clone());
1857 chat.add_child(page);
1858 let view = TranscriptView::new(chat);
1859 view.set_hide_thinking(true);
1860 assert!(
1861 view.toggle_message_thinking("h7"),
1862 "click on a nested history page found no component"
1863 );
1864 assert!(strip_ansi(&comp.render(80).join("\n")).contains("old reasoning"));
1865 }
1866
1867 #[test]
1868 fn click_on_globally_visible_thinking_collapses_then_restores() {
1869 let view = view();
1873 view.apply(
1874 &UiEvent::AssistantStart {
1875 blocks: vec![AssistantBlock::Thinking("shown reasoning".into())],
1876 },
1877 80,
1878 );
1879 let comp = view.current_assistant.lock().unwrap().clone().unwrap();
1880 let id = comp.message_id().unwrap();
1881 let visible = || strip_ansi(&comp.render(80).join("\n")).contains("shown reasoning");
1882 assert!(visible());
1883 assert!(view.toggle_message_thinking(&id));
1884 assert!(!visible(), "first click must collapse a visible body");
1885 assert!(view.toggle_message_thinking(&id));
1886 assert!(visible(), "second click must restore the global show");
1887 }
1888}