Skip to main content

wsx_core/
ops.rs

1//! Git/project operations projected against the wsx-owned runtime.
2// ^ [[wsx Architecture]] Git owns worktree discovery; the daemon owns sessions and panes.
3
4use crate::{
5    config::global::GlobalConfig,
6    git::{info as git_info, worktree as git_worktree},
7    hooks,
8    model::workspace::{
9        FetchFailReason, GitInfo, PaneInfo, Project, ProjectConfig, SessionInfo, WorkspaceState,
10        WorktreeInfo,
11    },
12    runtime::{
13        AgentState, Client, ProjectSpec, Request, Response, SessionId, SessionPlacement, Snapshot,
14        WorktreeId, WorktreeSpec,
15    },
16};
17use anyhow::{anyhow, bail, Result};
18use std::{
19    collections::{HashMap, HashSet},
20    path::{Path, PathBuf},
21};
22
23struct WorktreeState {
24    git_info: Option<GitInfo>,
25    git_info_fetched_at: Option<std::time::Instant>,
26    expanded: bool,
27    sessions: Vec<SessionInfo>,
28    last_fetched: Option<std::time::Instant>,
29    fetch_failed: bool,
30    fetch_fail_count: u32,
31    fetch_fail_reason: Option<FetchFailReason>,
32}
33
34#[derive(Debug, Clone)]
35struct DiscoveredProject {
36    name: String,
37    path: PathBuf,
38    worktrees: Vec<git_worktree::WorktreeEntry>,
39}
40
41#[derive(Debug, Clone)]
42pub struct WorkspaceDiscovery {
43    projects: Vec<DiscoveredProject>,
44}
45
46impl WorkspaceDiscovery {
47    pub fn into_worktrees(self) -> Vec<(PathBuf, Vec<git_worktree::WorktreeEntry>)> {
48        self.projects
49            .into_iter()
50            .map(|project| (project.path, project.worktrees))
51            .collect()
52    }
53}
54
55fn is_git_repo(path: &Path) -> bool {
56    path.exists() && path.join(".git").exists()
57}
58
59pub fn runtime_snapshot() -> Result<Snapshot> {
60    match Client::local().call(&Request::Snapshot)? {
61        Response::Snapshot(snapshot) => Ok(snapshot),
62        Response::Error(error) => bail!("{}: {}", error.code, error.message),
63        _ => bail!("wsx daemon returned an unexpected snapshot response"),
64    }
65}
66
67fn synchronize(client: &Client, projects: Vec<ProjectSpec>) -> Result<Snapshot> {
68    match client.call(&Request::SynchronizeProjects { projects })? {
69        Response::Ack { .. } => {}
70        Response::Error(error) => bail!("{}: {}", error.code, error.message),
71        _ => bail!("wsx daemon returned an unexpected synchronization response"),
72    }
73    match client.call(&Request::Snapshot)? {
74        Response::Snapshot(snapshot) => Ok(snapshot),
75        Response::Error(error) => bail!("{}: {}", error.code, error.message),
76        _ => bail!("wsx daemon returned an unexpected snapshot response"),
77    }
78}
79
80pub fn workspace_from_config(config: &GlobalConfig) -> WorkspaceState {
81    WorkspaceState {
82        projects: config
83            .projects
84            .iter()
85            .filter(|entry| is_git_repo(&entry.path))
86            .map(|entry| Project {
87                name: entry.name.clone(),
88                path: entry.path.clone(),
89                default_branch: "main".into(),
90                last_agent_active_unix_ms: None,
91                last_terminal_active_unix_ms: None,
92                worktrees: Vec::new(),
93                routines: Vec::new(),
94                routine_revision: 0,
95                routines_expanded: true,
96                config: Some(crate::config::project::load_project_config(&entry.path)),
97                expanded: true,
98                missing: false,
99            })
100            .collect(),
101    }
102}
103
104pub fn discover_workspace(config: &GlobalConfig) -> Result<WorkspaceDiscovery> {
105    discover_workspace_with(config, git_worktree::list_worktrees)
106}
107
108fn discover_workspace_with<F>(
109    config: &GlobalConfig,
110    mut list_worktrees: F,
111) -> Result<WorkspaceDiscovery>
112where
113    F: FnMut(&Path) -> Result<Vec<git_worktree::WorktreeEntry>>,
114{
115    let projects = config
116        .projects
117        .iter()
118        .filter(|entry| is_git_repo(&entry.path))
119        .map(|entry| {
120            let worktrees = list_worktrees(&entry.path)?;
121            Ok(DiscoveredProject {
122                name: entry.name.clone(),
123                path: entry.path.clone(),
124                worktrees,
125            })
126        })
127        .collect::<Result<Vec<_>>>()?;
128    Ok(WorkspaceDiscovery { projects })
129}
130
131pub fn synchronize_discovery(discovery: &WorkspaceDiscovery) -> Result<Snapshot> {
132    let projects = discovery
133        .projects
134        .iter()
135        .map(|project| ProjectSpec {
136            path: project.path.clone(),
137            name: project.name.clone(),
138            worktrees: project
139                .worktrees
140                .iter()
141                .map(|worktree| WorktreeSpec {
142                    path: worktree.path.clone(),
143                    branch: worktree.branch.clone(),
144                })
145                .collect(),
146        })
147        .collect();
148    synchronize(&Client::local(), projects)
149}
150
151fn apply_discovery(
152    workspace: &mut WorkspaceState,
153    config: &GlobalConfig,
154    snapshot: &Snapshot,
155    discovery: WorkspaceDiscovery,
156) -> Result<()> {
157    let worktrees = discovery
158        .projects
159        .into_iter()
160        .map(|project| (project.path, project.worktrees))
161        .collect();
162    refresh_workspace_with_worktrees(workspace, config, snapshot, worktrees)
163}
164
165pub fn load_full_workspace(config: &GlobalConfig) -> Result<WorkspaceState> {
166    let discovery = discover_workspace(config)?;
167    let snapshot = synchronize_discovery(&discovery)?;
168    let mut workspace = workspace_from_config(config);
169    apply_discovery(&mut workspace, config, &snapshot, discovery)?;
170    Ok(workspace)
171}
172
173pub fn refresh_workspace_with_worktrees(
174    workspace: &mut WorkspaceState,
175    config: &GlobalConfig,
176    snapshot: &Snapshot,
177    worktrees: Vec<(PathBuf, Vec<git_worktree::WorktreeEntry>)>,
178) -> Result<()> {
179    let mut worktrees_map: HashMap<PathBuf, Vec<git_worktree::WorktreeEntry>> =
180        worktrees.into_iter().collect();
181    update_project_activity(workspace, snapshot);
182    for project in &mut workspace.projects {
183        if let Some(default_branch) = worktrees_map
184            .get(&project.path)
185            .and_then(|entries| entries.iter().find(|entry| entry.is_main))
186            .filter(|entry| entry.branch != "HEAD")
187            .map(|entry| entry.branch.clone())
188        {
189            project.default_branch = default_branch;
190        }
191        let previous: HashMap<PathBuf, WorktreeState> = project
192            .worktrees
193            .iter()
194            .map(|worktree| {
195                (
196                    worktree.path.clone(),
197                    WorktreeState {
198                        git_info: worktree.git_info.clone(),
199                        git_info_fetched_at: worktree.git_info_fetched_at,
200                        expanded: worktree.expanded,
201                        sessions: worktree.sessions.clone(),
202                        last_fetched: worktree.last_fetched,
203                        fetch_failed: worktree.fetch_failed,
204                        fetch_fail_count: worktree.fetch_fail_count,
205                        fetch_fail_reason: worktree.fetch_fail_reason.clone(),
206                    },
207                )
208            })
209            .collect();
210        let aliases = config
211            .projects
212            .iter()
213            .find(|entry| entry.path == project.path)
214            .map(|entry| &entry.aliases);
215        let entries = worktrees_map.remove(&project.path).unwrap_or_default();
216        project.worktrees = entries
217            .into_iter()
218            .filter(|entry| !config.is_worktree_excluded(&entry.path))
219            .map(|entry| {
220                let old = previous.get(&entry.path);
221                Ok(WorktreeInfo {
222                    name: entry.name,
223                    branch: entry.branch.clone(),
224                    path: entry.path.clone(),
225                    is_main: entry.is_main,
226                    alias: aliases.and_then(|map| map.get(&entry.branch)).cloned(),
227                    sessions: sessions_for_worktree(
228                        snapshot,
229                        &entry.path,
230                        old.map(|state| state.sessions.as_slice())
231                            .unwrap_or_default(),
232                    )?,
233                    expanded: old.map(|state| state.expanded).unwrap_or(true),
234                    git_info: old.and_then(|state| state.git_info.clone()),
235                    fetch_failed: old.map(|state| state.fetch_failed).unwrap_or(false),
236                    fetch_fail_count: old.map(|state| state.fetch_fail_count).unwrap_or(0),
237                    fetch_fail_reason: old.and_then(|state| state.fetch_fail_reason.clone()),
238                    last_fetched: old.and_then(|state| state.last_fetched),
239                    git_info_fetched_at: old.and_then(|state| state.git_info_fetched_at),
240                })
241            })
242            .collect::<Result<Vec<_>>>()?;
243    }
244    workspace.projects.retain(|project| !project.missing);
245    for project in &mut workspace.projects {
246        project.missing = !is_git_repo(&project.path);
247    }
248    Ok(())
249}
250
251pub fn refresh_sessions_from_snapshot(
252    workspace: &mut WorkspaceState,
253    snapshot: &Snapshot,
254) -> Result<()> {
255    update_project_activity(workspace, snapshot);
256    for worktree in workspace
257        .projects
258        .iter_mut()
259        .flat_map(|project| &mut project.worktrees)
260    {
261        worktree.sessions = sessions_for_worktree(snapshot, &worktree.path, &worktree.sessions)?;
262    }
263    Ok(())
264}
265
266fn update_project_activity(workspace: &mut WorkspaceState, snapshot: &Snapshot) {
267    for project in &mut workspace.projects {
268        let runtime_project = snapshot
269            .projects
270            .iter()
271            .find(|candidate| candidate.path == project.path)
272            .or_else(|| {
273                let project_id = snapshot.worktrees.iter().find_map(|runtime_worktree| {
274                    project
275                        .worktrees
276                        .iter()
277                        .any(|worktree| worktree.path == runtime_worktree.path)
278                        .then_some(runtime_worktree.project_id)
279                })?;
280                snapshot
281                    .projects
282                    .iter()
283                    .find(|candidate| candidate.id == project_id)
284            });
285        if let Some(runtime_project) = runtime_project {
286            project.last_agent_active_unix_ms = runtime_project.last_agent_active_unix_ms;
287            project.last_terminal_active_unix_ms = runtime_project.last_terminal_active_unix_ms;
288        }
289    }
290}
291
292fn sessions_for_worktree(
293    snapshot: &Snapshot,
294    path: &Path,
295    previous: &[SessionInfo],
296) -> Result<Vec<SessionInfo>> {
297    let Some(worktree) = snapshot
298        .worktrees
299        .iter()
300        .find(|worktree| worktree.path == path)
301    else {
302        return Ok(Vec::new());
303    };
304    let previous = previous
305        .iter()
306        .map(|session| (session.session_id, session))
307        .collect::<HashMap<_, _>>();
308    let listening_ports = snapshot
309        .listening_ports
310        .iter()
311        .map(|ports| (ports.pane_id, ports.tcp.as_slice()))
312        .collect::<HashMap<_, _>>();
313    let foreground_jobs = snapshot
314        .pane_activity
315        .iter()
316        .filter_map(|activity| activity.foreground_job.then_some(activity.pane_id))
317        .collect::<HashSet<_>>();
318    snapshot
319        .sessions
320        .iter()
321        .filter(|session| session.worktree_id == worktree.id)
322        .map(|session| {
323            let focused = snapshot
324                .panes
325                .iter()
326                .find(|pane| pane.id == session.focused_pane)
327                .ok_or_else(|| anyhow!("session {} has no focused pane", session.id))?;
328            let old = previous.get(&session.id).copied();
329            let panes = session
330                .panes
331                .iter()
332                .map(|pane_id| {
333                    let pane = snapshot
334                        .panes
335                        .iter()
336                        .find(|pane| pane.id == *pane_id)
337                        .ok_or_else(|| {
338                            anyhow!("session {} references missing pane {}", session.id, pane_id)
339                        })?;
340                    Ok(PaneInfo {
341                        pane_id: pane.id,
342                        terminal_id: pane.terminal_id,
343                        label: pane.label.clone(),
344                        agent: pane.agent.as_ref().map(|agent| agent.provider.clone()),
345                        agent_status: pane
346                            .agent
347                            .as_ref()
348                            .map_or(AgentState::Unknown, |agent| agent.state),
349                        revision: pane.revision,
350                        exited: pane.exited,
351                        listening_ports: listening_ports
352                            .get(&pane.id)
353                            .copied()
354                            .unwrap_or_default()
355                            .to_vec(),
356                        foreground_job: foreground_jobs.contains(&pane.id),
357                        outcome_acknowledged: old
358                            .and_then(|session| {
359                                session
360                                    .panes
361                                    .iter()
362                                    .find(|previous| previous.terminal_id == pane.terminal_id)
363                            })
364                            .is_some_and(|previous| {
365                                previous.revision == pane.revision && previous.outcome_acknowledged
366                            }),
367                    })
368                })
369                .collect::<Result<Vec<_>>>()?;
370            let revision = session.revision.max(focused.revision);
371            let outcome_acknowledged = panes
372                .iter()
373                .find(|pane| pane.pane_id == focused.id)
374                .is_some_and(|pane| pane.outcome_acknowledged);
375            Ok(SessionInfo {
376                session_id: session.id,
377                pane_id: focused.id,
378                terminal_id: focused.terminal_id,
379                agent: focused.agent.as_ref().map(|agent| agent.provider.clone()),
380                display_name: session.label.clone(),
381                agent_status: focused
382                    .agent
383                    .as_ref()
384                    .map_or(AgentState::Unknown, |agent| agent.state),
385                revision,
386                layout: session.layout.clone(),
387                panes,
388                muted: old.is_some_and(|session| session.muted),
389                outcome_acknowledged,
390            })
391        })
392        .collect()
393}
394
395pub fn expand_path(value: &str) -> PathBuf {
396    value
397        .strip_prefix("~/")
398        .and_then(|tail| dirs::home_dir().map(|home| home.join(tail)))
399        .unwrap_or_else(|| PathBuf::from(value))
400}
401pub fn detect_default_branch(path: &Path) -> String {
402    git_info::current_branch(path).unwrap_or_else(|| "main".into())
403}
404
405pub fn register_project(path: PathBuf, config: &mut GlobalConfig) -> Result<Project> {
406    if path.as_os_str().is_empty() {
407        bail!("empty path");
408    }
409    let path = crate::config::global::normalize_project_path(&path);
410    if !path.exists() {
411        bail!("path does not exist: {}", path.display());
412    }
413    if !is_git_repo(&path) {
414        bail!("not a git repository: {}", path.display());
415    }
416    if config.projects.iter().any(|entry| entry.path == path) {
417        bail!("project already registered: {}", path.display());
418    }
419    let name = path
420        .file_name()
421        .map(|name| name.to_string_lossy().into_owned())
422        .unwrap_or_else(|| "unknown".into());
423    let project = Project {
424        name: name.clone(),
425        path: path.clone(),
426        default_branch: detect_default_branch(&path),
427        last_agent_active_unix_ms: None,
428        last_terminal_active_unix_ms: None,
429        worktrees: git_worktree::to_worktree_infos(
430            git_worktree::list_worktrees(&path).unwrap_or_default(),
431            &HashMap::new(),
432        ),
433        routines: Vec::new(),
434        routine_revision: 0,
435        routines_expanded: true,
436        config: Some(crate::config::project::load_project_config(&path)),
437        expanded: true,
438        missing: false,
439    };
440    config.add_project(name, path);
441    Ok(project)
442}
443pub fn unregister_project(path: &PathBuf, config: &mut GlobalConfig) {
444    config.remove_project(path);
445}
446
447pub fn create_worktree(
448    repo_path: &Path,
449    default_branch: &str,
450    project_config: &ProjectConfig,
451    branch: &str,
452) -> Result<(PathBuf, Option<String>)> {
453    let path = git_worktree::create_worktree(repo_path, branch, default_branch)?;
454    let mut warning = hooks::copy_env_files(repo_path, &path, project_config)
455        .err()
456        .map(|error| format!("Warning: .env copy: {error}"));
457    if let Some(command) = &project_config.post_create {
458        if let Err(error) = hooks::run_post_create(&path, command) {
459            warning = Some(format!("Warning: postCreate: {error}"));
460        }
461    }
462    Ok((path, warning))
463}
464
465pub fn delete_worktree(repo_path: &Path, wt_path: &Path, branch: &str) -> Result<()> {
466    let client = Client::local();
467    let snapshot = runtime_snapshot()?;
468    if let Some(worktree) = snapshot
469        .worktrees
470        .iter()
471        .find(|worktree| worktree.path == wt_path)
472    {
473        for session in snapshot
474            .sessions
475            .iter()
476            .filter(|session| session.worktree_id == worktree.id)
477        {
478            expect_ack(client.call(&Request::SessionClose {
479                session_id: session.id,
480                expected_revision: session.revision,
481            })?)?;
482        }
483    }
484    git_worktree::remove_worktree(repo_path, wt_path, branch)
485}
486fn snapshot_with_worktree<F>(
487    snapshot: Snapshot,
488    worktree_path: &Path,
489    synchronize_once: F,
490) -> Result<(Snapshot, WorktreeId)>
491where
492    F: FnOnce() -> Result<Snapshot>,
493{
494    if let Some(id) = snapshot
495        .worktrees
496        .iter()
497        .find(|worktree| worktree.path == worktree_path)
498        .map(|worktree| worktree.id)
499    {
500        return Ok((snapshot, id));
501    }
502    let refreshed = synchronize_once()?;
503    let id = refreshed
504        .worktrees
505        .iter()
506        .find(|worktree| worktree.path == worktree_path)
507        .map(|worktree| worktree.id)
508        .ok_or_else(|| anyhow!("worktree is not synchronized with wsx daemon"))?;
509    Ok((refreshed, id))
510}
511
512pub fn create_session(
513    config: &GlobalConfig,
514    project_name: &str,
515    _worktree_slug: &str,
516    worktree_path: &Path,
517    session_label: Option<String>,
518    command: Option<String>,
519) -> Result<(SessionId, String)> {
520    let client = Client::local();
521    let (snapshot, worktree_id) =
522        snapshot_with_worktree(runtime_snapshot()?, worktree_path, || {
523            let discovery = discover_workspace(config)?;
524            synchronize_discovery(&discovery)
525        })?;
526    let base = session_label
527        .filter(|label| !label.trim().is_empty())
528        .or_else(|| {
529            command
530                .as_ref()
531                .and_then(|command| command.split_whitespace().next().map(str::to_owned))
532        })
533        .unwrap_or_else(|| project_name.to_owned());
534    let used = snapshot
535        .sessions
536        .iter()
537        .filter(|session| session.worktree_id == worktree_id)
538        .map(|session| session.label.as_str())
539        .collect::<std::collections::HashSet<_>>();
540    let mut label = base.clone();
541    let mut suffix = 2;
542    while used.contains(label.as_str()) {
543        label = format!("{base}-{suffix}");
544        suffix += 1;
545    }
546    let response = client.call(&Request::SessionCreate {
547        worktree_id,
548        label: label.clone(),
549        command: Vec::new(),
550        initial_input: command,
551        rows: 24,
552        cols: 80,
553    })?;
554    let session_id = match response {
555        Response::Created { id, .. } => SessionId(id),
556        Response::Error(error) => bail!("{}: {}", error.code, error.message),
557        _ => bail!("wsx daemon returned an unexpected create response"),
558    };
559    Ok((session_id, label))
560}
561
562pub fn reorder_session(
563    session_id: SessionId,
564    target_session_id: SessionId,
565    placement: SessionPlacement,
566    expected_revision: u64,
567) -> Result<u64> {
568    expect_ack_revision(Client::local().call(&Request::SessionReorder {
569        session_id,
570        target_session_id,
571        placement,
572        expected_revision,
573    })?)
574}
575
576pub fn rename_session(session_id: SessionId, new_label: &str) -> Result<()> {
577    let snapshot = runtime_snapshot()?;
578    let session = snapshot
579        .sessions
580        .iter()
581        .find(|session| session.id == session_id)
582        .ok_or_else(|| anyhow!("session not found"))?;
583    expect_ack(Client::local().call(&Request::SessionRename {
584        session_id,
585        label: new_label.into(),
586        expected_revision: session.revision,
587    })?)
588}
589pub fn kill_session(session_id: SessionId) -> Result<()> {
590    let snapshot = runtime_snapshot()?;
591    let session = snapshot
592        .sessions
593        .iter()
594        .find(|session| session.id == session_id)
595        .ok_or_else(|| anyhow!("session not found"))?;
596    expect_ack(Client::local().call(&Request::SessionClose {
597        session_id,
598        expected_revision: session.revision,
599    })?)
600}
601
602fn expect_ack(response: Response) -> Result<()> {
603    expect_ack_revision(response).map(|_| ())
604}
605
606fn expect_ack_revision(response: Response) -> Result<u64> {
607    match response {
608        Response::Ack { revision } => Ok(revision),
609        Response::Error(error) => bail!("{}: {}", error.code, error.message),
610        _ => bail!("wsx daemon returned an unexpected mutation response"),
611    }
612}
613pub fn set_alias(config: &mut GlobalConfig, project_path: &PathBuf, branch: &str, alias: &str) {
614    config.set_alias(project_path, branch, alias);
615}
616
617#[cfg(test)]
618mod tests {
619    use super::*;
620    use crate::runtime::{
621        self, Capabilities, Pane, PaneId, PaneLayout, Project as RuntimeProject, ProjectId,
622        Session, TerminalId, Worktree, WorktreeId,
623    };
624
625    #[test]
626    fn projection_lists_sessions_directly_under_their_worktree() {
627        let snapshot = Snapshot {
628            protocol: runtime::PROTOCOL_VERSION,
629            epoch: 1,
630            revision: 4,
631            projects: vec![RuntimeProject {
632                id: ProjectId(1),
633                path: "/repo".into(),
634                name: "repo".into(),
635                revision: 1,
636                last_agent_active_unix_ms: Some(42),
637                last_terminal_active_unix_ms: Some(43),
638            }],
639            worktrees: vec![Worktree {
640                id: WorktreeId(2),
641                project_id: ProjectId(1),
642                path: "/repo".into(),
643                branch: "main".into(),
644                revision: 1,
645            }],
646            sessions: vec![Session {
647                id: SessionId(3),
648                worktree_id: WorktreeId(2),
649                label: "shell".into(),
650                primary_pane: PaneId(4),
651                focused_pane: PaneId(6),
652                panes: vec![PaneId(4), PaneId(6)],
653                layout: PaneLayout::Split {
654                    axis: runtime::SplitAxis::Vertical,
655                    ratio_millis: 500,
656                    first: Box::new(PaneLayout::Leaf { pane_id: PaneId(4) }),
657                    second: Box::new(PaneLayout::Leaf { pane_id: PaneId(6) }),
658                },
659                revision: 4,
660            }],
661            panes: vec![
662                Pane {
663                    id: PaneId(4),
664                    terminal_id: TerminalId(5),
665                    session_id: SessionId(3),
666                    label: "primary".into(),
667                    agent: None,
668                    exited: false,
669                    revision: 4,
670                },
671                Pane {
672                    id: PaneId(6),
673                    terminal_id: TerminalId(7),
674                    session_id: SessionId(3),
675                    label: "split".into(),
676                    agent: None,
677                    exited: false,
678                    revision: 4,
679                },
680            ],
681            listening_ports: vec![
682                runtime::PanePorts {
683                    pane_id: PaneId(4),
684                    tcp: vec![5173],
685                },
686                runtime::PanePorts {
687                    pane_id: PaneId(6),
688                    tcp: vec![3000, 5173],
689                },
690            ],
691            pane_activity: vec![runtime::PaneActivity {
692                pane_id: PaneId(6),
693                foreground_job: true,
694            }],
695            capabilities: Capabilities::default(),
696        };
697        let sessions = sessions_for_worktree(&snapshot, Path::new("/repo"), &[]).unwrap();
698        assert_eq!(sessions.len(), 1);
699        assert_eq!(sessions[0].session_id, SessionId(3));
700        assert_eq!(sessions[0].display_name, "shell");
701        assert_eq!(sessions[0].pane_id, PaneId(6));
702        assert_eq!(sessions[0].panes.len(), 2);
703        assert_eq!(sessions[0].panes[0].label, "primary");
704        assert_eq!(sessions[0].panes[1].label, "split");
705        assert_eq!(sessions[0].listening_ports(), vec![3000, 5173]);
706        assert!(sessions[0].has_foreground_job());
707
708        let mut workspace = WorkspaceState {
709            projects: vec![Project {
710                name: "repo".into(),
711                path: "/repo".into(),
712                default_branch: "main".into(),
713                last_agent_active_unix_ms: None,
714                last_terminal_active_unix_ms: None,
715                worktrees: Vec::new(),
716                routines: Vec::new(),
717                routine_revision: 0,
718                routines_expanded: true,
719                config: None,
720                expanded: true,
721                missing: false,
722            }],
723        };
724        refresh_sessions_from_snapshot(&mut workspace, &snapshot).unwrap();
725        assert_eq!(workspace.projects[0].last_agent_active_unix_ms, Some(42));
726        assert_eq!(workspace.projects[0].last_terminal_active_unix_ms, Some(43));
727    }
728
729    #[test]
730    fn discovery_lists_each_registered_project_once() {
731        let root = Path::new(env!("CARGO_MANIFEST_DIR"))
732            .join(".work")
733            .join(format!("discovery-{}", std::process::id()));
734        let _ = std::fs::remove_dir_all(&root);
735        let paths = [root.join("one"), root.join("two")];
736        for path in &paths {
737            std::fs::create_dir_all(path.join(".git")).unwrap();
738        }
739        let config = GlobalConfig {
740            projects: paths
741                .iter()
742                .map(|path| crate::config::global::ProjectEntry {
743                    name: path.file_name().unwrap().to_string_lossy().into_owned(),
744                    path: path.clone(),
745                    groups: Vec::new(),
746                    aliases: HashMap::new(),
747                })
748                .collect(),
749            ..GlobalConfig::default()
750        };
751        let shell = workspace_from_config(&config);
752        assert_eq!(shell.projects.len(), paths.len());
753        assert!(shell
754            .projects
755            .iter()
756            .all(|project| project.worktrees.is_empty()));
757        let calls = std::cell::Cell::new(0usize);
758
759        let discovery = discover_workspace_with(&config, |path| {
760            calls.set(calls.get() + 1);
761            Ok(vec![git_worktree::WorktreeEntry {
762                name: "main".into(),
763                path: path.to_path_buf(),
764                branch: "trunk".into(),
765                is_main: true,
766            }])
767        })
768        .unwrap();
769
770        assert_eq!(calls.get(), paths.len());
771        assert_eq!(discovery.into_worktrees().len(), paths.len());
772        let failed =
773            discover_workspace_with(&config, |_| Err(anyhow!("worktree discovery failed")));
774        assert!(failed.is_err());
775        std::fs::remove_dir_all(root).unwrap();
776    }
777
778    #[test]
779    fn session_worktree_fast_path_skips_synchronization() {
780        let (snapshot, worktree_id) = snapshot_with_worktree(
781            snapshot_with_worktree_path("/repo"),
782            Path::new("/repo"),
783            || panic!("synchronized snapshot must not refresh"),
784        )
785        .unwrap();
786
787        assert_eq!(snapshot.worktrees[0].path, Path::new("/repo"));
788        assert_eq!(worktree_id, WorktreeId(2));
789    }
790
791    #[test]
792    fn missing_session_worktree_retries_synchronization_once() {
793        let calls = std::cell::Cell::new(0usize);
794        let (snapshot, worktree_id) = snapshot_with_worktree(
795            snapshot_with_worktree_path("/other"),
796            Path::new("/repo"),
797            || {
798                calls.set(calls.get() + 1);
799                Ok(snapshot_with_worktree_path("/repo"))
800            },
801        )
802        .unwrap();
803
804        assert_eq!(calls.get(), 1);
805        assert_eq!(snapshot.worktrees[0].path, Path::new("/repo"));
806        assert_eq!(worktree_id, WorktreeId(2));
807    }
808
809    #[test]
810    fn missing_session_worktree_still_fails_after_one_synchronization() {
811        let calls = std::cell::Cell::new(0usize);
812        let error = snapshot_with_worktree(
813            snapshot_with_worktree_path("/other"),
814            Path::new("/repo"),
815            || {
816                calls.set(calls.get() + 1);
817                Ok(snapshot_with_worktree_path("/still-other"))
818            },
819        )
820        .unwrap_err();
821
822        assert_eq!(calls.get(), 1);
823        assert_eq!(
824            error.to_string(),
825            "worktree is not synchronized with wsx daemon"
826        );
827    }
828
829    fn snapshot_with_worktree_path(path: &str) -> Snapshot {
830        Snapshot {
831            protocol: runtime::PROTOCOL_VERSION,
832            epoch: 1,
833            revision: 1,
834            projects: vec![RuntimeProject {
835                id: ProjectId(1),
836                path: "/repo".into(),
837                name: "repo".into(),
838                revision: 1,
839                last_agent_active_unix_ms: None,
840                last_terminal_active_unix_ms: None,
841            }],
842            worktrees: vec![Worktree {
843                id: WorktreeId(2),
844                project_id: ProjectId(1),
845                path: path.into(),
846                branch: "main".into(),
847                revision: 1,
848            }],
849            sessions: Vec::new(),
850            panes: Vec::new(),
851            listening_ports: Vec::new(),
852            pane_activity: Vec::new(),
853            capabilities: Capabilities::default(),
854        }
855    }
856
857    #[test]
858    fn register_project_rejects_empty_paths() {
859        let mut config = GlobalConfig::default();
860        assert!(register_project(PathBuf::new(), &mut config).is_err());
861    }
862}