wsx-core 0.16.2

Library crate for wsx: worktree, tmux, git, hooks, config, model primitives. Ratatui-free; consumable by wsx binary and external orchestrators (e.g. auwsx).
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
// Workspace operation functions — pure business logic, no App state.
// These take explicit arguments rather than &mut App so they can be
// tested and reasoned about independently of the TUI state machine.

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use anyhow::{bail, Result};

use crate::{
    cache::SessionSnapshot,
    config::global::GlobalConfig,
    git::{info as git_info, worktree as git_worktree},
    hooks,
    model::workspace::{
        session_display_name_from_tmux, FetchFailReason, ForegroundKind, GitInfo, Project,
        ProjectConfig, SessionInfo, WorkspaceState, WorktreeInfo,
    },
    tmux::{monitor::SessionStatus, session},
};

// (pane_capture, muted)
type PaneSnap = HashMap<String, (Option<String>, bool)>;
// session_order preserves user-defined sort across refresh
type WorktreeSnap = HashMap<PathBuf, WorktreeSnapEntry>;

struct WorktreeSnapEntry {
    git_info: Option<GitInfo>,
    git_info_fetched_at: Option<Instant>,
    expanded: bool,
    panes: PaneSnap,
    session_order: Vec<String>,
    last_fetched: Option<Instant>,
    fetch_failed: bool,
    fetch_fail_count: u32,
    fetch_fail_reason: Option<FetchFailReason>,
}

pub const IDLE_SECS: u64 = 3;

fn is_git_repo(path: &std::path::Path) -> bool {
    path.exists() && path.join(".git").exists()
}

// ── Refresh helpers ───────────────────────────────────────────────────────────

fn unix_ts_to_instant(unix_ts: u64) -> Option<Instant> {
    let now_unix = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let secs_ago = now_unix.saturating_sub(unix_ts);
    Instant::now().checked_sub(Duration::from_secs(secs_ago))
}

/// Rebuild all worktrees + sessions for every project from live data.
/// Calls `list_worktrees` per project synchronously — use for user-triggered refreshes.
pub fn refresh_workspace(
    workspace: &mut WorkspaceState,
    config: &GlobalConfig,
    sessions_with_paths: &[(String, PathBuf)],
    activity: &HashMap<String, SessionStatus>,
) {
    let worktrees: Vec<(PathBuf, Vec<git_worktree::WorktreeEntry>)> = workspace
        .projects
        .iter()
        .map(|p| {
            let entries = git_worktree::list_worktrees(&p.path).unwrap_or_default();
            (p.path.clone(), entries)
        })
        .collect();
    refresh_workspace_with_worktrees(workspace, config, sessions_with_paths, activity, worktrees);
}

/// Like `refresh_workspace` but with pre-computed worktree entries — avoids subprocess calls
/// on the caller's thread. Used by the periodic background refresh path.
pub fn refresh_workspace_with_worktrees(
    workspace: &mut WorkspaceState,
    config: &GlobalConfig,
    sessions_with_paths: &[(String, PathBuf)],
    activity: &HashMap<String, SessionStatus>,
    worktrees: Vec<(PathBuf, Vec<git_worktree::WorktreeEntry>)>,
) {
    // Pre-index sessions by worktree path for O(1) lookup per worktree
    let mut sessions_by_path: HashMap<&PathBuf, Vec<&str>> = HashMap::new();
    for (name, path) in sessions_with_paths {
        sessions_by_path
            .entry(path)
            .or_default()
            .push(name.as_str());
    }

    let aliases_by_path: Vec<(PathBuf, HashMap<String, String>)> = config
        .projects
        .iter()
        .map(|e| (e.path.clone(), e.aliases.clone()))
        .collect();

    let mut worktrees_map: HashMap<PathBuf, Vec<git_worktree::WorktreeEntry>> =
        worktrees.into_iter().collect();

    for i in 0..workspace.projects.len() {
        let path = workspace.projects[i].path.clone();
        let proj_name = workspace.projects[i].name.clone();
        let aliases = aliases_by_path
            .iter()
            .find(|(p, _)| p == &path)
            .map(|(_, a)| a.clone())
            .unwrap_or_default();

        let snapshot: WorktreeSnap = workspace.projects[i]
            .worktrees
            .iter()
            .map(|w| {
                let panes = w
                    .sessions
                    .iter()
                    .map(|s| (s.name.clone(), (s.pane_capture.clone(), s.muted)))
                    .collect();
                let order = w.sessions.iter().map(|s| s.name.clone()).collect();
                (
                    w.path.clone(),
                    WorktreeSnapEntry {
                        git_info: w.git_info.clone(),
                        git_info_fetched_at: w.git_info_fetched_at,
                        expanded: w.expanded,
                        panes,
                        session_order: order,
                        last_fetched: w.last_fetched,
                        fetch_failed: w.fetch_failed,
                        fetch_fail_count: w.fetch_fail_count,
                        fetch_fail_reason: w.fetch_fail_reason.clone(),
                    },
                )
            })
            .collect();

        let entries = worktrees_map.remove(&path).unwrap_or_default();
        let mut new_worktrees = Vec::new();
        for entry in entries
            .into_iter()
            .filter(|e| !config.is_worktree_excluded(&e.path))
        {
            let alias = aliases.get(&entry.branch).cloned();
            let wt_path = entry.path.clone();
            let prev = snapshot.get(&entry.path);

            let prev_order: &[String] = prev
                .map(|snap| snap.session_order.as_slice())
                .unwrap_or(&[]);
            // Index prev_order for O(1) sort-key lookup
            let order_index: HashMap<&str, usize> = prev_order
                .iter()
                .enumerate()
                .map(|(i, n)| (n.as_str(), i))
                .collect();

            let empty_names: Vec<&str> = Vec::new();
            let session_names = sessions_by_path.get(&wt_path).unwrap_or(&empty_names);
            let mut sessions: Vec<SessionInfo> = session_names
                .iter()
                .map(|&name| {
                    let display_name = session_display_name_from_tmux(
                        name,
                        &proj_name,
                        &wt_path,
                        &entry.branch,
                        alias.as_deref(),
                    );
                    let prev_pane = prev.and_then(|snap| snap.panes.get(name));
                    let (pane_capture, prev_muted) = prev_pane
                        .map(|(p, m)| (p.clone(), *m))
                        .unwrap_or((None, false));
                    let status = activity.get(name);
                    // Prefer tmux-sourced muted flag over snapshot so all instances agree.
                    let muted = status.map(|s| s.wsx_muted).unwrap_or(prev_muted);
                    let last_activity = status
                        .filter(|s| s.last_activity_ts > 0)
                        .and_then(|s| unix_ts_to_instant(s.last_activity_ts));
                    // Mute is sticky — only user interaction in wsx (attach, send, etc.)
                    // unmutes a session. Background output no longer breaks it.
                    // Muted sessions skip all activity tracking.
                    let (has_activity, last_activity) = if muted {
                        (false, None)
                    } else {
                        (status.map(|s| s.has_bell).unwrap_or(false), last_activity)
                    };
                    SessionInfo {
                        name: name.to_string(),
                        display_name,
                        has_activity,
                        pane_capture,
                        last_activity,
                        foreground: status
                            .map(|s| s.foreground)
                            .unwrap_or(ForegroundKind::Unknown),
                        is_running_wsx: status.map(|s| s.is_running_wsx).unwrap_or(false),
                        muted,
                    }
                })
                .collect();
            sessions.sort_by_key(|s| *order_index.get(s.name.as_str()).unwrap_or(&usize::MAX));

            let (
                git_info,
                git_info_fetched_at,
                expanded,
                last_fetched,
                fetch_failed,
                fetch_fail_count,
                fetch_fail_reason,
            ) = prev
                .map(|snap| {
                    (
                        snap.git_info.clone(),
                        snap.git_info_fetched_at,
                        snap.expanded,
                        snap.last_fetched,
                        snap.fetch_failed,
                        snap.fetch_fail_count,
                        snap.fetch_fail_reason.clone(),
                    )
                })
                .unwrap_or((None, None, true, None, false, 0, None));

            new_worktrees.push(WorktreeInfo {
                name: entry.name,
                branch: entry.branch,
                path: entry.path,
                is_main: entry.is_main,
                alias,
                sessions,
                expanded,
                git_info,
                git_info_fetched_at,
                fetch_failed,
                fetch_fail_count,
                fetch_fail_reason,
                last_fetched,
            });
        }
        workspace.projects[i].worktrees = new_worktrees;
    }
    // Drop projects that were already marked missing last cycle; mark newly-gone ones.
    // This gives one refresh cycle (~3 s) of visual "(missing)" indication before removal.
    workspace.projects.retain(|p| !p.missing);
    for p in &mut workspace.projects {
        p.missing = !is_git_repo(&p.path);
    }
}

/// Update session activity state from live tmux data. Returns true if any field changed.
pub fn update_activity(
    workspace: &mut WorkspaceState,
    activity: &HashMap<String, SessionStatus>,
) -> bool {
    let mut changed = false;
    for project in &mut workspace.projects {
        for wt in &mut project.worktrees {
            for sess in &mut wt.sessions {
                if sess.muted {
                    continue;
                }
                let old_bell = sess.has_activity;
                let old_foreground = sess.foreground;
                if let Some(status) = activity.get(&sess.name) {
                    sess.has_activity = status.has_bell;
                    sess.foreground = status.foreground;
                    sess.is_running_wsx = status.is_running_wsx;
                    sess.last_activity = Some(status.last_activity_ts)
                        .filter(|&ts| ts > 0)
                        .and_then(|ts| unix_ts_to_instant(ts));
                } else {
                    sess.has_activity = false;
                    sess.foreground = ForegroundKind::Unknown;
                    sess.is_running_wsx = false;
                }
                if sess.has_activity != old_bell || sess.foreground != old_foreground {
                    changed = true;
                }
            }
        }
    }
    changed
}

// ── Workspace loading ─────────────────────────────────────────────────────────

pub fn load_workspace(config: &GlobalConfig) -> WorkspaceState {
    if config.projects.is_empty() {
        return WorkspaceState::empty();
    }

    let projects = config
        .projects
        .iter()
        .filter_map(|entry| {
            let path = &entry.path;
            if !is_git_repo(path) {
                return None;
            }

            let default_branch = detect_default_branch(path);
            let proj_config = crate::config::project::load_project_config(path);
            let entries = git_worktree::list_worktrees(path).unwrap_or_default();
            let entries = entries
                .into_iter()
                .filter(|e| !config.is_worktree_excluded(&e.path))
                .collect();
            let worktrees = git_worktree::to_worktree_infos(entries, &entry.aliases);

            Some(Project {
                name: entry.name.clone(),
                path: path.clone(),
                default_branch,
                worktrees,
                config: Some(proj_config),
                expanded: true,
                missing: false,
            })
        })
        .collect();

    WorkspaceState { projects }
}

pub fn expand_path(s: &str) -> PathBuf {
    if s.starts_with("~/") {
        if let Some(home) = dirs::home_dir() {
            return home.join(&s[2..]);
        }
    }
    PathBuf::from(s)
}

pub fn detect_default_branch(path: &std::path::Path) -> String {
    git_info::current_branch(path).unwrap_or_else(|| "main".into())
}

// ── Project registration ──────────────────────────────────────────────────────

/// Register a new project at `path`. Returns the constructed `Project` and
/// mutates `config` (caller must call `config.save()`).
pub fn register_project(path: PathBuf, config: &mut GlobalConfig) -> Result<Project> {
    if path.as_os_str().is_empty() {
        bail!("empty path");
    }
    // Normalize before any equality checks so the returned Project.path matches
    // what config stores — otherwise delete/dedup/cache lookups silently miss and
    // the tree shows duplicate or undeletable entries. Shared normalizer keeps
    // this in lockstep with GlobalConfig::add_project / load.
    let path = crate::config::global::normalize_project_path(&path);
    if !path.exists() {
        bail!("path does not exist: {}", path.display());
    }
    if !is_git_repo(&path) {
        bail!("not a git repository: {}", path.display());
    }
    if config.projects.iter().any(|e| e.path == path) {
        bail!("project already registered: {}", path.display());
    }

    let name = path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| "unknown".to_string());

    let default_branch = detect_default_branch(&path);
    let proj_config = crate::config::project::load_project_config(&path);
    let entries = git_worktree::list_worktrees(&path).unwrap_or_default();
    let aliases = config
        .projects
        .iter()
        .find(|e| e.path == path)
        .map(|e| e.aliases.clone())
        .unwrap_or_default();
    let worktrees = git_worktree::to_worktree_infos(entries, &aliases);

    config.add_project(name.clone(), path.clone());

    Ok(Project {
        name,
        path,
        default_branch,
        worktrees,
        config: Some(proj_config),
        expanded: true,
        missing: false,
    })
}

/// Remove a project by path from config. Caller must call `config.save()`.
pub fn unregister_project(path: &PathBuf, config: &mut GlobalConfig) {
    config.remove_project(path);
}

// ── Worktree operations ───────────────────────────────────────────────────────

/// Create a new git worktree under `repo_path` for `branch`.
/// Runs hooks (env copy, post_create) and returns the new worktree path.
/// Returns a warning string if a hook failed (non-fatal).
pub fn create_worktree(
    repo_path: &PathBuf,
    default_branch: &str,
    proj_config: &ProjectConfig,
    branch: &str,
) -> Result<(PathBuf, Option<String>)> {
    let wt_path = git_worktree::create_worktree(repo_path, branch, default_branch)?;

    let mut warning: Option<String> = None;

    if let Err(e) = hooks::copy_env_files(repo_path, &wt_path, proj_config) {
        warning = Some(format!("Warning: .env copy: {}", e));
    }
    if let Some(ref cmd) = proj_config.post_create {
        if let Err(e) = hooks::run_post_create(&wt_path, cmd) {
            warning = Some(format!("Warning: postCreate: {}", e));
        }
    }

    Ok((wt_path, warning))
}

/// Remove a git worktree and kill any associated tmux sessions.
pub fn delete_worktree(
    repo_path: &PathBuf,
    wt_path: &PathBuf,
    branch: &str,
    session_names: &[String],
) -> Result<()> {
    git_worktree::remove_worktree(repo_path, wt_path, branch)?;
    for sess in session_names {
        let _ = session::kill_session(sess);
    }
    Ok(())
}

// ── Session operations ────────────────────────────────────────────────────────

/// Create a named tmux session at `wt_path` and optionally send an initial command.
/// Returns (tmux_name, display_name). Tmux name is prefixed with `{proj_name}-{wt_slug}-`;
/// display_name is the user-visible part (what the user typed).
pub fn create_session(
    proj_name: &str,
    wt_slug: &str,
    wt_path: &PathBuf,
    session_name: Option<String>,
    command: Option<String>,
) -> Result<(String, String)> {
    // display name priority: explicit > command first word > proj_name
    let base_display = match &session_name {
        Some(n) if !n.is_empty() => n.clone(),
        _ => match &command {
            Some(cmd) => cmd
                .split_whitespace()
                .next()
                .unwrap_or(proj_name)
                .to_string(),
            None => proj_name.to_string(),
        },
    };
    let base_tmux = format!("{}-{}-{}", proj_name, wt_slug, base_display);
    let tmux_name = session::unique_session_name(&base_tmux);
    // strip "{proj_name}-{wt_slug}-" prefix to get display name
    let prefix_len = proj_name.len() + 1 + wt_slug.len() + 1;
    let display_name = tmux_name[prefix_len..].to_string();
    session::create_session(&tmux_name, wt_path)?;
    if let Some(cmd) = command {
        session::send_keys(&tmux_name, &cmd)?;
    }
    Ok((tmux_name, display_name))
}

/// Rename a tmux session from `old_name` to `new_name`.
pub fn rename_session(old_name: &str, new_name: &str) -> Result<()> {
    session::rename_session(old_name, new_name)
}

/// Recreate tmux sessions after a server restart (reboot/crash).
///
/// ! Only restores when the tmux server PID has changed. If the same server is
/// ! still running, missing sessions were intentionally killed — skip restore.
///
/// Uses the newest non-empty session source. Older versions always preferred
/// sessions.toml, but that let a stale crash snapshot override a newer cache.
///
/// Returns the number of sessions recreated.
pub fn restore_cached_sessions(workspace: &WorkspaceState, cached_pid: Option<u32>) -> usize {
    let current_pid = session::server_pid();
    if cached_pid.is_some() && cached_pid == current_pid {
        return 0;
    }

    let live: HashSet<String> = session::list_sessions_with_paths()
        .into_iter()
        .map(|(name, _)| name)
        .collect();

    let source = choose_restore_source(
        crate::cache::load_session_snapshot_with_meta(),
        crate::cache::collect_session_names(workspace),
        crate::cache::WorkspaceCache::load().written_at_unix_ms,
    );

    let mut restored = 0usize;
    for (path_str, names) in &source {
        let path = std::path::Path::new(path_str.as_str());
        for name in names {
            if !live.contains(name) && session::create_session(name, path).is_ok() {
                restored += 1;
            }
        }
    }
    restored
}

fn choose_restore_source(
    snapshot: SessionSnapshot,
    workspace_sessions: HashMap<String, Vec<String>>,
    workspace_written_at: Option<u64>,
) -> HashMap<String, Vec<String>> {
    let snapshot_is_newer = match (snapshot.written_at_unix_ms, workspace_written_at) {
        // Legacy snapshots had no timestamp, so keep the old crash-restore
        // behavior and prefer them when present.
        (None, _) => true,
        (Some(_), None) => true,
        (Some(snapshot_ms), Some(workspace_ms)) => snapshot_ms >= workspace_ms,
    };
    if !snapshot.sessions.is_empty() && (workspace_sessions.is_empty() || snapshot_is_newer) {
        snapshot.sessions
    } else {
        workspace_sessions
    }
}

// ── Alias operations ──────────────────────────────────────────────────────────

/// Persist an alias for a branch in the global config. Caller must call `config.save()`.
pub fn set_alias(config: &mut GlobalConfig, proj_path: &PathBuf, branch: &str, alias: &str) {
    config.set_alias(proj_path, branch, alias);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::workspace::{Project, WorkspaceState};
    use std::collections::HashMap;

    fn make_project(path: PathBuf) -> Project {
        Project {
            name: "test".to_string(),
            path,
            default_branch: "main".to_string(),
            worktrees: vec![],
            config: None,
            expanded: true,
            missing: false,
        }
    }

    fn sessions(path: &str, names: &[&str]) -> HashMap<String, Vec<String>> {
        HashMap::from([(
            path.to_string(),
            names.iter().map(|name| name.to_string()).collect(),
        )])
    }

    #[test]
    fn restore_source_uses_workspace_when_snapshot_is_older() {
        let source = choose_restore_source(
            SessionSnapshot {
                sessions: sessions("/tmp/repo", &["old"]),
                written_at_unix_ms: Some(10),
            },
            sessions("/tmp/repo", &["new"]),
            Some(20),
        );

        assert_eq!(source["/tmp/repo"], vec!["new"]);
    }

    #[test]
    fn restore_source_uses_snapshot_when_snapshot_is_newer() {
        let source = choose_restore_source(
            SessionSnapshot {
                sessions: sessions("/tmp/repo", &["new"]),
                written_at_unix_ms: Some(20),
            },
            sessions("/tmp/repo", &["old"]),
            Some(10),
        );

        assert_eq!(source["/tmp/repo"], vec!["new"]);
    }

    #[test]
    fn restore_source_keeps_legacy_snapshot_preference() {
        let source = choose_restore_source(
            SessionSnapshot {
                sessions: sessions("/tmp/repo", &["legacy"]),
                written_at_unix_ms: None,
            },
            sessions("/tmp/repo", &["workspace"]),
            Some(20),
        );

        assert_eq!(source["/tmp/repo"], vec!["legacy"]);
    }

    #[test]
    fn refresh_drops_project_whose_directory_was_deleted() {
        let suffix = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        let base = std::env::temp_dir().join(format!("wsx-test-{}", suffix));
        std::fs::create_dir_all(&base).unwrap();
        let exists_path = base.join("real");
        std::fs::create_dir_all(&exists_path).unwrap();
        std::fs::create_dir(exists_path.join(".git")).unwrap();
        let missing_path = base.join("ghost");

        let config = GlobalConfig::default();
        let activity: HashMap<String, crate::tmux::monitor::SessionStatus> = HashMap::new();

        let mut workspace = WorkspaceState {
            projects: vec![
                make_project(exists_path.clone()),
                make_project(missing_path.clone()),
            ],
        };

        // First refresh: missing_path is newly gone — stays in tree, marked missing.
        refresh_workspace_with_worktrees(
            &mut workspace,
            &config,
            &[],
            &activity,
            vec![
                (exists_path.clone(), vec![]),
                (missing_path.clone(), vec![]),
            ],
        );
        assert_eq!(workspace.projects.len(), 2);
        assert!(workspace
            .projects
            .iter()
            .any(|p| p.missing && p.path == missing_path));

        // Second refresh: missing_path still gone — now dropped.
        refresh_workspace_with_worktrees(
            &mut workspace,
            &config,
            &[],
            &activity,
            vec![(exists_path.clone(), vec![]), (missing_path, vec![])],
        );
        assert_eq!(workspace.projects.len(), 1);
        assert_eq!(workspace.projects[0].path, exists_path);
        let _ = std::fs::remove_dir_all(&base);
    }

    fn unique_base() -> PathBuf {
        let suffix = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        let base = std::env::temp_dir().join(format!("wsx-test-register-{}", suffix));
        std::fs::create_dir_all(&base).unwrap();
        base
    }

    fn make_repo_dir(base: &std::path::Path, name: &str) -> PathBuf {
        let p = base.join(name);
        std::fs::create_dir_all(p.join(".git")).unwrap();
        p
    }

    #[test]
    fn given_trailing_slash_path_when_registered_then_returned_path_has_no_trailing_slash() {
        let base = unique_base();
        let repo = make_repo_dir(&base, "myrepo");
        let with_slash = PathBuf::from(format!("{}/", repo.to_string_lossy()));
        let mut config = GlobalConfig::default();

        let project = register_project(with_slash, &mut config).unwrap();

        assert_eq!(project.path, repo);
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn given_valid_repo_when_registered_then_name_is_final_path_component() {
        let base = unique_base();
        let repo = make_repo_dir(&base, "coolproject");
        let mut config = GlobalConfig::default();

        let project = register_project(repo, &mut config).unwrap();

        assert_eq!(project.name, "coolproject");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn given_valid_repo_when_registered_then_appended_to_config() {
        let base = unique_base();
        let repo = make_repo_dir(&base, "myrepo");
        let mut config = GlobalConfig::default();

        let _ = register_project(repo, &mut config).unwrap();

        assert_eq!(config.projects.len(), 1);
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn given_two_distinct_repos_when_both_registered_then_both_stored() {
        let base = unique_base();
        let repo_a = make_repo_dir(&base, "alpha");
        let repo_b = make_repo_dir(&base, "beta");
        let mut config = GlobalConfig::default();

        register_project(repo_a, &mut config).unwrap();
        register_project(repo_b, &mut config).unwrap();

        assert_eq!(config.projects.len(), 2);
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn given_same_exact_path_registered_twice_when_second_call_then_returns_err() {
        let base = unique_base();
        let repo = make_repo_dir(&base, "myrepo");
        let mut config = GlobalConfig::default();

        register_project(repo.clone(), &mut config).unwrap();
        let second = register_project(repo, &mut config);

        assert!(second.is_err());
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn given_same_exact_path_registered_twice_when_second_call_then_projects_len_stays_one() {
        let base = unique_base();
        let repo = make_repo_dir(&base, "myrepo");
        let mut config = GlobalConfig::default();

        register_project(repo.clone(), &mut config).unwrap();
        let _ = register_project(repo, &mut config);

        assert_eq!(config.projects.len(), 1);
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn given_path_differing_only_by_trailing_slash_when_second_call_then_returns_err() {
        let base = unique_base();
        let repo = make_repo_dir(&base, "myrepo");
        let with_slash = PathBuf::from(format!("{}/", repo.to_string_lossy()));
        let mut config = GlobalConfig::default();

        register_project(repo, &mut config).unwrap();
        let second = register_project(with_slash, &mut config);

        assert!(second.is_err());
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn given_path_differing_only_by_trailing_slash_when_second_call_then_projects_len_stays_one() {
        let base = unique_base();
        let repo = make_repo_dir(&base, "myrepo");
        let with_slash = PathBuf::from(format!("{}/", repo.to_string_lossy()));
        let mut config = GlobalConfig::default();

        register_project(repo, &mut config).unwrap();
        let _ = register_project(with_slash, &mut config);

        assert_eq!(config.projects.len(), 1);
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn given_empty_path_when_registered_then_returns_err() {
        let mut config = GlobalConfig::default();

        let result = register_project(PathBuf::from(""), &mut config);

        assert!(result.is_err());
    }

    #[test]
    fn given_empty_path_when_registered_then_projects_stays_empty() {
        let mut config = GlobalConfig::default();

        let _ = register_project(PathBuf::from(""), &mut config);

        assert_eq!(config.projects.len(), 0);
    }

    #[test]
    fn given_nonexistent_path_when_registered_then_returns_err() {
        let base = unique_base();
        let missing = base.join("does-not-exist");
        let mut config = GlobalConfig::default();

        let result = register_project(missing, &mut config);

        assert!(result.is_err());
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn given_existing_dir_without_git_when_registered_then_returns_err() {
        let base = unique_base();
        let plain = base.join("plaindir");
        std::fs::create_dir_all(&plain).unwrap();
        let mut config = GlobalConfig::default();

        let result = register_project(plain, &mut config);

        assert!(result.is_err());
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn given_file_at_path_instead_of_dir_when_registered_then_returns_err() {
        let base = unique_base();
        let file_path = base.join("notadir");
        std::fs::write(&file_path, b"i am a file").unwrap();
        let mut config = GlobalConfig::default();

        let result = register_project(file_path, &mut config);

        assert!(result.is_err());
        let _ = std::fs::remove_dir_all(&base);
    }
}