workmux 0.1.163

An opinionated workflow tool that orchestrates git worktrees and tmux
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
//! Sidebar daemon: single process that polls tmux and pushes snapshots to clients.

use anyhow::Result;
use notify::{RecursiveMode, Watcher};
use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use crate::cmd::Cmd;
use crate::config::Config;
use crate::git::GitStatus;
use crate::multiplexer::{Multiplexer, create_backend, detect_backend};
use crate::state::StateStore;

use super::app::SidebarLayoutMode;
use super::snapshot::build_snapshot;

/// Compute socket path from instance_id.
pub fn socket_path(instance_id: &str) -> PathBuf {
    let safe_id = instance_id.replace(['/', '\\'], "-");
    std::env::temp_dir().join(format!("workmux-sidebar-{}.sock", safe_id))
}

/// Result of a batched tmux query.
struct TmuxState {
    window_statuses: HashMap<String, Option<String>>,
    active_windows: HashSet<(String, String)>,
    pane_window_ids: HashMap<String, String>,
    active_pane_ids: HashSet<String>,
    window_pane_counts: HashMap<String, usize>,
}

/// Query all sidebar-relevant tmux state in a single command.
fn query_tmux_state() -> TmuxState {
    let format = "#{pane_id}\t#{session_name}\t#{window_id}\t#{@workmux_pane_status}\t#{window_active}\t#{session_attached}\t#{pane_active}";
    let output = Cmd::new("tmux")
        .args(&["list-panes", "-a", "-F", format])
        .run_and_capture_stdout()
        .unwrap_or_default();

    let mut window_statuses = HashMap::new();
    let mut active_windows = HashSet::new();
    let mut pane_window_ids = HashMap::new();
    let mut active_pane_ids = HashSet::new();
    let mut window_pane_counts: HashMap<String, usize> = HashMap::new();

    for line in output.lines() {
        let mut parts = line.split('\t');
        let (
            Some(pane_id),
            Some(session),
            Some(window_id),
            Some(status),
            Some(win_active),
            Some(sess_attached),
            Some(pane_active),
        ) = (
            parts.next(),
            parts.next(),
            parts.next(),
            parts.next(),
            parts.next(),
            parts.next(),
            parts.next(),
        )
        else {
            continue;
        };
        let win_active = win_active == "1";
        let sess_attached = sess_attached == "1";
        let pane_active = pane_active == "1";

        let status_val = if status.is_empty() {
            None
        } else {
            Some(status.to_string())
        };
        window_statuses.insert(pane_id.to_string(), status_val);
        pane_window_ids.insert(pane_id.to_string(), window_id.to_string());
        *window_pane_counts.entry(window_id.to_string()).or_default() += 1;

        if win_active && sess_attached {
            active_windows.insert((session.to_string(), window_id.to_string()));
        }
        if pane_active {
            active_pane_ids.insert(pane_id.to_string());
        }
    }

    TmuxState {
        window_statuses,
        active_windows,
        pane_window_ids,
        active_pane_ids,
        window_pane_counts,
    }
}

/// Unix socket server for broadcasting snapshots to clients.
struct SocketServer {
    clients: Arc<Mutex<Vec<UnixStream>>>,
}

impl SocketServer {
    fn bind(path: &Path, dirty_flag: Arc<AtomicBool>) -> std::io::Result<Self> {
        let listener = UnixListener::bind(path)?;
        // Restrict socket to owner only (prevent other local users from reading snapshots)
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
        listener.set_nonblocking(true)?;
        let clients: Arc<Mutex<Vec<UnixStream>>> = Arc::new(Mutex::new(Vec::new()));
        let clients_clone = clients.clone();

        thread::spawn(move || {
            loop {
                match listener.accept() {
                    Ok((stream, _)) => {
                        // 1ms write timeout: local Unix sockets shouldn't block
                        let _ = stream.set_write_timeout(Some(Duration::from_millis(1)));
                        clients_clone.lock().unwrap().push(stream);
                        // Trigger an immediate broadcast so the new client gets
                        // the current snapshot without waiting for the next timer.
                        dirty_flag.store(true, Ordering::Relaxed);
                    }
                    Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                        thread::sleep(Duration::from_millis(50));
                    }
                    Err(_) => break,
                }
            }
        });

        Ok(Self { clients })
    }

    fn broadcast(&self, snapshot: &super::snapshot::SidebarSnapshot) {
        let data = serde_json::to_vec(snapshot).unwrap_or_default();
        let len = (data.len() as u32).to_be_bytes();

        // Take clients out of mutex to avoid holding lock during writes
        let mut clients = std::mem::take(&mut *self.clients.lock().unwrap());
        clients
            .retain_mut(|stream| stream.write_all(&len).is_ok() && stream.write_all(&data).is_ok());
        // Merge surviving clients back (append to preserve any new connections accepted during writes)
        self.clients.lock().unwrap().append(&mut clients);
    }

    fn client_count(&self) -> usize {
        self.clients.lock().unwrap().len()
    }
}

/// Read the sidebar layout mode from tmux global, falling back to settings.json, then config.
fn read_sidebar_layout_mode(config: &Config) -> Option<SidebarLayoutMode> {
    // Check tmux global first (set by toggle_layout_mode during this session)
    if let Ok(output) = Cmd::new("tmux")
        .args(&["show-option", "-gqv", "@workmux_sidebar_layout"])
        .run_and_capture_stdout()
    {
        match output.trim() {
            "tiles" => return Some(SidebarLayoutMode::Tiles),
            "compact" => return Some(SidebarLayoutMode::Compact),
            _ => {}
        }
    }

    // Fall back to persisted setting (user toggled layout in a previous tmux session)
    if let Ok(store) = StateStore::new()
        && let Ok(settings) = store.load_settings()
    {
        match settings.sidebar_layout.as_deref() {
            Some("tiles") => return Some(SidebarLayoutMode::Tiles),
            Some("compact") => return Some(SidebarLayoutMode::Compact),
            _ => {}
        }
    }

    // Fall back to config file
    match config.sidebar.layout.as_deref() {
        Some("tiles") => return Some(SidebarLayoutMode::Tiles),
        Some("compact") => return Some(SidebarLayoutMode::Compact),
        _ => {}
    }

    None
}

/// Shared git status cache, updated by a background worker thread.
type GitCache = Arc<Mutex<HashMap<PathBuf, GitStatus>>>;

/// Resolve the .git directory for a worktree path.
/// For linked worktrees, .git is a file containing "gitdir: /path/to/real/gitdir".
fn resolve_git_dir(worktree_path: &Path) -> Option<PathBuf> {
    let dot_git = worktree_path.join(".git");
    if dot_git.is_dir() {
        return Some(dot_git);
    }
    if dot_git.is_file() {
        // Linked worktree: read the gitdir pointer
        let content = std::fs::read_to_string(&dot_git).ok()?;
        let gitdir = content.strip_prefix("gitdir: ")?.trim();
        let path = PathBuf::from(gitdir);
        if path.is_absolute() {
            return Some(path);
        }
        // Relative path: resolve relative to worktree
        Some(worktree_path.join(path))
    } else {
        None
    }
}

/// Resolve the common git directory for linked worktrees.
/// Returns None for normal (non-linked) worktrees.
fn resolve_common_git_dir(gitdir: &Path) -> Option<PathBuf> {
    let content = std::fs::read_to_string(gitdir.join("commondir")).ok()?;
    let rel = content.trim();
    let path = if Path::new(rel).is_absolute() {
        PathBuf::from(rel)
    } else {
        gitdir.join(rel)
    };
    path.canonicalize().ok().or(Some(path))
}

/// Compare two GitStatus values ignoring the cached_at timestamp.
fn git_status_semantically_equal(a: &GitStatus, b: &GitStatus) -> bool {
    a.ahead == b.ahead
        && a.behind == b.behind
        && a.has_conflict == b.has_conflict
        && a.is_dirty == b.is_dirty
        && a.lines_added == b.lines_added
        && a.lines_removed == b.lines_removed
        && a.uncommitted_added == b.uncommitted_added
        && a.uncommitted_removed == b.uncommitted_removed
        && a.base_branch == b.base_branch
        && a.branch == b.branch
        && a.has_upstream == b.has_upstream
}

/// Find which worktrees are affected by a filesystem event at the given path.
fn find_worktrees_for_path(
    event_path: &Path,
    watch_to_worktrees: &HashMap<PathBuf, HashSet<PathBuf>>,
) -> Vec<PathBuf> {
    let mut result = Vec::new();
    for (watched_dir, worktrees) in watch_to_worktrees {
        if event_path.starts_with(watched_dir) {
            result.extend(worktrees.iter().cloned());
        }
    }
    result
}

/// Register a watch path and associate it with a worktree.
/// If the path is already watched by another worktree, just adds the mapping.
/// Only records the mapping after the OS watch succeeds (or was already active).
fn add_watch(
    watcher: &mut notify::RecommendedWatcher,
    path: &Path,
    mode: RecursiveMode,
    worktree: &Path,
    watch_to_worktrees: &mut HashMap<PathBuf, HashSet<PathBuf>>,
    watched_for_worktree: &mut Vec<PathBuf>,
) {
    let already_watching = watch_to_worktrees.get(path).is_some_and(|s| !s.is_empty());

    if !already_watching && let Err(e) = watcher.watch(path, mode) {
        tracing::warn!("failed to watch {}: {}", path.display(), e);
        return;
    }

    watch_to_worktrees
        .entry(path.to_path_buf())
        .or_default()
        .insert(worktree.to_path_buf());
    watched_for_worktree.push(path.to_path_buf());
}

/// Remove watch association for a worktree. Unwatches the path if no other worktree needs it.
fn remove_worktree_watch(
    watcher: &mut notify::RecommendedWatcher,
    watch_path: &Path,
    worktree: &Path,
    watch_to_worktrees: &mut HashMap<PathBuf, HashSet<PathBuf>>,
) {
    if let Some(worktrees) = watch_to_worktrees.get_mut(watch_path) {
        worktrees.remove(worktree);
        if worktrees.is_empty() {
            watch_to_worktrees.remove(watch_path);
            let _ = watcher.unwatch(watch_path);
        }
    }
}

/// Set up filesystem watches for a worktree.
fn setup_worktree_watches(
    watcher: &mut notify::RecommendedWatcher,
    worktree: &Path,
    watch_to_worktrees: &mut HashMap<PathBuf, HashSet<PathBuf>>,
) -> Vec<PathBuf> {
    let mut watched = Vec::new();
    let dot_git = worktree.join(".git");
    let is_linked = dot_git.is_file();

    if is_linked {
        // Linked worktree: gitdir is outside the worktree root
        if let Some(git_dir) = resolve_git_dir(worktree) {
            // Watch per-worktree gitdir (HEAD, index)
            add_watch(
                watcher,
                &git_dir,
                RecursiveMode::Recursive,
                worktree,
                watch_to_worktrees,
                &mut watched,
            );

            // Watch common dir's refs/ for shared branch updates
            if let Some(common_dir) = resolve_common_git_dir(&git_dir) {
                let refs_dir = common_dir.join("refs");
                if refs_dir.is_dir() {
                    add_watch(
                        watcher,
                        &refs_dir,
                        RecursiveMode::Recursive,
                        worktree,
                        watch_to_worktrees,
                        &mut watched,
                    );
                }
                // Watch common dir non-recursively for packed-refs
                add_watch(
                    watcher,
                    &common_dir,
                    RecursiveMode::NonRecursive,
                    worktree,
                    watch_to_worktrees,
                    &mut watched,
                );
            }
        }
        // Watch worktree root for file edits
        add_watch(
            watcher,
            worktree,
            RecursiveMode::Recursive,
            worktree,
            watch_to_worktrees,
            &mut watched,
        );
    } else {
        // Normal worktree: .git/ is inside, single recursive watch covers everything
        add_watch(
            watcher,
            worktree,
            RecursiveMode::Recursive,
            worktree,
            watch_to_worktrees,
            &mut watched,
        );
    }

    watched
}

/// Calculate the next timeout for the worker's recv_timeout.
/// Returns the shortest wait until either a debounced worktree is ready,
/// the full sweep is due, or a 1s cap for checking the term flag.
fn next_worker_timeout(
    pending: &HashMap<PathBuf, Instant>,
    debounce: Duration,
    last_sweep: Instant,
    sweep_interval: Duration,
) -> Duration {
    let now = Instant::now();
    let sweep_wait = sweep_interval.saturating_sub(last_sweep.elapsed());
    let mut min_wait = sweep_wait;

    for last_event in pending.values() {
        let ready_at = *last_event + debounce;
        if ready_at <= now {
            return Duration::from_millis(1);
        }
        let wait = ready_at - now;
        if wait < min_wait {
            min_wait = wait;
        }
    }

    // Cap at 1s to check term flag periodically
    min_wait.min(Duration::from_secs(1))
}

/// Refresh git status for a worktree path, updating the cache.
/// Returns true if the status actually changed (semantically, ignoring cached_at).
fn refresh_git_status(path: &Path, cache: &GitCache) -> bool {
    let new_status = crate::git::get_git_status(path, None);
    let changed = cache
        .lock()
        .ok()
        .map(|c| {
            c.get(path)
                .is_none_or(|old| !git_status_semantically_equal(old, &new_status))
        })
        .unwrap_or(true);
    if let Ok(mut c) = cache.lock() {
        c.insert(path.to_path_buf(), new_status);
    }
    changed
}

/// Info about an active agent path sent to the git worker.
struct GitWorkerPath {
    path: PathBuf,
    /// Whether this agent is stale (idle > threshold). Stale agents only
    /// get git status on the full sweep, not on every poll cycle.
    is_stale: bool,
}

/// Spawn a background thread that watches for git changes and updates the cache.
///
/// Uses the `notify` crate for OS-level filesystem event detection (FSEvents on macOS).
/// Watches .git internals and worktree roots for each active worktree. Events are
/// debounced per-worktree (300ms) before triggering `get_git_status()`. A fallback
/// sweep runs every 30s for edge cases where the watcher might miss events.
fn spawn_git_worker(
    term: Arc<AtomicBool>,
    dirty_flag: Arc<AtomicBool>,
) -> (GitCache, std::sync::mpsc::Sender<Vec<GitWorkerPath>>) {
    let cache: GitCache = Arc::new(Mutex::new(HashMap::new()));
    let cache_clone = cache.clone();
    let (tx, rx) = std::sync::mpsc::channel::<Vec<GitWorkerPath>>();

    thread::spawn(move || {
        // Filesystem event channel for notify
        let (fs_tx, fs_rx) = std::sync::mpsc::channel();
        let mut watcher: Option<notify::RecommendedWatcher> =
            match notify::RecommendedWatcher::new(fs_tx, notify::Config::default()) {
                Ok(w) => Some(w),
                Err(e) => {
                    tracing::warn!(
                        "filesystem watcher unavailable, falling back to polling: {}",
                        e
                    );
                    None
                }
            };

        let mut active_entries: Vec<GitWorkerPath> = Vec::new();
        // Maps: watched directory -> set of worktrees it covers
        let mut watch_to_worktrees: HashMap<PathBuf, HashSet<PathBuf>> = HashMap::new();
        // Maps: worktree path -> list of watched paths for it
        let mut worktree_watches: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
        // Per-worktree: timestamp of last fs event (for debouncing)
        let mut pending_worktrees: HashMap<PathBuf, Instant> = HashMap::new();
        // Stale status per path (true = all agents at path are stale)
        let mut path_stale: HashMap<PathBuf, bool> = HashMap::new();
        // Track unique active paths for fallback polling
        let mut unique_active: Vec<PathBuf> = Vec::new();
        let mut last_full_sweep = Instant::now();
        // Watcher mode: 30s fallback sweep. Poll-only mode: 2s sweep interval.
        let full_sweep_interval = if watcher.is_some() {
            Duration::from_secs(30)
        } else {
            Duration::from_secs(2)
        };
        let debounce_duration = Duration::from_millis(300);

        while !term.load(Ordering::Relaxed) {
            // Block on filesystem events (zero CPU when idle), or sleep briefly in poll mode
            if watcher.is_some() {
                let timeout = next_worker_timeout(
                    &pending_worktrees,
                    debounce_duration,
                    last_full_sweep,
                    full_sweep_interval,
                );
                match fs_rx.recv_timeout(timeout) {
                    Ok(Ok(event)) => {
                        for path in &event.paths {
                            for wt in find_worktrees_for_path(path, &watch_to_worktrees) {
                                pending_worktrees
                                    .entry(wt)
                                    .and_modify(|t| *t = Instant::now())
                                    .or_insert_with(Instant::now);
                            }
                        }
                    }
                    Ok(Err(e)) => {
                        tracing::warn!("filesystem watch error: {}", e);
                    }
                    Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
                    Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
                }

                // Drain any additional buffered events
                while let Ok(event_result) = fs_rx.try_recv() {
                    if let Ok(event) = event_result {
                        for path in &event.paths {
                            for wt in find_worktrees_for_path(path, &watch_to_worktrees) {
                                pending_worktrees
                                    .entry(wt)
                                    .and_modify(|t| *t = Instant::now())
                                    .or_insert_with(Instant::now);
                            }
                        }
                    }
                }
            } else {
                // Poll-only fallback: sleep until next sweep check
                let sleep = full_sweep_interval
                    .saturating_sub(last_full_sweep.elapsed())
                    .min(Duration::from_secs(1));
                thread::sleep(sleep);
            }

            // Check for path updates (non-blocking)
            let mut paths_changed = false;
            while let Ok(entries) = rx.try_recv() {
                active_entries = entries;
                paths_changed = true;
            }

            if paths_changed {
                // Deduplicate paths. A path is stale only if ALL agents at that path are stale.
                path_stale.clear();
                for entry in &active_entries {
                    let e = path_stale.entry(entry.path.clone()).or_insert(true);
                    if !entry.is_stale {
                        *e = false;
                    }
                }
                unique_active = path_stale.keys().cloned().collect();
                unique_active.sort();
                let unique_set: HashSet<PathBuf> = unique_active.iter().cloned().collect();

                if let Some(ref mut w) = watcher {
                    // Remove watches for worktrees no longer active
                    let removed: Vec<PathBuf> = worktree_watches
                        .keys()
                        .filter(|p| !unique_set.contains(*p))
                        .cloned()
                        .collect();
                    for path in &removed {
                        if let Some(watched_paths) = worktree_watches.remove(path) {
                            for wp in &watched_paths {
                                remove_worktree_watch(w, wp, path, &mut watch_to_worktrees);
                            }
                        }
                        pending_worktrees.remove(path);
                    }

                    // Add watches for new worktrees
                    for path in &unique_active {
                        if worktree_watches.contains_key(path) {
                            continue;
                        }
                        let watched = setup_worktree_watches(w, path, &mut watch_to_worktrees);
                        worktree_watches.insert(path.clone(), watched);
                        // Trigger immediate status fetch for new worktrees
                        pending_worktrees.insert(path.clone(), Instant::now() - debounce_duration);
                    }

                    // Prune cache for removed worktrees
                    if !removed.is_empty() {
                        if let Ok(mut c) = cache_clone.lock() {
                            c.retain(|p, _| unique_set.contains(p));
                        }
                        dirty_flag.store(true, Ordering::Relaxed);
                    }
                } else {
                    // Poll-only mode: just prune cache, no watches to manage
                    if let Ok(mut c) = cache_clone.lock() {
                        let before = c.len();
                        c.retain(|p, _| unique_set.contains(p));
                        if c.len() != before {
                            dirty_flag.store(true, Ordering::Relaxed);
                        }
                    }
                    // Trigger immediate fetch for new paths
                    for path in &unique_active {
                        if !cache_clone
                            .lock()
                            .ok()
                            .is_some_and(|c| c.contains_key(path))
                        {
                            pending_worktrees
                                .insert(path.clone(), Instant::now() - debounce_duration);
                        }
                    }
                }
            }

            // Process debounce-ready worktrees (skip stale ones, they only refresh on sweep)
            let now = Instant::now();
            let ready: Vec<PathBuf> = pending_worktrees
                .iter()
                .filter(|(_, last_event)| now.duration_since(**last_event) >= debounce_duration)
                .map(|(path, _)| path.clone())
                .collect();

            let mut any_changed = false;
            for path in &ready {
                pending_worktrees.remove(path);
                let is_stale = path_stale.get(path).copied().unwrap_or(false);
                if is_stale {
                    continue;
                }
                if refresh_git_status(path, &cache_clone) {
                    any_changed = true;
                }
            }

            // Fallback full sweep (30s with watcher, 2s without; includes stale worktrees)
            if last_full_sweep.elapsed() >= full_sweep_interval {
                last_full_sweep = Instant::now();
                let sweep_paths: Vec<PathBuf> = if watcher.is_some() {
                    worktree_watches.keys().cloned().collect()
                } else {
                    unique_active.clone()
                };
                for path in &sweep_paths {
                    if pending_worktrees.contains_key(path) {
                        continue;
                    }
                    if refresh_git_status(path, &cache_clone) {
                        any_changed = true;
                    }
                }
            }

            if any_changed {
                dirty_flag.store(true, Ordering::Relaxed);
            }
        }
    });

    (cache, tx)
}

/// Tracks pane content hashes to detect agents that stopped producing output.
///
/// For each agent in `Working` status, captures the last few lines of the pane,
/// hashes them, and records when the hash was first seen unchanged. If the hash
/// stays the same for longer than the timeout, the agent is considered interrupted.
///
/// Once interrupted, the state is sticky: it only clears when the agent's state
/// is updated via RPC (detected by `updated_ts` changing) or when the agent
/// leaves Working status. Pane content changes (cursor movement, typing) do not
/// clear the interrupted state.
struct InactivityTracker {
    /// pane_id -> (content_hash, first_seen_at)
    entries: HashMap<String, (u64, Instant)>,
    /// pane_id -> (updated_ts at confirmation, unix timestamp when confirmed).
    /// Cleared when updated_ts changes (agent sent a new RPC status update).
    confirmed: HashMap<String, (u64, u64)>,
    /// How long content must be unchanged before marking as interrupted.
    timeout: Duration,
}

impl InactivityTracker {
    fn new(timeout: Duration) -> Self {
        Self {
            entries: HashMap::new(),
            confirmed: HashMap::new(),
            timeout,
        }
    }

    /// Check all working agents for inactivity.
    ///
    /// Returns `(interrupted, resumed)` where:
    /// - `interrupted`: map of pane IDs to unix timestamp when interruption was confirmed
    /// - `resumed`: pane IDs that just cleared from interrupted (agent sent new RPC)
    fn check(
        &mut self,
        agents: &[crate::multiplexer::AgentPane],
        mux: &dyn crate::multiplexer::Multiplexer,
    ) -> (HashMap<String, u64>, Vec<String>) {
        use std::hash::{Hash, Hasher};

        let now = Instant::now();

        // Build lookup of working agents
        let working: HashMap<&str, &crate::multiplexer::AgentPane> = agents
            .iter()
            .filter(|a| a.status == Some(crate::multiplexer::AgentStatus::Working))
            .map(|a| (a.pane_id.as_str(), a))
            .collect();

        // Remove entries for agents no longer in Working status
        self.entries
            .retain(|id, _| working.contains_key(id.as_str()));
        self.confirmed
            .retain(|id, _| working.contains_key(id.as_str()));

        // Clear interrupted state if the agent's state was updated via RPC
        // (updated_ts changed since we confirmed the interruption).
        // Track which agents just resumed so we can reset their status_ts.
        let mut resumed = Vec::new();
        let prev_confirmed: HashSet<String> = self.confirmed.keys().cloned().collect();
        self.confirmed.retain(|id, (confirmed_ts, _)| {
            if let Some(agent) = working.get(id.as_str()) {
                agent.updated_ts.unwrap_or(0) <= *confirmed_ts
            } else {
                false
            }
        });
        for id in &prev_confirmed {
            if !self.confirmed.contains_key(id) {
                resumed.push(id.clone());
            }
        }

        for (pane_id, agent) in &working {
            // Already confirmed interrupted - skip capture
            if self.confirmed.contains_key(*pane_id) {
                continue;
            }

            let Some(raw) = mux.capture_pane(pane_id, 5) else {
                continue;
            };

            // Strip ANSI escapes and normalize whitespace for stable hashing
            let stripped = console::strip_ansi_codes(&raw);
            let normalized = stripped.trim();

            let mut hasher = std::hash::DefaultHasher::new();
            normalized.hash(&mut hasher);
            let hash = hasher.finish();

            match self.entries.get(*pane_id) {
                Some(&(prev_hash, first_seen)) if prev_hash == hash => {
                    if now.duration_since(first_seen) >= self.timeout {
                        // Record the agent's updated_ts and current wall-clock time
                        let agent_ts = agent.updated_ts.unwrap_or(0);
                        let now_ts = SystemTime::now()
                            .duration_since(UNIX_EPOCH)
                            .unwrap_or_default()
                            .as_secs();
                        self.confirmed
                            .insert(pane_id.to_string(), (agent_ts, now_ts));
                    }
                }
                _ => {
                    self.entries.insert(pane_id.to_string(), (hash, now));
                }
            }
        }

        let interrupted = self
            .confirmed
            .iter()
            .map(|(k, (_, ts))| (k.clone(), *ts))
            .collect();
        (interrupted, resumed)
    }
}

/// Run the sidebar daemon (headless, no TUI).
pub fn run() -> Result<()> {
    let mux = create_backend(detect_backend());
    let instance_id = mux.instance_id();
    let config = Config::load(None)?;
    let status_icons = config.status_icons.clone();

    // Signal handlers for clean shutdown and dirty notification
    let term = Arc::new(AtomicBool::new(false));
    let dirty_flag = Arc::new(AtomicBool::new(false));
    signal_hook::flag::register(signal_hook::consts::SIGTERM, term.clone())?;
    signal_hook::flag::register(signal_hook::consts::SIGUSR1, dirty_flag.clone())?;

    let sock_path = socket_path(&instance_id);
    let _ = std::fs::remove_file(&sock_path); // Clean stale
    let server = SocketServer::bind(&sock_path, dirty_flag.clone())?;

    // Background git status worker (shares dirty_flag for immediate broadcast on changes)
    let (git_cache, git_path_tx) = spawn_git_worker(term.clone(), dirty_flag.clone());

    // Store PID so toggle-off can kill us and hooks can signal us
    Cmd::new("tmux")
        .args(&[
            "set-option",
            "-g",
            "@workmux_sidebar_daemon_pid",
            &std::process::id().to_string(),
        ])
        .run()?;

    let mut inactivity_tracker = InactivityTracker::new(Duration::from_secs(10));
    let mut last_interrupted: HashMap<String, u64> = HashMap::new();
    let mut last_runtime_write = Instant::now();
    let backend_name = mux.name().to_string();

    let mut last_refresh = Instant::now();
    let mut last_client_seen = Instant::now();
    let mut dirty_pending = false;
    let mut last_agent_list = String::new();
    let refresh_interval = Duration::from_secs(2);
    let debounce_interval = Duration::from_millis(50);

    while !term.load(Ordering::Relaxed) {
        // Coalesce dirty signals: SIGUSR1 sets the flag, we service it once
        // per debounce interval to prevent signal floods from causing CPU storms
        if dirty_flag.swap(false, Ordering::Relaxed) {
            dirty_pending = true;
        }

        let time_since_refresh = last_refresh.elapsed();
        let debounce_cleared = dirty_pending && time_since_refresh >= debounce_interval;
        let timer_expired = time_since_refresh >= refresh_interval;

        if debounce_cleared || timer_expired {
            dirty_pending = false;
            last_refresh = Instant::now();

            if let Some(mut snapshot) = try_build_snapshot(&mux, &status_icons, &config, &git_cache)
            {
                // Detect interrupted agents (working but no pane output change)
                let (interrupted, resumed) =
                    inactivity_tracker.check(&snapshot.agents, mux.as_ref());
                snapshot.interrupted_pane_ids = interrupted.clone();

                // Reset status_ts for agents that just resumed from interruption
                // so their timer starts fresh from the new work phase.
                if !resumed.is_empty()
                    && let Ok(store) = StateStore::new()
                {
                    let now_ts = SystemTime::now()
                        .duration_since(UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_secs();
                    for pane_id in &resumed {
                        let pane_key = crate::state::PaneKey {
                            backend: backend_name.clone(),
                            instance: instance_id.clone(),
                            pane_id: pane_id.clone(),
                        };
                        if let Ok(Some(mut state)) = store.get_agent(&pane_key) {
                            state.status_ts = Some(now_ts);
                            let _ = store.upsert_agent(&state);
                        }
                    }
                }

                // Persist to runtime file so dashboard can read it.
                // Write on change, or periodically to keep updated_ts fresh
                // (dashboard ignores files older than 15s).
                let set_changed = interrupted != last_interrupted;
                let heartbeat_due = last_runtime_write.elapsed() >= Duration::from_secs(10);
                if set_changed || heartbeat_due {
                    last_interrupted = interrupted;
                    last_runtime_write = Instant::now();
                    if let Ok(store) = StateStore::new() {
                        let now_ts = SystemTime::now()
                            .duration_since(UNIX_EPOCH)
                            .unwrap_or_default()
                            .as_secs();
                        let runtime = crate::state::RuntimeState {
                            interrupted_pane_ids: last_interrupted.clone(),
                            updated_ts: now_ts,
                        };
                        let _ = store.write_runtime(&backend_name, &instance_id, &runtime);
                    }
                }

                // Update git worker with current agent paths and stale status.
                // Stale agents (idle > 1 hour) are polled less frequently.
                let now_secs = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs();
                let stale_threshold = 60 * 60; // 1 hour, matches sidebar UI
                let entries: Vec<GitWorkerPath> = snapshot
                    .agents
                    .iter()
                    .map(|a| GitWorkerPath {
                        path: a.path.clone(),
                        is_stale: a
                            .status_ts
                            .map(|ts| now_secs.saturating_sub(ts) > stale_threshold)
                            .unwrap_or(false),
                    })
                    .collect();
                let _ = git_path_tx.send(entries);

                server.broadcast(&snapshot);

                let agent_list: String = snapshot
                    .agents
                    .iter()
                    .map(|a| a.pane_id.as_str())
                    .collect::<Vec<_>>()
                    .join(" ");

                if agent_list != last_agent_list {
                    if !agent_list.is_empty() {
                        let _ = Cmd::new("tmux")
                            .args(&["set-option", "-g", "@workmux_sidebar_agents", &agent_list])
                            .run();
                    } else {
                        let _ = Cmd::new("tmux")
                            .args(&["set-option", "-gu", "@workmux_sidebar_agents"])
                            .run();
                    }
                    last_agent_list = agent_list;
                }
            }
        }

        // Track client activity for auto-exit
        if server.client_count() > 0 {
            last_client_seen = Instant::now();
        } else if last_client_seen.elapsed() > Duration::from_secs(10) {
            break;
        }

        // Always sleep to prevent CPU spinning (never skip on dirty)
        thread::sleep(Duration::from_millis(10));
    }

    // Cleanup
    let _ = std::fs::remove_file(&sock_path);
    if let Ok(store) = StateStore::new() {
        store.delete_runtime(&backend_name, &instance_id);
    }
    let _ = Cmd::new("tmux")
        .args(&["set-option", "-gu", "@workmux_sidebar_daemon_pid"])
        .run();
    let _ = Cmd::new("tmux")
        .args(&["set-option", "-gu", "@workmux_sidebar_agents"])
        .run();
    Ok(())
}

/// Try to build a snapshot. Returns None on transient failures.
fn try_build_snapshot(
    mux: &Arc<dyn Multiplexer>,
    status_icons: &crate::config::StatusIcons,
    config: &Config,
    git_cache: &GitCache,
) -> Option<super::snapshot::SidebarSnapshot> {
    let tmux_state = query_tmux_state();
    let agents = StateStore::new()
        .and_then(|store| store.load_reconciled_agents(mux.as_ref()))
        .ok()?;
    let layout_mode = read_sidebar_layout_mode(config).unwrap_or_default();

    let git_statuses = git_cache.lock().ok().map(|c| c.clone()).unwrap_or_default();

    Some(build_snapshot(
        agents,
        &tmux_state.window_statuses,
        &tmux_state.pane_window_ids,
        tmux_state.active_windows,
        tmux_state.active_pane_ids,
        tmux_state.window_pane_counts,
        layout_mode,
        status_icons,
        git_statuses,
    ))
}