1use 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 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}
486pub fn create_session(
487 project_name: &str,
488 _worktree_slug: &str,
489 worktree_path: &Path,
490 session_label: Option<String>,
491 command: Option<String>,
492) -> Result<(SessionId, String)> {
493 let client = Client::local();
494 let snapshot = runtime_snapshot()?;
495 let worktree = snapshot
496 .worktrees
497 .iter()
498 .find(|worktree| worktree.path == worktree_path)
499 .ok_or_else(|| anyhow!("worktree is not synchronized with wsx daemon"))?;
500 let base = session_label
501 .filter(|label| !label.trim().is_empty())
502 .or_else(|| {
503 command
504 .as_ref()
505 .and_then(|command| command.split_whitespace().next().map(str::to_owned))
506 })
507 .unwrap_or_else(|| project_name.to_owned());
508 let used = snapshot
509 .sessions
510 .iter()
511 .filter(|session| session.worktree_id == worktree.id)
512 .map(|session| session.label.as_str())
513 .collect::<std::collections::HashSet<_>>();
514 let mut label = base.clone();
515 let mut suffix = 2;
516 while used.contains(label.as_str()) {
517 label = format!("{base}-{suffix}");
518 suffix += 1;
519 }
520 let response = client.call(&Request::SessionCreate {
521 worktree_id: worktree.id,
522 label: label.clone(),
523 command: Vec::new(),
524 initial_input: command,
525 rows: 24,
526 cols: 80,
527 })?;
528 let session_id = match response {
529 Response::Created { id, .. } => SessionId(id),
530 Response::Error(error) => bail!("{}: {}", error.code, error.message),
531 _ => bail!("wsx daemon returned an unexpected create response"),
532 };
533 Ok((session_id, label))
534}
535
536pub fn reorder_session(
537 session_id: SessionId,
538 target_session_id: SessionId,
539 placement: SessionPlacement,
540 expected_revision: u64,
541) -> Result<u64> {
542 expect_ack_revision(Client::local().call(&Request::SessionReorder {
543 session_id,
544 target_session_id,
545 placement,
546 expected_revision,
547 })?)
548}
549
550pub fn rename_session(session_id: SessionId, new_label: &str) -> Result<()> {
551 let snapshot = runtime_snapshot()?;
552 let session = snapshot
553 .sessions
554 .iter()
555 .find(|session| session.id == session_id)
556 .ok_or_else(|| anyhow!("session not found"))?;
557 expect_ack(Client::local().call(&Request::SessionRename {
558 session_id,
559 label: new_label.into(),
560 expected_revision: session.revision,
561 })?)
562}
563pub fn kill_session(session_id: SessionId) -> Result<()> {
564 let snapshot = runtime_snapshot()?;
565 let session = snapshot
566 .sessions
567 .iter()
568 .find(|session| session.id == session_id)
569 .ok_or_else(|| anyhow!("session not found"))?;
570 expect_ack(Client::local().call(&Request::SessionClose {
571 session_id,
572 expected_revision: session.revision,
573 })?)
574}
575
576fn expect_ack(response: Response) -> Result<()> {
577 expect_ack_revision(response).map(|_| ())
578}
579
580fn expect_ack_revision(response: Response) -> Result<u64> {
581 match response {
582 Response::Ack { revision } => Ok(revision),
583 Response::Error(error) => bail!("{}: {}", error.code, error.message),
584 _ => bail!("wsx daemon returned an unexpected mutation response"),
585 }
586}
587pub fn set_alias(config: &mut GlobalConfig, project_path: &PathBuf, branch: &str, alias: &str) {
588 config.set_alias(project_path, branch, alias);
589}
590
591#[cfg(test)]
592mod tests {
593 use super::*;
594 use crate::runtime::{
595 self, Capabilities, Pane, PaneId, PaneLayout, Project as RuntimeProject, ProjectId,
596 Session, TerminalId, Worktree, WorktreeId,
597 };
598
599 #[test]
600 fn projection_lists_sessions_directly_under_their_worktree() {
601 let snapshot = Snapshot {
602 protocol: runtime::PROTOCOL_VERSION,
603 epoch: 1,
604 revision: 4,
605 projects: vec![RuntimeProject {
606 id: ProjectId(1),
607 path: "/repo".into(),
608 name: "repo".into(),
609 revision: 1,
610 last_agent_active_unix_ms: Some(42),
611 last_terminal_active_unix_ms: Some(43),
612 }],
613 worktrees: vec![Worktree {
614 id: WorktreeId(2),
615 project_id: ProjectId(1),
616 path: "/repo".into(),
617 branch: "main".into(),
618 revision: 1,
619 }],
620 sessions: vec![Session {
621 id: SessionId(3),
622 worktree_id: WorktreeId(2),
623 label: "shell".into(),
624 primary_pane: PaneId(4),
625 focused_pane: PaneId(6),
626 panes: vec![PaneId(4), PaneId(6)],
627 layout: PaneLayout::Split {
628 axis: runtime::SplitAxis::Vertical,
629 ratio_millis: 500,
630 first: Box::new(PaneLayout::Leaf { pane_id: PaneId(4) }),
631 second: Box::new(PaneLayout::Leaf { pane_id: PaneId(6) }),
632 },
633 revision: 4,
634 }],
635 panes: vec![
636 Pane {
637 id: PaneId(4),
638 terminal_id: TerminalId(5),
639 session_id: SessionId(3),
640 label: "primary".into(),
641 agent: None,
642 exited: false,
643 revision: 4,
644 },
645 Pane {
646 id: PaneId(6),
647 terminal_id: TerminalId(7),
648 session_id: SessionId(3),
649 label: "split".into(),
650 agent: None,
651 exited: false,
652 revision: 4,
653 },
654 ],
655 listening_ports: vec![
656 runtime::PanePorts {
657 pane_id: PaneId(4),
658 tcp: vec![5173],
659 },
660 runtime::PanePorts {
661 pane_id: PaneId(6),
662 tcp: vec![3000, 5173],
663 },
664 ],
665 pane_activity: vec![runtime::PaneActivity {
666 pane_id: PaneId(6),
667 foreground_job: true,
668 }],
669 capabilities: Capabilities::default(),
670 };
671 let sessions = sessions_for_worktree(&snapshot, Path::new("/repo"), &[]).unwrap();
672 assert_eq!(sessions.len(), 1);
673 assert_eq!(sessions[0].session_id, SessionId(3));
674 assert_eq!(sessions[0].display_name, "shell");
675 assert_eq!(sessions[0].pane_id, PaneId(6));
676 assert_eq!(sessions[0].panes.len(), 2);
677 assert_eq!(sessions[0].panes[0].label, "primary");
678 assert_eq!(sessions[0].panes[1].label, "split");
679 assert_eq!(sessions[0].listening_ports(), vec![3000, 5173]);
680 assert!(sessions[0].has_foreground_job());
681
682 let mut workspace = WorkspaceState {
683 projects: vec![Project {
684 name: "repo".into(),
685 path: "/repo".into(),
686 default_branch: "main".into(),
687 last_agent_active_unix_ms: None,
688 last_terminal_active_unix_ms: None,
689 worktrees: Vec::new(),
690 routines: Vec::new(),
691 routine_revision: 0,
692 routines_expanded: true,
693 config: None,
694 expanded: true,
695 missing: false,
696 }],
697 };
698 refresh_sessions_from_snapshot(&mut workspace, &snapshot).unwrap();
699 assert_eq!(workspace.projects[0].last_agent_active_unix_ms, Some(42));
700 assert_eq!(workspace.projects[0].last_terminal_active_unix_ms, Some(43));
701 }
702
703 #[test]
704 fn discovery_lists_each_registered_project_once() {
705 let root = Path::new(env!("CARGO_MANIFEST_DIR"))
706 .join(".work")
707 .join(format!("discovery-{}", std::process::id()));
708 let _ = std::fs::remove_dir_all(&root);
709 let paths = [root.join("one"), root.join("two")];
710 for path in &paths {
711 std::fs::create_dir_all(path.join(".git")).unwrap();
712 }
713 let config = GlobalConfig {
714 projects: paths
715 .iter()
716 .map(|path| crate::config::global::ProjectEntry {
717 name: path.file_name().unwrap().to_string_lossy().into_owned(),
718 path: path.clone(),
719 groups: Vec::new(),
720 aliases: HashMap::new(),
721 })
722 .collect(),
723 ..GlobalConfig::default()
724 };
725 let shell = workspace_from_config(&config);
726 assert_eq!(shell.projects.len(), paths.len());
727 assert!(shell
728 .projects
729 .iter()
730 .all(|project| project.worktrees.is_empty()));
731 let calls = std::cell::Cell::new(0usize);
732
733 let discovery = discover_workspace_with(&config, |path| {
734 calls.set(calls.get() + 1);
735 Ok(vec![git_worktree::WorktreeEntry {
736 name: "main".into(),
737 path: path.to_path_buf(),
738 branch: "trunk".into(),
739 is_main: true,
740 }])
741 })
742 .unwrap();
743
744 assert_eq!(calls.get(), paths.len());
745 assert_eq!(discovery.into_worktrees().len(), paths.len());
746 let failed =
747 discover_workspace_with(&config, |_| Err(anyhow!("worktree discovery failed")));
748 assert!(failed.is_err());
749 std::fs::remove_dir_all(root).unwrap();
750 }
751
752 #[test]
753 fn register_project_rejects_empty_paths() {
754 let mut config = GlobalConfig::default();
755 assert!(register_project(PathBuf::new(), &mut config).is_err());
756 }
757}