Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(sidebar): open row action groups as hover submenus
vastsa23475c555322
diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsxindex 650d21ed8..c0d92d09d 100644--- a/apps/desktop/src/components/Sidebar.tsx+++ b/apps/desktop/src/components/Sidebar.tsx@@ -87,6 +87,7 @@ import {sidebarMenuCheck,sidebarMenuGroup,sidebarMenuSection,+ sidebarMenuSubmenu,type SidebarMenuPanelContent,} from "../lib/sidebar-menu";import { useArmedDelete } from "../hooks/use-armed-delete";@@ -1641,11 +1642,6 @@ export function Sidebar({: t("nav.sortCreated", { defaultValue: "Created date" });- /** Delete is the only row that destroys durable history, so it gets its own group. */- const dangerSection = (- id: "session-danger" | "project-danger",- label: string,- ) => sidebarMenuSection({ id, label });const sessionMenuContent = useCallback((session: SessionSummary): SidebarMenuPanelContent => {@@ -1653,6 +1649,21 @@ export function Sidebar({const archived = sessionArchived(session, meta);const pinned = sessionPinned(session, meta);const native = session.source === "pi-native";+ const gitItems = [+ ...(native || !sessionAllows(session, "canEditMessages")+ ? []+ : [+ sidebarMenuAction({+ id: "fork-session",+ label: t("nav.createBranch"),+ icon: <IconBranch size={14} />,+ title: t("nav.createBranch"),+ disabled: Boolean(runningSessions[session.id]),+ onSelect: () => void forkSession(session),+ }),+ ]),+ ...sessionWorktreeItems,+ ];return {label: t("nav.sessionActions", { defaultValue: "Session actions" }),items: [@@ -1685,78 +1696,70 @@ export function Sidebar({icon: archived ? <IconArchiveRestore size={14} /> : <IconArchive size={14} />,onSelect: () => void archiveSession(session),}),- ...(native || !sessionAllows(session, "canEditMessages")- ? []- : [- sidebarMenuAction({- id: "fork-session",- label: t("nav.createBranch"),- icon: <IconBranch size={14} />,- title: t("nav.createBranch"),- disabled: Boolean(runningSessions[session.id]),- onSelect: () => void forkSession(session),- }),- ]),- ...(sessionWorktreeItems.length+ ...(gitItems.length? [- sidebarMenuSection({+ sidebarMenuSubmenu({id: "session-git",label: t("worktree.menu.group", { defaultValue: "Git" }),+ icon: <IconBranch size={14} />,+ items: gitItems,}),- ...sessionWorktreeItems,]: []),sidebarMenuAction({id: "copy-session-link",label: t("nav.copySessionLink"),- title: t("nav.copySessionLink"),+ icon: <IconCopy size={14} />,onSelect: () => void copySessionLink(session),}),...(settings?.developerMode === true && !isRemoteSession(session)? [- sidebarMenuAction({- id: "copy-conversation-id",- label: t("nav.copyConversationId"),- icon: <IconCopy size={14} />,- title: t("nav.copyConversationId"),- onSelect: () => void copyConversationId(session),- }),- sidebarMenuAction({- id: "open-session-path",- label: t("nav.openSessionPath"),- icon: <IconFolder size={14} />,- title: t("nav.openSessionPath"),- onSelect: () => void openSessionPath(session),+ sidebarMenuSubmenu({+ id: "session-developer",+ label: t("nav.developerMode", { defaultValue: "Developer tools" }),+ icon: <IconSettings size={14} />,+ items: [+ sidebarMenuAction({+ id: "copy-conversation-id",+ label: t("nav.copyConversationId"),+ icon: <IconCopy size={14} />,+ onSelect: () => void copyConversationId(session),+ }),+ sidebarMenuAction({+ id: "open-session-path",+ label: t("nav.openSessionPath"),+ icon: <IconFolder size={14} />,+ onSelect: () => void openSessionPath(session),+ }),+ ],}),]: []),...(native? []: [- dangerSection(- "session-danger",- t("nav.dangerZone", { defaultValue: "Danger zone" }),- ),- sidebarMenuAction({- id: "delete-session",- label:- armedDelete === session.id- ? t("nav.deleteTaskConfirm", { defaultValue: "Delete?" })- : t("nav.deleteTask", { defaultValue: "Delete" }),- icon: <IconX size={14} />,- danger: true,- armed: armedDelete === session.id,- onSelect: () => requestDeleteSession(session),+ sidebarMenuSubmenu({+ id: "session-danger",+ label: t("nav.dangerZone", { defaultValue: "Danger zone" }),+ icon: <IconTrash size={14} />,+ items: [+ sidebarMenuAction({+ id: "delete-session",+ label: armedDelete === session.id+ ? t("nav.deleteTaskConfirm", { defaultValue: "Delete?" })+ : t("nav.deleteTask", { defaultValue: "Delete" }),+ icon: <IconX size={14} />,+ danger: true,+ armed: armedDelete === session.id,+ onSelect: () => requestDeleteSession(session),+ }),+ ],+ notes: sessionDeleteLoss+ ? [{ id: "session-delete-loss", text: sessionDeleteLoss }]+ : undefined,}),]),- ].map((item) =>- item.kind === "action" && item.id === "delete-session" && armedDelete === session.id- ? item- : item,- ),- notes: sessionDeleteLoss- ? [{ id: "session-delete-loss", text: sessionDeleteLoss }]- : undefined,+ ],};},[@@ -1812,18 +1815,24 @@ export function Sidebar({icon: archived ? <IconArchiveRestore size={14} /> : <IconArchive size={14} />,onSelect: () => void archiveProject(entry),}),- sidebarMenuSection({+ sidebarMenuSubmenu({id: "project-git",label: t("worktree.menu.group", { defaultValue: "Git" }),+ items: projectIsolationItems,}),- ...projectIsolationItems,- dangerSection("project-danger", t("nav.dangerZone", { defaultValue: "Danger zone" })),- sidebarMenuAction({- id: "delete-project",- label: t("project.delete", { defaultValue: "Delete project" }),+ sidebarMenuSubmenu({+ id: "project-danger",+ label: t("nav.dangerZone", { defaultValue: "Danger zone" }),icon: <IconTrash size={14} />,- danger: true,- onSelect: () => requestDeleteProject(entry),+ items: [+ sidebarMenuAction({+ id: "delete-project",+ label: t("project.delete", { defaultValue: "Delete project" }),+ icon: <IconTrash size={14} />,+ danger: true,+ onSelect: () => requestDeleteProject(entry),+ }),+ ],}),],};@@ -1832,6 +1841,7 @@ export function Sidebar({archiveProject,openProjectFolder,projectIsolationItems,+ requestDeleteProject,t,toggleProjectPin,],@@ -1851,24 +1861,29 @@ export function Sidebar({icon: <IconArchive size={14} />,onSelect: () => void batchArchiveSessions(),}),- dangerSection("session-danger", t("nav.dangerZone", { defaultValue: "Danger zone" })),- sidebarMenuAction({- id: "batch-delete",- label:- armedDelete === "batch"- ? t("nav.batchDeleteConfirm", { defaultValue: "Delete {{count}} sessions?", count })- : t("nav.batchDelete", { defaultValue: "Delete {{count}} sessions", count }),+ sidebarMenuSubmenu({+ id: "batch-danger",+ label: t("nav.dangerZone", { defaultValue: "Danger zone" }),icon: <IconTrash size={14} />,- danger: true,- armed: armedDelete === "batch",- onSelect: () => {- if (armedDelete !== "batch") {- setArmedDelete("batch");- return;- }- setArmedDelete(null);- void batchDeleteSessions();- },+ items: [+ sidebarMenuAction({+ id: "batch-delete",+ label: armedDelete === "batch"+ ? t("nav.batchDeleteConfirm", { defaultValue: "Delete {{count}} sessions?", count })+ : t("nav.batchDelete", { defaultValue: "Delete {{count}} sessions", count }),+ icon: <IconTrash size={14} />,+ danger: true,+ armed: armedDelete === "batch",+ onSelect: () => {+ if (armedDelete !== "batch") {+ setArmedDelete("batch");+ return;+ }+ setArmedDelete(null);+ void batchDeleteSessions();+ },+ }),+ ],}),],}),diff --git a/apps/desktop/src/components/SidebarMenuPanel.tsx b/apps/desktop/src/components/SidebarMenuPanel.tsxindex 4e80d63c4..a6ba5cfc0 100644--- a/apps/desktop/src/components/SidebarMenuPanel.tsx+++ b/apps/desktop/src/components/SidebarMenuPanel.tsx@@ -1,33 +1,39 @@/**- * The one floating panel behind every sidebar menu.+ * Shared floating menu panel for the sidebar.*- * The sidebar offers row actions, the sort popover, and section actions, and- * each of them used to hand-write its own button list. They are one surface, so- * they are rendered by one component: placement (via the caller's ref), roving- * focus, checked rows, and labeled groups have a single implementation instead- * of three that drift.- *- * The panel is data-driven (`SidebarMenuItem`) and stateless; `Sidebar.tsx`- * owns the open menu, the placement, and the focus refs.+ * Submenus open on mouse hover and on click (including touch); keyboard users+ * open them with ArrowRight/Enter and return with ArrowLeft/Escape. The child+ * panel is viewport-positioned beside its trigger so the root menu's scroll+ * area cannot clip it.*/-import { Fragment, type KeyboardEvent as ReactKeyboardEvent, type RefObject } from "react";+import {+ Fragment,+ useCallback,+ useLayoutEffect,+ useRef,+ useState,+ type KeyboardEvent as ReactKeyboardEvent,+ type PointerEvent as ReactPointerEvent,+ type RefObject,+} from "react";+import { IconChevronRight } from "./icons";import type {SidebarMenuActionItem,SidebarMenuGroupItem,+ SidebarMenuItem,SidebarMenuPanelContent,+ SidebarMenuSubmenuItem,} from "../lib/sidebar-menu";--/** Arrow/Home/End moves focus between the rows that can actually take it. */+import { placeSidebarSubmenu } from "../lib/sidebar-menu";const MENU_ROW_SELECTOR ='[role="menuitem"]:not(:disabled), [role="menuitemradio"]:not(:disabled), [role="menuitemcheckbox"]:not(:disabled)';-function groupOptions(group: SidebarMenuGroupItem) {- /* A lone option with no caption is not a group; it is one more row. */- return group.label || group.options.length > 1- ? group.options- : group.options.map((option) => ({ ...option, icon: undefined }));+function rowsIn(menu: HTMLElement): HTMLButtonElement[] {+ return Array.from(menu.querySelectorAll<HTMLButtonElement>(MENU_ROW_SELECTOR))+ .filter((row) => row.closest('[role="menu"]') === menu);}+export function SidebarMenuPanel({content,menuRef,@@ -37,31 +43,145 @@ export function SidebarMenuPanel({position,}: {content: SidebarMenuPanelContent;- /** Placement measurement lives with the caller's resize/scroll effects. */menuRef?: RefObject<HTMLDivElement | null>;- /** The row the menu focuses when it opens. */firstItemRef?: RefObject<HTMLButtonElement | null>;onKeyDown: (event: ReactKeyboardEvent<HTMLDivElement>) => void;className?: string;position: { top: number; left: number };}) {- let firstItemTaken = false;- const takeFirstItemRef = () => {- if (firstItemTaken) return undefined;- firstItemTaken = true;- return firstItemRef;+ const localMenuRef = useRef<HTMLDivElement>(null);+ const rootMenuRef = menuRef ?? localMenuRef;+ const submenuRef = useRef<HTMLDivElement>(null);+ const focusSubmenuOnOpen = useRef(false);+ const [openSubmenuId, setOpenSubmenuId] = useState<string | null>(null);+ const [submenuPosition, setSubmenuPosition] = useState<{ top: number; left: number } | null>(null);+ const openSubmenuItem = content.items.find(+ (item): item is SidebarMenuSubmenuItem =>+ item.kind === "submenu" && item.id === openSubmenuId,+ );++ const openSubmenu = useCallback((id: string, focusFirstItem: boolean) => {+ if (openSubmenuId === id) {+ if (focusFirstItem) {+ requestAnimationFrame(() => {+ if (submenuRef.current) rowsIn(submenuRef.current)[0]?.focus();+ });+ }+ return;+ }+ focusSubmenuOnOpen.current = focusFirstItem;+ setSubmenuPosition(null);+ setOpenSubmenuId(id);+ }, [openSubmenuId]);++ const closeSubmenu = useCallback((restoreFocus: boolean) => {+ const id = openSubmenuId;+ focusSubmenuOnOpen.current = false;+ setOpenSubmenuId(null);+ setSubmenuPosition(null);+ if (restoreFocus && id) {+ requestAnimationFrame(() => {+ const trigger = Array.from(+ rootMenuRef.current?.querySelectorAll<HTMLButtonElement>("[data-submenu-trigger]") ?? [],+ ).find((button) => button.dataset.submenuTrigger === id);+ trigger?.focus();+ });+ }+ }, [openSubmenuId, rootMenuRef]);++ useLayoutEffect(() => {+ if (!openSubmenuId) return;+ const reposition = () => {+ const root = rootMenuRef.current;+ const submenu = submenuRef.current;+ if (!root || !submenu) return;+ const trigger = Array.from(+ root.querySelectorAll<HTMLButtonElement>("[data-submenu-trigger]"),+ ).find((button) => button.dataset.submenuTrigger === openSubmenuId);+ if (!trigger) return;++ const triggerRect = trigger.getBoundingClientRect();+ const submenuRect = submenu.getBoundingClientRect();+ const next = placeSidebarSubmenu(+ { top: triggerRect.top, left: triggerRect.left, right: triggerRect.right },+ { width: submenuRect.width, height: submenuRect.height },+ { width: window.innerWidth, height: window.innerHeight },+ );+ setSubmenuPosition((previous) =>+ previous?.left === next.left && previous.top === next.top ? previous : next,+ );+ };++ reposition();+ if (typeof ResizeObserver === "undefined" || !submenuRef.current) return;+ const observer = new ResizeObserver(reposition);+ observer.observe(submenuRef.current);+ window.addEventListener("resize", reposition);+ return () => {+ observer.disconnect();+ window.removeEventListener("resize", reposition);+ };+ }, [openSubmenuId, rootMenuRef]);++ useLayoutEffect(() => {+ if (!openSubmenuId || !submenuPosition || !focusSubmenuOnOpen.current) return;+ focusSubmenuOnOpen.current = false;+ const frame = requestAnimationFrame(() => {+ const submenu = submenuRef.current;+ if (submenu) rowsIn(submenu)[0]?.focus();+ });+ return () => cancelAnimationFrame(frame);+ }, [openSubmenuId, submenuPosition]);++ const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {+ const target = event.target instanceof Element ? event.target : null;+ const activeMenu = target?.closest<HTMLElement>('[role="menu"]') ?? rootMenuRef.current;+ const isSubmenu = activeMenu !== rootMenuRef.current;++ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ if (isSubmenu) closeSubmenu(true);+ else onKeyDown(event);+ return;+ }+ if (event.key === "ArrowLeft" && isSubmenu) {+ event.preventDefault();+ closeSubmenu(true);+ return;+ }+ if (event.key === "ArrowRight") {+ const trigger = target?.closest<HTMLButtonElement>("[data-submenu-trigger]");+ if (trigger?.dataset.submenuTrigger) {+ event.preventDefault();+ openSubmenu(trigger.dataset.submenuTrigger, true);+ return;+ }+ }+ if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key) || !activeMenu) {+ return;+ }++ const rows = rowsIn(activeMenu);+ if (!rows.length) return;+ event.preventDefault();+ const current = rows.indexOf(document.activeElement as HTMLButtonElement);+ const next = event.key === "Home"+ ? 0+ : event.key === "End"+ ? rows.length - 1+ : (current + (event.key === "ArrowDown" ? 1 : -1) + rows.length) % rows.length;+ rows[next]?.focus();};const renderAction = (item: SidebarMenuActionItem,- options?: { iconFrom?: SidebarMenuActionItem["icon"]; keyPrefix?: string },+ options?: { keyPrefix?: string; inSubmenu?: boolean },) => (<Fragment key={`${options?.keyPrefix ?? ""}${item.id}`}>- {item.separatorBefore ? (- <div className="sidebar-menu-separator" role="separator" />- ) : null}+ {item.separatorBefore ? <div className="sidebar-menu-separator" role="separator" /> : null}<button- ref={takeFirstItemRef()}+ ref={options?.inSubmenu ? undefined : takeFirstItemRef()}type="button"role="menuitem"className={item.danger ? "danger" : undefined}@@ -71,134 +191,169 @@ export function SidebarMenuPanel({title={item.title}aria-busy={item.busy || undefined}aria-describedby={item.describedBy}+ onPointerEnter={(event) => {+ if (!options?.inSubmenu && event.pointerType === "mouse") closeSubmenu(false);+ }}onClick={item.onSelect}>- {options?.iconFrom ?? (item.icon ? item.icon : null)}+ {item.icon ?? null}<span className="sidebar-menu-label">{item.label}</span></button>{item.describedBy && item.title ? (- <p id={item.describedBy} className="sidebar-menu-hint">- {item.title}- </p>+ <p id={item.describedBy} className="sidebar-menu-hint">{item.title}</p>) : null}</Fragment>);+ function takeFirstItemRef() {+ if (firstItemTaken.current) return undefined;+ firstItemTaken.current = true;+ return firstItemRef;+ }++ const firstItemTaken = useRef(false);+ firstItemTaken.current = false;++ const renderItem = (item: SidebarMenuItem) => {+ if (item.kind === "section") {+ return (+ <Fragment key={item.id}>+ <div className="sidebar-menu-separator" role="separator" />+ <p className="sidebar-menu-section" data-sidebar-menu-section={item.id}>{item.label}</p>+ </Fragment>+ );+ }+ if (item.kind === "check") {+ return (+ <button+ key={item.id}+ ref={takeFirstItemRef()}+ type="button"+ role="menuitemcheckbox"+ aria-checked={item.checked}+ data-action={item.id}+ onPointerEnter={(event) => event.pointerType === "mouse" && closeSubmenu(false)}+ onClick={item.onSelect}+ >+ <span className="sidebar-menu-label">{item.label}</span>+ <span className={`sidebar-checkbox ${item.checked ? "checked" : ""}`} aria-hidden>+ {item.checked ? "✓" : ""}+ </span>+ </button>+ );+ }+ if (item.kind === "submenu") {+ const expanded = openSubmenuId === item.id;+ return (+ <button+ key={item.id}+ ref={takeFirstItemRef()}+ type="button"+ role="menuitem"+ className={`sidebar-menu-submenu-trigger${expanded ? " is-expanded" : ""}`}+ data-submenu-trigger={item.id}+ aria-haspopup="menu"+ aria-expanded={expanded}+ aria-controls={`sidebar-submenu-${item.id}`}+ onPointerEnter={(event: ReactPointerEvent<HTMLButtonElement>) => {+ if (event.pointerType === "mouse") openSubmenu(item.id, false);+ }}+ onClick={(event) => openSubmenu(item.id, event.detail === 0)}+ >+ {item.icon ?? null}+ <span className="sidebar-menu-label">{item.label}</span>+ <IconChevronRight size={13} className="sidebar-menu-submenu-chevron" aria-hidden />+ </button>+ );+ }+ if (item.kind === "group") {+ const titled = Boolean(item.label);+ return (+ <Fragment key={item.id}>+ {titled ? (+ <>+ <div className="sidebar-menu-separator" role="separator" />+ <p className="sidebar-menu-section" data-sidebar-menu-section={item.id}>{item.label}</p>+ </>+ ) : null}+ {item.options.map((option) => (+ <button+ key={`${item.id}-${option.id}`}+ ref={takeFirstItemRef()}+ type="button"+ role="menuitemradio"+ className={option.selected ? "selected" : undefined}+ aria-checked={option.selected}+ data-action={option.id}+ onPointerEnter={(event) => event.pointerType === "mouse" && closeSubmenu(false)}+ onClick={option.onSelect}+ >+ <span className="sidebar-menu-label">{option.label}</span>+ {option.selected ? <span className="sidebar-sort-check" aria-hidden>✓</span> : null}+ </button>+ ))}+ </Fragment>+ );+ }+ return renderAction(item);+ };+return (<div- ref={menuRef}+ ref={rootMenuRef}className={className ? `sidebar-row-menu sidebar-floating-menu ${className}` : "sidebar-row-menu sidebar-floating-menu"}role="menu"aria-label={content.label}- onKeyDown={onKeyDown}+ onKeyDown={handleKeyDown}+ onPointerLeave={(event) => {+ if (event.pointerType !== "mouse") return;+ const related = event.relatedTarget;+ if (related instanceof Node && event.currentTarget.contains(related)) return;+ closeSubmenu(false);+ }}style={{ top: position.top, left: position.left }}>{content.hint ? <p className="sidebar-menu-hint">{content.hint}</p> : null}- {content.items.map((item) => {- if (item.kind === "section") {- return (- <Fragment key={item.id}>- <div className="sidebar-menu-separator" role="separator" />- <p className="sidebar-menu-section" data-sidebar-menu-section={item.id}>- {item.label}- </p>- </Fragment>- );- }- if (item.kind === "check") {- return (- <button- key={item.id}- ref={takeFirstItemRef()}- type="button"- role="menuitemcheckbox"- aria-checked={item.checked}- data-action={item.id}- onClick={item.onSelect}- >- <span className="sidebar-menu-label">{item.label}</span>- <span- className={`sidebar-checkbox ${item.checked ? "checked" : ""}`}- aria-hidden- >- {item.checked ? "✓" : ""}- </span>- </button>- );- }- if (item.kind === "group") {- const titled = Boolean(item.label) && (item.options.length > 1 || item.label);- return (- <Fragment key={item.id}>- {titled ? (- <>- <div className="sidebar-menu-separator" role="separator" />- <p className="sidebar-menu-section" data-sidebar-menu-section={item.id}>- {item.label}- </p>- </>- ) : null}- {groupOptions(item).map((option) => (- <button- key={`${item.id}-${option.id}`}- ref={takeFirstItemRef()}- type="button"- role="menuitemradio"- className={option.selected ? "selected" : undefined}- aria-checked={option.selected}- data-action={option.id}- onClick={option.onSelect}- >- <span className="sidebar-menu-label">{option.label}</span>- {option.selected ? (- <span className="sidebar-sort-check" aria-hidden>- ✓- </span>- ) : null}- </button>- ))}- </Fragment>- );- }- return renderAction(item);- })}+ {content.items.map(renderItem)}{content.notes?.map((note) => (<Fragment key={note.id}>- {note.separatorBefore ? (- <div className="sidebar-menu-separator" role="separator" />- ) : null}- <p className="sidebar-menu-note" data-sidebar-menu-note={note.id}>- {note.text}- </p>+ {note.separatorBefore ? <div className="sidebar-menu-separator" role="separator" /> : null}+ <p className="sidebar-menu-note" data-sidebar-menu-note={note.id}>{note.text}</p></Fragment>))}+ {openSubmenuItem ? (+ <div+ ref={submenuRef}+ id={`sidebar-submenu-${openSubmenuItem.id}`}+ className="sidebar-row-menu sidebar-submenu"+ role="menu"+ aria-label={openSubmenuItem.label}+ style={submenuPosition+ ? { top: submenuPosition.top, left: submenuPosition.left }+ : { top: -10000, left: -10000, visibility: "hidden" }}+ >+ {openSubmenuItem.items.map((item) => renderAction(item, {+ keyPrefix: `${openSubmenuItem.id}-`,+ inSubmenu: true,+ }))}+ {openSubmenuItem.notes?.map((note) => (+ <Fragment key={note.id}>+ {note.separatorBefore ? <div className="sidebar-menu-separator" role="separator" /> : null}+ <p className="sidebar-menu-note" data-sidebar-menu-note={note.id}>{note.text}</p>+ </Fragment>+ ))}+ </div>+ ) : null}</div>);}-/** Shared keyboard handling for every sidebar floating menu. */+/** Closes the top-level sidebar menu and restores its trigger focus. */export function sidebarMenuKeyDown(event: ReactKeyboardEvent<HTMLDivElement>,onClose: (restoreFocus?: boolean) => void,) {- if (event.key === "Escape") {- event.preventDefault();- onClose();- return;- }- if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;- const items = Array.from(- event.currentTarget.querySelectorAll<HTMLButtonElement>(MENU_ROW_SELECTOR),- );- if (!items.length) return;+ if (event.key !== "Escape") return;event.preventDefault();- const current = items.indexOf(document.activeElement as HTMLButtonElement);- const next =- event.key === "Home"- ? 0- : event.key === "End"- ? items.length - 1- : (current + (event.key === "ArrowDown" ? 1 : -1) + items.length) %- items.length;- items[next]?.focus();+ onClose();}diff --git a/apps/desktop/src/features/worktree/WorktreeSidebarParts.tsx b/apps/desktop/src/features/worktree/WorktreeSidebarParts.tsxindex 92ef526e4..2b3459aea 100644--- a/apps/desktop/src/features/worktree/WorktreeSidebarParts.tsx+++ b/apps/desktop/src/features/worktree/WorktreeSidebarParts.tsx@@ -14,7 +14,7 @@ import { api } from "../../lib/api";import { useAppStore } from "../../stores/app-store";import {sidebarMenuAction,- type SidebarMenuItem,+ type SidebarMenuActionItem,} from "../../lib/sidebar-menu";import { WorktreeMergeDialog } from "./WorktreeMergeDialog";import { WorktreeSetupCommandDialog, WorktreeSetupLogDialog } from "./WorktreeSetupDialogs";@@ -77,7 +77,7 @@ export function useWorktreeProjectMenuItems({projectPath: string;projectName: string;onDone: () => void;-}): SidebarMenuItem[] {+}): SidebarMenuActionItem[] {const { t } = useTranslation();const open = useWorktreeUi((s) => s.open);const reasonId = useId();@@ -147,7 +147,7 @@ export function useWorktreeSessionMenuItems({worktree?: SessionWorktreeSummary;running: boolean;onDone: () => void;-}): SidebarMenuItem[] {+}): SidebarMenuActionItem[] {const { t } = useTranslation();const open = useWorktreeUi((s) => s.open);// A conflicted session resolves first; syncing again would only reportdiff --git a/apps/desktop/src/lib/sidebar-menu.ts b/apps/desktop/src/lib/sidebar-menu.tsindex fea93e6f7..d35d6a014 100644--- a/apps/desktop/src/lib/sidebar-menu.ts+++ b/apps/desktop/src/lib/sidebar-menu.ts@@ -58,6 +58,16 @@ export type SidebarMenuGroupItem = {label?: string;options: SidebarMenuRadioOption[];};+/** A hover/click-opened second-level menu of commands. */+export type SidebarMenuSubmenuItem = {+ kind: "submenu";+ id: string;+ label: string;+ icon?: React.ReactNode;+ items: SidebarMenuActionItem[];+ notes?: SidebarMenuNote[];+};+/** A titled separator, e.g. "Danger zone". */export type SidebarMenuSectionItem = {@@ -70,7 +80,8 @@ export type SidebarMenuItem =| SidebarMenuActionItem| SidebarMenuCheckItem| SidebarMenuSectionItem- | SidebarMenuGroupItem;+ | SidebarMenuGroupItem+ | SidebarMenuSubmenuItem;/** A rule carrying a caption: pending work that would be lost by deleting. */export type SidebarMenuNote = {@@ -106,8 +117,36 @@ export function sidebarMenuGroup(return { kind: "group", ...item };}+export function sidebarMenuSubmenu(+ item: Omit<SidebarMenuSubmenuItem, "kind">,+): SidebarMenuSubmenuItem {+ return { kind: "submenu", ...item };+}+export function sidebarMenuSection(item: Omit<SidebarMenuSectionItem, "kind">,): SidebarMenuSectionItem {return { kind: "section", ...item };}++export type SidebarMenuSubmenuPlacement = { top: number; left: number };++/** Place a submenu beside its trigger, flipping left and clamping vertically. */+export function placeSidebarSubmenu(+ trigger: { top: number; left: number; right: number },+ surface: { width: number; height: number },+ viewport: { width: number; height: number },+ margin = 8,+ gap = 0,+): SidebarMenuSubmenuPlacement {+ const maxLeft = viewport.width - surface.width - margin;+ const preferredRight = trigger.right + gap;+ const preferredLeft = preferredRight + surface.width <= viewport.width - margin+ ? preferredRight+ : trigger.left - surface.width - gap;+ const maxTop = viewport.height - surface.height - margin;+ return {+ left: Math.round(Math.max(margin, Math.min(preferredLeft, maxLeft))),+ top: Math.round(Math.max(margin, Math.min(trigger.top, maxTop))),+ };+}diff --git a/apps/desktop/src/styles/sessions.css b/apps/desktop/src/styles/sessions.cssindex 66815c1f7..13268eda9 100644--- a/apps/desktop/src/styles/sessions.css+++ b/apps/desktop/src/styles/sessions.css@@ -498,6 +498,29 @@max-width: calc(100vw - 16px);}+.sidebar-submenu {+ position: fixed;+ z-index: 61;+ width: max-content;+ min-width: 184px;+ max-width: calc(100vw - 16px);+ max-height: min(360px, calc(100vh - 16px));+ overflow-y: auto;+ box-shadow: var(--ds-shadow-dialog);+}++.sidebar-row-menu .sidebar-menu-submenu-trigger[aria-expanded="true"] {+ background: var(--ds-bg-hover);+}++.sidebar-menu-submenu-trigger .sidebar-menu-label {+ flex: 1 1 auto;+}++.sidebar-menu-submenu-chevron {+ margin-inline-start: auto;+ color: var(--ds-text-muted);+}.sidebar-row-menu button,.sidebar-popover button {display: flex;@@ -513,7 +536,10 @@}.sidebar-row-menu button:hover,+.sidebar-row-menu button:focus-visible,+.sidebar-row-menu button[aria-expanded="true"],.sidebar-popover button:hover,+.sidebar-popover button:focus-visible,.sidebar-popover button.selected {background: var(--ds-bg-hover);}diff --git a/apps/desktop/test/sidebar-menu-panel.test.mjs b/apps/desktop/test/sidebar-menu-panel.test.mjsindex fbac58bf6..2fa474f66 100644--- a/apps/desktop/test/sidebar-menu-panel.test.mjs+++ b/apps/desktop/test/sidebar-menu-panel.test.mjs@@ -1,7 +1,7 @@import assert from "node:assert/strict";import { readFile } from "node:fs/promises";import test from "node:test";-+import { placeSidebarSubmenu } from "../src/lib/sidebar-menu.ts";const panelSource = await readFile(new URL("../src/components/SidebarMenuPanel.tsx", import.meta.url),"utf8",@@ -33,11 +33,37 @@ test("keyboard navigation walks the rows the menu can actually run", () => {assert.match(panelSource, /event\.key === "Escape"[\s\S]*?onClose\(\)/);});-test("a lone uncaptioned option joins the rows instead of heading its own group", () => {- assert.match(- panelSource,- /group\.label \|\| group\.options\.length > 1/,- "a single option without a caption must not render a group header",+test("submenu trigger advertises its expanded state and opens on hover or click", () => {+ assert.match(panelSource, /data-submenu-trigger=\{item\.id\}/);+ assert.match(panelSource, /aria-haspopup="menu"/);+ assert.match(panelSource, /aria-expanded=\{expanded\}/);+ assert.match(panelSource, /event\.pointerType === "mouse"\) openSubmenu\(item\.id, false\)/);+ assert.match(panelSource, /onClick=\{\(event\) => openSubmenu\(item\.id, event\.detail === 0\)\}/);+});++test("submenu keyboard entry and return preserve focus", () => {+ assert.match(panelSource, /event\.key === "ArrowRight"/);+ assert.match(panelSource, /event\.key === "ArrowLeft" && isSubmenu/);+ assert.match(panelSource, /if \(isSubmenu\) closeSubmenu\(true\)/);+ assert.match(panelSource, /trigger\?\.focus\(\)/);+});++test("submenu flips left and clamps against viewport edges", () => {+ assert.deepEqual(+ placeSidebarSubmenu(+ { top: 100, left: 200, right: 224 },+ { width: 180, height: 120 },+ { width: 800, height: 600 },+ ),+ { top: 100, left: 224 },+ );+ assert.deepEqual(+ placeSidebarSubmenu(+ { top: 590, left: 740, right: 764 },+ { width: 180, height: 120 },+ { width: 800, height: 600 },+ ),+ { top: 472, left: 560 },);});diff --git a/apps/desktop/test/sidebar-navigation.test.mjs b/apps/desktop/test/sidebar-navigation.test.mjsindex dc2e4ca8c..0f1eb27cb 100644--- a/apps/desktop/test/sidebar-navigation.test.mjs+++ b/apps/desktop/test/sidebar-navigation.test.mjs@@ -197,12 +197,11 @@ test("sidebar floating menus stay anchored to triggers and pointer positions", (});/*- The row menus were outgrowing a flat list: rename/pin/archive/branch/git/- copy/dev/delete all sat in one column, and delete sat next to what it- destroys. Each menu is now a small set of labelled groups, with the- destructive row alone under its own caption.+ The row menus had grown into long flat lists; these assertions keep related+ actions behind hover-opened second-level menus while leaving common actions+ one click away and destructive actions isolated.*/-test("sidebar row menus group their rows and isolate the destructive one", () => {+test("sidebar row menus expose hover submenus for related actions", () => {const sessionMenu = sidebarSource.match(/const sessionMenuContent = useCallback\([\s\S]*?\n \[\n[\s\S]*?\n \],\n \);/,)?.[0] ?? "";@@ -217,24 +216,18 @@ test("sidebar row menus group their rows and isolate the destructive one", () =>assert.ok(projectMenu, "project menu content must exist");assert.ok(sortMenu, "sort menu content must exist");- /* One destructive row per menu, alone in its own group. */- for (const [menu, dangerId, deleteId] of [- [sessionMenu, /dangerSection\(\s*"session-danger"/, /id: "delete-session"/],- [projectMenu, /dangerSection\("project-danger"/, /id: "delete-project"/],- ]) {- const dangerIndex = menu.search(dangerId);- const deleteIndex = menu.search(deleteId);- assert.ok(dangerIndex >= 0, "menu must caption its destructive group");- assert.ok(deleteIndex > dangerIndex, "delete must sit under its caption");- }- assert.match(sessionMenu, /id: "batch-archive"|sidebarMenuAction/);- assert.doesNotMatch(projectMenu, /danger: true[\s\S]*?id: "toggle-project-archive"/);-- /* The Git rows are one captioned group of each row menu, not loose items. */- assert.match(sessionMenu, /id: "session-git"/);- assert.match(sessionMenu, /\.\.\.sessionWorktreeItems/);- assert.match(projectMenu, /id: "project-git"/);- assert.match(projectMenu, /\.\.\.projectIsolationItems/);+ /* Destructive actions are nested instead of sharing the root menu. */+ assert.match(sessionMenu, /sidebarMenuSubmenu\(\{[\s\S]*?id: "session-danger"[\s\S]*?id: "delete-session"/);+ assert.match(projectMenu, /sidebarMenuSubmenu\(\{[\s\S]*?id: "project-danger"[\s\S]*?id: "delete-project"/);+ assert.match(sidebarSource, /sidebarMenuSubmenu\(\{[\s\S]*?id: "batch-danger"[\s\S]*?id: "batch-delete"/);+ assert.match(sessionMenu, /id: "batch-archive"|id: "copy-session-link"/);++ /* Related actions open as real second-level menus. */+ assert.match(sessionMenu, /sidebarMenuSubmenu\(\{[\s\S]*?id: "session-git"[\s\S]*?items: gitItems/);+ assert.match(sessionMenu, /id: "copy-session-link"/);+ assert.doesNotMatch(sessionMenu, /id: "session-copy"/);+ assert.match(sessionMenu, /id: "session-developer"[\s\S]*?id: "open-session-path"/);+ assert.match(projectMenu, /sidebarMenuSubmenu\(\{[\s\S]*?id: "project-git"[\s\S]*?items: projectIsolationItems/);/* The sort popover is two labelled groups instead of a title plus loose rows. */assert.match(sortMenu, /id: "sort"/);diff --git a/apps/desktop/test/worktree-menu-user-path.test.mjs b/apps/desktop/test/worktree-menu-user-path.test.mjsindex c15c8ccff..2261303c8 100644--- a/apps/desktop/test/worktree-menu-user-path.test.mjs+++ b/apps/desktop/test/worktree-menu-user-path.test.mjs@@ -20,6 +20,8 @@ import i18n from "i18next";import { initReactI18next } from "react-i18next";import { catalogs, flattenCatalog } from "@pi-desktop/i18n";import { IPC } from "@pi-desktop/shared";+import { SidebarMenuPanel } from "../../apps/desktop/src/components/SidebarMenuPanel";+import { sidebarMenuAction, sidebarMenuSubmenu } from "../../apps/desktop/src/lib/sidebar-menu";import { WorktreeBadge, useWorktreeProjectMenuItems, useWorktreeSessionMenuItems } from "../../apps/desktop/src/features/worktree/WorktreeSidebarParts";import { WorktreeBehindWatcher } from "../../apps/desktop/src/features/worktree/WorktreeBehind";import { WorktreeMergeDialog } from "../../apps/desktop/src/features/worktree/WorktreeMergeDialog";@@ -197,12 +199,74 @@ window.menuProbe = async () => {check(behindAllCalls >= 2, "a sync must re-read the counts");check(!marker("stale"), "the marker must clear after the sync");flushSync(() => menuRoot.unmount());+ const submenuHost = document.createElement("div");+ document.body.appendChild(submenuHost);+ const submenuRoot = createRoot(submenuHost);+ const selectedSubmenuActions = [];+ const submenuContent = {+ label: "Session actions",+ items: [sidebarMenuSubmenu({+ id: "git",+ label: "Git",+ items: [+ sidebarMenuAction({+ id: "fork",+ label: "Branch from here",+ onSelect: () => selectedSubmenuActions.push("fork"),+ }),+ sidebarMenuAction({+ id: "reveal",+ label: "Show worktree folder",+ onSelect: () => selectedSubmenuActions.push("reveal"),+ }),+ ],+ })],+ };+ flushSync(() => submenuRoot.render(React.createElement(SidebarMenuPanel, {+ content: submenuContent,+ position: { top: 90, left: Math.max(8, window.innerWidth - 230) },+ onKeyDown() {},+ })));+ const submenuTrigger = submenuHost.querySelector('[data-submenu-trigger="git"]');+ check(submenuTrigger?.getAttribute("aria-expanded") === "false", "submenu starts closed");+ submenuTrigger.dispatchEvent(new PointerEvent("pointerover", {+ bubbles: true,+ pointerType: "mouse",+ }));+ await settle();+ check(submenuTrigger.getAttribute("aria-expanded") === "true", "hover opens the submenu");+ check(submenuHost.querySelector('#sidebar-submenu-git [data-action="fork"]'), "hover shows child actions");++ submenuTrigger.focus();+ submenuTrigger.dispatchEvent(new KeyboardEvent("keydown", {+ key: "ArrowRight",+ bubbles: true,+ cancelable: true,+ }));+ await settle();+ check(document.activeElement?.getAttribute("data-action") === "fork", "ArrowRight enters the submenu");+ document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {+ key: "Escape",+ bubbles: true,+ cancelable: true,+ }));+ await settle();+ check(!submenuHost.querySelector("#sidebar-submenu-git"), "Escape closes the child menu");+ check(document.activeElement === submenuTrigger, "closing restores focus to its trigger");++ submenuTrigger.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));+ await settle();+ check(submenuTrigger.getAttribute("aria-expanded") === "true", "click opens the submenu without hover");+ submenuHost.querySelector('[data-action="reveal"]').click();+ check(JSON.stringify(selectedSubmenuActions) === JSON.stringify(["reveal"]), "child action executes");+ flushSync(() => submenuRoot.unmount());+ submenuHost.remove();flushSync(() => rows.unmount());return { passed: true };};`;-test("isolated-session sidebar: unavailable reason, merge preview, behind marker, and sync from project", {+test("sidebar submenu opens on hover, click, and keyboard; worktree actions still work", {skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,}, async () => {const temp = await mkdtemp(join(root, "apps/desktop/.worktree-menu-ui-"));diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex f5b29bcfb..b9926b327 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -427,14 +427,19 @@ may be retained while exactly one workspace supplies the visible shell context.retain `aria-current`.- Toggling disclosure or a menu action keeps focus on its control. Selecting aproject/session returns focus to the composer after loading.-- Sort, archive, restore, pin, Create branch, and close actions remain- keyboard-reachable;- they cannot exist only as pointer-hover affordances.-- Sidebar body-level menus opened from toolbar or row triggers remain- content-sized and use the same fixed rule as right-click menus: open 4px to- the anchor's right without flipping to the left. Their surface width is- capped for narrow viewports. This includes the Sessions sort menu,- session/project overflow menus, and section create menus.+- Sort choices and all row actions remain keyboard-reachable; hover is never the+ only way to reveal an action. Project and session overflow menus keep common+ actions at the root and place related Git, Developer, and Danger actions in+ menuitem/haspopup second-level menus.+- A submenu opens on mouse hover or click/tap. ArrowRight or Enter opens the+ focused submenu trigger; ArrowLeft or Escape closes the child first and+ restores focus to its trigger. A second Escape closes the root menu. Moving+ the pointer between the trigger and child does not dismiss the parent.+- Sidebar body-level root menus remain content-sized and open 4px to the+ trigger's right. A submenu opens flush beside its trigger, prefers the right,+ flips left when needed, and clamps vertically inside the viewport. Neither+ parent nor child may be clipped; the child does not resize or scroll the+ sidebar.#### Floating dropdown surfacesdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex a5c74d143..4de1f1b7e 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -3127,26 +3127,36 @@ identify the platform validation still needed.- **Milestone**: M2- **Status**: Draft (run only in a capable environment when this surface changes)-#### E2E-021b: Developer mode copies a conversation id and opens session scratch--- **Preconditions**: Developer mode is enabled. A session exists, including one- whose scratch directory has not been created yet.-- **Steps**: 1) Open a conversation overflow menu. 2) Confirm Copy conversation- ID and Open session path appear after Create branch and before Delete, and- that Copy session path is absent. 3) Choose Copy conversation ID and paste- the clipboard. 4) Choose Open session path. 5) Disable developer mode and- reopen the menu.-- **Expected**: The clipboard contains the exact session id. The system file- manager opens `<data_dir>/scratch/<sessionId>/`, creating that directory if- it was missing. The renderer does not send a filesystem path; Main opens- only a resolved scratch directory for that session id. With developer mode- off, both actions are absent.+#### E2E-021b: Session context menus expose hover submenus++- **Preconditions**: A session exists, including one whose scratch directory+ has not been created yet. The session can create a branch; worktree actions+ are available when it belongs to a Git project.+- **Steps**: 1) Open the session overflow menu or right-click its row. Hover Git+ and verify its second-level actions appear; click/tap Git to open the same+ submenu without hover. Use ArrowRight to enter it, ArrowLeft to return, and+ Escape to close only the child menu. Choose Copy conversation link from the+ root menu. 2) Enable developer mode and reopen the menu. Hover or click+ Developer mode, then choose Copy conversation ID and paste the clipboard.+ Reopen the submenu and choose Open session path. 3) Disable developer mode+ and verify the Developer submenu is absent.+- **Expected**: Git and Developer mode are menuitem/haspopup triggers; hover and+ click reveal their child menus without dismissing the root. ArrowRight enters+ a child, ArrowLeft and the first Escape return to its trigger, and a second+ Escape closes the root. Child actions remain keyboard reachable and execute+ once. Copy conversation link remains available at the root. The clipboard+ contains the exact session id. The system file manager opens+ `<data_dir>/scratch/<sessionId>/`, creating it if missing. The renderer does+ not send a filesystem path; Main opens only a resolved scratch directory for+ that session id. Developer-only actions are absent with developer mode off.- **Specs linked**: `03-runtime/01-ipc-protocol.md`,- `04-ux/08-component-spec.md`, `04-ux/06-settings-ia.md`-- **Acceptance**: C (sessions), Quality (developer tools)+ `04-ux/08-component-spec.md`, `04-ux/06-settings-ia.md`,+ `04-ux/09-interaction-patterns.md`+- **Acceptance**: C (sessions), Quality (nested menu interaction)- **Milestone**: M2-- **Status**: Unit-covered (`session-scratch-path.test.mjs`); desktop journey- Draft (run only in a capable environment when this surface changes)+- **Status**: Component interaction automated (`worktree-menu-user-path.test.mjs`,+ `sidebar-menu-panel.test.mjs`, `sidebar-navigation.test.mjs`); full Sidebar+ desktop journey remains Draft#### E2E-021c: Bottom-edge project menus stay beside their anchor