tmai-core 0.8.2

Core library for tmai - agent detection, state management, and monitoring
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
use regex::Regex;

use crate::agents::{AgentMode, AgentStatus, AgentType, ApprovalType};

use super::{DetectionConfidence, DetectionContext, DetectionResult, StatusDetector};

/// Title icon: ready/idle (diamond outline)
const TITLE_READY_ICON: char = '';

/// Title icon: working/processing (filled diamond)
const TITLE_WORKING_ICON: char = '';

/// Title icon: silent working (timer)
const TITLE_SILENT_WORKING_ICON: char = '';

/// Title icon: action required (raised hand)
const TITLE_ACTION_REQUIRED_ICON: char = '';

/// Braille spinner characters used by Gemini CLI in content
const BRAILLE_SPINNERS: &[char] = &['', '', '', '', '', '', '', '', '', ''];

/// Static braille character for "Waiting for user confirmation..."
const WAITING_SPINNER: char = '';

/// Detector for Gemini CLI
///
/// Detects agent status from terminal title icons and content patterns.
/// Gemini CLI uses specific Unicode icons in the terminal title to indicate
/// its current state, and radio-button-style selection in content for approvals.
pub struct GeminiDetector {
    radio_selected_pattern: Regex,
    radio_unselected_pattern: Regex,
}

impl GeminiDetector {
    /// Create a new GeminiDetector with compiled regex patterns
    pub fn new() -> Self {
        Self {
            // Selected radio item: ● followed by number, dot, space, text
            radio_selected_pattern: Regex::new(r"^●\s*(\d+)\.\s+(.+)$").unwrap(),
            // Unselected radio item: number, dot, space, text (no bullet prefix)
            radio_unselected_pattern: Regex::new(r"^\s*(\d+)\.\s+(.+)$").unwrap(),
        }
    }

    /// Detect approval type and details from content patterns
    ///
    /// Checks for RadioButtonSelect patterns, header texts, confirmation questions,
    /// and WaitingForConfirmation patterns in the recent content lines.
    fn detect_content_approval(&self, content: &str) -> Option<(ApprovalType, String, &str)> {
        let lines: Vec<&str> = content.lines().collect();
        let check_start = lines.len().saturating_sub(30);
        let recent_lines = &lines[check_start..];

        // Check for WaitingForConfirmation pattern
        if let Some(result) = self.detect_waiting_for_confirmation(recent_lines) {
            return Some(result);
        }

        // Check for RadioButtonSelect pattern
        if let Some(result) = self.detect_radio_button_select(recent_lines) {
            return Some(result);
        }

        // Check for header-based approval detection
        if let Some(result) = self.detect_header_approval(recent_lines) {
            return Some(result);
        }

        // Check for confirmation question patterns
        if let Some(result) = self.detect_confirmation_question(recent_lines) {
            return Some(result);
        }

        None
    }

    /// Detect RadioButtonSelect pattern with `●` for selected and numbered items
    ///
    /// Extracts choices from patterns like:
    /// ```text
    /// ● 1. Allow once
    ///   2. Allow for this session
    ///   3. No, suggest changes
    /// ```
    fn detect_radio_button_select(
        &self,
        lines: &[&str],
    ) -> Option<(ApprovalType, String, &'static str)> {
        let mut choices: Vec<String> = Vec::new();
        let mut cursor_position: usize = 0;
        let mut found_any = false;

        for line in lines {
            let trimmed = line.trim();

            // Check selected item (● N. text)
            if let Some(caps) = self.radio_selected_pattern.captures(trimmed) {
                if let (Some(num_match), Some(text_match)) = (caps.get(1), caps.get(2)) {
                    let num: usize = num_match.as_str().parse().unwrap_or(0);
                    choices.push(text_match.as_str().to_string());
                    cursor_position = num;
                    found_any = true;
                }
            }
            // Check unselected item (N. text) - only if we already found at least one radio item
            // or if the line starts with a digit
            else if let Some(caps) = self.radio_unselected_pattern.captures(trimmed) {
                if let Some(text_match) = caps.get(2) {
                    // Only consider this a radio item if it looks like a choice
                    let text = text_match.as_str();
                    if Self::looks_like_choice(text) || found_any {
                        choices.push(text.to_string());
                        found_any = true;
                    }
                }
            }
        }

        if found_any && choices.len() >= 2 {
            let details = choices.join(" / ");
            return Some((
                ApprovalType::UserQuestion {
                    choices,
                    multi_select: false,
                    cursor_position,
                },
                details,
                "radio_button_select",
            ));
        }

        None
    }

    /// Check if text looks like a typical approval choice
    fn looks_like_choice(text: &str) -> bool {
        let lower = text.to_lowercase();
        lower.contains("allow")
            || lower.contains("deny")
            || lower.contains("yes")
            || lower.contains("no")
            || lower.contains("suggest")
            || lower.contains("cancel")
            || lower.contains("proceed")
            || lower.contains("approve")
            || lower.contains("reject")
            || lower.contains("accept")
            || lower.contains("session")
            || lower.contains("once")
            || lower.contains("always")
    }

    /// Detect header-based approval patterns like "Action Required" and "Answer Questions"
    fn detect_header_approval(
        &self,
        lines: &[&str],
    ) -> Option<(ApprovalType, String, &'static str)> {
        for line in lines {
            let trimmed = line.trim();

            if trimmed.contains("Answer Questions") || trimmed.contains("answer questions") {
                return Some((
                    ApprovalType::UserQuestion {
                        choices: Vec::new(),
                        multi_select: false,
                        cursor_position: 0,
                    },
                    "Answer Questions".to_string(),
                    "answer_questions_header",
                ));
            }

            if trimmed.contains("Action Required") || trimmed.contains("action required") {
                // Try to determine specific type from surrounding context
                let context_text = lines.iter().map(|l| l.trim()).collect::<Vec<_>>().join(" ");
                let approval_type = Self::determine_tool_approval_type(&context_text);
                return Some((
                    approval_type,
                    "Action Required".to_string(),
                    "action_required_header",
                ));
            }
        }
        None
    }

    /// Detect specific confirmation question patterns
    fn detect_confirmation_question(
        &self,
        lines: &[&str],
    ) -> Option<(ApprovalType, String, &'static str)> {
        for line in lines {
            let trimmed = line.trim();

            if trimmed.contains("Apply this change?") {
                return Some((
                    ApprovalType::FileEdit,
                    "Apply this change?".to_string(),
                    "confirmation_question",
                ));
            }

            if trimmed.contains("Allow execution of") {
                return Some((
                    ApprovalType::ShellCommand,
                    trimmed.to_string(),
                    "confirmation_question",
                ));
            }

            if trimmed.contains("Do you want to proceed?") {
                let context_text = lines.iter().map(|l| l.trim()).collect::<Vec<_>>().join(" ");
                let approval_type = Self::determine_tool_approval_type(&context_text);
                return Some((
                    approval_type,
                    "Do you want to proceed?".to_string(),
                    "confirmation_question",
                ));
            }

            if trimmed.contains("Ready to start implementation?") {
                return Some((
                    ApprovalType::Other("Plan execution".to_string()),
                    "Ready to start implementation?".to_string(),
                    "confirmation_question",
                ));
            }
        }
        None
    }

    /// Detect "Waiting for user confirmation..." pattern with static spinner
    fn detect_waiting_for_confirmation(
        &self,
        lines: &[&str],
    ) -> Option<(ApprovalType, String, &'static str)> {
        for line in lines.iter().rev().take(10) {
            let trimmed = line.trim();
            if trimmed.contains(WAITING_SPINNER)
                && trimmed.contains("Waiting for user confirmation")
            {
                return Some((
                    ApprovalType::Other("Gemini approval".to_string()),
                    "Waiting for user confirmation".to_string(),
                    "waiting_for_confirmation",
                ));
            }
        }
        None
    }

    /// Determine ApprovalType from tool name context in content
    fn determine_tool_approval_type(context: &str) -> ApprovalType {
        let lower = context.to_lowercase();

        if lower.contains("write_file")
            || lower.contains("edit_file")
            || lower.contains("patch_file")
        {
            return ApprovalType::FileEdit;
        }

        if lower.contains("exec") || lower.contains("shell") || lower.contains("run_command") {
            return ApprovalType::ShellCommand;
        }

        if lower.contains("mcp") {
            return ApprovalType::McpTool;
        }

        ApprovalType::Other("Gemini approval".to_string())
    }

    /// Detect error patterns in recent content lines
    fn detect_error(&self, content: &str) -> Option<String> {
        super::common::detect_error_common(content, 500)
    }

    /// Detect braille spinner characters in content (Processing indicator)
    fn detect_content_spinner(&self, content: &str) -> bool {
        let lines: Vec<&str> = content.lines().collect();
        for line in lines.iter().rev().take(5) {
            let trimmed = line.trim();
            if let Some(first_char) = trimmed.chars().next() {
                if BRAILLE_SPINNERS.contains(&first_char)
                    && first_char != WAITING_SPINNER
                    && !trimmed.contains("Waiting for user confirmation")
                {
                    return true;
                }
            }
        }
        false
    }

    /// Detect input prompt at end of content (Idle indicator)
    ///
    /// Gemini CLI uses different prompt prefixes for different modes:
    /// - `> ` for normal mode
    /// - `! ` for shell mode
    /// - `* ` for YOLO mode
    /// - `(r:` prefix for reverse search
    fn detect_input_prompt(content: &str) -> bool {
        let lines: Vec<&str> = content.lines().collect();
        if let Some(last) = lines.last() {
            let trimmed = last.trim();
            // Check for Gemini CLI prompt patterns
            if trimmed == ">"
                || trimmed == "!"
                || trimmed == "*"
                || trimmed.ends_with("> ")
                || trimmed.ends_with("! ")
                || trimmed.ends_with("* ")
                || trimmed.starts_with("(r:")
            {
                return true;
            }
        }
        false
    }

    /// Detect agent mode from content
    ///
    /// Gemini CLI modes:
    /// - `* ` prompt or "YOLO mode" in footer → AutoApprove
    /// - "Plan mode" in footer → Plan
    /// - Default otherwise
    pub fn detect_mode(content: &str) -> AgentMode {
        let lines: Vec<&str> = content.lines().collect();

        // Check footer lines (last 5 lines) for mode indicators
        let footer_start = lines.len().saturating_sub(5);
        let footer_lines = &lines[footer_start..];

        for line in footer_lines {
            let trimmed = line.trim();
            if trimmed.contains("YOLO mode") {
                return AgentMode::AutoApprove;
            }
            if trimmed.contains("Plan mode") {
                return AgentMode::Plan;
            }
        }

        // Check for YOLO mode via `* ` prompt prefix
        if let Some(last) = lines.last() {
            let trimmed = last.trim();
            if trimmed == "*" || trimmed.ends_with("* ") {
                return AgentMode::AutoApprove;
            }
        }

        AgentMode::Default
    }
}

impl Default for GeminiDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl StatusDetector for GeminiDetector {
    /// Detect agent status from title and content (simple version)
    fn detect_status(&self, title: &str, content: &str) -> AgentStatus {
        self.detect_status_with_reason(title, content, &DetectionContext::default())
            .status
    }

    /// Detect agent status with detailed reason for audit logging
    ///
    /// Detection flow (priority order):
    /// 1. Title `✋` icon → AwaitingApproval (also check content for specific type)
    /// 2. Content-based approval (RadioButtonSelect, headers, WaitingForConfirmation)
    /// 3. Error patterns
    /// 4. Title `✦` or `⏲` → Processing
    /// 5. Title `◇` → Idle
    /// 6. Content braille spinner → Processing
    /// 7. Content input prompt → Idle
    /// 8. Fallback → Processing (Low confidence)
    fn detect_status_with_reason(
        &self,
        title: &str,
        content: &str,
        _context: &DetectionContext,
    ) -> DetectionResult {
        // 1. Title ✋ icon → AwaitingApproval (highest priority)
        if title.contains(TITLE_ACTION_REQUIRED_ICON) {
            // Also check content for specific ApprovalType
            if let Some((approval_type, details, rule)) = self.detect_content_approval(content) {
                return DetectionResult::new(
                    AgentStatus::AwaitingApproval {
                        approval_type,
                        details: details.clone(),
                    },
                    rule,
                    DetectionConfidence::High,
                )
                .with_matched_text(&details);
            }
            // Title says action required but content doesn't specify type
            return DetectionResult::new(
                AgentStatus::AwaitingApproval {
                    approval_type: ApprovalType::Other("Gemini approval".to_string()),
                    details: String::new(),
                },
                "title_action_required_icon",
                DetectionConfidence::High,
            )
            .with_matched_text(title);
        }

        // 2. Content-based approval detection (without title icon)
        if let Some((approval_type, details, rule)) = self.detect_content_approval(content) {
            return DetectionResult::new(
                AgentStatus::AwaitingApproval {
                    approval_type,
                    details: details.clone(),
                },
                rule,
                DetectionConfidence::High,
            )
            .with_matched_text(&details);
        }

        // 3. Error detection
        if let Some(message) = self.detect_error(content) {
            return DetectionResult::new(
                AgentStatus::Error {
                    message: message.clone(),
                },
                "error_pattern",
                DetectionConfidence::High,
            )
            .with_matched_text(&message);
        }

        // 4. Title ✦ or ⏲ → Processing
        if title.contains(TITLE_WORKING_ICON) {
            return DetectionResult::new(
                AgentStatus::Processing {
                    activity: String::new(),
                },
                "title_working_icon",
                DetectionConfidence::High,
            )
            .with_matched_text(title);
        }

        if title.contains(TITLE_SILENT_WORKING_ICON) {
            return DetectionResult::new(
                AgentStatus::Processing {
                    activity: String::new(),
                },
                "title_silent_working_icon",
                DetectionConfidence::High,
            )
            .with_matched_text(title);
        }

        // 5. Title ◇ → Idle
        if title.contains(TITLE_READY_ICON) {
            return DetectionResult::new(
                AgentStatus::Idle,
                "title_ready_icon",
                DetectionConfidence::High,
            )
            .with_matched_text(title);
        }

        // 6. Content braille spinner → Processing
        if self.detect_content_spinner(content) {
            return DetectionResult::new(
                AgentStatus::Processing {
                    activity: String::new(),
                },
                "braille_spinner",
                DetectionConfidence::Medium,
            );
        }

        // 7. Content input prompt → Idle
        if Self::detect_input_prompt(content) {
            return DetectionResult::new(
                AgentStatus::Idle,
                "input_prompt",
                DetectionConfidence::Medium,
            );
        }

        // 8. Fallback → Processing
        DetectionResult::new(
            AgentStatus::Processing {
                activity: String::new(),
            },
            "fallback_processing",
            DetectionConfidence::Low,
        )
    }

    /// Get the agent type this detector handles
    fn agent_type(&self) -> AgentType {
        AgentType::GeminiCli
    }

    /// Keys to send for approval
    fn approval_keys(&self) -> &str {
        "Enter"
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn detect(title: &str, content: &str) -> DetectionResult {
        let detector = GeminiDetector::new();
        detector.detect_status_with_reason(title, content, &DetectionContext::default())
    }

    // --- Title icon detection ---

    #[test]
    fn test_title_ready_icon_idle() {
        let result = detect("◇ Gemini", "Some content\n> ");
        assert!(matches!(result.status, AgentStatus::Idle));
        assert_eq!(result.reason.rule, "title_ready_icon");
        assert_eq!(result.reason.confidence, DetectionConfidence::High);
    }

    #[test]
    fn test_title_working_icon_processing() {
        let result = detect("✦ Gemini", "Working on something...");
        assert!(matches!(result.status, AgentStatus::Processing { .. }));
        assert_eq!(result.reason.rule, "title_working_icon");
        assert_eq!(result.reason.confidence, DetectionConfidence::High);
    }

    #[test]
    fn test_title_silent_working_icon_processing() {
        let result = detect("⏲ Gemini", "Waiting for response...");
        assert!(matches!(result.status, AgentStatus::Processing { .. }));
        assert_eq!(result.reason.rule, "title_silent_working_icon");
        assert_eq!(result.reason.confidence, DetectionConfidence::High);
    }

    #[test]
    fn test_title_action_required_icon_generic() {
        let result = detect("✋ Gemini", "Some content without specific pattern");
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval { .. }
        ));
        assert_eq!(result.reason.rule, "title_action_required_icon");
        assert_eq!(result.reason.confidence, DetectionConfidence::High);
    }

    #[test]
    fn test_title_action_required_with_radio_buttons() {
        let content = "Some tool output\n● 1. Allow once\n  2. Allow for this session\n  3. No, suggest changes\n";
        let result = detect("✋ Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::UserQuestion { .. },
                ..
            }
        ));
        assert_eq!(result.reason.rule, "radio_button_select");
        assert_eq!(result.reason.confidence, DetectionConfidence::High);
    }

    // --- RadioButtonSelect detection ---

    #[test]
    fn test_radio_button_select() {
        let content =
            "Tool wants to do something\n● 1. Allow once\n  2. Allow for this session\n  3. No, suggest changes\n";
        let result = detect("Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::UserQuestion { .. },
                ..
            }
        ));
        assert_eq!(result.reason.rule, "radio_button_select");

        if let AgentStatus::AwaitingApproval {
            approval_type:
                ApprovalType::UserQuestion {
                    choices,
                    cursor_position,
                    multi_select,
                },
            ..
        } = &result.status
        {
            assert_eq!(choices.len(), 3);
            assert_eq!(choices[0], "Allow once");
            assert_eq!(choices[1], "Allow for this session");
            assert_eq!(choices[2], "No, suggest changes");
            assert_eq!(*cursor_position, 1);
            assert!(!multi_select);
        }
    }

    // --- Header-based detection ---

    #[test]
    fn test_action_required_header() {
        let content = "Some output\nAction Required\nwrite_file: src/main.rs\n";
        let result = detect("Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::FileEdit,
                ..
            }
        ));
        assert_eq!(result.reason.rule, "action_required_header");
    }

    #[test]
    fn test_answer_questions_header() {
        let content = "Some output\nAnswer Questions\nWhat should we do?\n";
        let result = detect("Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::UserQuestion { .. },
                ..
            }
        ));
        assert_eq!(result.reason.rule, "answer_questions_header");
    }

    #[test]
    fn test_confirmation_question_apply_change() {
        let content = "Diff output here\nApply this change?\n";
        let result = detect("Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::FileEdit,
                ..
            }
        ));
        assert_eq!(result.reason.rule, "confirmation_question");
    }

    #[test]
    fn test_confirmation_question_allow_execution() {
        let content = "Command preview\nAllow execution of `ls -la`\n";
        let result = detect("Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::ShellCommand,
                ..
            }
        ));
        assert_eq!(result.reason.rule, "confirmation_question");
    }

    #[test]
    fn test_confirmation_question_ready_to_implement() {
        let content = "Plan summary here\nReady to start implementation?\n";
        let result = detect("Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::Other(_),
                ..
            }
        ));
        if let AgentStatus::AwaitingApproval {
            approval_type: ApprovalType::Other(ref s),
            ..
        } = result.status
        {
            assert_eq!(s, "Plan execution");
        }
    }

    // --- WaitingForConfirmation detection ---

    #[test]
    fn test_waiting_for_confirmation() {
        let content = "Some output\n⠏ Waiting for user confirmation...\n";
        let result = detect("Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval { .. }
        ));
        assert_eq!(result.reason.rule, "waiting_for_confirmation");
        assert_eq!(result.reason.confidence, DetectionConfidence::High);
    }

    // --- Input prompt idle detection ---

    #[test]
    fn test_input_prompt_normal_mode() {
        let content = "Previous output\n> ";
        let result = detect("Gemini", content);
        assert!(matches!(result.status, AgentStatus::Idle));
        assert_eq!(result.reason.rule, "input_prompt");
        assert_eq!(result.reason.confidence, DetectionConfidence::Medium);
    }

    #[test]
    fn test_input_prompt_shell_mode() {
        let content = "Previous output\n! ";
        let result = detect("Gemini", content);
        assert!(matches!(result.status, AgentStatus::Idle));
        assert_eq!(result.reason.rule, "input_prompt");
    }

    #[test]
    fn test_input_prompt_yolo_mode() {
        let content = "Previous output\n* ";
        let result = detect("Gemini", content);
        assert!(matches!(result.status, AgentStatus::Idle));
        assert_eq!(result.reason.rule, "input_prompt");
    }

    #[test]
    fn test_input_prompt_reverse_search() {
        let content = "Previous output\n(r:search term) ";
        let result = detect("Gemini", content);
        assert!(matches!(result.status, AgentStatus::Idle));
        assert_eq!(result.reason.rule, "input_prompt");
    }

    // --- Braille spinner detection ---

    #[test]
    fn test_braille_spinner_processing() {
        let content = "Working on task\n⠋ Thinking...";
        let result = detect("Gemini", content);
        assert!(matches!(result.status, AgentStatus::Processing { .. }));
        assert_eq!(result.reason.rule, "braille_spinner");
        assert_eq!(result.reason.confidence, DetectionConfidence::Medium);
    }

    #[test]
    fn test_braille_spinner_not_confused_with_waiting() {
        // ⠏ + "Waiting for user confirmation" should be approval, not spinner
        let content = "Some output\n⠏ Waiting for user confirmation...\n";
        let result = detect("Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval { .. }
        ));
        assert_eq!(result.reason.rule, "waiting_for_confirmation");
    }

    // --- Error detection ---

    #[test]
    fn test_error_detection() {
        let content = "Processing...\nError: something went wrong\n";
        let result = detect("Gemini", content);
        assert!(matches!(result.status, AgentStatus::Error { .. }));
        assert_eq!(result.reason.rule, "error_pattern");
        assert_eq!(result.reason.confidence, DetectionConfidence::High);
    }

    // --- Fallback detection ---

    #[test]
    fn test_fallback_processing() {
        let content = "Some random output without any indicators";
        let result = detect("Gemini", content);
        assert!(matches!(result.status, AgentStatus::Processing { .. }));
        assert_eq!(result.reason.rule, "fallback_processing");
        assert_eq!(result.reason.confidence, DetectionConfidence::Low);
    }

    // --- Mode detection ---

    #[test]
    fn test_mode_yolo_prompt() {
        let content = "Some output\n* ";
        let mode = GeminiDetector::detect_mode(content);
        assert_eq!(mode, AgentMode::AutoApprove);
    }

    #[test]
    fn test_mode_yolo_footer() {
        let content = "Some output\nStatus bar | YOLO mode\n> ";
        let mode = GeminiDetector::detect_mode(content);
        assert_eq!(mode, AgentMode::AutoApprove);
    }

    #[test]
    fn test_mode_plan() {
        let content = "Some output\nStatus bar | Plan mode\n> ";
        let mode = GeminiDetector::detect_mode(content);
        assert_eq!(mode, AgentMode::Plan);
    }

    #[test]
    fn test_mode_default() {
        let content = "Some output\n> ";
        let mode = GeminiDetector::detect_mode(content);
        assert_eq!(mode, AgentMode::Default);
    }

    // --- Priority tests ---

    #[test]
    fn test_title_action_required_overrides_content_spinner() {
        // Title says action required, content has spinner - title should win
        let content = "⠋ Processing something\n";
        let result = detect("✋ Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval { .. }
        ));
    }

    #[test]
    fn test_content_approval_overrides_title_working() {
        // Title says working but content shows radio buttons - content approval should win
        // because content approval (step 2) is checked before title working (step 4)
        let content =
            "Tool output\n● 1. Allow once\n  2. Allow for this session\n  3. No, suggest changes\n";
        let result = detect("✦ Gemini", content);
        // Title ✋ is step 1, but ✦ is step 4 - content approval (step 2) should be checked
        // However, title ✋ check (step 1) only fires for ✋, not ✦
        // So flow goes: step 1 (no ✋) → step 2 (content approval found) → return
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval { .. }
        ));
        assert_eq!(result.reason.rule, "radio_button_select");
    }

    #[test]
    fn test_error_overrides_title_ready() {
        // Error takes priority over title idle
        let content = "Error: connection refused\n";
        let result = detect("◇ Gemini", content);
        assert!(matches!(result.status, AgentStatus::Error { .. }));
    }

    #[test]
    fn test_title_working_overrides_input_prompt() {
        // Title working icon should override content-based idle
        let content = "Previous output\n> ";
        let result = detect("✦ Gemini", content);
        assert!(matches!(result.status, AgentStatus::Processing { .. }));
        assert_eq!(result.reason.rule, "title_working_icon");
    }

    // --- Tool type detection ---

    #[test]
    fn test_action_required_shell_command() {
        let content = "Action Required\nexec: ls -la /tmp\n";
        let result = detect("Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::ShellCommand,
                ..
            }
        ));
    }

    #[test]
    fn test_action_required_mcp_tool() {
        let content = "Action Required\nmcp_tool: read_file\n";
        let result = detect("Gemini", content);
        assert!(matches!(
            result.status,
            AgentStatus::AwaitingApproval {
                approval_type: ApprovalType::McpTool,
                ..
            }
        ));
    }

    #[test]
    fn test_agent_type() {
        let detector = GeminiDetector::new();
        assert_eq!(detector.agent_type(), AgentType::GeminiCli);
    }

    #[test]
    fn test_approval_keys() {
        let detector = GeminiDetector::new();
        assert_eq!(detector.approval_keys(), "Enter");
    }

    // --- Backward compatibility ---

    #[test]
    fn test_detect_status_delegates_to_with_reason() {
        let detector = GeminiDetector::new();
        let status = detector.detect_status("◇ Gemini", "Some content\n> ");
        assert!(matches!(status, AgentStatus::Idle));
    }
}