wsx-core 0.17.0

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
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use serde::Serialize;

/// Foreground process class for a tmux session, classified by `tmux::monitor`.
/// "Running" (Active state) is decided downstream in `session_state` — this
/// enum stays a raw input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Default)]
pub enum ForegroundKind {
    #[default]
    Unknown,
    Shell,
    PassiveViewer,
    Runtime,
    Agent,
    InteractiveApp,
}

#[derive(Debug, Clone, Serialize)]
pub struct WorkspaceState {
    pub projects: Vec<Project>,
}

#[derive(Debug, Clone, Serialize)]
pub struct Project {
    pub name: String,
    pub path: PathBuf,
    pub default_branch: String,
    pub worktrees: Vec<WorktreeInfo>,
    #[serde(skip)]
    pub routines: Vec<asched_core::routine::ipc::RoutineView>,
    #[serde(skip)]
    pub routine_revision: u64,
    #[serde(skip)]
    pub routines_expanded: bool,
    #[serde(skip)]
    pub config: Option<ProjectConfig>,
    #[serde(skip)]
    pub expanded: bool,
    #[serde(skip)]
    pub missing: bool,
}

#[derive(Debug, Clone, Default)]
pub struct ProjectConfig {
    pub post_create: Option<String>,
    pub copy_includes: Vec<String>,
    pub copy_excludes: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct SessionInfo {
    pub name: String,         // full tmux session name
    pub display_name: String, // shown in UI (strips wt_slug prefix)
    pub has_activity: bool,   // tmux bell/alert flag
    #[serde(skip)]
    pub pane_capture: Option<String>,
    #[serde(skip)]
    pub last_activity: Option<std::time::Instant>,
    #[serde(skip)]
    pub agent_tail: Option<String>, // normalized bounded tail used for semantic motion
    #[serde(skip)]
    pub tmux_activity_ts: u64, // raw tmux window activity timestamp for capture gating
    pub foreground: ForegroundKind, // raw process classification — see tmux::monitor
    #[serde(skip)]
    pub is_running_wsx: bool, // foreground process is wsx — suppresses capture preview
    #[serde(skip)]
    pub muted: bool, // user silenced — no activity updates, shown as ⊘
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub enum FetchFailReason {
    Auth,    // "Authentication failed", "Permission denied", "could not read Username"
    Timeout, // killed after 10s
    Network, // generic / other failure
}

#[derive(Debug, Clone, Serialize)]
pub struct WorktreeInfo {
    pub name: String,
    pub branch: String,
    pub path: PathBuf,
    pub is_main: bool,
    pub alias: Option<String>,
    pub sessions: Vec<SessionInfo>,
    #[serde(skip)]
    pub expanded: bool,
    pub git_info: Option<GitInfo>,
    pub fetch_failed: bool,
    pub fetch_fail_count: u32,
    pub fetch_fail_reason: Option<FetchFailReason>,
    #[serde(skip)]
    pub last_fetched: Option<std::time::Instant>,
    #[serde(skip)]
    pub git_info_fetched_at: Option<std::time::Instant>,
}

impl Project {
    /// Maps branch name -> list of tmux session names for all worktrees.
    pub fn branch_session_names(&self) -> HashMap<String, Vec<String>> {
        self.worktrees
            .iter()
            .map(|wt| {
                let sessions = wt.sessions.iter().map(|s| s.name.clone()).collect();
                (wt.branch.clone(), sessions)
            })
            .collect()
    }
}

impl WorktreeInfo {
    pub fn display_name(&self) -> &str {
        self.alias.as_deref().unwrap_or(&self.name)
    }

    pub fn session_slug(&self, project_name: &str) -> String {
        canonical_session_slug(project_name, &self.path)
    }

    pub fn session_names(&self) -> Vec<String> {
        self.sessions.iter().map(|s| s.name.clone()).collect()
    }
}

fn sanitize_slug(raw: &str) -> String {
    raw.replace(|c: char| !c.is_alphanumeric() && c != '-' && c != '_', "-")
}

fn legacy_branch_slug(branch: &str) -> String {
    sanitize_slug(&branch.replace('/', "-"))
}

pub fn canonical_session_slug(project_name: &str, worktree_path: &Path) -> String {
    let dir_name = worktree_path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| project_name.to_string());
    let proj_prefix = format!("{}-", project_name);
    let short_name = dir_name.strip_prefix(&proj_prefix).unwrap_or(&dir_name);
    sanitize_slug(short_name)
}

pub fn session_display_name_from_tmux(
    tmux_name: &str,
    project_name: &str,
    worktree_path: &Path,
    branch: &str,
    alias: Option<&str>,
) -> String {
    let canonical = format!(
        "{}-{}-",
        project_name,
        canonical_session_slug(project_name, worktree_path)
    );
    if let Some(rest) = tmux_name.strip_prefix(&canonical) {
        return rest.to_string();
    }

    // Backward compatibility: older builds prefixed by branch/alias slug.
    let legacy_branch = format!("{}-{}-", project_name, legacy_branch_slug(branch));
    if let Some(rest) = tmux_name.strip_prefix(&legacy_branch) {
        return rest.to_string();
    }

    if let Some(alias) = alias {
        let legacy_alias = format!("{}-{}-", project_name, sanitize_slug(alias));
        if let Some(rest) = tmux_name.strip_prefix(&legacy_alias) {
            return rest.to_string();
        }
    }

    // Last-resort compatibility for historical `{project}-{any_slug}-{display}` names.
    if let Some(rest) = tmux_name.strip_prefix(&format!("{}-", project_name)) {
        if let Some((_, display)) = rest.split_once('-') {
            return display.to_string();
        }
    }

    tmux_name.to_string()
}

#[cfg(test)]
mod tests {
    use super::{canonical_session_slug, session_display_name_from_tmux};
    use std::path::Path;

    #[test]
    fn canonical_slug_uses_worktree_dir_for_main() {
        let slug = canonical_session_slug("wsx", Path::new("/tmp/wsx"));
        assert_eq!(slug, "wsx");
    }

    #[test]
    fn canonical_slug_strips_project_prefix_for_worktrees() {
        let slug = canonical_session_slug("wsx", Path::new("/tmp/wsx-feature-auth"));
        assert_eq!(slug, "feature-auth");
    }

    #[test]
    fn display_name_parses_canonical_prefix() {
        let display = session_display_name_from_tmux(
            "wsx-wsx-agent",
            "wsx",
            Path::new("/tmp/wsx"),
            "main",
            None,
        );
        assert_eq!(display, "agent");
    }

    #[test]
    fn display_name_parses_legacy_branch_prefix() {
        let display = session_display_name_from_tmux(
            "wsx-main-agent",
            "wsx",
            Path::new("/tmp/wsx"),
            "main",
            None,
        );
        assert_eq!(display, "agent");
    }

    #[test]
    fn display_name_parses_legacy_alias_prefix() {
        let display = session_display_name_from_tmux(
            "wsx-auth-agent",
            "wsx",
            Path::new("/tmp/wsx-feature-auth"),
            "feature/auth",
            Some("auth"),
        );
        assert_eq!(display, "agent");
    }

    #[test]
    fn display_name_falls_back_to_project_slug_pattern() {
        let display = session_display_name_from_tmux(
            "wsx-oldslug-agent",
            "wsx",
            Path::new("/tmp/wsx-feature-auth"),
            "feature/auth",
            None,
        );
        assert_eq!(display, "agent");
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct GitInfo {
    pub recent_commits: Vec<CommitSummary>,
    pub modified_files: Vec<String>,
    pub ahead: usize,
    pub behind: usize,
    pub remote_branch: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CommitSummary {
    pub hash: String,
    pub message: String,
}

/// Flat tree entry for rendering and 3-level navigation.
#[derive(Debug, Clone, PartialEq)]
pub enum FlatEntry {
    Project {
        idx: usize,
    },
    Worktree {
        project_idx: usize,
        worktree_idx: usize,
    },
    Session {
        project_idx: usize,
        worktree_idx: usize,
        session_idx: usize,
    },
    RoutinesHeader {
        project_idx: usize,
    },
    Routine {
        project_idx: usize,
        routine_idx: usize,
    },
}

/// Flatten workspace into visible tree entries based on expand state.
#[allow(dead_code)]
pub fn flatten_tree(workspace: &WorkspaceState) -> Vec<FlatEntry> {
    let mut result = Vec::new();
    for (pi, project) in workspace.projects.iter().enumerate() {
        result.push(FlatEntry::Project { idx: pi });
        if project.expanded {
            for (wi, wt) in project.worktrees.iter().enumerate() {
                result.push(FlatEntry::Worktree {
                    project_idx: pi,
                    worktree_idx: wi,
                });
                if wt.expanded {
                    for (si, _) in wt.sessions.iter().enumerate() {
                        result.push(FlatEntry::Session {
                            project_idx: pi,
                            worktree_idx: wi,
                            session_idx: si,
                        });
                    }
                }
            }
            if !project.routines.is_empty() {
                result.push(FlatEntry::RoutinesHeader { project_idx: pi });
                if project.routines_expanded {
                    for (ri, _) in project.routines.iter().enumerate() {
                        result.push(FlatEntry::Routine {
                            project_idx: pi,
                            routine_idx: ri,
                        });
                    }
                }
            }
        }
    }
    result
}

/// Like `flatten_tree` but skips projects whose index is not in `visible`.
pub fn flatten_tree_filtered(
    workspace: &WorkspaceState,
    visible: &HashSet<usize>,
) -> Vec<FlatEntry> {
    let mut result = Vec::new();
    for (pi, project) in workspace.projects.iter().enumerate() {
        if !visible.contains(&pi) {
            continue;
        }
        result.push(FlatEntry::Project { idx: pi });
        if project.expanded {
            for (wi, wt) in project.worktrees.iter().enumerate() {
                result.push(FlatEntry::Worktree {
                    project_idx: pi,
                    worktree_idx: wi,
                });
                if wt.expanded {
                    for (si, _) in wt.sessions.iter().enumerate() {
                        result.push(FlatEntry::Session {
                            project_idx: pi,
                            worktree_idx: wi,
                            session_idx: si,
                        });
                    }
                }
            }
            if !project.routines.is_empty() {
                result.push(FlatEntry::RoutinesHeader { project_idx: pi });
                if project.routines_expanded {
                    for (ri, _) in project.routines.iter().enumerate() {
                        result.push(FlatEntry::Routine {
                            project_idx: pi,
                            routine_idx: ri,
                        });
                    }
                }
            }
        }
    }
    result
}

/// What is currently focused.
#[derive(Debug, Clone, PartialEq)]
pub enum Selection {
    Project(usize),
    Worktree(usize, usize),
    Session(usize, usize, usize),
    RoutinesHeader(usize),
    Routine(usize, usize),
    None,
}

impl WorkspaceState {
    pub fn empty() -> Self {
        Self {
            projects: Vec::new(),
        }
    }

    pub fn worktree(&self, pi: usize, wi: usize) -> Option<&WorktreeInfo> {
        self.projects.get(pi)?.worktrees.get(wi)
    }

    pub fn worktree_mut(&mut self, pi: usize, wi: usize) -> Option<&mut WorktreeInfo> {
        self.projects.get_mut(pi)?.worktrees.get_mut(wi)
    }

    pub fn session(&self, pi: usize, wi: usize, si: usize) -> Option<&SessionInfo> {
        self.projects.get(pi)?.worktrees.get(wi)?.sessions.get(si)
    }

    pub fn session_mut(&mut self, pi: usize, wi: usize, si: usize) -> Option<&mut SessionInfo> {
        self.projects
            .get_mut(pi)?
            .worktrees
            .get_mut(wi)?
            .sessions
            .get_mut(si)
    }

    /// Resolve flat index to Selection using a pre-computed flat slice.
    pub fn get_selection(&self, flat_idx: usize, flat: &[FlatEntry]) -> Selection {
        match flat.get(flat_idx) {
            Some(FlatEntry::Project { idx }) => Selection::Project(*idx),
            Some(FlatEntry::Worktree {
                project_idx,
                worktree_idx,
            }) => Selection::Worktree(*project_idx, *worktree_idx),
            Some(FlatEntry::Session {
                project_idx,
                worktree_idx,
                session_idx,
            }) => Selection::Session(*project_idx, *worktree_idx, *session_idx),
            Some(FlatEntry::RoutinesHeader { project_idx }) => {
                Selection::RoutinesHeader(*project_idx)
            }
            Some(FlatEntry::Routine {
                project_idx,
                routine_idx,
            }) => Selection::Routine(*project_idx, *routine_idx),
            None => Selection::None,
        }
    }
}