🙌 OpenHands: AI-Driven Development
feat(home): group workspace folders by parent in the dropdown (#129) (#1368)
george larson9025e81066bc
diff --git a/__tests__/components/features/home/generic-dropdown-menu.test.tsx b/__tests__/components/features/home/generic-dropdown-menu.test.tsxnew file mode 100644index 0000000000..48df3c488b--- /dev/null+++ b/__tests__/components/features/home/generic-dropdown-menu.test.tsx@@ -0,0 +1,70 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";++import { GenericDropdownMenu } from "../../../../src/components/features/home/shared/generic-dropdown-menu";++interface Item {+ id: string;+ name: string;+}++const ITEMS: Item[] = [+ { id: "a", name: "a" },+ { id: "b", name: "b" },+];++function renderMenu(props: Record<string, unknown> = {}) {+ return render(+ <GenericDropdownMenu<Item>+ isOpen+ filteredItems={ITEMS}+ inputValue=""+ highlightedIndex={-1}+ selectedItem={null}+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getMenuProps={(opts: any) => ({ ...opts })}+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getItemProps={(opts: any) => ({ ...opts })}+ renderItem={(item) => (+ <li role="option" aria-selected={false} key={item.id}>+ {item.name}+ </li>+ )}+ renderEmptyState={() => <li aria-hidden="true" />}+ testId="generic-menu"+ itemKey={(item) => item.id}+ {...props}+ />,+ );+}++describe("GenericDropdownMenu list structure", () => {+ it("renders only <li> elements as direct children of the listbox <ul> (valid list markup)", () => {+ // numberOfRecentItems > 0 triggers the recent-items divider after the+ // first item. A <ul> may only contain <li> children; a <div> divider is+ // invalid markup that a11y tooling flags (Copilot, agent-canvas#1).+ renderMenu({ numberOfRecentItems: 1 });++ const list = screen.getByTestId("generic-menu");+ const nonLiChildren = Array.from(list.children).filter(+ (el) => el.tagName !== "LI",+ );++ expect(nonLiChildren.map((el) => el.tagName)).toEqual([]);+ });++ it("keeps the recent-items divider out of the accessibility tree", () => {+ renderMenu({ numberOfRecentItems: 1 });++ // The divider must be presentational so screen readers don't announce a+ // phantom list item. Match it by its role directly (not "not an option")+ // so the assertion stays pinned if another non-option child is added.+ const list = screen.getByTestId("generic-menu");+ const divider = Array.from(list.children).find(+ (el) => el.getAttribute("role") === "presentation",+ );+ expect(divider).toBeDefined();+ expect(divider).toHaveAttribute("role", "presentation");+ expect(divider).toHaveAttribute("aria-hidden", "true");+ });+});diff --git a/__tests__/components/features/home/workspace-dropdown.test.tsx b/__tests__/components/features/home/workspace-dropdown.test.tsxnew file mode 100644index 0000000000..9e2b0fb0c2--- /dev/null+++ b/__tests__/components/features/home/workspace-dropdown.test.tsx@@ -0,0 +1,264 @@+import type { ComponentProps } from "react";+import { render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";++import { WorkspaceDropdown } from "../../../../src/components/features/home/workspace-dropdown/workspace-dropdown";+import type { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++// Two parents whose NAMES deliberately differ from their path basenames, so a+// passing assertion proves the header uses the parent name (not basename-of-path).+const PARENTS: LocalWorkspaceParent[] = [+ { id: "p1", name: "Projects", path: "/projects" },+ { id: "p2", name: "My Work", path: "/work" },+];++const GROUPED_WORKSPACES: LocalWorkspace[] = [+ {+ id: "/projects/alpha",+ name: "alpha",+ path: "/projects/alpha",+ parentPath: "/projects",+ },+ { id: "/work/beta", name: "beta", path: "/work/beta", parentPath: "/work" },+ {+ id: "/projects/gamma",+ name: "gamma",+ path: "/projects/gamma",+ parentPath: "/projects",+ },+];++function renderDropdown(+ props: Partial<ComponentProps<typeof WorkspaceDropdown>> = {},+) {+ const onChange = vi.fn();+ render(+ <WorkspaceDropdown+ workspaces={GROUPED_WORKSPACES}+ parents={PARENTS}+ value={null}+ onChange={onChange}+ onAddClick={vi.fn()}+ onManageClick={vi.fn()}+ {...props}+ />,+ );+ return { onChange };+}++async function openMenu(user: ReturnType<typeof userEvent.setup>) {+ const input = screen.getByTestId("workspace-dropdown");+ await user.click(input);+ return screen.findByTestId("workspace-dropdown-menu");+}++describe("WorkspaceDropdown grouping (#129)", () => {+ it("renders a header with the parent's NAME (not the path basename) per group", async () => {+ const user = userEvent.setup();+ renderDropdown();+ const menu = await openMenu(user);++ const headers = within(menu).getAllByTestId("workspace-group-header");+ const headerText = headers.map((h) => h.textContent);+ expect(headerText).toContain("Projects"); // not "projects"+ expect(headerText).toContain("My Work"); // not "work"+ });++ it("groups every folder under its parent and shows all folders", async () => {+ const user = userEvent.setup();+ renderDropdown();+ const menu = await openMenu(user);++ expect(within(menu).getByText("alpha")).toBeInTheDocument();+ expect(within(menu).getByText("beta")).toBeInTheDocument();+ expect(within(menu).getByText("gamma")).toBeInTheDocument();+ // alpha and gamma (both /projects) render contiguously, before beta's group+ // boundary is crossed — exactly one header per distinct parent.+ expect(within(menu).getAllByTestId("workspace-group-header")).toHaveLength(+ 2,+ );+ });++ it("keyboard navigation skips headers: ArrowDown+Enter selects a real folder", async () => {+ const user = userEvent.setup();+ const { onChange } = renderDropdown();+ await openMenu(user);++ await user.keyboard("{ArrowDown}{Enter}");++ // A header must never be selectable; the first highlight lands on a workspace.+ expect(onChange).toHaveBeenCalledTimes(1);+ const selected = onChange.mock.calls[0][0] as LocalWorkspace | null;+ expect(selected).not.toBeNull();+ expect(GROUPED_WORKSPACES.map((w) => w.id)).toContain(selected?.id);+ });++ it("does NOT render headers when there is only one group (flat fallback)", async () => {+ const user = userEvent.setup();+ renderDropdown({+ workspaces: [+ {+ id: "/projects/alpha",+ name: "alpha",+ path: "/projects/alpha",+ parentPath: "/projects",+ },+ {+ id: "/projects/gamma",+ name: "gamma",+ path: "/projects/gamma",+ parentPath: "/projects",+ },+ ],+ });+ const menu = await openMenu(user);++ expect(within(menu).queryByTestId("workspace-group-header")).toBeNull();+ expect(within(menu).getByText("alpha")).toBeInTheDocument();+ expect(within(menu).getByText("gamma")).toBeInTheDocument();+ });++ it("groups static (no-parent) workspaces under their own header", async () => {+ const user = userEvent.setup();+ renderDropdown({+ workspaces: [+ {+ id: "/projects/alpha",+ name: "alpha",+ path: "/projects/alpha",+ parentPath: "/projects",+ },+ { id: "/standalone", name: "standalone", path: "/standalone" }, // no parentPath+ ],+ });+ const menu = await openMenu(user);++ const headers = within(menu).getAllByTestId("workspace-group-header");+ // one header for the named parent, one for the static group+ expect(headers).toHaveLength(2);+ expect(within(menu).getByText("Projects")).toBeInTheDocument();+ expect(within(menu).getByText("standalone")).toBeInTheDocument();+ });++ it("labels the static group with the HOME$WORKSPACE_GROUP_OTHER i18n key", async () => {+ const user = userEvent.setup();+ renderDropdown({+ workspaces: [+ {+ id: "/projects/alpha",+ name: "alpha",+ path: "/projects/alpha",+ parentPath: "/projects",+ },+ { id: "/standalone", name: "standalone", path: "/standalone" },+ ],+ });+ const menu = await openMenu(user);++ // `t` is mocked to echo the key, so this pins the i18n wiring.+ expect(+ within(menu).getByText("HOME$WORKSPACE_GROUP_OTHER"),+ ).toBeInTheDocument();+ });++ it("renders the static 'Other' group last, even when a standalone appears first", async () => {+ const user = userEvent.setup();+ renderDropdown({+ workspaces: [+ { id: "/loose", name: "loose", path: "/loose" }, // standalone, appears FIRST+ {+ id: "/work/beta",+ name: "beta",+ path: "/work/beta",+ parentPath: "/work",+ },+ ],+ parents: [{ id: "p2", name: "My Work", path: "/work" }],+ });+ const menu = await openMenu(user);++ const headerText = within(menu)+ .getAllByTestId("workspace-group-header")+ .map((h) => h.textContent);+ expect(headerText).toEqual(["My Work", "HOME$WORKSPACE_GROUP_OTHER"]);+ });++ it("falls back to the path basename when a folder's parent is absent from `parents`", async () => {+ const user = userEvent.setup();+ renderDropdown({+ workspaces: [+ {+ id: "/work/beta",+ name: "beta",+ path: "/work/beta",+ parentPath: "/work",+ },+ {+ id: "/unknown/x",+ name: "x",+ path: "/unknown/x",+ parentPath: "/unknown",+ },+ ],+ parents: [{ id: "p2", name: "My Work", path: "/work" }], // /unknown intentionally absent+ });+ const menu = await openMenu(user);++ const headerText = within(menu)+ .getAllByTestId("workspace-group-header")+ .map((h) => h.textContent);+ expect(headerText).toContain("My Work");+ expect(headerText).toContain("unknown"); // basename of /unknown+ });++ it("folds the group label into each option's accessible name (a11y)", async () => {+ const user = userEvent.setup();+ renderDropdown();+ const menu = await openMenu(user);++ // The visual header is presentational; the group lives in each option's name.+ expect(+ within(menu).getByRole("option", { name: "Projects, alpha" }),+ ).toBeInTheDocument();+ expect(+ within(menu).getByRole("option", { name: "My Work, beta" }),+ ).toBeInTheDocument();+ });++ it("stays flat (no headers) for an all-standalone list with no parents", async () => {+ const user = userEvent.setup();+ renderDropdown({+ parents: undefined, // exercises the single STATIC_GROUP_KEY group path+ workspaces: [+ { id: "/a", name: "a", path: "/a" },+ { id: "/b", name: "b", path: "/b" },+ ],+ });+ const menu = await openMenu(user);++ expect(within(menu).queryByTestId("workspace-group-header")).toBeNull();+ expect(within(menu).getByText("a")).toBeInTheDocument();+ expect(within(menu).getByText("b")).toBeInTheDocument();+ });++ it("does not set an aria-label on options in flat (ungrouped) mode", async () => {+ const user = userEvent.setup();+ renderDropdown({+ parents: undefined,+ workspaces: [+ { id: "/a", name: "a", path: "/a" },+ { id: "/b", name: "b", path: "/b" },+ ],+ });+ const menu = await openMenu(user);++ // No grouping → the option's accessible name is just its display text.+ const option = within(menu).getByRole("option", { name: "a" });+ expect(option).not.toHaveAttribute("aria-label");+ });+});diff --git a/src/components/features/home/shared/dropdown-item.tsx b/src/components/features/home/shared/dropdown-item.tsxindex d0ccba3065..28e0612624 100644--- a/src/components/features/home/shared/dropdown-item.tsx+++ b/src/components/features/home/shared/dropdown-item.tsx@@ -16,6 +16,12 @@ interface DropdownItemProps<T> {isProviderDropdown?: boolean;renderIcon?: (item: T) => React.ReactNode;itemClassName?: string;+ /**+ * Overrides the option's accessible name. Used to fold a group label into the+ * announced name (e.g. "Projects, alpha") when the visual group header is+ * presentational and therefore invisible to assistive tech.+ */+ ariaLabel?: string;}export function DropdownItem<T>({@@ -28,10 +34,12 @@ export function DropdownItem<T>({isProviderDropdown = false,renderIcon,itemClassName,+ ariaLabel,}: DropdownItemProps<T>) {const itemProps = getItemProps({index,item,+ ...(ariaLabel ? { "aria-label": ariaLabel } : {}),className: cn(isProviderDropdown? "group px-2 py-0 cursor-pointer text-xs rounded-md mx-0 my-0 h-6 flex items-center"diff --git a/src/components/features/home/shared/generic-dropdown-menu.tsx b/src/components/features/home/shared/generic-dropdown-menu.tsxindex 025b9c434a..a5d22882bc 100644--- a/src/components/features/home/shared/generic-dropdown-menu.tsx+++ b/src/components/features/home/shared/generic-dropdown-menu.tsx@@ -29,6 +29,13 @@ export interface GenericDropdownMenuProps<T> {options: UseComboboxGetItemPropsOptions<T> & Options,) => any, // eslint-disable-line @typescript-eslint/no-explicit-any) => React.ReactNode;+ /**+ * Optional presentational node rendered immediately BEFORE an item (e.g. a+ * group header). It is a sibling of the item, not part of downshift's `items`+ * array, so it consumes no item index — mirroring the `numberOfRecentItems`+ * divider. The consumer owns when a prefix appears (e.g. at group boundaries).+ */+ renderItemPrefix?: (item: T, index: number) => React.ReactNode;renderEmptyState: (inputValue: string) => React.ReactNode;stickyTopItem?: React.ReactNode;stickyFooterItem?: React.ReactNode;@@ -48,6 +55,7 @@ export function GenericDropdownMenu<T>({onScroll,menuRef,renderItem,+ renderItemPrefix,renderEmptyState,stickyTopItem,stickyFooterItem,@@ -106,6 +114,7 @@ export function GenericDropdownMenu<T>({const key = itemKey(item);return (<React.Fragment key={key}>+ {renderItemPrefix?.(item, index)}{renderItem(item,index,@@ -115,7 +124,11 @@ export function GenericDropdownMenu<T>({)}{numberOfRecentItems > 0 &&index === numberOfRecentItems - 1 && (- <div className="border-b border-[var(--oh-border-input)] bg-tertiary pb-1 mb-1 h-[1px]" />+ <li+ role="presentation"+ aria-hidden="true"+ className="border-b border-[var(--oh-border-input)] bg-tertiary pb-1 mb-1 h-[1px]"+ />)}</React.Fragment>);diff --git a/src/components/features/home/workspace-dropdown/workspace-dropdown.tsx b/src/components/features/home/workspace-dropdown/workspace-dropdown.tsxindex 6f731d8ebf..7e0c35a782 100644--- a/src/components/features/home/workspace-dropdown/workspace-dropdown.tsx+++ b/src/components/features/home/workspace-dropdown/workspace-dropdown.tsx@@ -8,7 +8,7 @@ import {dropdownMenuListClassName,} from "#/utils/dropdown-classes";import { formControlFieldClassName } from "#/utils/form-control-classes";-import { LocalWorkspace } from "#/types/workspace";+import type { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";import { I18nKey } from "#/i18n/declaration";import RepoIcon from "#/icons/repo.svg?react";import { StyledTooltip } from "#/components/shared/buttons/styled-tooltip";@@ -19,8 +19,21 @@ import { DropdownItem } from "../shared/dropdown-item";import { EmptyState } from "../shared/empty-state";import { GenericDropdownMenu } from "../shared/generic-dropdown-menu";+// Sentinel group key for standalone workspaces (no parent). Module-scoped so+// it's a stable reference for hooks and reads clearly as a non-path sentinel.+const STATIC_GROUP_KEY = "__ungrouped__";+export interface WorkspaceDropdownProps {workspaces: LocalWorkspace[];+ /**+ * The workspace parents that produced the dynamic children in `workspaces`+ * (from `useResolvedWorkspaces`, including the implicit `/projects`). Used to+ * label each folder's group by its parent's `name`. When two or more distinct+ * groups are present the list renders grouped under headers; with one group+ * (or omitted) it stays flat. A child whose `parentPath` has no matching+ * parent here falls back to the path basename.+ */+ parents?: LocalWorkspaceParent[];value: LocalWorkspace | null;placeholder?: string;className?: string;@@ -40,6 +53,7 @@ export interface WorkspaceDropdownProps {export function WorkspaceDropdown({workspaces,+ parents = [],value,placeholder,className,@@ -64,6 +78,77 @@ export function WorkspaceDropdown({);}, [workspaces, inputValue]);+ // Group the filtered list by parent so folders from the same workspace render+ // contiguously under a header. The grouped array is the SINGLE source for both+ // downshift's `items` and the menu render, so `highlightedIndex` and keyboard+ // navigation stay in lockstep with the visible order. Headers are presentational+ // siblings (see `renderItemPrefix`) and consume no downshift index; each option+ // carries its group label as an accessible name so screen-reader users get the+ // grouping the presentational header can't convey.+ const groupKeyOf = useCallback(+ (w: LocalWorkspace) => w.parentPath ?? STATIC_GROUP_KEY,+ [],+ );+ const parentNameByPath = useMemo(() => {+ const map = new Map<string, string>();+ parents.forEach((p) => map.set(p.path, p.name));+ return map;+ }, [parents]);++ const {+ groupedWorkspaces,+ isGrouped,+ headerByFirstIndex,+ groupLabelByIndex,+ } = useMemo(() => {+ const order: string[] = [];+ const byGroup = new Map<string, LocalWorkspace[]>();+ filteredWorkspaces.forEach((w) => {+ const key = groupKeyOf(w);+ if (!byGroup.has(key)) {+ byGroup.set(key, []);+ order.push(key);+ }+ byGroup.get(key)?.push(w);+ });++ // Keep the catch-all "Other" (no-parent) group last, wherever its first+ // member happened to appear. Stable sort preserves named-group order.+ order.sort((a, b) => {+ if (a === STATIC_GROUP_KEY) return 1;+ if (b === STATIC_GROUP_KEY) return -1;+ return 0;+ });++ const grouping = order.length > 1;+ const grouped: LocalWorkspace[] = [];+ const headers = new Map<number, string>();+ const labelByIndex = new Map<number, string>();+ order.forEach((key) => {+ // `||` (not `??`) so an empty parent name falls through to the basename.+ const label =+ key === STATIC_GROUP_KEY+ ? t(I18nKey.HOME$WORKSPACE_GROUP_OTHER)+ : parentNameByPath.get(key) ||+ key.split("/").filter(Boolean).pop() ||+ key;+ if (grouping) {+ headers.set(grouped.length, label);+ }+ (byGroup.get(key) ?? []).forEach((w) => {+ labelByIndex.set(grouped.length, label);+ grouped.push(w);+ });+ });++ return {+ groupedWorkspaces: grouped,+ isGrouped: grouping,+ headerByFirstIndex: headers,+ groupLabelByIndex: labelByIndex,+ };+ }, [filteredWorkspaces, groupKeyOf, parentNameByPath, t]);+const handleSelectionChange = useCallback((selectedItem: LocalWorkspace | null) => {onChange(selectedItem);@@ -89,7 +174,7 @@ export function WorkspaceDropdown({selectedItem,closeMenu,} = useCombobox<LocalWorkspace>({- items: filteredWorkspaces,+ items: groupedWorkspaces,itemToString: (item) => item?.name ?? "",selectedItem: value,onSelectedItemChange: ({ selectedItem: newSelectedItem }) => {@@ -128,6 +213,11 @@ export function WorkspaceDropdown({getItemProps={itemGetItemProps}getDisplayText={(workspace) => workspace.name}getItemKey={(workspace) => workspace.id}+ ariaLabel={+ isGrouped+ ? `${groupLabelByIndex.get(index) ?? ""}, ${item.name}`.trim()+ : undefined+ }/>);@@ -263,7 +353,7 @@ export function WorkspaceDropdown({<GenericDropdownMenu<LocalWorkspace>isOpen={isOpen}- filteredItems={filteredWorkspaces}+ filteredItems={groupedWorkspaces}inputValue={inputValue}highlightedIndex={highlightedIndex}selectedItem={selectedItem}@@ -271,6 +361,24 @@ export function WorkspaceDropdown({getItemProps={getItemProps}menuRef={menuRef}renderItem={renderItem}+ renderItemPrefix={+ isGrouped+ ? (_item, index) => {+ const label = headerByFirstIndex.get(index);+ if (!label) return null;+ return (+ <li+ role="presentation"+ aria-hidden="true"+ data-testid="workspace-group-header"+ className="px-2 pt-2 pb-1 text-xs font-medium text-[var(--oh-muted)] select-none"+ >+ {label}+ </li>+ );+ }+ : undefined+ }renderEmptyState={renderEmptyState}stickyFooterItem={stickyFooterItem}testId="workspace-dropdown-menu"diff --git a/src/components/features/home/workspace-selection-form.tsx b/src/components/features/home/workspace-selection-form.tsxindex 5dab287849..49e5dffc7b 100644--- a/src/components/features/home/workspace-selection-form.tsx+++ b/src/components/features/home/workspace-selection-form.tsx@@ -79,6 +79,7 @@ export function WorkspaceSelectionForm({const { mutate: removeWorkspaceParent } = useRemoveWorkspaceParent();const {workspaces,+ parents: resolvedParents,isLoading: isLoadingWorkspaces,isError: hasWorkspaceError,error: resolvedWorkspacesError,@@ -183,6 +184,7 @@ export function WorkspaceSelectionForm({<div className="flex flex-col gap-[10px] pb-4"><WorkspaceDropdownworkspaces={workspaces}+ parents={resolvedParents}value={selectedWorkspace}placeholder={workspacesUnsupportedMessagediff --git a/src/hooks/query/use-resolved-workspaces.ts b/src/hooks/query/use-resolved-workspaces.tsindex 94aca5bcd7..b6c8c2d8e2 100644--- a/src/hooks/query/use-resolved-workspaces.ts+++ b/src/hooks/query/use-resolved-workspaces.ts@@ -11,6 +11,14 @@ import { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";interface UseResolvedWorkspacesResult {workspaces: LocalWorkspace[];+ /**+ * The merged workspace parents that produced the dynamic children above:+ * the user's stored parents plus any implicit built-in parents (currently+ * `/projects` in dev). Consumers use this to label a child's group by its+ * parent's `name` — `parentPath` alone only yields a path. Includes the+ * implicit parents that `useLocalWorkspaces` does not expose on its own.+ */+ parents: LocalWorkspaceParent[];isLoading: boolean;isError: boolean;error: unknown;@@ -124,5 +132,11 @@ export function useResolvedWorkspaces(): UseResolvedWorkspacesResult {return Array.from(byPath.values());}, [workspaces, workspaceParents, queriesFingerprint]);- return { workspaces: merged, isLoading, isError, error: listError };+ return {+ workspaces: merged,+ parents: workspaceParents,+ isLoading,+ isError,+ error: listError,+ };}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 1238157551..fcba55ac62 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -20484,6 +20484,23 @@"uk": "+ Додати робочу область","ca": "+ Afegeix un espai de treball"},+ "HOME$WORKSPACE_GROUP_OTHER": {+ "en": "Other",+ "ja": "その他",+ "zh-CN": "其他",+ "zh-TW": "其他",+ "ko-KR": "기타",+ "no": "Annet",+ "it": "Altro",+ "pt": "Outros",+ "es": "Otros",+ "ar": "أخرى",+ "fr": "Autre",+ "tr": "Diğer",+ "de": "Sonstige",+ "uk": "Інше",+ "ca": "Altres"+ },"HOME$MANAGE_WORKSPACES": {"en": "Manage Workspaces","ja": "ワークスペースを管理",