tmux-tango 2.7.3

A CLI tool for managing tmux sessions - dance between your sessions!
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
//! Pane status detection for real-time monitoring.
//!
//! Two-path classification: Claude Code panes use hook-based detection (primary)
//! with content heuristics as fallback. Non-Claude panes use command + content analysis.
//! Hook status files are written by a shell script invoked by Claude Code's hooks API.

use ratatui::{
    style::{Color, Style},
    text::Span,
};
use std::collections::HashMap;
use std::fs;
use std::time::Duration;

/// Status of a single pane, ordered by priority for aggregation.
/// `max()` yields the "worst" (most attention-needed) status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum PaneStatus {
    Unknown,
    Idle,
    Active,
    Error,
    Waiting,
}

/// Pre-computed status cache, rebuilt each update cycle.
pub struct PaneMonitor {
    pane_statuses: HashMap<String, PaneStatus>,
    session_statuses: HashMap<String, PaneStatus>,
    window_statuses: HashMap<(String, u32), PaneStatus>,
}

impl PaneMonitor {
    pub fn new() -> Self {
        Self {
            pane_statuses: HashMap::new(),
            session_statuses: HashMap::new(),
            window_statuses: HashMap::new(),
        }
    }

    pub fn set(&mut self, pane_id: &str, session_name: &str, window_index: u32, status: PaneStatus) {
        self.pane_statuses.insert(pane_id.to_string(), status);

        let session_entry = self.session_statuses
            .entry(session_name.to_string())
            .or_insert(PaneStatus::Unknown);
        *session_entry = (*session_entry).max(status);

        let window_entry = self.window_statuses
            .entry((session_name.to_string(), window_index))
            .or_insert(PaneStatus::Unknown);
        *window_entry = (*window_entry).max(status);
    }

    pub fn begin_update(&mut self) {
        self.pane_statuses.clear();
        self.session_statuses.clear();
        self.window_statuses.clear();
    }

    pub fn get_pane(&self, pane_id: &str) -> PaneStatus {
        self.pane_statuses.get(pane_id).copied().unwrap_or(PaneStatus::Unknown)
    }

    pub fn get_session(&self, session_name: &str) -> PaneStatus {
        self.session_statuses.get(session_name).copied().unwrap_or(PaneStatus::Unknown)
    }

    pub fn get_window(&self, session_name: &str, window_index: u32) -> PaneStatus {
        self.window_statuses
            .get(&(session_name.to_string(), window_index))
            .copied()
            .unwrap_or(PaneStatus::Unknown)
    }

    pub fn clear(&mut self) {
        self.begin_update();
    }
}

pub const HOOK_STATUS_DIR: &str = "/tmp/tango-status";
const HOOK_STALENESS: Duration = Duration::from_secs(60);

/// Classify a pane using its foreground command, captured content, and hook status.
///
/// Decision tree:
///   1. Content has waiting patterns → Waiting
///   2. Content has error patterns → Error
///   3. Hook status file exists and is trusted → use it
///   4. Claude pane (by command) → content heuristics → default Active
///   5. Shell command → Idle
///   6. Otherwise → Active
pub fn classify(command: &str, content: Option<&str>, pane_id: &str) -> PaneStatus {
    if let Some(text) = content {
        if has_waiting_pattern(text) {
            return PaneStatus::Waiting;
        }
        if has_error_pattern(text) {
            return PaneStatus::Error;
        }
    }

    // Hook status takes priority over command-based classification.
    // When Claude runs a tool (bash, node, etc.), tmux reports the subprocess
    // as pane_current_command, but the hook file still reflects Claude's state.
    if let Some(status) = read_hook_status(pane_id, command) {
        return status;
    }

    if is_claude(command) {
        return classify_claude_heuristic(content);
    }

    if is_shell(command) {
        PaneStatus::Idle
    } else {
        PaneStatus::Active
    }
}

/// Claude content heuristics (hook check already happened in classify).
fn classify_claude_heuristic(content: Option<&str>) -> PaneStatus {
    if let Some(text) = content {
        if has_claude_working_indicators(text) {
            return PaneStatus::Active;
        }
        if is_claude_idle_strict(text) {
            return PaneStatus::Idle;
        }
    }
    PaneStatus::Active
}

/// Read a hook-written status file for the given pane.
///
/// Staleness policy: "active" and "waiting" hooks are trusted indefinitely
/// as long as the Claude process is still the pane's foreground command.
/// Long-running operations (subagents, plan mode) don't fire new hook events,
/// so a stale "active" file with `claude` still running is almost certainly
/// still correct. "Idle" hooks always use the short timeout — Claude may have
/// started new work since the idle hook fired.
fn read_hook_status(pane_id: &str, command: &str) -> Option<PaneStatus> {
    let sanitized = pane_id.replace('%', "_");
    let path = format!("{}/{}", HOOK_STATUS_DIR, sanitized);
    let content = fs::read_to_string(&path).ok()?;
    let metadata = fs::metadata(&path).ok()?;
    let age = metadata.modified().ok()?.elapsed().ok()?;
    resolve_hook_status(content.trim(), age, command)
}

const SHELLS: &[&str] = &[
    "bash", "zsh", "fish", "sh", "ksh", "csh", "dash", "tcsh",
    "ash", "nushell", "nu", "elvish", "oil", "pwsh", "powershell",
    "login", "-bash", "-zsh", "-sh", "-fish",
];

pub fn is_shell(command: &str) -> bool {
    let cmd = command.rsplit('/').next().unwrap_or(command);
    SHELLS.iter().any(|s| cmd.eq_ignore_ascii_case(s))
}

fn is_claude(command: &str) -> bool {
    let cmd = command.rsplit('/').next().unwrap_or(command);
    cmd.eq_ignore_ascii_case("claude")
}

/// Strict idle check: `❯` must appear in the last 4 non-empty lines.
/// When Claude is idle, the prompt sits above a multi-line status bar
/// (model, context, cost, mode). 4 lines accommodates a 3-line status bar.
/// When working, new output pushes `❯` well beyond position 4.
fn is_claude_idle_strict(content: &str) -> bool {
    content
        .lines()
        .rev()
        .filter(|l| !l.trim().is_empty())
        .take(4)
        .any(|l| l.trim().starts_with(''))
}

/// Detect positive signals that Claude is actively working.
/// Scans deeper than `is_claude_idle_strict` so working indicators
/// always take precedence over a stale `❯` in the same region.
fn has_claude_working_indicators(content: &str) -> bool {
    content
        .lines()
        .rev()
        .filter(|l| !l.trim().is_empty())
        .take(5)
        .any(|l| {
            let t = l.trim();
            // Tool execution marker
            t.starts_with('')
            // Agent/background task indicator (e.g., "* Coalescing…")
            || t.starts_with("* ")
            // Braille spinner characters (progress indicators)
            || t.starts_with('') || t.starts_with('') || t.starts_with('')
            || t.starts_with('') || t.starts_with('') || t.starts_with('')
            || t.starts_with('') || t.starts_with('') || t.starts_with('')
            || t.starts_with('')
            // Claude status line: "thinking", "Coalescing" (long-running agent tasks)
            || t.contains("· thinking")
            || t.starts_with("Coalescing")
        })
}

/// Check the last non-empty lines for patterns indicating the pane
/// is waiting for user input.
///
/// Two-tier scan: navigation hints (always rendered at the very bottom by
/// interactive CLIs) are checked in the last 3 lines only — so they stop
/// matching as soon as new output scrolls them up. Explicit prompt text
/// (Y/n, "Allow", etc.) uses a deeper 15-line scan.
pub fn has_waiting_pattern(content: &str) -> bool {
    let lines: Vec<&str> = content
        .lines()
        .rev()
        .filter(|l| !l.trim().is_empty())
        .take(5)
        .collect();

    // Tier 1: navigation hints — only the last 2 non-empty lines.
    // Interactive CLIs always render these at the very bottom.
    for line in lines.iter().take(2) {
        let trimmed = line.trim();
        if trimmed.contains("Enter to select")
            || trimmed.contains("Esc to cancel")
            || trimmed.contains("Arrow keys to navigate")
            || trimmed.contains("Tab/Arrow keys")
            || trimmed.contains("shift+tab to approve")
        {
            return true;
        }
    }

    // Tier 2: compact prompts (Y/n, Allow) — last 5 lines.
    // Tall menus (Claude Code approval) are already caught by tier 1.
    for line in &lines {
        let trimmed = line.trim();

        // Y/n confirmation prompts
        if trimmed.contains("(Y/n)")
            || trimmed.contains("(y/N)")
            || trimmed.contains("[Y/n]")
            || trimmed.contains("[y/N]")
            || trimmed.contains("(yes/no)")
        {
            return true;
        }

        // Claude Code permission prompts
        if trimmed.starts_with("Allow") || trimmed.starts_with("allow") {
            return true;
        }

        // Press enter prompts (e.g. "Press ENTER to continue")
        if trimmed.contains("Press ENTER") || trimmed.contains("press enter") {
            return true;
        }
    }
    false
}

/// Check the last few non-empty lines for error indicators.
pub fn has_error_pattern(content: &str) -> bool {
    let lines: Vec<&str> = content
        .lines()
        .rev()
        .filter(|l| !l.trim().is_empty())
        .take(10)
        .collect();

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

        // "error:" or "error[" (Rust compiler style)
        if lower.starts_with("error:") || lower.starts_with("error[") {
            return true;
        }
        // "fatal:" at start of line
        if lower.starts_with("fatal:") || lower.starts_with("fatal error") {
            return true;
        }
        // Rust panics
        if lower.contains("panicked at") {
            return true;
        }
        // Python tracebacks
        if trimmed.starts_with("Traceback (most recent call last)") {
            return true;
        }
        // Test suite failures
        if trimmed.contains("FAILED") && (trimmed.contains("test") || trimmed.contains("TEST")) {
            return true;
        }
        // npm/node errors
        if trimmed.starts_with("ERR!") || lower.starts_with("npm err!") {
            return true;
        }
        // Command not found
        if lower.ends_with("command not found") || lower.ends_with("not found") && lower.contains("error") {
            return true;
        }
        // Segfault / abort
        if lower.contains("segmentation fault") || lower.contains("core dumped") {
            return true;
        }
    }
    false
}

/// Resolve a parsed hook status given its age and the pane's current command.
/// Extracted for testability — the staleness policy lives here.
fn resolve_hook_status(status_str: &str, age: Duration, command: &str) -> Option<PaneStatus> {
    let status = match status_str {
        "active" => PaneStatus::Active,
        "idle" => PaneStatus::Idle,
        "waiting" => PaneStatus::Waiting,
        _ => return None,
    };

    if age <= HOOK_STALENESS {
        return Some(status);
    }

    match status {
        PaneStatus::Active | PaneStatus::Waiting if is_claude(command) => Some(status),
        _ => None,
    }
}

/// Read hook status from an explicit path (for testing).
#[cfg(test)]
fn read_hook_status_from_path(path: &std::path::Path) -> Option<PaneStatus> {
    let content = fs::read_to_string(path).ok()?;
    let metadata = fs::metadata(path).ok()?;
    let age = metadata.modified().ok()?.elapsed().ok()?;
    resolve_hook_status(content.trim(), age, "claude")
}

/// Returns a colored status indicator span for tree rendering.
pub fn status_indicator(status: PaneStatus) -> Span<'static> {
    match status {
        PaneStatus::Waiting => Span::styled("", Style::default().fg(Color::Yellow)),
        PaneStatus::Error => Span::styled("", Style::default().fg(Color::Red)),
        PaneStatus::Active => Span::styled("", Style::default().fg(Color::Green)),
        PaneStatus::Idle => Span::styled("", Style::default().fg(Color::DarkGray)),
        PaneStatus::Unknown => Span::styled("?", Style::default().fg(Color::DarkGray)),
    }
}

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

    #[test]
    fn test_pane_status_ordering() {
        assert!(PaneStatus::Waiting > PaneStatus::Error);
        assert!(PaneStatus::Error > PaneStatus::Active);
        assert!(PaneStatus::Active > PaneStatus::Idle);
        assert!(PaneStatus::Idle > PaneStatus::Unknown);
    }

    #[test]
    fn test_aggregation_via_max() {
        let statuses = vec![PaneStatus::Idle, PaneStatus::Active, PaneStatus::Unknown];
        assert_eq!(statuses.into_iter().max(), Some(PaneStatus::Active));

        let statuses = vec![PaneStatus::Idle, PaneStatus::Waiting];
        assert_eq!(statuses.into_iter().max(), Some(PaneStatus::Waiting));

        let statuses = vec![PaneStatus::Error, PaneStatus::Active];
        assert_eq!(statuses.into_iter().max(), Some(PaneStatus::Error));
    }

    // classify() tests — use empty pane_id to skip hook lookup

    #[test]
    fn test_shell_is_idle() {
        assert_eq!(classify("bash", None, ""), PaneStatus::Idle);
        assert_eq!(classify("zsh", None, ""), PaneStatus::Idle);
        assert_eq!(classify("fish", None, ""), PaneStatus::Idle);
        assert_eq!(classify("-bash", None, ""), PaneStatus::Idle);
    }

    #[test]
    fn test_non_shell_is_active() {
        assert_eq!(classify("node", None, ""), PaneStatus::Active);
        assert_eq!(classify("python", None, ""), PaneStatus::Active);
        assert_eq!(classify("vim", None, ""), PaneStatus::Active);
        assert_eq!(classify("claude", None, ""), PaneStatus::Active);
    }

    #[test]
    fn test_waiting_overrides_command() {
        let content = "output\nProceed? (Y/n)";
        assert_eq!(classify("bash", Some(content), ""), PaneStatus::Waiting);
        assert_eq!(classify("node", Some(content), ""), PaneStatus::Waiting);
    }

    #[test]
    fn test_non_shell_without_waiting_is_active() {
        let content = "Compiling project...\nBuilding 42 crates";
        assert_eq!(classify("cargo", Some(content), ""), PaneStatus::Active);
    }

    #[test]
    fn test_shell_without_waiting_is_idle() {
        let content = "user@host:~$ ls\nfile1  file2";
        assert_eq!(classify("bash", Some(content), ""), PaneStatus::Idle);
    }

    // is_shell() tests

    #[test]
    fn test_is_shell_common() {
        assert!(is_shell("bash"));
        assert!(is_shell("zsh"));
        assert!(is_shell("fish"));
        assert!(is_shell("sh"));
        assert!(is_shell("dash"));
    }

    #[test]
    fn test_is_shell_login_variants() {
        assert!(is_shell("-bash"));
        assert!(is_shell("-zsh"));
        assert!(is_shell("-sh"));
        assert!(is_shell("login"));
    }

    #[test]
    fn test_is_shell_full_path() {
        assert!(is_shell("/bin/bash"));
        assert!(is_shell("/usr/bin/zsh"));
    }

    #[test]
    fn test_is_not_shell() {
        assert!(!is_shell("node"));
        assert!(!is_shell("python"));
        assert!(!is_shell("vim"));
        assert!(!is_shell("claude"));
        assert!(!is_shell("cargo"));
    }

    // has_waiting_pattern() tests

    #[test]
    fn test_waiting_yn_prompt() {
        assert!(has_waiting_pattern("Some output\nDo you want to continue? (Y/n)"));
    }

    #[test]
    fn test_waiting_allow_prompt() {
        assert!(has_waiting_pattern("Reading file...\nAllow Read access to /tmp/foo?"));
    }

    #[test]
    fn test_waiting_interactive_menu() {
        assert!(has_waiting_pattern("Pick an option:\n❯ 1. Foo\nEnter to select · Esc to cancel"));
    }

    #[test]
    fn test_waiting_press_enter() {
        assert!(has_waiting_pattern("Installation complete.\nPress ENTER to continue"));
    }

    #[test]
    fn test_waiting_yes_no_variations() {
        assert!(has_waiting_pattern("Continue? [Y/n]"));
        assert!(has_waiting_pattern("Overwrite? [y/N]"));
        assert!(has_waiting_pattern("Save changes? (yes/no)"));
    }

    #[test]
    fn test_no_waiting_pattern() {
        assert!(!has_waiting_pattern("The answer is 42"));
        assert!(!has_waiting_pattern("Compiling...\nBuilding crates"));
        assert!(!has_waiting_pattern("user@host:~$"));
    }

    // classify() with errors

    #[test]
    fn test_error_rust_compiler() {
        let content = "Compiling foo v0.1.0\nerror[E0308]: mismatched types";
        assert_eq!(classify("cargo", Some(content), ""), PaneStatus::Error);
    }

    #[test]
    fn test_error_fatal() {
        let content = "fatal: not a git repository";
        assert_eq!(classify("git", Some(content), ""), PaneStatus::Error);
    }

    #[test]
    fn test_error_panic() {
        let content = "thread 'main' panicked at 'index out of bounds'";
        assert_eq!(classify("myapp", Some(content), ""), PaneStatus::Error);
    }

    #[test]
    fn test_error_python_traceback() {
        let content = "Traceback (most recent call last)\n  File \"app.py\"\nNameError: x";
        assert_eq!(classify("python", Some(content), ""), PaneStatus::Error);
    }

    #[test]
    fn test_error_test_failure() {
        let content = "test result: FAILED. 2 passed; 1 failed; 0 ignored";
        assert_eq!(classify("cargo", Some(content), ""), PaneStatus::Error);
    }

    #[test]
    fn test_error_segfault() {
        let content = "Segmentation fault (core dumped)";
        assert_eq!(classify("myapp", Some(content), ""), PaneStatus::Error);
    }

    #[test]
    fn test_error_on_shell_pane() {
        let content = "$ cargo build\nerror[E0433]: failed to resolve";
        assert_eq!(classify("bash", Some(content), ""), PaneStatus::Error);
    }

    #[test]
    fn test_waiting_overrides_error() {
        let content = "error: build failed\nRetry? (Y/n)";
        assert_eq!(classify("bash", Some(content), ""), PaneStatus::Waiting);
    }

    #[test]
    fn test_no_false_positive_error() {
        let content = "Processing error-handling module...\nDone.";
        assert_eq!(classify("cargo", Some(content), ""), PaneStatus::Active);
    }

    // has_error_pattern() tests

    #[test]
    fn test_npm_error() {
        assert!(has_error_pattern("npm ERR! code ENOENT"));
    }

    #[test]
    fn test_command_not_found() {
        assert!(has_error_pattern("foobar: command not found"));
    }

    // PaneMonitor tests

    #[test]
    fn test_monitor_set_and_get() {
        let mut m = PaneMonitor::new();
        m.set("%0", "main", 0, PaneStatus::Active);
        assert_eq!(m.get_pane("%0"), PaneStatus::Active);
        assert_eq!(m.get_session("main"), PaneStatus::Active);
        assert_eq!(m.get_window("main", 0), PaneStatus::Active);
    }

    #[test]
    fn test_monitor_aggregation() {
        let mut m = PaneMonitor::new();
        m.set("%0", "dev", 0, PaneStatus::Idle);
        m.set("%1", "dev", 0, PaneStatus::Waiting);
        m.set("%2", "dev", 1, PaneStatus::Active);

        assert_eq!(m.get_session("dev"), PaneStatus::Waiting);
        assert_eq!(m.get_window("dev", 0), PaneStatus::Waiting);
        assert_eq!(m.get_window("dev", 1), PaneStatus::Active);
    }

    #[test]
    fn test_monitor_clear() {
        let mut m = PaneMonitor::new();
        m.set("%0", "main", 0, PaneStatus::Active);
        m.clear();
        assert_eq!(m.get_pane("%0"), PaneStatus::Unknown);
        assert_eq!(m.get_session("main"), PaneStatus::Unknown);
    }

    #[test]
    fn test_monitor_begin_update_resets() {
        let mut m = PaneMonitor::new();
        m.set("%0", "main", 0, PaneStatus::Active);
        m.begin_update();
        assert_eq!(m.get_pane("%0"), PaneStatus::Unknown);
    }

    // Claude Code detection tests (heuristic fallback, no hook files)

    #[test]
    fn test_claude_idle_prompt() {
        let content = "Done writing file.\n\n\n";
        assert_eq!(classify("claude", Some(content), ""), PaneStatus::Idle);
    }

    #[test]
    fn test_claude_idle_with_status_bar() {
        let content = "● Write(file.rs)\n\n\n\n  project (main) | Opus 4.6 (1M context)";
        assert_eq!(classify("claude", Some(content), ""), PaneStatus::Idle);
    }

    #[test]
    fn test_claude_active_no_prompt() {
        let content = "Compiling project...\nBuilding 42 crates\nRunning tests";
        assert_eq!(classify("claude", Some(content), ""), PaneStatus::Active);
    }

    #[test]
    fn test_claude_waiting_overrides_idle() {
        let content = "\nAllow Read access to /tmp/foo?";
        assert_eq!(classify("claude", Some(content), ""), PaneStatus::Waiting);
    }

    #[test]
    fn test_claude_error_overrides_idle() {
        let content = "\nerror: build failed";
        assert_eq!(classify("claude", Some(content), ""), PaneStatus::Error);
    }

    // Bug fix: stale ❯ prompt pushed past last 2 lines

    #[test]
    fn test_claude_active_stale_prompt() {
        let content = "\nproject (main) | Opus 4.6\n⏺ Read(src/main.rs)\nReading file...\nProcessing content";
        assert_eq!(classify("claude", Some(content), ""), PaneStatus::Active);
    }

    #[test]
    fn test_claude_active_tool_execution() {
        let content = "Some previous output\n⏺ Write(src/lib.rs)";
        assert_eq!(classify("claude", Some(content), ""), PaneStatus::Active);
    }

    #[test]
    fn test_claude_active_plan_agent_coalescing() {
        let content = "● Now let me launch the Plan agent to synthesize the audit findings.\n\n  Plan(Synthesize audit findings)\n   L Read(Project.toml)\n     +25 more tool uses\n\n* Coalescing… (5m 42s · ↓ 15.7k tokens · thinking)\n\n\n\nWhatsThePoint (main) | Opus 4.6 (1M context)\n  ■ plan mode on (shift+tab to cycle)";
        assert_eq!(classify("claude", Some(content), ""), PaneStatus::Active);
    }

    #[test]
    fn test_claude_no_content_is_active() {
        assert_eq!(classify("claude", None, ""), PaneStatus::Active);
    }

    #[test]
    fn test_claude_idle_prompt_only() {
        let content = "";
        assert_eq!(classify("claude", Some(content), ""), PaneStatus::Idle);
    }

    #[test]
    fn test_non_claude_unaffected_by_prompt_char() {
        let content = "❯ some output";
        assert_eq!(classify("vim", Some(content), ""), PaneStatus::Active);
        assert_eq!(classify("bash", Some(content), ""), PaneStatus::Idle);
    }

    // Hook-based detection tests

    #[test]
    fn test_hook_status_active() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("_99");
        fs::write(&path, "active").unwrap();

        let result = read_hook_status_from_path(&path);
        assert_eq!(result, Some(PaneStatus::Active));
    }

    #[test]
    fn test_hook_status_idle() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("_99");
        fs::write(&path, "idle").unwrap();

        let result = read_hook_status_from_path(&path);
        assert_eq!(result, Some(PaneStatus::Idle));
    }

    #[test]
    fn test_hook_status_waiting() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("_99");
        fs::write(&path, "waiting").unwrap();

        let result = read_hook_status_from_path(&path);
        assert_eq!(result, Some(PaneStatus::Waiting));
    }

    #[test]
    fn test_hook_status_unknown_content() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("_99");
        fs::write(&path, "garbage").unwrap();

        let result = read_hook_status_from_path(&path);
        assert_eq!(result, None);
    }

    #[test]
    fn test_hook_status_missing_file() {
        let result = read_hook_status("%nonexistent_test_pane", "claude");
        assert_eq!(result, None);
    }

    // Staleness policy tests (via resolve_hook_status)

    #[test]
    fn test_fresh_hook_always_trusted() {
        let fresh = Duration::from_secs(10);
        assert_eq!(resolve_hook_status("active", fresh, "bash"), Some(PaneStatus::Active));
        assert_eq!(resolve_hook_status("idle", fresh, "bash"), Some(PaneStatus::Idle));
        assert_eq!(resolve_hook_status("waiting", fresh, "bash"), Some(PaneStatus::Waiting));
    }

    #[test]
    fn test_stale_active_trusted_when_claude_running() {
        let stale = Duration::from_secs(300);
        assert_eq!(resolve_hook_status("active", stale, "claude"), Some(PaneStatus::Active));
    }

    #[test]
    fn test_stale_waiting_trusted_when_claude_running() {
        let stale = Duration::from_secs(300);
        assert_eq!(resolve_hook_status("waiting", stale, "claude"), Some(PaneStatus::Waiting));
    }

    #[test]
    fn test_stale_active_rejected_when_shell_running() {
        let stale = Duration::from_secs(300);
        assert_eq!(resolve_hook_status("active", stale, "bash"), None);
        assert_eq!(resolve_hook_status("active", stale, "zsh"), None);
    }

    #[test]
    fn test_stale_idle_always_rejected() {
        let stale = Duration::from_secs(300);
        assert_eq!(resolve_hook_status("idle", stale, "claude"), None);
        assert_eq!(resolve_hook_status("idle", stale, "bash"), None);
    }

    #[test]
    fn test_stale_unknown_content_rejected() {
        let stale = Duration::from_secs(300);
        assert_eq!(resolve_hook_status("garbage", stale, "claude"), None);
    }

    #[test]
    fn test_shell_command_with_fresh_hook_uses_hook_status() {
        // When Claude runs a Bash tool, pane_current_command becomes "bash".
        // Without a hook file this would be Idle; with a fresh hook saying
        // "active", classify() should return Active.
        let dir = tempfile::tempdir().unwrap();
        let pane_id = "%test_shell_hook";
        let sanitized = pane_id.replace('%', "_");
        let path = dir.path().join(&sanitized);
        fs::write(&path, "active").unwrap();

        // Use read_hook_status_from_path to verify the hook value,
        // since classify() uses the global HOOK_STATUS_DIR.
        let hook = read_hook_status_from_path(&path);
        assert_eq!(hook, Some(PaneStatus::Active));

        // Without hooks, a shell command would be Idle.
        assert_eq!(classify("bash", None, "%nonexistent"), PaneStatus::Idle);
    }

    // Working indicator tests

    #[test]
    fn test_working_indicator_tool_marker() {
        assert!(has_claude_working_indicators("output\n⏺ Edit(file.rs)"));
    }

    #[test]
    fn test_working_indicator_spinner() {
        assert!(has_claude_working_indicators("output\n⠋ Processing..."));
    }

    #[test]
    fn test_working_indicator_agent_asterisk() {
        assert!(has_claude_working_indicators("Plan(Synthesize audit findings)\n* Coalescing… (5m 42s · ↓ 15.7k tokens · thinking)"));
    }

    #[test]
    fn test_working_indicator_thinking_status() {
        assert!(has_claude_working_indicators("output\n⠋ 2m 30s · thinking"));
    }

    #[test]
    fn test_working_indicator_coalescing() {
        assert!(has_claude_working_indicators("output\nCoalescing… (3m 12s)"));
    }

    #[test]
    fn test_no_working_indicator() {
        assert!(!has_claude_working_indicators("just regular output\nmore text"));
    }

    // Strict idle tests

    #[test]
    fn test_strict_idle_prompt_on_last_line() {
        assert!(is_claude_idle_strict("output\n"));
    }

    #[test]
    fn test_strict_idle_multi_line_status_bar() {
        // Claude with 3-line status bar below the prompt
        let content = "previous output\n\n  project (main) | Opus 4.6 (1M context)\n  cost: $0.05\n  auto mode";
        assert!(is_claude_idle_strict(content));
    }

    #[test]
    fn test_strict_idle_prompt_too_far_up() {
        assert!(!is_claude_idle_strict("\nline2\nline3\nline4\nline5"));
    }
}