diff --git a/crates/ide-host/src/menu.rs b/crates/ide-host/src/menu.rs index 1d7b31d0f..af0595e65 100644 --- a/crates/ide-host/src/menu.rs +++ b/crates/ide-host/src/menu.rs @@ -9,12 +9,21 @@ use std::path::Path; /// Prefix of Open Recent item ids; the rest of the id is the project path. pub const RECENT_PREFIX: &str = "recent:"; +/// Item id of the local-projects section header in Open Recent. +pub const RECENT_LOCAL_ID: &str = "recent.local"; +/// Prefix of remote host section header ids in Open Recent. +pub const RECENT_SECTION_PREFIX: &str = "recent.section:"; /// Prefix of items the frontend lists ([`MenuConfig::dynamic`]): `dyn:` or `dyn:|`. pub const DYNAMIC_PREFIX: &str = "dyn:"; /// Action run for an Open Recent entry (argument: the project path). pub const OPEN_RECENT_ACTION: &str = "file.openRecentProject"; pub const MAX_RECENT: usize = 15; +/// Whether `id` names a non-interactive Open Recent placeholder or section header. +pub fn is_recent_placeholder(id: &str) -> bool { + id == "recent.none" || id == RECENT_LOCAL_ID || id.starts_with(RECENT_SECTION_PREFIX) +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Os { Mac, @@ -1087,33 +1096,107 @@ pub struct RemoteRecent { pub opened_at_ms: f64, } -pub struct RecentItem { - pub path: String, +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RecentSection { + pub id: String, pub label: String, } -/// The local and remote recent projects, most recently opened first. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RecentItem { + pub path: String, + pub label: String, + pub section: Option, +} + +fn parse_remote_recent(r: &RemoteRecent) -> (RecentSection, String) { + const SCHEMES: [(&str, &str, &str); 3] = + [("ssh://", "ssh", "SSH"), ("wsl://", "wsl", "WSL"), ("devcontainer://", "devContainer", "Dev Container")]; + for (prefix, kind, kind_label) in SCHEMES { + if let Some(rest) = r.location.strip_prefix(prefix) + && let Some(slash) = rest.find('/') + && slash > 0 + { + let remote_path = &rest[slash..]; + let (host, shown_path) = match r.detail.strip_suffix(remote_path).and_then(|h| h.strip_suffix(':')) { + Some(host) if !host.is_empty() => (host, remote_path), + _ => r.detail.split_once(':').unwrap_or((&rest[..slash], remote_path)), + }; + return ( + RecentSection { + id: format!("{RECENT_SECTION_PREFIX}{kind}:{host}"), + label: format!("{kind_label} · {host}"), + }, + format!("{} — {shown_path}", r.name), + ); + } + } + let (host, shown_path) = r.detail.split_once(':').unwrap_or((r.detail.as_str(), r.detail.as_str())); + ( + RecentSection { id: format!("{RECENT_SECTION_PREFIX}remote:{host}"), label: host.to_owned() }, + format!("{} — {shown_path}", r.name), + ) +} + +/// The local and remote recent projects, grouped by host in MRU order when remote projects exist. pub fn recent_items( recent: &[ide_workspace::RecentProject], remote: &[RemoteRecent], home: Option<&Path>, ) -> Vec { + enum Candidate<'a> { + Local { path: String, label: String }, + Remote(&'a RemoteRecent), + } + let local = recent.iter().map(|p| { let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) { Some(rest) => format!("~/{}", rest.display()), None => p.path.display().to_string(), }; - let item = - RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) }; - (p.opened_at_ms, item) + ( + p.opened_at_ms, + Candidate::Local { + path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) + }, + ) }); - let remote = remote.iter().map(|r| { - (r.opened_at_ms, RecentItem { path: r.location.clone(), label: format!("{} — {}", r.name, r.detail) }) - }); - let mut items: Vec<(f64, RecentItem)> = local.chain(remote).collect(); + let remote_candidates = remote.iter().map(|r| (r.opened_at_ms, Candidate::Remote(r))); + let mut items: Vec<(f64, Candidate<'_>)> = local.chain(remote_candidates).collect(); // Stable: the local list's own order holds among equal times. items.sort_by(|a, b| b.0.total_cmp(&a.0)); - items.into_iter().take(MAX_RECENT).map(|(_, item)| item).collect() + items.truncate(MAX_RECENT); + + let has_remote = items.iter().any(|(_, c)| matches!(c, Candidate::Remote(_))); + if !has_remote { + return items + .into_iter() + .filter_map(|(_, c)| match c { + Candidate::Local { path, label } => Some(RecentItem { path, label, section: None }), + Candidate::Remote(_) => None, + }) + .collect(); + } + + let mut groups: Vec<(String, Vec)> = Vec::new(); + for (_, candidate) in items { + let (section, path, label) = match candidate { + Candidate::Local { path, label } => { + (RecentSection { id: RECENT_LOCAL_ID.into(), label: "Local".into() }, path, label) + } + Candidate::Remote(r) => { + let (section, label) = parse_remote_recent(r); + (section, r.location.clone(), label) + } + }; + let item = RecentItem { path, label, section: Some(section.clone()) }; + if let Some((_, members)) = groups.iter_mut().find(|(id, _)| *id == section.id) { + members.push(item); + } else { + groups.push((section.id, vec![item])); + } + } + groups.into_iter().flat_map(|(_, members)| members).collect() } /// A menu entry for a menu bar drawn by the frontend (Windows title bar). @@ -1202,13 +1285,30 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec< Entry::RecentProjects if recent.is_empty() => { out.push(MenuNode::Placeholder { id: "recent.none".into(), label: "No Recent Projects".into() }) } - Entry::RecentProjects => out.extend(recent.iter().map(|r| MenuNode::Action { - id: OPEN_RECENT_ACTION.into(), - label: r.label.clone(), - hint: None, - arg: Some(r.path.clone()), - checked: None, - })), + Entry::RecentProjects => { + let mut current_section: Option<&str> = None; + for r in recent { + if let Some(sec) = &r.section + && current_section != Some(sec.id.as_str()) + { + if current_section.is_some() { + out.push(MenuNode::Separator); + } + out.push(MenuNode::Placeholder { + id: sec.id.clone(), + label: config.label(&sec.id, &sec.label), + }); + current_section = Some(sec.id.as_str()); + } + out.push(MenuNode::Action { + id: OPEN_RECENT_ACTION.into(), + label: r.label.clone(), + hint: None, + arg: Some(r.path.clone()), + checked: None, + }); + } + } } } out diff --git a/e2e/recentProjectsByHost.spec.ts b/e2e/recentProjectsByHost.spec.ts new file mode 100644 index 000000000..fc8abcf93 --- /dev/null +++ b/e2e/recentProjectsByHost.spec.ts @@ -0,0 +1,119 @@ +import { expect, stubDesktop, test } from "./fixtures"; + +test("groups recent projects by Local and remote host across Welcome, Recent Projects, and Project Popup without row overlap", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 980, height: 740 }); + await stubDesktop(page); + + await page.evaluate(async () => { + const localProjects = [ + { path: "/Users/dev/git/gocommon", name: "gocommon", openedAtMs: 70_000, branch: "main" }, + { path: "/Users/dev/git/openidea_all", name: "openidea_all", openedAtMs: 40_000, branch: null }, + { path: "/Users/dev/git/superpowers", name: "superpowers", openedAtMs: 20_000, branch: "main" }, + ]; + const remoteProjects = [ + { + target: { kind: "ssh", config: "devbox" }, + path: "/home/coder/git/openidea_all", + name: "openidea_all", + host: "dev@devbox.coder:22", + openedAtMs: 100_000, + }, + { + target: { kind: "ssh", config: "mbp1" }, + path: "/Users/dev/git/gocommon", + name: "gocommon", + host: "dev-mbp1.local", + openedAtMs: 90_000, + }, + { + target: { kind: "ssh", config: "devbox" }, + path: "/home/coder/git/gocommon", + name: "gocommon", + host: "dev@devbox.coder:22", + openedAtMs: 60_000, + }, + { + target: { kind: "wsl", distro: "Ubuntu-24.04" }, + path: "/home/dev/git/openidea_all", + name: "openidea_all", + host: "Ubuntu-24.04", + openedAtMs: 30_000, + }, + ]; + localStorage.setItem("openidea.remote.recent", JSON.stringify(remoteProjects)); + + window.__ipc.handlers.recent_projects = () => localProjects; + window.__ipc.handlers.recent_project_groups = () => []; + window.__ipc.handlers.app_info = () => ({ version: "0.1.55" }); + window.__ipc.handlers.window_open_projects = () => [ + { name: "openidea_all", root: "/Users/dev/git/openidea_all", current: true, remote: null }, + { + name: "openidea_all", + root: "/home/coder/git/openidea_all", + current: false, + remote: { kind: "ssh", config: "devbox" }, + }, + ]; + + const projectMod = "/src/platform/project.ts"; + const recentMod = "/src/features/welcome/recent.ts"; + const { useProject } = await import(/* @vite-ignore */ projectMod); + const { loadRecent, useRecent } = await import(/* @vite-ignore */ recentMod); + await loadRecent(); + useRecent.setState({ home: "/Users/dev" }); + const prev = useProject.getState().project; + if (prev) { + useProject.setState({ + project: { ...prev, name: "openidea_all", displayName: "openidea_all", root: "/Users/dev/git/openidea_all" }, + }); + } + }); + + // 1. Project Widget dropdown keeps Open Projects flat and groups Recent Projects by host. + await page.getByRole("button", { name: "openidea_all" }).click(); + const projectPopup = page.getByRole("dialog", { name: "Projects" }); + await expect(projectPopup).toBeVisible(); + await expect(projectPopup).toContainText("Open Projects"); + await expect(projectPopup).toContainText("Recent Projects"); + await expect(projectPopup).toContainText("dev-mbp1.local"); + await expect(projectPopup).toContainText("Local"); + await expect(projectPopup).toContainText("Ubuntu-24.04"); + await page.keyboard.press("Escape"); + await expect(projectPopup).toBeHidden(); + + // 2. Recent Projects popup groups by host and never overlaps rows (grouped or 3-line search results). + await page.evaluate(async () => { + const popupMod = "/src/features/welcome/RecentProjectsPopup.tsx"; + const { showRecentProjectsPopup } = await import(/* @vite-ignore */ popupMod); + showRecentProjectsPopup(); + }); + const recentDialog = page.getByRole("dialog", { name: "Recent Projects" }); + await expect(recentDialog).toBeVisible(); + const assertNoVerticalOverlap = async () => { + const options = recentDialog.getByRole("option"); + const count = await options.count(); + expect(count).toBeGreaterThan(1); + const boxes = await Promise.all(Array.from({ length: count }, (_, i) => options.nth(i).boundingBox())); + for (let i = 1; i < boxes.length; i++) { + expect(boxes[i]!.y).toBeGreaterThanOrEqual(boxes[i - 1]!.y + boxes[i - 1]!.height - 0.5); + } + }; + await assertNoVerticalOverlap(); + await recentDialog.getByRole("textbox", { name: "Search recent projects" }).fill("openidea_all"); + await assertNoVerticalOverlap(); + await page.keyboard.press("Escape"); + await expect(recentDialog).toBeHidden(); + + // 3. Welcome › Projects folds and unfolds host groups. + await page.evaluate(async () => { + const projectMod = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectMod); + useProject.setState({ project: null, lightEdit: false }); + }); + const welcomeList = page.getByRole("listbox", { name: "Recent projects" }); + await expect(welcomeList.getByRole("option")).toHaveCount(11); + await welcomeList.getByRole("option").first().click(); + await expect(welcomeList.getByRole("option")).toHaveCount(9); +}); diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 7420abf25..9442cc775 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -94,7 +94,7 @@ pub fn fires_natively(spec: &[Entry], id: &str) -> bool { /// The action an item id stands for, if it is an IDE action item. fn item_action(id: &str) -> Option<&str> { - if id.starts_with(RECENT_PREFIX) || id == "recent.none" || id.starts_with("submenu:") { + if id.starts_with(RECENT_PREFIX) || is_recent_placeholder(id) || id.starts_with("submenu:") { return None; } Some(id.strip_prefix(DYNAMIC_PREFIX).map_or(id, |rest| rest.split_once('|').map_or(rest, |(a, _)| a))) @@ -102,7 +102,7 @@ fn item_action(id: &str) -> Option<&str> { /// Whether the item `id` is enabled given the disabled action ids. pub fn item_enabled(id: &str, disabled: &HashSet) -> bool { - id != "recent.none" && item_action(id).is_none_or(|a| !disabled.contains(a)) + !is_recent_placeholder(id) && item_action(id).is_none_or(|a| !disabled.contains(a)) } /// Updates the enabled state of the installed menu's items in place (no rebuild). @@ -254,7 +254,20 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) - text: config.label("recent.none", "No Recent Projects"), }), Entry::RecentProjects => { + let mut current_section: Option<&str> = None; for item in recent { + if let Some(sec) = &item.section + && current_section != Some(sec.id.as_str()) + { + if current_section.is_some() { + out.push(RenderedItem::Separator); + } + out.push(RenderedItem::Placeholder { + id: sec.id.clone(), + text: config.label(&sec.id, &sec.label), + }); + current_section = Some(sec.id.as_str()); + } out.push(RenderedItem::Action { id: format!("{RECENT_PREFIX}{}", item.path), text: item.label.clone(), @@ -769,7 +782,7 @@ mod tests { fn recent_projects_change_only_the_file_menu() { let entries = spec(Os::Mac); let config = MenuConfig::default(); - let recent = [RecentItem { path: "/p/a".into(), label: "a — ~/a".into() }]; + let recent = [RecentItem { path: "/p/a".into(), label: "a — ~/a".into(), section: None }]; assert_eq!( changed_menus(&render_bar(&entries, &config, &[]), &render_bar(&entries, &config, &recent)), ["file"] @@ -808,7 +821,13 @@ mod tests { let spec = spec(Os::Mac); assert_eq!(route(&spec, "submenu:file"), None); assert_eq!(route(&spec, "recent.none"), None); + assert_eq!(route(&spec, "recent.local"), None); + assert_eq!(route(&spec, "recent.section:ssh:dev@host:22"), None); assert_eq!(route(&spec, "nonexistent.action"), None); + let disabled = HashSet::new(); + assert!(!item_enabled("recent.none", &disabled)); + assert!(!item_enabled("recent.local", &disabled)); + assert!(!item_enabled("recent.section:ssh:dev@host:22", &disabled)); } #[test] @@ -1076,7 +1095,7 @@ mod tests { } #[test] - fn remote_projects_join_the_recent_list_by_when_they_were_opened() { + fn remote_projects_group_open_recent_by_host_in_mru_order() { let local = |path: &str, at: f64| ide_workspace::RecentProject { path: path.into(), name: path.rsplit('/').next().unwrap().into(), @@ -1085,19 +1104,99 @@ mod tests { missing: false, }; let recent = vec![local("/home/me/new", 30.0), local("/home/me/old", 10.0)]; - let remote = [RemoteRecent { - location: "wsl://Ubuntu/home/me/api".into(), - name: "api".into(), - detail: "Ubuntu:/home/me/api".into(), - opened_at_ms: 20.0, - }]; + let remote = [ + RemoteRecent { + location: "ssh://devbox/home/coder/app".into(), + name: "app".into(), + detail: "dev@devbox.coder:22:/home/coder/app".into(), + opened_at_ms: 25.0, + }, + RemoteRecent { + location: "wsl://Ubuntu/home/me/api".into(), + name: "api".into(), + detail: "Ubuntu:/home/me/api".into(), + opened_at_ms: 20.0, + }, + RemoteRecent { + location: "ssh://devbox/home/coder/lib".into(), + name: "lib".into(), + detail: "dev@devbox.coder:22:/home/coder/lib".into(), + opened_at_ms: 5.0, + }, + ]; let items = recent_items(&recent, &remote, Some(Path::new("/home/me"))); let paths: Vec<&str> = items.iter().map(|i| i.path.as_str()).collect(); - assert_eq!(paths, ["/home/me/new", "wsl://Ubuntu/home/me/api", "/home/me/old"]); - assert_eq!(items[1].label, "api — Ubuntu:/home/me/api"); + assert_eq!( + paths, + [ + "/home/me/new", + "/home/me/old", + "ssh://devbox/home/coder/app", + "ssh://devbox/home/coder/lib", + "wsl://Ubuntu/home/me/api", + ] + ); + assert_eq!(items[0].section.as_ref().map(|s| s.label.as_str()), Some("Local")); + assert_eq!(items[2].section.as_ref().map(|s| s.label.as_str()), Some("SSH · dev@devbox.coder:22")); + assert_eq!(items[2].label, "app — /home/coder/app"); + assert_eq!(items[4].section.as_ref().map(|s| s.label.as_str()), Some("WSL · Ubuntu")); + assert_eq!(items[4].label, "api — /home/me/api"); + + let spec = vec![sub("openRecent", "Open Recent", vec![Entry::RecentProjects])]; + let mut config = MenuConfig::default(); + config.labels.insert("menu.recent.local".into(), "本地".into()); + let MenuNode::Submenu { children, .. } = &model(&spec, &items, &config)[0] else { panic!("not a submenu") }; + assert_eq!( + children, + &[ + MenuNode::Placeholder { id: "recent.local".into(), label: "本地".into() }, + MenuNode::Action { + id: OPEN_RECENT_ACTION.into(), + label: "new — ~/new".into(), + hint: None, + arg: Some("/home/me/new".into()), + checked: None, + }, + MenuNode::Action { + id: OPEN_RECENT_ACTION.into(), + label: "old — ~/old".into(), + hint: None, + arg: Some("/home/me/old".into()), + checked: None, + }, + MenuNode::Separator, + MenuNode::Placeholder { + id: "recent.section:ssh:dev@devbox.coder:22".into(), + label: "SSH · dev@devbox.coder:22".into(), + }, + MenuNode::Action { + id: OPEN_RECENT_ACTION.into(), + label: "app — /home/coder/app".into(), + hint: None, + arg: Some("ssh://devbox/home/coder/app".into()), + checked: None, + }, + MenuNode::Action { + id: OPEN_RECENT_ACTION.into(), + label: "lib — /home/coder/lib".into(), + hint: None, + arg: Some("ssh://devbox/home/coder/lib".into()), + checked: None, + }, + MenuNode::Separator, + MenuNode::Placeholder { id: "recent.section:wsl:Ubuntu".into(), label: "WSL · Ubuntu".into() }, + MenuNode::Action { + id: OPEN_RECENT_ACTION.into(), + label: "api — /home/me/api".into(), + hint: None, + arg: Some("wsl://Ubuntu/home/me/api".into()), + checked: None, + }, + ] + ); let many: Vec<_> = (0..20).map(|i| local(&format!("/p/{i}"), f64::from(i))).collect(); - let items = recent_items(&many, &remote, None); + let items = recent_items(&many, &remote[1..2], None); assert_eq!(items.len(), MAX_RECENT); assert_eq!([items[0].path.as_str(), items[1].path.as_str()], ["wsl://Ubuntu/home/me/api", "/p/19"]); assert_eq!(items[MAX_RECENT - 1].path, format!("/p/{}", 20 - MAX_RECENT + 1), "the remote one takes a slot"); @@ -1110,7 +1209,7 @@ mod tests { "File", vec![Entry::Native(Native::Undo), act("file.save", "Save All"), SEP, Entry::RecentProjects], )]; - let recent = [RecentItem { path: "/p/a".into(), label: "a — ~/a".into() }]; + let recent = [RecentItem { path: "/p/a".into(), label: "a — ~/a".into(), section: None }]; let MenuNode::Submenu { children, .. } = &model(&spec, &recent, &MenuConfig::default())[0] else { panic!("not a submenu") }; diff --git a/src/features/welcome/ProjectPopup.test.tsx b/src/features/welcome/ProjectPopup.test.tsx index 8269a95d0..4241cc274 100644 --- a/src/features/welcome/ProjectPopup.test.tsx +++ b/src/features/welcome/ProjectPopup.test.tsx @@ -172,4 +172,48 @@ describe("ProjectPopup", () => { fireEvent.keyDown(list, { key: "Enter" }); expect(openRecent).toHaveBeenLastCalledWith(exampleWeb, null); }); + + it("groups Recent Projects by host in MRU order while keeping Open Projects flat", async () => { + const sshA = { kind: "ssh", config: "devbox" } as const; + const sshB = { kind: "ssh", config: "mbp" } as const; + open = [{ name: "openidea_all", root: "/Users/me/git/openidea_all", current: true, remote: null }]; + groups = []; + recent = [ + { path: remoteLocation(sshA, "/srv/openidea_all"), name: "openidea_all", openedAtMs: 90, branch: null }, + { path: "/Users/me/git/gocommon", name: "gocommon", openedAtMs: 80, branch: "main" }, + { path: remoteLocation(sshB, "/Users/dev/gocommon"), name: "gocommon", openedAtMs: 70, branch: null }, + { path: remoteLocation(sshA, "/srv/gocommon"), name: "gocommon", openedAtMs: 60, branch: null }, + { path: "/Users/me/git/superpowers", name: "superpowers", openedAtMs: 50, branch: null }, + ]; + const anchor = createRef(); + render( + <> +