matrixcode-tui 0.3.7

Terminal UI for MatrixCode
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::Paragraph,
};

use crate::types::{Activity, ApproveMode, Role};
use crate::utils::{truncate, fmt_tokens, progress_bar, word_wrap};
use crate::markdown::render_markdown;
use crate::app::TuiApp;
use crate::SPINNER;

impl TuiApp {
    pub(crate) fn draw(&self, f: &mut ratatui::Frame) {
        // Dynamic queue height: show if there are pending messages
        let queue_height = if self.pending_messages.is_empty() {
            Constraint::Length(0)
        } else {
            Constraint::Length(1)
        };
        
        // Dynamic input height: expand for multiline content
        let input_lines = self.input.lines().count().max(1);
        let input_height = if input_lines <= 1 {
            Constraint::Length(1)
        } else {
            // Max 5 lines for input area
            Constraint::Length(input_lines.min(5) as u16 + 1)  // +1 for prompt
        };
        
        let constraints = vec![
            Constraint::Length(1),           // Status (MatrixCode + Model + mode)
            Constraint::Min(3),              // Messages (弹性高度,最大化)
            queue_height,                    // Queue (pending messages preview)
            Constraint::Length(1),           // Usage + Hints
            input_height,                    // Input (dynamic height)
        ];

        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints(constraints)
            .split(f.area());

        // Store messages area top for mouse selection
        self.msg_area_top.set(chunks[1].y);

        self.draw_status(f, chunks[0]);
        self.draw_messages(f, chunks[1]);
        if !self.pending_messages.is_empty() {
            self.draw_queue(f, chunks[2]);
        }
        self.draw_usage(f, chunks[3]);
        self.draw_input(f, chunks[4]);
    }

    fn draw_status(&self, f: &mut ratatui::Frame, area: Rect) {
        // Status indicator on the right
        let status_text = if self.activity == Activity::Idle {
            " Ready "
        } else {
            " ... "
        };
        let status_color = if self.activity == Activity::Idle {
            Color::Green
        } else {
            Color::Yellow
        };
        
        let spans = vec![
            Span::styled(" MatrixCode ", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)),
            Span::styled("", Style::default().fg(Color::DarkGray)),
            Span::styled(format!(" {} ", self.model), Style::default().fg(Color::White)),
            Span::styled("", Style::default().fg(Color::DarkGray)),
            Span::styled(
                format!(" mode:{} ", self.approve_mode.label()),
                Style::default().fg(match self.approve_mode {
                    ApproveMode::Ask => Color::Yellow,
                    ApproveMode::Auto => Color::Green,
                    ApproveMode::Strict => Color::Red,
                })
            ),
            Span::styled("", Style::default().fg(Color::DarkGray)),
            Span::styled(status_text, Style::default().fg(status_color)),
        ];
        f.render_widget(Paragraph::new(Line::from(spans)), area);
    }

    fn draw_usage(&self, f: &mut ratatui::Frame, area: Rect) {
        if self.tokens_in == 0 && self.tokens_out == 0 {
            f.render_widget(Paragraph::new(Line::styled(
                " /help │ PgUp/PgDn: scroll │ Home/End: top/bot │ Use terminal for text selection",
                Style::default().fg(Color::DarkGray)
            )), area);
            return;
        }
        
        let context_pct = if self.context_size > 0 {
            (self.tokens_in as f64 / self.context_size as f64 * 100.0).min(100.0)
        } else { 0.0 };
        
        let ctx_color = if context_pct < 50.0 { Color::Green }
                       else if context_pct < 75.0 { Color::Yellow }
                       else { Color::Red };
        
        let bar = progress_bar(context_pct, 20);
        
        let mut parts: Vec<Span> = vec![
            Span::styled(
                format!("in {} / out {} (session: {})", 
                    fmt_tokens(self.tokens_in), 
                    fmt_tokens(self.tokens_out),
                    fmt_tokens(self.session_total_out)
                ),
                Style::default().fg(Color::Gray)
            ),
        ];
        
        // Cache info: always show
        parts.push(Span::styled("", Style::default().fg(Color::DarkGray)));
        parts.push(Span::styled(
            format!("cache r/w {}/{}", 
                fmt_tokens(self.cache_read), 
                fmt_tokens(self.cache_created)
            ),
            Style::default().fg(Color::Cyan)
        ));
        
        // Debug mode: show api/tools/compress counts
        if self.debug_mode {
            parts.push(Span::styled("", Style::default().fg(Color::DarkGray)));
            parts.push(Span::styled(
                format!("api:{} ", self.api_calls),
                Style::default().fg(Color::Magenta)
            ));
            if self.tool_calls > 0 {
                parts.push(Span::styled(
                    format!("tools:{} ", self.tool_calls),
                    Style::default().fg(Color::Blue)
                ));
            }
            if self.compressions > 0 {
                parts.push(Span::styled(
                    format!("compress:{} ", self.compressions),
                    Style::default().fg(Color::Yellow)
                ));
            }
        }
        
        parts.push(Span::styled("", Style::default().fg(Color::DarkGray)));
        
        parts.push(Span::styled(
            format!("ctx {} / {} ({:.1}%) {}", 
                fmt_tokens(self.tokens_in), 
                fmt_tokens(self.context_size),
                context_pct,
                bar
            ),
            Style::default().fg(ctx_color)
        ));
        
        f.render_widget(Paragraph::new(Line::from(parts)), area);
    }

    fn draw_messages(&self, f: &mut ratatui::Frame, area: Rect) {
        let mut lines: Vec<Line> = Vec::new();
        let max_w = area.width.saturating_sub(5) as usize;

        // Get selection range for highlighting
        let selection = self.selection.map(|s| s.normalized());

        // Welcome
        if self.show_welcome && self.messages.is_empty() {
            lines.push(Line::styled(
                "╭─────────────────────────────────────────────────────────────╮",
                Style::default().fg(Color::Cyan)
            ));
            lines.push(Line::styled(
                "│                     🤖 MatrixCode                           │",
                Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)
            ));
            lines.push(Line::styled(
                "│   AI-powered coding assistant with extended thinking       │",
                Style::default().fg(Color::DarkGray)
            ));
            lines.push(Line::raw("│                                                             │"));
            lines.push(Line::styled(
                "│   Commands: /help /clear /history /mode /new /exit         │",
                Style::default().fg(Color::Gray)
            ));
            lines.push(Line::styled(
                "│   Shortcuts: Enter=send │ PgUp/PgDn=scroll │ Alt+T=thinking │",
                Style::default().fg(Color::Gray)
            ));
            lines.push(Line::styled(
                "╰─────────────────────────────────────────────────────────────╯",
                Style::default().fg(Color::Cyan)
            ));
            lines.push(Line::raw(""));
        }

        // Render all messages
        for msg in &self.messages {
            let icon = msg.role.icon();
            let label = msg.role.label();
            let color = msg.role.color();
            
            // Check if this is an approval request message
            let is_approval = msg.content.contains("APPROVAL REQUIRED");
            
            // Thinking uses dim header style (appears smaller)
            if matches!(msg.role, Role::Thinking) {
                lines.push(Line::from(vec![
                    Span::styled("    💭 ", Style::default().fg(Color::DarkGray)),
                    Span::styled("Thinking", Style::default().fg(Color::DarkGray)),
                ]));
            } else {
                let header_color = if is_approval { Color::Red } else { color };
                lines.push(Line::from(vec![
                    Span::styled(icon, Style::default().fg(header_color)),
                    Span::raw(" "),
                    Span::styled(label, Style::default().fg(header_color).add_modifier(Modifier::BOLD)),
                ]));
            }
            
            if matches!(msg.role, Role::Thinking) {
                // Thinking uses markdown rendering with dim style and indent (appears smaller)
                let md_lines = render_markdown(&msg.content, max_w.saturating_sub(4));  // Leave room for indent
                if self.thinking_collapsed {
                    // Show only first 2 lines when collapsed
                    for line in md_lines.iter().take(2) {
                        // Add indent to make it look "smaller"
                        let indented = Line::styled(
                            format!("    {}", line.spans.iter().map(|s| s.content.as_ref()).collect::<String>()),
                            Style::default().fg(Color::DarkGray)
                        );
                        lines.push(indented);
                    }
                    if md_lines.len() > 2 {
                        lines.push(Line::styled(
                            format!("    ... ({} more lines)", md_lines.len() - 2),
                            Style::default().fg(Color::DarkGray)
                        ));
                    }
                } else {
                    for line in md_lines {
                        // Add indent to make it look "smaller"
                        let indented = Line::styled(
                            format!("    {}", line.spans.iter().map(|s| s.content.as_ref()).collect::<String>()),
                            Style::default().fg(Color::DarkGray)
                        );
                        lines.push(indented);
                    }
                }
            } else {
                if msg.role == Role::Assistant {
                    let md_lines = render_markdown(&msg.content, max_w);
                    lines.extend(md_lines);
                } else if let Role::Tool { name, is_error } = &msg.role {
                    // Tool results show abbreviated summary
                    let summary = summarize_tool_result(name, &msg.content, is_error, max_w);
                    for line in summary {
                        lines.push(line);
                    }
                } else {
                    // Use different style for approval messages
                    let content_color = if is_approval { Color::Yellow } else { Color::White };
                    // Word wrap for non-markdown content (User, System)
                    let wrapped = word_wrap(&msg.content, max_w);
                    for line in wrapped {
                        lines.push(Line::styled(
                            format!("  {}", line),
                            Style::default().fg(content_color)
                        ));
                    }
                }
            }
            
            lines.push(Line::raw(""));
        }

        // Current thinking (streaming) - markdown rendered with indent (appears smaller)
        if !self.thinking.is_empty() {
            lines.push(Line::from(vec![
                Span::styled("💭 ", Style::default().fg(Color::DarkGray)),
                Span::styled("Thinking", Style::default().fg(Color::DarkGray)),
            ]));
            
            let md_lines = render_markdown(&self.thinking, max_w.saturating_sub(4));
            if self.thinking_collapsed {
                // Show only first line when collapsed
                for line in md_lines.iter().take(1) {
                    let indented = Line::styled(
                        format!("    {}", line.spans.iter().map(|s| s.content.as_ref()).collect::<String>()),
                        Style::default().fg(Color::DarkGray)
                    );
                    lines.push(indented);
                }
                if md_lines.len() > 1 {
                    lines.push(Line::styled(
                        format!("    ... ({} more lines)", md_lines.len() - 1),
                        Style::default().fg(Color::DarkGray)
                    ));
                }
            } else {
                for line in md_lines {
                    let indented = Line::styled(
                        format!("    {}", line.spans.iter().map(|s| s.content.as_ref()).collect::<String>()),
                        Style::default().fg(Color::DarkGray)
                    );
                    lines.push(indented);
                }
            }
            lines.push(Line::raw(""));
        }

        // Streaming text - markdown rendered (only if not empty)
        if !self.streaming.is_empty() {
            let spinner = SPINNER[self.frame];
            lines.push(Line::from(vec![
                Span::styled("🤖", Style::default().fg(Color::Blue)),
                Span::raw(" "),
                Span::styled("Assistant", Style::default().fg(Color::Blue).add_modifier(Modifier::BOLD)),
                Span::styled(format!(" {} ", spinner), Style::default().fg(self.activity.color())),
            ]));
            let md_lines = render_markdown(&self.streaming, max_w);
            lines.extend(md_lines);
            lines.push(Line::styled("", Style::default().fg(Color::Cyan)));
        }
        
        // Activity indicator (tool execution progress)
        // Show when activity is a tool operation (not Thinking/Idle/Asking) and no streaming content
        let is_tool_activity = matches!(self.activity, 
            Activity::Reading | Activity::Writing | Activity::Editing | 
            Activity::Searching | Activity::Running | Activity::WebSearch | 
            Activity::WebFetch | Activity::Tool(_)
        );
        
        // Show spinner for Thinking state when waiting for AI response (empty content)
        if self.activity == Activity::Thinking && self.streaming.is_empty() && self.thinking.is_empty() {
            let spinner = SPINNER[self.frame];
            lines.push(Line::from(vec![
                Span::styled(spinner, Style::default().fg(self.activity.color())),
                Span::raw(" "),
                Span::styled(self.activity.label(), Style::default().fg(self.activity.color())),
                Span::styled("  Waiting for AI response...", Style::default().fg(Color::DarkGray)),
            ]));
        }
        
        if is_tool_activity && self.streaming.is_empty() && self.thinking.is_empty() {
            let mut spans = vec![
                Span::styled(SPINNER[self.frame], Style::default().fg(self.activity.color())),
                Span::raw(" "),
                Span::styled(self.activity.label(), Style::default().fg(self.activity.color())),
            ];
            if !self.activity_detail.is_empty() {
                spans.push(Span::styled(
                    format!(" {}", self.activity_detail),
                    Style::default().fg(Color::DarkGray)
                ));
            }
            lines.push(Line::from(spans));
        }

        // Scroll
        let total_lines = lines.len() as u16;
        let visible_height = area.height;
        let max_scroll = if total_lines > visible_height {
            total_lines.saturating_sub(visible_height)
        } else {
            0
        };
        
        // Store max_scroll for scroll detection in on_mouse
        self.max_scroll.set(max_scroll);
        
        // Force auto_scroll when AI is actively streaming/thinking (but not when user is selecting)
        let force_auto_scroll = (!self.streaming.is_empty() 
            || !self.thinking.is_empty() 
            || self.activity == Activity::Thinking)
            && !self.selecting;
        
        let scroll_offset = if self.auto_scroll || force_auto_scroll {
            max_scroll  // Scroll to bottom when auto_scroll or AI is active
        } else {
            self.scroll_offset.min(max_scroll)
        };

        // Apply selection highlight to lines
        let highlighted_lines = if let Some(sel) = selection {
            let sel_start = sel.start_line;
            let sel_end = sel.end_line;
            lines.into_iter().enumerate().map(|(i, line)| {
                if i >= sel_start && i <= sel_end {
                    // Add selection background color
                    let content = line.spans.iter().map(|s| s.content.as_ref()).collect::<String>();
                    Line::styled(content, Style::default().fg(Color::White).bg(Color::DarkGray))
                } else {
                    line
                }
            }).collect()
        } else {
            lines
        };

        f.render_widget(
            Paragraph::new(highlighted_lines)
                .scroll((scroll_offset, 0)),
            area
        );
    }

    fn draw_queue(&self, f: &mut ratatui::Frame, area: Rect) {
        let mut spans: Vec<Span> = vec![
            Span::styled("", Style::default().fg(Color::Magenta)),
            Span::styled(
                format!("Queue ({}): ", self.pending_messages.len()),
                Style::default().fg(Color::Magenta).add_modifier(Modifier::BOLD)
            ),
        ];
        
        // Show preview of each queued message (truncated)
        for (i, msg) in self.pending_messages.iter().enumerate() {
            if i > 0 {
                spans.push(Span::styled("", Style::default().fg(Color::DarkGray)));
            }
            let preview = msg.lines().next().unwrap_or("");
            let truncated = truncate(preview, 30);
            spans.push(Span::styled(
                format!("\"{}\"", truncated),
                Style::default().fg(Color::Yellow)
            ));
        }
        
        f.render_widget(Paragraph::new(Line::from(spans)), area);
    }

    fn draw_input(&self, f: &mut ratatui::Frame, area: Rect) {
        // Prompt indicator based on activity
        let prompt = match self.activity {
            Activity::Idle => "",
            Activity::Asking => "",
            _ => "",
        };
        let prompt_color = match self.activity {
            Activity::Idle => Color::Yellow,
            Activity::Asking => Color::Yellow,
            _ => Color::Gray,
        };
        
        // Check if multiline content
        let is_multiline = self.input.contains('\n');
        let max_w = area.width as usize;
        
        if !is_multiline {
            // Single line mode
            let mut spans: Vec<Span> = vec![
                Span::styled(prompt, Style::default().fg(prompt_color).add_modifier(Modifier::BOLD)),
            ];
            
            if self.activity == Activity::Asking {
                spans.push(Span::styled("[reply: y/n or option] ", Style::default().fg(Color::Yellow)));
            }
            
            if self.input.is_empty() {
                spans.push(Span::styled("_", Style::default().fg(Color::Cyan)));
            } else {
                spans.push(Span::styled(truncate(&self.input, max_w - 25), Style::default().fg(Color::White)));
            }
            
            spans.push(Span::styled(" Shift+Enter↵", Style::default().fg(Color::DarkGray)));
            
            f.render_widget(Paragraph::new(Line::from(spans)), area);
        } else {
            // Multiline mode: show actual content
            let mut lines: Vec<Line> = Vec::new();
            
            // First line with prompt
            let first_line = self.input.lines().next().unwrap_or("");
            let first_spans: Vec<Span> = vec![
                Span::styled(prompt, Style::default().fg(prompt_color).add_modifier(Modifier::BOLD)),
                Span::styled(truncate(first_line, max_w - 5), Style::default().fg(Color::White)),
            ];
            lines.push(Line::from(first_spans));
            
            // Remaining lines
            for line in self.input.lines().skip(1).take(area.height as usize - 2) {
                lines.push(Line::styled(
                    format!("  {}", truncate(line, max_w - 5)),
                    Style::default().fg(Color::White)
                ));
            }
            
            // Show line count if truncated
            let total_lines = self.input.lines().count();
            if total_lines > area.height as usize - 1 {
                lines.push(Line::styled(
                    format!("  ... ({}/{} lines shown)", area.height as usize - 2, total_lines),
                    Style::default().fg(Color::DarkGray)
                ));
            }
            
            // Hint on last line
            if lines.len() < area.height as usize {
                lines.push(Line::styled(
                    "  Shift+Enter↵ for newline, Enter↵ to send",
                    Style::default().fg(Color::DarkGray)
                ));
            }
            
            f.render_widget(Paragraph::new(lines), area);
        }
    }
}

/// Summarize tool result for display (abbreviated format)
fn summarize_tool_result(name: &str, content: &str, is_error: &bool, max_w: usize) -> Vec<Line<'static>> {
    let mut lines: Vec<Line<'static>> = Vec::new();
    let color = if *is_error { Color::Red } else { Color::Cyan };
    let error_prefix = if *is_error { "" } else { "" };
    
    // Parse tool name from label (e.g., "📖 Reading" -> "read")
    let tool_type = name.to_lowercase();
    
    match tool_type {
        // Read: show file preview with line count
        t if t.contains("read") || t.contains("reading") => {
            let line_count = content.lines().count();
            if line_count <= 3 {
                for line in content.lines().take(3) {
                    lines.push(Line::styled(
                        format!("  {}{}", error_prefix, truncate(line, max_w - 4)),
                        Style::default().fg(color)
                    ));
                }
            } else {
                for line in content.lines().take(2) {
                    lines.push(Line::styled(
                        format!("  {}{}", error_prefix, truncate(line, max_w - 4)),
                        Style::default().fg(color)
                    ));
                }
                lines.push(Line::styled(
                    format!("  {}... ({}) lines total", error_prefix, line_count),
                    Style::default().fg(Color::DarkGray)
                ));
            }
        }
        
        // Edit: show what was changed
        t if t.contains("edit") || t.contains("editing") => {
            if *is_error {
                lines.push(Line::styled(
                    format!("  {}{}", error_prefix, truncate(content, max_w - 4)),
                    Style::default().fg(Color::Red)
                ));
            } else {
                lines.push(Line::styled(
                    "  ✓ Applied changes",
                    Style::default().fg(Color::Green)
                ));
                // Show first few lines of diff preview
                for line in content.lines().take(3) {
                    let prefix = if line.starts_with('+') { "+" } 
                                 else if line.starts_with('-') { "-" }
                                 else { " " };
                    let line_color = if line.starts_with('+') { Color::Green }
                                     else if line.starts_with('-') { Color::Red }
                                     else { Color::DarkGray };
                    lines.push(Line::styled(
                        format!("  {}{}", prefix, truncate(line, max_w - 4)),
                        Style::default().fg(line_color)
                    ));
                }
            }
        }
        
        // Search/Glob: show match count + preview
        t if t.contains("search") || t.contains("glob") => {
            let matches: Vec<&str> = content.lines().filter(|l| !l.is_empty()).take(10).collect();
            let total = content.lines().filter(|l| !l.is_empty()).count();
            
            lines.push(Line::styled(
                format!("  {}{} matches{}", error_prefix, total, if total > 10 { format!(" (showing {})", matches.len()) } else { String::new() }),
                Style::default().fg(color)
            ));
            for m in matches.iter().take(5) {
                lines.push(Line::styled(
                    format!("    {}", truncate(m, max_w - 6)),
                    Style::default().fg(Color::DarkGray)
                ));
            }
        }
        
        // Bash: show command output preview
        t if t.contains("run") || t.contains("bash") => {
            let line_count = content.lines().count();
            if line_count <= 5 {
                for line in content.lines() {
                    lines.push(Line::styled(
                        format!("  {}{}", error_prefix, truncate(line, max_w - 4)),
                        Style::default().fg(color)
                    ));
                }
            } else {
                // Show first 2 and last 2 lines
                for line in content.lines().take(2) {
                    lines.push(Line::styled(
                        format!("  {}{}", error_prefix, truncate(line, max_w - 4)),
                        Style::default().fg(color)
                    ));
                }
                lines.push(Line::styled(
                    format!("  {}... ({}) lines ...", error_prefix, line_count - 4),
                    Style::default().fg(Color::DarkGray)
                ));
                let last_lines: Vec<&str> = content.lines().rev().take(2).collect();
                for line in last_lines.iter().rev() {
                    lines.push(Line::styled(
                        format!("  {}{}", error_prefix, truncate(line, max_w - 4)),
                        Style::default().fg(color)
                    ));
                }
            }
        }
        
        // Write: show file created
        t if t.contains("write") || t.contains("writing") => {
            if *is_error {
                lines.push(Line::styled(
                    format!("  {}{}", error_prefix, truncate(content, max_w - 4)),
                    Style::default().fg(Color::Red)
                ));
            } else {
                lines.push(Line::styled(
                    "  ✓ File written successfully",
                    Style::default().fg(Color::Green)
                ));
            }
        }
        
        // Todo_write: show full todo list with colored status markers
        t if t.contains("todo") => {
            // Show full todo list
            for line in content.lines() {
                let trimmed = line.trim();
                let (marker_color, content_color) = if trimmed.starts_with("[~]") {
                    // in_progress - yellow
                    (Color::Yellow, Color::Yellow)
                } else if trimmed.starts_with("[x]") {
                    // completed - green
                    (Color::Green, Color::Green)
                } else if trimmed.starts_with("[ ]") {
                    // pending - dark gray
                    (Color::DarkGray, Color::Gray)
                } else if trimmed.starts_with("Todos") {
                    // header - cyan bold
                    (Color::Cyan, Color::Cyan)
                } else {
                    (color, color)
                };
                
                // Format with proper indentation and colors
                if trimmed.starts_with("[") {
                    lines.push(Line::styled(
                        format!("  {}", truncate(line, max_w - 4)),
                        Style::default().fg(content_color)
                    ));
                } else {
                    // Header or other text
                    lines.push(Line::styled(
                        format!("  {}", truncate(line, max_w - 4)),
                        Style::default().fg(marker_color)
                    ));
                }
            }
        }
        
        // WebSearch/WebFetch: show results preview
        t if t.contains("web") || t.contains("search") || t.contains("fetch") => {
            let line_count = content.lines().count();
            for line in content.lines().take(5) {
                lines.push(Line::styled(
                    format!("  {}{}", error_prefix, truncate(line, max_w - 4)),
                    Style::default().fg(color)
                ));
            }
            if line_count > 5 {
                lines.push(Line::styled(
                    format!("  {}... {} more results", error_prefix, line_count - 5),
                    Style::default().fg(Color::DarkGray)
                ));
            }
        }
        
        // Default: truncate and show
        _ => {
            let line_count = content.lines().count();
            if line_count <= 3 {
                for line in content.lines() {
                    lines.push(Line::styled(
                        format!("  {}{}", error_prefix, truncate(line, max_w - 4)),
                        Style::default().fg(color)
                    ));
                }
            } else {
                for line in content.lines().take(2) {
                    lines.push(Line::styled(
                        format!("  {}{}", error_prefix, truncate(line, max_w - 4)),
                        Style::default().fg(color)
                    ));
                }
                lines.push(Line::styled(
                    format!("  {}... ({}) lines total", error_prefix, line_count),
                    Style::default().fg(Color::DarkGray)
                ));
            }
        }
    }
    
    lines
}