Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
refactor(sidebar): group row menus and render them from one panel
vastsa7ca6edbf9943
diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsxindex da63090e9..650d21ed8 100644--- a/apps/desktop/src/components/Sidebar.tsx+++ b/apps/desktop/src/components/Sidebar.tsx@@ -73,19 +73,27 @@ import {} from "../lib/sidebar-resize";import { BrandLogo } from "./BrandLogo";import { NotificationCenter } from "./NotificationCenter";-import { ProjectEditDialog } from "./ProjectEditDialog";import {WorktreeBadge,- WorktreeDeleteLossNote,WorktreeDialogs,- WorktreeProjectMenuItems,- WorktreeSessionMenuItems,+ useWorktreeDeleteLossText,+ useWorktreeProjectMenuItems,+ useWorktreeSessionMenuItems,} from "../features/worktree/WorktreeSidebarParts";import { WorktreeBehindWatcher } from "../features/worktree/WorktreeBehind";+import { SidebarMenuPanel, sidebarMenuKeyDown } from "./SidebarMenuPanel";+import {+ sidebarMenuAction,+ sidebarMenuCheck,+ sidebarMenuGroup,+ sidebarMenuSection,+ type SidebarMenuPanelContent,+} from "../lib/sidebar-menu";import { useArmedDelete } from "../hooks/use-armed-delete";+import { useUpdateState } from "../hooks/use-update-state";import { ProjectDeleteDialog } from "./ProjectDeleteDialog";+import { ProjectEditDialog } from "./ProjectEditDialog";import { SessionRenameDialog } from "./SessionRenameDialog";-import { useUpdateState } from "../hooks/use-update-state";import {IconArchive,IconArchiveRestore,@@ -644,8 +652,6 @@ export function Sidebar({sortOpen,]);- // Footer utility bar: settings / plugins / notifications + build chip.-// An update only earns the accent dot once it is actionable — a pending// check or a failed one keeps the chip quiet.const updateReady =@@ -661,32 +667,6 @@ export function Sidebar({const buildTitle = updateReady? t("updates.available", { version: update?.availableVersion ?? "" }): t("nav.checkForUpdates");-- const onMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {- if (event.key === "Escape") {- event.preventDefault();- closeMenus();- return;- }- if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;- const items = Array.from(- event.currentTarget.querySelectorAll<HTMLButtonElement>(- '[role="menuitem"]:not(:disabled), [role="menuitemradio"]:not(:disabled), [role="menuitemcheckbox"]:not(:disabled)',- ),- );- if (!items.length) 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();- };-const taskTitle = useCallback((title?: string | null) => {const value = (title || "").trim();return isDefaultSessionTitle(value) ? t("chat.untitledTask") : value;@@ -1611,6 +1591,319 @@ export function Sidebar({[moveSessionProject, reportError, runningSessions, showToast, t],);+ /**+ * The row menu acts on the selection while a multi-selection is open, so the+ * panel's items come from the selection rather than from the clicked row.+ */+ const batchSelected = Boolean(+ sessionMenu && selectedIds.size > 1 && selectedIds.has(sessionMenu),+ );++ /**+ * Repository rows of the open menu. Both builders run every render, but they+ * key their probes and reads to the open target, so a closed menu reads+ * nothing; `onDone` is the sidebar's own close path.+ */+ const menuSession = sessionMenu+ ? sessions.find((item) => item.id === sessionMenu)+ : undefined;+ const sessionWorktreeItems = useWorktreeSessionMenuItems({+ sessionId: menuSession?.id ?? "",+ title: taskTitle(menuSession?.title),+ worktree: menuSession?.worktree,+ running: Boolean(menuSession && runningSessions[menuSession.id]),+ onDone: () => closeMenus(false),+ });+ const sessionDeleteLoss = useWorktreeDeleteLossText(+ menuSession && armedDelete === menuSession.id ? menuSession.id : "",+ );+ const menuProject = projectMenu+ ? projectEntries.find((item) => item.key === projectMenu)+ : undefined;+ const projectIsolationItems = useWorktreeProjectMenuItems({+ projectPath: menuProject?.path ?? "",+ projectName: menuProject?.name ?? "",+ onDone: () => closeMenus(false),+ });+++ const onMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {+ sidebarMenuKeyDown(event, closeMenus);+ };++ const menuSortLabel = (value: Exclude<SessionSort, "manual"> | "created") =>+ value === "recent"+ ? t("nav.sortRecent", { defaultValue: "Recently updated" })+ : value === "oldest"+ ? t("nav.sortOldest", { defaultValue: "Oldest first" })+ : value === "name"+ ? t("nav.sortName", { defaultValue: "Name" })+ : 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 => {+ const meta = sessionMeta[session.id] ?? {};+ const archived = sessionArchived(session, meta);+ const pinned = sessionPinned(session, meta);+ const native = session.source === "pi-native";+ return {+ label: t("nav.sessionActions", { defaultValue: "Session actions" }),+ items: [+ ...(native+ ? []+ : [+ sidebarMenuAction({+ id: "rename-session",+ label: t("nav.renameTask", { defaultValue: "Rename task" }),+ icon: <IconPencil size={14} />,+ onSelect: () => {+ closeMenus(false);+ setRenameFor(session);+ },+ }),+ ]),+ sidebarMenuAction({+ id: "toggle-session-pin",+ label: pinned+ ? t("nav.unpinTask", { defaultValue: "Unpin" })+ : t("nav.pinTask", { defaultValue: "Pin" }),+ icon: <IconPin size={14} />,+ onSelect: () => toggleSessionPin(session),+ }),+ sidebarMenuAction({+ id: "toggle-session-archive",+ label: archived+ ? t("nav.restoreTask", { defaultValue: "Restore" })+ : t("nav.archiveTask", { defaultValue: "Archive" }),+ 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+ ? [+ sidebarMenuSection({+ id: "session-git",+ label: t("worktree.menu.group", { defaultValue: "Git" }),+ }),+ ...sessionWorktreeItems,+ ]+ : []),+ sidebarMenuAction({+ id: "copy-session-link",+ label: t("nav.copySessionLink"),+ title: t("nav.copySessionLink"),+ 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),+ }),+ ]+ : []),+ ...(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),+ }),+ ]),+ ].map((item) =>+ item.kind === "action" && item.id === "delete-session" && armedDelete === session.id+ ? item+ : item,+ ),+ notes: sessionDeleteLoss+ ? [{ id: "session-delete-loss", text: sessionDeleteLoss }]+ : undefined,+ };+ },+ [+ armedDelete,+ archiveSession,+ copyConversationId,+ copySessionLink,+ forkSession,+ openSessionPath,+ requestDeleteSession,+ runningSessions,+ sessionDeleteLoss,+ sessionMeta,+ sessionWorktreeItems,+ settings?.developerMode,+ t,+ toggleSessionPin,+ ],+ );++ const projectMenuContent = useCallback(+ (entry: ProjectEntry): SidebarMenuPanelContent => {+ const archived = Boolean(entry.meta.archived);+ return {+ label: t("project.openActions", { name: entry.name }),+ items: [+ sidebarMenuAction({+ id: "open-project-folder",+ label: t("project.openFolder", { defaultValue: "Open folder" }),+ icon: <IconFolder size={14} />,+ onSelect: () => void openProjectFolder(entry),+ }),+ sidebarMenuAction({+ id: "edit-project",+ label: t("project.edit", { defaultValue: "Edit project" }),+ icon: <IconPencil size={14} />,+ onSelect: () => {+ closeMenus(false);+ setEditProjectFor(entry);+ },+ }),+ sidebarMenuAction({+ id: "toggle-project-pin",+ label: entry.meta.pinned ? t("project.unpin") : t("project.pin"),+ icon: <IconPin size={14} />,+ onSelect: () => toggleProjectPin(entry),+ }),+ sidebarMenuAction({+ id: "toggle-project-archive",+ label: archived+ ? t("project.restore", { defaultValue: "Restore project" })+ : t("project.archive", { defaultValue: "Archive project" }),+ icon: archived ? <IconArchiveRestore size={14} /> : <IconArchive size={14} />,+ onSelect: () => void archiveProject(entry),+ }),+ sidebarMenuSection({+ id: "project-git",+ label: t("worktree.menu.group", { defaultValue: "Git" }),+ }),+ ...projectIsolationItems,+ dangerSection("project-danger", t("nav.dangerZone", { defaultValue: "Danger zone" })),+ sidebarMenuAction({+ id: "delete-project",+ label: t("project.delete", { defaultValue: "Delete project" }),+ icon: <IconTrash size={14} />,+ danger: true,+ onSelect: () => requestDeleteProject(entry),+ }),+ ],+ };+ },+ [+ archiveProject,+ openProjectFolder,+ projectIsolationItems,+ t,+ toggleProjectPin,+ ],+ );++ const batchMenuContent = useCallback(+ (count: number): SidebarMenuPanelContent => ({+ label: t("nav.sessionActions", { defaultValue: "Session actions" }),+ hint: t("nav.batchSelectionHint", {+ defaultValue: "{{count}} sessions selected",+ count,+ }),+ items: [+ sidebarMenuAction({+ id: "batch-archive",+ label: t("nav.batchArchive", { defaultValue: "Archive {{count}} sessions", count }),+ 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 }),+ icon: <IconTrash size={14} />,+ danger: true,+ armed: armedDelete === "batch",+ onSelect: () => {+ if (armedDelete !== "batch") {+ setArmedDelete("batch");+ return;+ }+ setArmedDelete(null);+ void batchDeleteSessions();+ },+ }),+ ],+ }),+ [armedDelete, batchArchiveSessions, batchDeleteSessions, t],+ );++ const sortMenuContent = useMemo(+ (): SidebarMenuPanelContent => ({+ label: t("nav.sortSessions", { defaultValue: "Sort sessions" }),+ items: [+ sidebarMenuGroup({+ id: "sort",+ label: t("nav.sortSessions", { defaultValue: "Sort sessions" }),+ options: (["recent", "oldest", "name", "created"] as const).map((value) => ({+ id: `sort-${value}`,+ label: menuSortLabel(value),+ selected: displaySessionSort === value,+ onSelect: () => setSort(value),+ })),+ }),+ sidebarMenuSection({+ id: "view",+ label: t("nav.viewOptions", { defaultValue: "View" }),+ }),+ sidebarMenuCheck({+ id: "toggle-show-archived",+ label: t("nav.showArchived", { defaultValue: "Show archived" }),+ checked: showArchived,+ onSelect: toggleShowArchived,+ }),+ ],+ }),+ [displaySessionSort, menuSortLabel, setSort, showArchived, t, toggleShowArchived],+ );+const beginSessionDrag = useCallback((event: ReactDragEvent<HTMLDivElement>, sessionId: string) => {event.dataTransfer.effectAllowed = "move";@@ -2064,310 +2357,90 @@ export function Sidebar({);};+ /**+ * One panel renders whatever menu is open. The content builders above decide+ * which rows exist, so this stays placement and nothing else.+ */const renderFloatingMenu = () => {- if (- !menuPosition ||- typeof document === "undefined" ||- (!sessionMenu && !projectMenu && !sectionMenu && !sortOpen)- ) {- return null;- }+ if (!menuPosition || typeof document === "undefined") return null;+ const position = { top: menuPosition.top, left: menuPosition.left };+ const session = sessionMenu+ ? sessions.find((item) => item.id === sessionMenu)+ : undefined;+ const entry = projectMenu+ ? projectEntries.find((item) => item.key === projectMenu)+ : undefined;if (sectionMenu) {const isSessions = sectionMenu === "sessions";- const action = isSessions ? "new-standalone-session" : "new-project";- const label = isSessions- ? t("nav.newTemporarySession")- : t("nav.newProject");- const Icon = isSessions ? IconNewSession : IconNewProject;return portalToBody(- <div- ref={floatingMenuRef}- className="sidebar-row-menu sidebar-floating-menu sidebar-section-menu"- role="menu"- data-sidebar-section-menu={sectionMenu}+ <SidebarMenuPanel+ menuRef={floatingMenuRef}+ firstItemRef={menuFirstItemRef}+ className="sidebar-section-menu"+ position={position}onKeyDown={onMenuKeyDown}- style={{- top: menuPosition.top,- left: menuPosition.left,+ content={{+ label: isSessions ? t("nav.newTemporarySession") : t("nav.newProject"),+ items: [+ sidebarMenuAction({+ id: isSessions ? "new-standalone-session" : "new-project",+ label: isSessions+ ? t("nav.newTemporarySession")+ : t("nav.newProject"),+ icon: isSessions+ ? <IconNewSession size={14} />+ : <IconNewProject size={14} />,+ onSelect: () => {+ closeMenus(false);+ if (isSessions) void createSession({ projectPath: null });+ else void openProjectPicker();+ },+ }),+ ],}}- >- <button- ref={menuFirstItemRef}- type="button"- role="menuitem"- data-action={action}- onClick={() => {- closeMenus(false);- if (isSessions) void createSession({ projectPath: null });- else void openProjectPicker();- }}- >- <Icon size={14} />- <span>{label}</span>- </button>- </div>,+ />,);}if (sortOpen) {return portalToBody(- <div- ref={floatingMenuRef}- className="sidebar-popover sidebar-sort-menu sidebar-floating-menu"- role="menu"+ <SidebarMenuPanel+ menuRef={floatingMenuRef}+ firstItemRef={menuFirstItemRef}+ className="sidebar-sort-menu"+ position={position}onKeyDown={onMenuKeyDown}- style={{- top: menuPosition.top,- left: menuPosition.left,- }}- >- <div className="sidebar-popover-title">- {t("nav.sortSessions", { defaultValue: "Sort sessions" })}- </div>- {(["recent", "oldest", "name", "created"] as const).map((value, index) => (- <button ref={index === 0 ? menuFirstItemRef : undefined} key={value} type="button" role="menuitemradio" aria-checked={displaySessionSort === value} className={displaySessionSort === value ? "selected" : ""} data-sort={value} onClick={() => setSort(value)}>- <span>{value === "recent" ? t("nav.sortRecent", { defaultValue: "Recently updated" }) : value === "oldest" ? t("nav.sortOldest", { defaultValue: "Oldest first" }) : value === "name" ? t("nav.sortName", { defaultValue: "Name" }) : t("nav.sortCreated", { defaultValue: "Created date" })}</span>- {displaySessionSort === value ? <span className="sidebar-sort-check">✓</span> : null}- </button>- ))}- <div className="sidebar-popover-divider" />- <button type="button" role="menuitemcheckbox" aria-checked={showArchived} data-action="toggle-show-archived" onClick={toggleShowArchived}>- <span>{showArchived ? t("nav.hideArchived", { defaultValue: "Hide archived" }) : t("nav.showArchived", { defaultValue: "Show archived" })}</span>- <span className={`sidebar-checkbox ${showArchived ? "checked" : ""}`}>{showArchived ? "✓" : ""}</span>- </button>- </div>,+ content={sortMenuContent}+ />,);}- const session = sessionMenu- ? sessions.find((item) => item.id === sessionMenu)- : undefined;- const entry = projectMenu- ? projectEntries.find((item) => item.key === projectMenu)- : undefined;- if (!session && !entry) return null;- return portalToBody(- <div- ref={floatingMenuRef}- className="sidebar-row-menu sidebar-floating-menu"- role="menu"- onKeyDown={onMenuKeyDown}- style={{- top: menuPosition.top,- left: menuPosition.left,- }}- >- {session ? (- selectedIds.size > 1 && selectedIds.has(session.id) ? (- <>- <button- ref={menuFirstItemRef}- type="button"- role="menuitem"- data-action="batch-archive"- onClick={() => void batchArchiveSessions()}- >- <IconArchive size={14} />- {t("nav.batchArchive", { defaultValue: "Archive {{count}} sessions", count: selectedIds.size })}- </button>- <button- type="button"- role="menuitem"- className={cx("danger", armedDelete === "batch" && "is-armed")}- data-action="batch-delete"- data-armed={armedDelete === "batch" ? "true" : undefined}- onClick={() => {- if (armedDelete !== "batch") {- setArmedDelete("batch");- return;- }- setArmedDelete(null);- void batchDeleteSessions();- }}- >- <IconTrash size={14} />- {armedDelete === "batch"- ? t("nav.batchDeleteConfirm", { defaultValue: "Delete {{count}} sessions?", count: selectedIds.size })- : t("nav.batchDelete", { defaultValue: "Delete {{count}} sessions", count: selectedIds.size })}- </button>- </>- ) : (- <>- {session.source !== "pi-native" ? (- <button- ref={menuFirstItemRef}- type="button"- role="menuitem"- data-action="rename-session"- onClick={() => {- closeMenus(false);- setRenameFor(session);- }}- >- <IconPencil size={14} />- {t("nav.renameTask", { defaultValue: "Rename task" })}- </button>- ) : null}- <button- type="button"- role="menuitem"- data-action="toggle-session-pin"- onClick={() => toggleSessionPin(session)}- >- <IconPin size={14} />- {sessionPinned(session, sessionMeta[session.id])- ? t("nav.unpinTask", { defaultValue: "Unpin" })- : t("nav.pinTask", { defaultValue: "Pin" })}- </button>- <button- type="button"- role="menuitem"- data-action="toggle-session-archive"- onClick={() => void archiveSession(session)}- >- {sessionArchived(session, sessionMeta[session.id]) ? (- <IconArchiveRestore size={14} />- ) : (- <IconArchive size={14} />- )}- {sessionArchived(session, sessionMeta[session.id])- ? t("nav.restoreTask", { defaultValue: "Restore" })- : t("nav.archiveTask", { defaultValue: "Archive" })}- </button>- {session.source !== "pi-native" && sessionAllows(session, "canEditMessages") ? (- <button- type="button"- role="menuitem"- data-action="fork-session"- disabled={Boolean(runningSessions[session.id])}- onClick={() => void forkSession(session)}- >- <IconBranch size={14} />- {t("nav.createBranch")}- </button>- ) : null}- <WorktreeSessionMenuItems- sessionId={session.id}- title={taskTitle(session.title)}- worktree={session.worktree}- running={Boolean(runningSessions[session.id])}- onDone={() => closeMenus(false)}- />- <button- type="button"- role="menuitem"- data-action="copy-session-link"- onClick={() => void copySessionLink(session)}- >- <IconCopy size={14} />- {t("nav.copySessionLink")}- </button>- {settings?.developerMode === true && !isRemoteSession(session) ? (- <>- <button- type="button"- role="menuitem"- data-action="copy-conversation-id"- onClick={() => void copyConversationId(session)}- >- <IconCopy size={14} />- {t("nav.copyConversationId")}- </button>- <button- type="button"- role="menuitem"- data-action="open-session-path"- onClick={() => void openSessionPath(session)}- >- <IconFolder size={14} />- {t("nav.openSessionPath")}- </button>- </>- ) : null}- {session.source !== "pi-native" ? (- <button- type="button"- role="menuitem"- className={cx("danger", armedDelete === session.id && "is-armed")}- data-action="delete-session"- data-armed={armedDelete === session.id ? "true" : undefined}- onClick={() => requestDeleteSession(session)}- >- <IconX size={14} />- {armedDelete === session.id ? t("nav.deleteTaskConfirm", { defaultValue: "Delete?" }) : t("nav.deleteTask", { defaultValue: "Delete" })}- {armedDelete === session.id && session.worktree ? (- <WorktreeDeleteLossNote sessionId={session.id} />- ) : null}- </button>- ) : null}- </>- )- ) : null}- {entry ? (- <>- <button- ref={menuFirstItemRef}- type="button"- role="menuitem"- data-action="open-project-folder"- onClick={() => void openProjectFolder(entry)}- >- <IconFolder size={14} />- {t("project.openFolder", { defaultValue: "Open folder" })}- </button>- <button- type="button"- role="menuitem"- data-action="edit-project"- onClick={() => {- closeMenus(false);- setEditProjectFor(entry);- }}- >- <IconPencil size={14} />- {t("project.edit", { defaultValue: "Edit project" })}- </button>- <WorktreeProjectMenuItems- projectPath={entry.path}- projectName={entry.name}- onDone={() => closeMenus(false)}- />- <button- type="button"- role="menuitem"- data-action="toggle-project-pin"- onClick={() => toggleProjectPin(entry)}- >- <IconPin size={14} />- {entry.meta.pinned ? t("project.unpin") : t("project.pin")}- </button>- <button- type="button"- role="menuitem"- data-action="toggle-project-archive"- onClick={() => void archiveProject(entry)}- >- {entry.meta.archived ? (- <IconArchiveRestore size={14} />- ) : (- <IconArchive size={14} />- )}- {entry.meta.archived- ? t("project.restore", { defaultValue: "Restore project" })- : t("project.archive", { defaultValue: "Archive project" })}- </button>- <button- type="button"- role="menuitem"- className="danger"- data-action="delete-project"- onClick={() => requestDeleteProject(entry)}- >- <IconTrash size={14} />- {t("project.delete", { defaultValue: "Delete project" })}- </button>- </>- ) : null}- </div>,- );+ if (session) {+ return portalToBody(+ <SidebarMenuPanel+ menuRef={floatingMenuRef}+ firstItemRef={menuFirstItemRef}+ position={position}+ onKeyDown={onMenuKeyDown}+ content={+ batchSelected+ ? batchMenuContent(selectedIds.size)+ : sessionMenuContent(session)+ }+ />,+ );+ }+ if (entry) {+ const content = projectMenuContent(entry);+ return portalToBody(+ <SidebarMenuPanel+ menuRef={floatingMenuRef}+ firstItemRef={menuFirstItemRef}+ position={position}+ onKeyDown={onMenuKeyDown}+ content={content}+ />,+ );+ }+ return null;};return (diff --git a/apps/desktop/src/components/SidebarMenuPanel.tsx b/apps/desktop/src/components/SidebarMenuPanel.tsxnew file mode 100644index 000000000..4e80d63c4--- /dev/null+++ b/apps/desktop/src/components/SidebarMenuPanel.tsx@@ -0,0 +1,204 @@+/**+ * The one floating panel behind every sidebar menu.+ *+ * 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.+ */+import { Fragment, type KeyboardEvent as ReactKeyboardEvent, type RefObject } from "react";+import type {+ SidebarMenuActionItem,+ SidebarMenuGroupItem,+ SidebarMenuPanelContent,+} from "../lib/sidebar-menu";++/** Arrow/Home/End moves focus between the rows that can actually take it. */+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 }));+}++export function SidebarMenuPanel({+ content,+ menuRef,+ firstItemRef,+ onKeyDown,+ className,+ 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 renderAction = (+ item: SidebarMenuActionItem,+ options?: { iconFrom?: SidebarMenuActionItem["icon"]; keyPrefix?: string },+ ) => (+ <Fragment key={`${options?.keyPrefix ?? ""}${item.id}`}>+ {item.separatorBefore ? (+ <div className="sidebar-menu-separator" role="separator" />+ ) : null}+ <button+ ref={takeFirstItemRef()}+ type="button"+ role="menuitem"+ className={item.danger ? "danger" : undefined}+ data-action={item.id}+ data-armed={item.armed ? "true" : undefined}+ disabled={item.disabled}+ title={item.title}+ aria-busy={item.busy || undefined}+ aria-describedby={item.describedBy}+ onClick={item.onSelect}+ >+ {options?.iconFrom ?? (item.icon ? 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>+ ) : null}+ </Fragment>+ );++ return (+ <div+ ref={menuRef}+ className={className ? `sidebar-row-menu sidebar-floating-menu ${className}` : "sidebar-row-menu sidebar-floating-menu"}+ role="menu"+ aria-label={content.label}+ onKeyDown={onKeyDown}+ 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.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>+ );+}++/** Shared keyboard handling for every sidebar floating menu. */+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;+ 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();+}diff --git a/apps/desktop/src/features/worktree/WorktreeSidebarParts.tsx b/apps/desktop/src/features/worktree/WorktreeSidebarParts.tsxindex 5019e9c9e..92ef526e4 100644--- a/apps/desktop/src/features/worktree/WorktreeSidebarParts.tsx+++ b/apps/desktop/src/features/worktree/WorktreeSidebarParts.tsx@@ -12,6 +12,10 @@ import {import { Badge } from "../../components/ui";import { api } from "../../lib/api";import { useAppStore } from "../../stores/app-store";+import {+ sidebarMenuAction,+ type SidebarMenuItem,+} from "../../lib/sidebar-menu";import { WorktreeMergeDialog } from "./WorktreeMergeDialog";import { WorktreeSetupCommandDialog, WorktreeSetupLogDialog } from "./WorktreeSetupDialogs";import {@@ -23,7 +27,6 @@ import {} from "./worktree-actions";import { WorktreeBehindMarker } from "./WorktreeBehind";import { useWorktreeUi } from "./worktree-ui-store";-/** Session-row badge for an isolated session (PRD R3). */export function WorktreeBadge({worktree,@@ -61,7 +64,12 @@ export function WorktreeBadge({}/** Project-menu items: create an isolated session, edit the setup command. */-export function WorktreeProjectMenuItems({+/**+ * Project-menu rows for isolation: start an isolated session, or edit the+ * setup command. Returned as menu data so the sidebar renders them inside its+ * own "Git" group next to the other repository actions.+ */+export function useWorktreeProjectMenuItems({projectPath,projectName,onDone,@@ -69,63 +77,162 @@ export function WorktreeProjectMenuItems({projectPath: string;projectName: string;onDone: () => void;-}) {+}): SidebarMenuItem[] {const { t } = useTranslation();const open = useWorktreeUi((s) => s.open);const reasonId = useId();- const [probe, setProbe] = useState<IsolationProbeState>("checking");- // Probed each time the menu opens, so the item reflects the current- // repository state; a stale answer for another project is dropped.+ const [probe, setProbe] = useState<{+ projectPath: string;+ state: IsolationProbeState;+ }>({ projectPath: "", state: "checking" });+ // Probe only while a project menu is open. A new project starts disabled+ // until its own answer arrives; the previous project's answer never leaks.useEffect(() => {+ if (!projectPath) {+ setProbe({ projectPath: "", state: "checking" });+ return;+ }let current = true;- setProbe("checking");+ setProbe({ projectPath, state: "checking" });api.probeWorktree(projectPath)- .then((result) => current && setProbe(result))- .catch(() => current && setProbe("unknown"));+ .then((result) => current && setProbe({ projectPath, state: result }))+ .catch(() => current && setProbe({ projectPath, state: "unknown" }));return () => {current = false;};}, [projectPath]);- const { disabled, reason } = isolationAvailability(probe, t);- return (- <>- <button- type="button"- role="menuitem"- data-action="new-isolated-session"- disabled={disabled}- aria-busy={probe === "checking" || undefined}- aria-describedby={reason ? reasonId : undefined}- title={reason}- onClick={() => {- onDone();- void createIsolatedSession(projectPath, t);- }}- >- <IconBranch size={14} />- {t("worktree.newIsolatedSession")}- </button>- {reason ? (- <p id={reasonId} className="worktree-menu-reason" data-worktree-unavailable="">- {reason}- </p>- ) : null}- <button- type="button"- role="menuitem"- data-action="worktree-setup-command"- title={t("worktree.setupCommand.menu")}- onClick={() => {- onDone();- open({ kind: "setupCommand", projectPath, projectName });- }}- >- <IconWrench size={14} />- <span className="worktree-menu-label">{t("worktree.setupCommand.menu")}</span>- </button>- </>- );+ const probeState = probe.projectPath === projectPath ? probe.state : "checking";+ const { disabled, reason } = isolationAvailability(probeState, t);+ return [+ sidebarMenuAction({+ id: "new-isolated-session",+ label: t("worktree.newIsolatedSession"),+ icon: <IconBranch size={14} />,+ disabled,+ busy: probeState === "checking",+ describedBy: reason ? reasonId : undefined,+ title: reason,+ onSelect: () => {+ onDone();+ void createIsolatedSession(projectPath, t);+ },+ }),+ sidebarMenuAction({+ id: "worktree-setup-command",+ label: t("worktree.setupCommand.menu"),+ icon: <IconWrench size={14} />,+ title: t("worktree.setupCommand.menu"),+ onSelect: () => {+ onDone();+ open({ kind: "setupCommand", projectPath, projectName });+ },+ }),+ ];+}++/**+ * A session's isolation rows, when the session has a worktree at all. The+ * sidebar places them in its "Git" group, so no other session pays for them.+ */+export function useWorktreeSessionMenuItems({+ sessionId,+ title,+ worktree,+ running,+ onDone,+}: {+ sessionId: string;+ title: string;+ worktree?: SessionWorktreeSummary;+ running: boolean;+ onDone: () => void;+}): SidebarMenuItem[] {+ const { t } = useTranslation();+ const open = useWorktreeUi((s) => s.open);+ // A conflicted session resolves first; syncing again would only report+ // the same conflict.+ const conflicted = worktree?.status === "conflict";+ const syncable = Boolean(worktree) && worktree?.status !== "missing" && !conflicted;+ // Project commits the session lacks, counted when the menu opens; `-1`+ // when the count failed (syncing still reports the reason).+ const [behind, setBehind] = useState<number | null>(null);+ useEffect(() => {+ if (!sessionId || !syncable) return;+ let current = true;+ setBehind(null);+ api+ .getWorktreeBehind(sessionId)+ .then((count) => {+ if (!current) return;+ setBehind(count);+ useWorktreeUi.getState().setBehindFor(sessionId, count);+ })+ .catch(() => current && setBehind(-1));+ return () => {+ current = false;+ };+ }, [sessionId, syncable]);+ if (!worktree) return [];+ const missing = worktree.status === "missing";+ return [+ sidebarMenuAction({+ id: "worktree-merge",+ label: t("worktree.merge.menu"),+ icon: <IconPullRequest size={14} />,+ disabled: running || missing,+ onSelect: () => {+ onDone();+ open({ kind: "merge", sessionId, title });+ },+ }),+ sidebarMenuAction({+ id: "worktree-sync",+ label:+ syncable && behind !== null && behind > 0+ ? t("worktree.sync.menuBehind", { count: behind })+ : t("worktree.sync.menu"),+ icon: <IconRefresh size={14} />,+ disabled: running || !syncable || behind === null || behind === 0,+ busy: behind === null && syncable,+ title: conflicted+ ? t("worktree.sync.resolveFirst")+ : behind === 0+ ? t("worktree.sync.upToDate")+ : undefined,+ onSelect: () => {+ onDone();+ void syncIsolatedSession(sessionId, t);+ },+ }),+ sidebarMenuAction({+ id: "worktree-reveal",+ label: t("worktree.reveal"),+ icon: <IconFolderOpen size={14} />,+ disabled: missing,+ onSelect: () => {+ onDone();+ void api.revealWorktree(sessionId).catch((error: unknown) =>+ useAppStore+ .getState()+ .showToast(worktreeErrorMessage(error, t), { variant: "error" }),+ );+ },+ }),+ ...(worktree.setupStatus && worktree.setupStatus !== "none"+ ? [+ sidebarMenuAction({+ id: "worktree-setup-log",+ label: t("worktree.setupLog.menu"),+ icon: <IconFileText size={14} />,+ onSelect: () => {+ onDone();+ open({ kind: "setupLog", sessionId, title });+ },+ }),+ ]+ : []),+ ];}/** Session-menu items of an isolated session; nothing for other sessions. */@@ -167,88 +274,81 @@ export function WorktreeSessionMenuItems({current = false;};}, [sessionId, syncable]);- if (!worktree) return null;+ if (!worktree) return [];const missing = worktree.status === "missing";- return (- <>- <button- type="button"- role="menuitem"- data-action="worktree-merge"- disabled={running || missing}- onClick={() => {- onDone();- open({ kind: "merge", sessionId, title });- }}- >- <IconPullRequest size={14} />- {t("worktree.merge.menu")}- </button>- <button- type="button"- role="menuitem"- data-action="worktree-sync"- disabled={running || !syncable || behind === null || behind === 0}- aria-busy={behind === null && syncable ? true : undefined}- title={- conflicted- ? t("worktree.sync.resolveFirst")- : behind === 0- ? t("worktree.sync.upToDate")- : undefined- }- onClick={() => {- onDone();- void syncIsolatedSession(sessionId, t);- }}- >- <IconRefresh size={14} />- {syncable && behind !== null && behind > 0+ return [+ sidebarMenuAction({+ id: "worktree-merge",+ label: t("worktree.merge.menu"),+ icon: <IconPullRequest size={14} />,+ disabled: running || missing,+ onSelect: () => {+ onDone();+ open({ kind: "merge", sessionId, title });+ },+ }),+ sidebarMenuAction({+ id: "worktree-sync",+ label:+ syncable && behind !== null && behind > 0? t("worktree.sync.menuBehind", { count: behind })- : t("worktree.sync.menu")}- </button>- <button- type="button"- role="menuitem"- data-action="worktree-reveal"- disabled={missing}- onClick={() => {- onDone();- api.revealWorktree(sessionId).catch((error: unknown) =>- useAppStore.getState().showToast(worktreeErrorMessage(error, t), { variant: "error" }),- );- }}- >- <IconFolderOpen size={14} />- {t("worktree.reveal")}- </button>- {worktree.setupStatus && worktree.setupStatus !== "none" ? (- <button- type="button"- role="menuitem"- data-action="worktree-setup-log"- onClick={() => {- onDone();- open({ kind: "setupLog", sessionId, title });- }}- >- <IconFileText size={14} />- {t("worktree.setupLog.menu")}- </button>- ) : null}- </>- );+ : t("worktree.sync.menu"),+ icon: <IconRefresh size={14} />,+ disabled: running || !syncable || behind === null || behind === 0,+ busy: behind === null && syncable,+ title: conflicted+ ? t("worktree.sync.resolveFirst")+ : behind === 0+ ? t("worktree.sync.upToDate")+ : undefined,+ onSelect: () => {+ onDone();+ void syncIsolatedSession(sessionId, t);+ },+ }),+ sidebarMenuAction({+ id: "worktree-reveal",+ label: t("worktree.reveal"),+ icon: <IconFolderOpen size={14} />,+ disabled: missing,+ onSelect: () => {+ onDone();+ void api.revealWorktree(sessionId).catch((error: unknown) =>+ useAppStore+ .getState()+ .showToast(worktreeErrorMessage(error, t), { variant: "error" }),+ );+ },+ }),+ ...(worktree.setupStatus && worktree.setupStatus !== "none"+ ? [+ sidebarMenuAction({+ id: "worktree-setup-log",+ label: t("worktree.setupLog.menu"),+ icon: <IconFileText size={14} />,+ onSelect: () => {+ onDone();+ open({ kind: "setupLog", sessionId, title });+ },+ }),+ ]+ : []),+ ];}/**- * Note after the armed "Delete?" label of an isolated session: deleting removes+ * The text of the pre-delete warning for an isolated session: deleting removes* its worktree and branch, so unmerged work is named before the second click- * (PRD R5). Renders nothing when nothing would be lost.+ * (PRD R5). `null` when nothing would be lost.*/-export function WorktreeDeleteLossNote({ sessionId }: { sessionId: string }) {+export function useWorktreeDeleteLossText(sessionId: string): string | null {const { t } = useTranslation();const [pending, setPending] = useState<WorktreePendingWork | null>(null);useEffect(() => {+ if (!sessionId) {+ setPending(null);+ return;+ }let alive = true;api.getWorktreePendingWork(sessionId)@@ -258,12 +358,10 @@ export function WorktreeDeleteLossNote({ sessionId }: { sessionId: string }) {alive = false;};}, [sessionId]);- if (!pending || (pending.unmergedCommits === 0 && !pending.uncommittedChanges)) return null;- return (- <span className="worktree-delete-loss" data-worktree-loss="true">- {t("worktree.deleteLoss")}- </span>- );+ if (!pending || (pending.unmergedCommits === 0 && !pending.uncommittedChanges)) {+ return null;+ }+ return t("worktree.deleteLoss");}/** Renders the open worktree dialog. Mounted once by the sidebar. */diff --git a/apps/desktop/src/lib/sidebar-menu.ts b/apps/desktop/src/lib/sidebar-menu.tsnew file mode 100644index 000000000..fea93e6f7--- /dev/null+++ b/apps/desktop/src/lib/sidebar-menu.ts@@ -0,0 +1,113 @@+/**+ * The sidebar's floating menu surface, as data.+ *+ * A row menu, the sort popover, and a section menu were three hand-written+ * bodies growing in `Sidebar.tsx`. They are one grammar — a floating panel of+ * rows, each either a command, a check, or a labeled group — so the surface is+ * declared as a value here and rendered by `SidebarMenuPanel`. Building the+ * value stays where the actions live (the sidebar), which keeps this module+ * pure and testable while the panel keeps one keyboard and focus contract for+ * every menu.+ */++/** A command row. `danger` paints destructive ink; `separatorBefore` adds a rule. */+export type SidebarMenuActionItem = {+ kind: "action";+ /** Stable identity for tests and React keys. */+ id: string;+ label: string;+ icon?: React.ReactNode;+ disabled?: boolean;+ /** Full label for a row whose text is clamped, and its accessible name. */+ title?: string;+ danger?: boolean;+ /** Second, confirming click is armed: the item relabels and highlights. */+ armed?: boolean;+ /** Explains a disabled row (availability reason) to assistive tech. */+ describedBy?: string;+ busy?: boolean;+ separatorBefore?: boolean;+ onSelect: () => void;+};++/** A labeled toggle, e.g. "Show archived". */+export type SidebarMenuCheckItem = {+ kind: "check";+ id: string;+ label: string;+ checked: boolean;+ onSelect: () => void;+};++/** One option of a radio group, e.g. a sort order. */+export type SidebarMenuRadioOption = {+ id: string;+ label: string;+ selected: boolean;+ onSelect: () => void;+};++/**+ * A labeled group. Rendered as a titled section, or — with a single option and+ * no title — as nothing but its rows, which is how a lone secondary action+ * joins the rows above it instead of opening a one-row submenu.+ */+export type SidebarMenuGroupItem = {+ kind: "group";+ id: string;+ label?: string;+ options: SidebarMenuRadioOption[];+};++/** A titled separator, e.g. "Danger zone". */+export type SidebarMenuSectionItem = {+ kind: "section";+ id: string;+ label: string;+};++export type SidebarMenuItem =+ | SidebarMenuActionItem+ | SidebarMenuCheckItem+ | SidebarMenuSectionItem+ | SidebarMenuGroupItem;++/** A rule carrying a caption: pending work that would be lost by deleting. */+export type SidebarMenuNote = {+ id: string;+ text: string;+ /** Measured line by the caller; the panel only places it. */+ separatorBefore?: boolean;+};++/** Accessible name of the surface, and the optional hint row under it. */+export type SidebarMenuPanelContent = {+ label: string;+ hint?: string;+ items: SidebarMenuItem[];+ notes?: SidebarMenuNote[];+};++export function sidebarMenuAction(+ item: Omit<SidebarMenuActionItem, "kind">,+): SidebarMenuActionItem {+ return { kind: "action", ...item };+}++export function sidebarMenuCheck(+ item: Omit<SidebarMenuCheckItem, "kind">,+): SidebarMenuCheckItem {+ return { kind: "check", ...item };+}++export function sidebarMenuGroup(+ item: Omit<SidebarMenuGroupItem, "kind">,+): SidebarMenuGroupItem {+ return { kind: "group", ...item };+}++export function sidebarMenuSection(+ item: Omit<SidebarMenuSectionItem, "kind">,+): SidebarMenuSectionItem {+ return { kind: "section", ...item };+}diff --git a/apps/desktop/src/styles/sessions.css b/apps/desktop/src/styles/sessions.cssindex 760de9b55..66815c1f7 100644--- a/apps/desktop/src/styles/sessions.css+++ b/apps/desktop/src/styles/sessions.css@@ -721,13 +721,39 @@right: auto;}-.sidebar-popover-title {- padding: 4px 8px 6px;+/* A group caption inside the panel: quiet, and never a pointer target. */+.sidebar-menu-section {+ margin: 0;+ padding: 6px 8px 4px;color: var(--ds-text-muted);font-size: var(--text-xs-plus);font-weight: var(--font-weight-medium);}+.sidebar-menu-separator {+ height: 1px;+ margin: 4px 6px;+ background: var(--ds-border-subtle);+}++.sidebar-menu-hint {+ margin: 0;+ padding: 2px 8px 6px;+ color: var(--ds-text-muted);+ font-size: var(--text-xs-plus);+}++/* A note hangs under its own rule, so it reads as part of the row above. */+.sidebar-menu-note {+ max-width: 260px;+ margin: -2px 0 4px;+ padding: 0 8px 0 30px;+ color: var(--ds-error);+ font-size: var(--text-sm);+ white-space: normal;+ overflow-wrap: anywhere;+}+.sidebar-popover button {justify-content: space-between;}@@ -754,10 +780,6 @@background: color-mix(in oklab, var(--ds-accent) 22%, transparent);}-.sidebar-popover-divider {- height: 6px;-}-/* Compact hover card for session rows. Related-session references stayreal buttons so the card remains usable with a keyboard. */.sidebar-session-hover-card {diff --git a/apps/desktop/src/styles/worktree.css b/apps/desktop/src/styles/worktree.cssindex e0ac0ed60..5f1feed86 100644--- a/apps/desktop/src/styles/worktree.css+++ b/apps/desktop/src/styles/worktree.css@@ -6,15 +6,6 @@margin-inline-end: 4px;}-/* Keep long localized project-menu labels aligned without widening the menu. */-.worktree-menu-label {- min-width: 0;- flex: 1 1 auto;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;-}-.worktree-dialog-body {display: flex;flex-direction: column;@@ -43,25 +34,8 @@margin: 0;padding: 8px 12px;overflow: auto;- white-space: pre-wrap;border: 1px solid var(--ds-border-default);border-radius: var(--radius-xs);background: var(--ds-bg-inset);font-size: var(--text-sm);}--/* Why "New isolated session" is unavailable, under the disabled item. */-.worktree-menu-reason {- max-width: 260px;- margin: -2px 0 4px;- padding: 0 8px 0 30px;- color: var(--ds-text-muted);- font-size: var(--text-sm);- white-space: normal;- overflow-wrap: anywhere;-}--.worktree-delete-loss {- margin-inline-start: 6px;- color: var(--ds-error);-}diff --git a/apps/desktop/test/project-delete.test.mjs b/apps/desktop/test/project-delete.test.mjsindex 262e650c5..ccf879f3b 100644--- a/apps/desktop/test/project-delete.test.mjs+++ b/apps/desktop/test/project-delete.test.mjs@@ -65,7 +65,9 @@ function projectValue(block, key) {* menus of the same surface.*/function deleteHandler(source) {- const start = source.indexOf('data-action="delete-project"');+ const start = source.indexOf('data-action="delete-project"') >= 0+ ? source.indexOf('data-action="delete-project"')+ : source.indexOf('id: "delete-project"');assert.ok(start >= 0, "the delete action is present");const rest = source.slice(start);const end = rest.search(/\n\s+>\n/);@@ -139,8 +141,12 @@ test("both project menus expose a destructive delete action", () => {["Sidebar", sidebarSource],]) {// The destructive style stays on the menu action until confirmation.- assert.match(source, /className="danger"/, surface);- assert.match(source, /data-action="delete-project"/, surface);+ assert.match(source, /className="danger"|danger: true/, surface);+ assert.match(+ source,+ surface === "Sidebar" ? /id: "delete-project"/ : /data-action="delete-project"/,+ surface,+ );assert.match(source, /<ProjectDeleteDialog/, surface);}@@ -151,8 +157,8 @@ test("both project menus expose a destructive delete action", () => {"ProjectsPage orders delete after archive",);assert.ok(- sidebarSource.indexOf('data-action="delete-project"') >- sidebarSource.indexOf('data-action="toggle-project-archive"'),+ sidebarSource.indexOf('id: "delete-project"') >+ sidebarSource.indexOf('id: "toggle-project-archive"'),"Sidebar orders delete after archive",);assert.match(projectsSource, /sessionCount: totalSessions/);diff --git a/apps/desktop/test/project-edit.test.mjs b/apps/desktop/test/project-edit.test.mjsindex 8b7debabe..b8c5980b6 100644--- a/apps/desktop/test/project-edit.test.mjs+++ b/apps/desktop/test/project-edit.test.mjs@@ -29,7 +29,7 @@ const []);test("project rows expose an edit action in both project surfaces", () => {- assert.match(sidebarSource, /data-action="edit-project"/);+ assert.match(sidebarSource, /id: "edit-project"/);assert.match(sidebarSource, /setEditProjectFor\(entry\)/);assert.match(sidebarSource, /ProjectEditDialog/);assert.match(projectsSource, /data-action="edit-project"/);diff --git a/apps/desktop/test/session-fork.test.mjs b/apps/desktop/test/session-fork.test.mjsindex c23ccca59..401afae8d 100644--- a/apps/desktop/test/session-fork.test.mjs+++ b/apps/desktop/test/session-fork.test.mjs@@ -18,6 +18,7 @@ test("session fork is wired through protocol, main, API, store, and sidebar", ()readStoreModuleSync("runtime/session-coordination.ts"),].join("\n");const sidebar = read("../src/components/Sidebar.tsx");+ const panelSource = read("../src/components/SidebarMenuPanel.tsx");assert.match(protocol,@@ -33,10 +34,10 @@ test("session fork is wired through protocol, main, API, store, and sidebar", ());assert.match(store, /forkSession:\s*async \(id\)/);assert.match(store, /commitForkedSession\(result\.session/);- assert.match(sidebar, /data-action="fork-session"/);- assert.match(sidebar, /disabled=\{Boolean\(runningSessions\[session\.id\]\)\}/);- assert.match(sidebar, /<IconBranch size=\{14\} \/>/);- assert.match(sidebar, /\[role="menuitem"\]:not\(:disabled\)/);+ assert.match(sidebar, /id: "fork-session"/);+ assert.match(sidebar, /disabled: Boolean\(runningSessions\[session\.id\]\)/);+ assert.match(sidebar, /icon: <IconBranch size=\{14\} \/>/);+ assert.match(panelSource, /\[role="menuitem"\]:not\(:disabled\)/);});test("assistant response fork reuses isolated session snapshots", () => {diff --git a/apps/desktop/test/session-project-move.test.mjs b/apps/desktop/test/session-project-move.test.mjsindex c80c29820..f285a13c3 100644--- a/apps/desktop/test/session-project-move.test.mjs+++ b/apps/desktop/test/session-project-move.test.mjs@@ -98,7 +98,7 @@ test("sidebar sessions drag onto project groups without a menu fallback", () =>assert.match(sidebar, /dropProjectKey === entry\.key \? "is-drop-target" : ""/);assert.doesNotMatch(sidebar, /data-action="move-session-to-project"/);assert.doesNotMatch(sidebar, /nav\.moveToProject/);- assert.match(sidebar, /disabled=\{Boolean\(runningSessions\[session\.id\]\)\}/);+ assert.match(sidebar, /disabled: Boolean\(runningSessions\[session\.id\]\)/);// A drag inside the same project group must not offer itself as a target.assert.match(sidebar,diff --git a/apps/desktop/test/session-reference-ui.test.mjs b/apps/desktop/test/session-reference-ui.test.mjsindex 7100d7974..3188dd6cd 100644--- a/apps/desktop/test/session-reference-ui.test.mjs+++ b/apps/desktop/test/session-reference-ui.test.mjs@@ -304,14 +304,14 @@ test("a referenced conversation never reaches the file-attachment resolver", asytest("the conversation overflow menu copies the link for every reader", () => {const sidebar = read("../src/components/Sidebar.tsx");- assert.match(sidebar, /data-action="copy-session-link"/);+ assert.match(sidebar, /id: "copy-session-link"/);assert.match(sidebar, /t\("nav\.copySessionLink"\)/);assert.match(sidebar, /navigator\.clipboard\.writeText\(formatSessionLink\(session\.id\)\)/);assert.doesNotMatch(sidebar, /pi-desktop:\/\/session\//, "the scheme stays in shared");- const link = sidebar.indexOf('data-action="copy-session-link"');- const fork = sidebar.indexOf('data-action="fork-session"');- const developer = sidebar.indexOf('data-action="copy-conversation-id"');+ const link = sidebar.indexOf('id: "copy-session-link"');+ const fork = sidebar.indexOf('id: "fork-session"');+ const developer = sidebar.indexOf('id: "copy-conversation-id"');assert.ok(link > 0 && link > fork && link < developer,"an ordinary reader sees it; the developer-only actions stay behind their gate",diff --git a/apps/desktop/test/session-rename.test.mjs b/apps/desktop/test/session-rename.test.mjsindex 60e0d650a..4d4089d13 100644--- a/apps/desktop/test/session-rename.test.mjs+++ b/apps/desktop/test/session-rename.test.mjs@@ -29,7 +29,7 @@ const []);test("session rename is available from sidebar and project archive task rows", () => {- assert.match(sidebarSource, /data-action="rename-session"/);+ assert.match(sidebarSource, /id: "rename-session"/);assert.match(sidebarSource, /setRenameFor\(session\)/);assert.match(projectsDetailSource, /projects-detail-task-rename/);assert.match(projectsDetailSource, /onRenameSession\(session\)/);diff --git a/apps/desktop/test/session-scratch-path.test.mjs b/apps/desktop/test/session-scratch-path.test.mjsindex ff2c2472d..774c6db61 100644--- a/apps/desktop/test/session-scratch-path.test.mjs+++ b/apps/desktop/test/session-scratch-path.test.mjs@@ -45,17 +45,17 @@ test("main opens only a resolved session scratch directory", () => {});test("developer-mode conversation overflow copies the id then opens scratch", () => {- assert.match(sidebarSource, /data-action="copy-conversation-id"/);+ assert.match(sidebarSource, /id: "copy-conversation-id"/);assert.match(sidebarSource, /navigator\.clipboard\.writeText\(session\.id\)/);- assert.match(sidebarSource, /data-action="open-session-path"/);+ assert.match(sidebarSource, /id: "open-session-path"/);assert.match(sidebarSource, /api\.openSessionScratchPath\(session\.id\)/);- assert.doesNotMatch(sidebarSource, /data-action="copy-session-path"/);- assert.doesNotMatch(sidebarSource, /data-action="open-session-folder"/);+ assert.doesNotMatch(sidebarSource, /id: "copy-session-path"/);+ assert.doesNotMatch(sidebarSource, /id: "open-session-folder"/);assert.doesNotMatch(sidebarSource, /copySessionPath/);- const copyIndex = sidebarSource.indexOf('data-action="copy-conversation-id"');- const openIndex = sidebarSource.indexOf('data-action="open-session-path"');- const deleteIndex = sidebarSource.indexOf('data-action="delete-session"');+ const copyIndex = sidebarSource.indexOf('id: "copy-conversation-id"');+ const openIndex = sidebarSource.indexOf('id: "open-session-path"');+ const deleteIndex = sidebarSource.indexOf('id: "delete-session"');assert.ok(copyIndex > 0 && openIndex > copyIndex && deleteIndex > openIndex);const developerBlock = sidebarSource.slice(diff --git a/apps/desktop/test/sidebar-menu-panel.test.mjs b/apps/desktop/test/sidebar-menu-panel.test.mjsnew file mode 100644index 000000000..fbac58bf6--- /dev/null+++ b/apps/desktop/test/sidebar-menu-panel.test.mjs@@ -0,0 +1,61 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";++const panelSource = await readFile(+ new URL("../src/components/SidebarMenuPanel.tsx", import.meta.url),+ "utf8",+);++test("the panel renders every item kind with its own accessible role", () => {+ assert.match(panelSource, /role="menuitem"[\s\S]*?data-action=\{item\.id\}/);+ assert.match(panelSource, /role="menuitemradio"/);+ assert.match(panelSource, /role="menuitemcheckbox"/);+ assert.match(panelSource, /assert|aria-checked=\{item\.checked\}|aria-checked=\{option\.selected\}/);+ assert.match(panelSource, /className="sidebar-menu-separator"|role="separator"/);+ assert.match(panelSource, /className="sidebar-menu-section"/);+ assert.match(panelSource, /className="sidebar-menu-hint"/);+ assert.match(panelSource, /className="sidebar-menu-note"/);+ /* A caption is a label, not a row: it must never become a menuitem. */+ assert.doesNotMatch(panelSource, /<button[^>]*data-sidebar-menu-section/);+ assert.match(panelSource, /aria-label=\{content\.label\}/);+});++test("keyboard navigation walks the rows the menu can actually run", () => {+ assert.match(+ panelSource,+ /\[role="menuitem"\]:not\(:disabled\), \[role="menuitemradio"\]:not\(:disabled\), \[role="menuitemcheckbox"\]:not\(:disabled\)/,+ );+ assert.match(panelSource, /ArrowDown/);+ assert.match(panelSource, /ArrowUp/);+ assert.match(panelSource, /Home/);+ assert.match(panelSource, /End/);+ 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",+ );+});++/*+ The new menu vocabulary is product copy, so every shipped locale carries it;+ a missing key would silently fall back to English.+*/+test("every locale ships the sidebar menu keys", async () => {+ const { catalogs } = await import("@pi-desktop/i18n");+ for (const [locale, catalog] of Object.entries(catalogs)) {+ const nav = catalog.nav ?? {};+ assert.equal(typeof nav.dangerZone, "string", `${locale}: nav.dangerZone`);+ assert.equal(typeof nav.viewOptions, "string", `${locale}: nav.viewOptions`);+ assert.equal(typeof nav.batchSelectionHint, "string", `${locale}: nav.batchSelectionHint`);+ assert.equal(+ typeof catalog.worktree?.menu?.group,+ "string",+ `${locale}: worktree.menu.group`,+ );+ }+});diff --git a/apps/desktop/test/sidebar-navigation.test.mjs b/apps/desktop/test/sidebar-navigation.test.mjsindex 0bad450de..dc2e4ca8c 100644--- a/apps/desktop/test/sidebar-navigation.test.mjs+++ b/apps/desktop/test/sidebar-navigation.test.mjs@@ -166,11 +166,8 @@ test("sidebar section toolbars open create actions from context menus", () => {assert.match(sidebarSource, /data-sidebar-section=\"projects\"/);assert.match(sidebarSource, /openSectionMenu\(\"sessions\"/);assert.match(sidebarSource, /openSectionMenu\(\"projects\"/);- assert.match(sidebarSource, /data-sidebar-section-menu=\{sectionMenu\}/);- assert.match(- sidebarSource,- /className=\"sidebar-row-menu sidebar-floating-menu sidebar-section-menu\"/,- );+ assert.match(sidebarSource, /className="sidebar-section-menu"/);+ assert.doesNotMatch(sidebarSource, /data-sidebar-section-menu=\{sectionMenu\}/);assert.match(sidebarSource, /e\.button === 2/);assert.match(sidebarSource, /addEventListener\("pointerdown"/);});@@ -182,8 +179,8 @@ test("sidebar floating menus stay anchored to triggers and pointer positions", (const pointPlacement = sidebarSource.match(/const placeMenuAtPoint = useCallback\([\s\S]*?\n }, \[\]\);/,)?.[0] ?? "";-- assert.match(triggerPlacement, /const anchor = \{ top: rect\.top, bottom: rect\.bottom \}/);+ assert.match(sidebarSource, /return portalToBody\(/);+ assert.match(sidebarSource, /<SidebarMenuPanel/);assert.match(triggerPlacement, /placeSidebarFloatingMenuTop\(/);assert.match(triggerPlacement, /left:\s*Math\.max\(/);assert.match(triggerPlacement, /rect\.right \+ 4/);@@ -191,13 +188,60 @@ test("sidebar floating menus stay anchored to triggers and pointer positions", (assert.match(pointPlacement, /placeSidebarFloatingMenuTop\(/);assert.match(pointPlacement, /x \+ 4/);assert.match(sidebarSource, /placeMenuAtPoint\(event\.clientX, event\.clientY\)/);- assert.match(sidebarSource, /menu\.getBoundingClientRect\(\)\.height/);+ /* One panel owns every menu, so exactly one surface is ref'd per open. */+ assert.equal((sidebarSource.match(/ref=\{floatingMenuRef\}/g) ?? []).length, 0);+ assert.equal((sidebarSource.match(/menuRef=\{floatingMenuRef\}/g) ?? []).length, 4);assert.match(sidebarSource, /new ResizeObserver\(reposition\)/);- assert.equal((sidebarSource.match(/ref=\{floatingMenuRef\}/g) ?? []).length, 3);- assert.match(sidebarSource, /left: menuPosition\.left/);- assert.doesNotMatch(sidebarSource, /right: menuPosition\.right/);+ assert.match(sidebarSource, /const position = \{ top: menuPosition\.top, left: menuPosition\.left \}/);+ assert.equal((sidebarSource.match(/position=\{position\}/g) ?? []).length, 4);});+/*+ 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.+*/+test("sidebar row menus group their rows and isolate the destructive one", () => {+ const sessionMenu = sidebarSource.match(+ /const sessionMenuContent = useCallback\([\s\S]*?\n \[\n[\s\S]*?\n \],\n \);/,+ )?.[0] ?? "";+ const projectMenu = sidebarSource.match(+ /const projectMenuContent = useCallback\([\s\S]*?\n \[\n[\s\S]*?\n \],\n \);/,+ )?.[0] ?? "";+ const sortMenu = sidebarSource.match(+ /const sortMenuContent = useMemo\([\s\S]*?\n \[displaySessionSort[\s\S]*?\n \);/,+ )?.[0] ?? "";++ assert.ok(sessionMenu, "session menu content must exist");+ 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/);++ /* The sort popover is two labelled groups instead of a title plus loose rows. */+ assert.match(sortMenu, /id: "sort"/);+ assert.match(sortMenu, /id: "view"/);+ assert.doesNotMatch(sidebarSource, /className="sidebar-popover-title"/);+ assert.doesNotMatch(sidebarSource, /className="sidebar-popover-divider"/);+});test("portaled sort menu does not stretch to the viewport edge", () => {const basePopoverRule = globalStyles.match(/\.sidebar-row-menu,\n\.sidebar-popover\s*\{[^}]*\}/s,@@ -245,7 +289,7 @@ test("sidebar action icons stay quiet until their toolbar or row is hovered", ()});test("project rows expose folder actions and full-path hover", () => {- assert.match(sidebarSource, /data-action="open-project-folder"/);+ assert.match(sidebarSource, /id: "open-project-folder"/);assert.match(sidebarSource, /api\.openProjectFolder\(entry\.path\)/);assert.doesNotMatch(sidebarSource, /data-action="edit-project-instructions"/);assert.doesNotMatch(sidebarSource, /<ProjectInstructionsDialog/);diff --git a/apps/desktop/test/two-step-delete.test.mjs b/apps/desktop/test/two-step-delete.test.mjsindex 2bc98bce8..6d034f25a 100644--- a/apps/desktop/test/two-step-delete.test.mjs+++ b/apps/desktop/test/two-step-delete.test.mjs@@ -98,19 +98,13 @@ test("only session rows use the shared two-step delete arm", () => {});test("the session menu deletes on the second click, not the first", () => {- assert.match(sidebarSource, /data-action="delete-session"/);- assert.match(sidebarSource, /onClick=\{\(\) => requestDeleteSession\(session\)\}/);+ assert.match(sidebarSource, /id: "delete-session"/);+ assert.match(sidebarSource, /onSelect: \(\) => requestDeleteSession\(session\),/);// The item shows which click it is on, for the pointer and for the tests.- assert.match(sidebarSource, /data-armed=\{armedDelete === session\.id \? "true" : undefined\}/);assert.match(sidebarSource,- /className=\{cx\("danger", armedDelete === session\.id && "is-armed"\)\}/,+ /label:[\s\S]*?armedDelete === session\.id[\s\S]*?t\("nav\.deleteTaskConfirm", \{ defaultValue: "Delete\?" \}\)[\s\S]*?t\("nav\.deleteTask", \{ defaultValue: "Delete" \}\)/,);- assert.match(- sidebarSource,- /\{armedDelete === session\.id\s*\?\s*t\("nav\.deleteTaskConfirm", \{ defaultValue: "Delete\?" \}\)\s*:\s*t\("nav\.deleteTask", \{ defaultValue: "Delete" \}\)\}/,- );- // Session ids are the armed keys of the sidebar's session items.const request = handlerBlock(sidebarSource, "requestDeleteSession");assert.match(request, /if \(armedDelete !== session\.id\) \{/);diff --git a/apps/desktop/test/worktree-menu-user-path.test.mjs b/apps/desktop/test/worktree-menu-user-path.test.mjsindex c58290d1e..c15c8ccff 100644--- a/apps/desktop/test/worktree-menu-user-path.test.mjs+++ b/apps/desktop/test/worktree-menu-user-path.test.mjs@@ -20,7 +20,7 @@ import i18n from "i18next";import { initReactI18next } from "react-i18next";import { catalogs, flattenCatalog } from "@pi-desktop/i18n";import { IPC } from "@pi-desktop/shared";-import { WorktreeBadge, WorktreeProjectMenuItems, WorktreeSessionMenuItems } from "../../apps/desktop/src/features/worktree/WorktreeSidebarParts";+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";import { useAppStore } from "../../apps/desktop/src/stores/app-store";@@ -70,12 +70,48 @@ async function settle() { await frame(); await frame(); }function check(condition, message) { if (!condition) throw new Error(message); }const item = () => document.querySelector('[data-action="new-isolated-session"]');const reason = () => document.querySelector("[data-worktree-unavailable]");+/*+ The sidebar's rows are menu data now, so these fixtures render the item list+ the way the sidebar menu panel does: one button per row, the availability+ reason attached to the disabled row it explains.+*/+const ProjectItems = ({ projectPath, projectName, onDone }) => {+ const items = useWorktreeProjectMenuItems({ projectPath, projectName, onDone });+ return React.createElement(React.Fragment, null, items.map((entry) =>+ React.createElement(React.Fragment, { key: entry.id },+ React.createElement("button", { type: "button", role: "menuitem",+ "data-action": entry.id, disabled: entry.disabled,+ "aria-busy": entry.busy || undefined,+ "aria-describedby": entry.describedBy, title: entry.title,+ onClick: entry.onSelect },+ entry.icon,+ React.createElement("span", { className: "sidebar-menu-label" }, entry.label)),+ entry.disabled && entry.describedBy+ ? React.createElement("p", { id: entry.describedBy, "data-worktree-unavailable": "" }, entry.title)+ : null)));+};+const SessionItems = ({ sessionId, title, running, worktree, onDone }) => {+ const items = useWorktreeSessionMenuItems({ sessionId, title, running, worktree, onDone });+ return React.createElement(React.Fragment, null, items.map((entry) =>+ React.createElement("button", { key: entry.id, type: "button", role: "menuitem",+ "data-action": entry.id, disabled: entry.disabled,+ "aria-busy": entry.busy || undefined, title: entry.title,+ onClick: entry.onSelect },+ entry.icon,+ React.createElement("span", { className: "sidebar-menu-label" }, entry.label))));+};const rootNode = createRoot(document.getElementById("root"));function show(projectPath) {- flushSync(() => rootNode.render(React.createElement(WorktreeProjectMenuItems,+ flushSync(() => rootNode.render(React.createElement(ProjectItems,{ projectPath, projectName: "P", onDone() {} })));}-async function answer() { while (pending.length) pending.shift()(); await settle(); }+async function answer() {+ while (pending.length) pending.shift()();+ await settle();+ // The row's own action probes again; drain whatever that queued.+ while (pending.length) pending.shift()();+ await settle();+}window.menuProbe = async () => {show("/plain");check(item().disabled, "item must be disabled while the probe runs");@@ -97,7 +133,7 @@ window.menuProbe = async () => {check(!item().disabled && !reason(), "a git project must enable the item");const setupCommandItem = document.querySelector('[data-action="worktree-setup-command"]');check(- setupCommandItem?.querySelector(".worktree-menu-label")?.textContent === i18n.t("worktree.setupCommand.menu"),+ setupCommandItem?.querySelector(".sidebar-menu-label")?.textContent === i18n.t("worktree.setupCommand.menu"),"setup command label must use the shrinkable text container",);check(setupCommandItem?.getAttribute("title") === i18n.t("worktree.setupCommand.menu"), "full label must remain available on hover");@@ -142,7 +178,7 @@ window.menuProbe = async () => {// "Sync from project" shows how far behind the session is and syncs it.const menuRoot = createRoot(document.getElementById("root"));const sessionMenu = (sessionId) => flushSync(() => menuRoot.render(React.createElement(React.StrictMode, null,- React.createElement(WorktreeSessionMenuItems, { sessionId, title: "Task", running: false, onDone() {},+ React.createElement(SessionItems, { sessionId, title: "Task", running: false, onDone() {},worktree: { branch: "pi-desktop/" + sessionId, status: "active", setupStatus: "none" } }))));const syncItem = () => document.querySelector('[data-action="worktree-sync"]');sessionMenu("current");diff --git a/apps/desktop/test/worktree-ui.test.mjs b/apps/desktop/test/worktree-ui.test.mjsindex 4670b3f69..5e39de41e 100644--- a/apps/desktop/test/worktree-ui.test.mjs+++ b/apps/desktop/test/worktree-ui.test.mjs@@ -1,7 +1,7 @@import assert from "node:assert/strict";import test, { after, before } from "node:test";import { fileURLToPath } from "node:url";-import { createElement } from "react";+import { createElement, Fragment } from "react";import { renderToStaticMarkup } from "react-dom/server";import i18n from "i18next";import { I18nextProvider } from "react-i18next";@@ -15,6 +15,31 @@ import { createServer } from "vite";let server;let modules;const en = catalogs.en.worktree;++/*+ The worktree rows are menu data now, rendered by the sidebar's own panel.+ This mirror keeps the assertions about those rows in one place.+*/+const renderItems = (items) =>+ items.map((item) =>+ createElement("button", {+ key: item.id,+ type: "button",+ role: "menuitem",+ "data-action": item.id,+ disabled: item.disabled === true,+ "aria-busy": item.busy ? true : undefined,+ title: item.title,+ onClick: item.onSelect,+ }, item.icon, createElement("span", { className: "sidebar-menu-label" }, item.label)));++const SessionItems = (props) =>+ createElement(Fragment, null, renderItems(modules.parts.useWorktreeSessionMenuItems(props)));+const ProjectItems = (props) =>+ createElement(Fragment, null, renderItems(modules.parts.useWorktreeProjectMenuItems(props)));+const DeleteLoss = ({ sessionId }) =>+ createElement(Fragment, null, modules.parts.useWorktreeDeleteLossText(sessionId));+const previousDocument = globalThis.document;const previousWindow = globalThis.window;@@ -122,12 +147,11 @@ test("the sidebar badges isolated sessions and leaves ordinary ones unchanged",});test("only isolated sessions get worktree menu items, disabled while running or missing", () => {- const { WorktreeSessionMenuItems, WorktreeProjectMenuItems } = modules.parts;const props = { sessionId: "s1", title: "Task", running: false, onDone() {} };- assert.equal(wrap(createElement(WorktreeSessionMenuItems, props)), "");+ assert.equal(wrap(createElement(SessionItems, props)), "");const idle = wrap(- createElement(WorktreeSessionMenuItems, {+ createElement(SessionItems, {...props,worktree: { branch: "pi-desktop/s1", status: "active", setupStatus: "failed" },}),@@ -141,7 +165,7 @@ test("only isolated sessions get worktree menu items, disabled while running orassert.ok(idle.includes(en.sync.menu));const running = wrap(- createElement(WorktreeSessionMenuItems, {+ createElement(SessionItems, {...props,running: true,worktree: { branch: "pi-desktop/s1", status: "active", setupStatus: "none" },@@ -151,7 +175,7 @@ test("only isolated sessions get worktree menu items, disabled while running orassert.doesNotMatch(running, /worktree-setup-log/);const missing = wrap(- createElement(WorktreeSessionMenuItems, {+ createElement(SessionItems, {...props,worktree: { branch: "pi-desktop/s1", status: "missing" },}),@@ -160,7 +184,7 @@ test("only isolated sessions get worktree menu items, disabled while running orassert.match(missing, /data-action="worktree-reveal"[^>]*disabled/);const project = wrap(- createElement(WorktreeProjectMenuItems, { projectPath: "/p", projectName: "P", onDone() {} }),+ createElement(ProjectItems, { projectPath: "/p", projectName: "P", onDone() {} }),);assert.ok(project.includes(en.newIsolatedSession));assert.ok(project.includes(en.setupCommand.menu));@@ -254,9 +278,8 @@ test("merge failures keep conflicts in the session and re-preview a changed sess});test("the delete loss note stays empty until unmerged work is known", () => {- const { WorktreeDeleteLossNote } = modules.parts;// Before the pending-work answer arrives only the ordinary armed label shows.- assert.equal(wrap(createElement(WorktreeDeleteLossNote, { sessionId: "s1" })), "");+ assert.equal(wrap(createElement(DeleteLoss, { sessionId: "s1" })), "");assert.ok(en.deleteLoss.length > 0);});@@ -329,7 +352,7 @@ test("the behind marker shows only for sessions that lack project commits", () =});test("a conflicted session hides the behind marker and cannot sync until it resolves", () => {- const { WorktreeBadge, WorktreeSessionMenuItems } = modules.parts;+ const { WorktreeBadge } = modules.parts;const { useWorktreeUi } = modules.worktreeUi;Object.assign(useWorktreeUi.getInitialState(), { behind: { s1: 3 } });const conflicted = { branch: "pi-desktop/s1", status: "conflict", setupStatus: "none" };@@ -339,7 +362,7 @@ test("a conflicted session hides the behind marker and cannot sync until it resoassert.doesNotMatch(badge, /data-worktree-behind/);const menu = wrap(- createElement(WorktreeSessionMenuItems, {+ createElement(SessionItems, {sessionId: "s1",title: "Task",running: false,diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex bf51b92a8..ba1ca229a 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -2,6 +2,7 @@ import { en, type EnglishCatalog } from "../en/index.js";export const de = {"worktree": {+ "menu": { "group": "Git" },"newIsolatedSession": "Neue isolierte Sitzung","uncommittedNotIncluded": "Nicht committete Änderungen im Projekt werden nicht in die isolierte Sitzung übernommen.","reveal": "Worktree-Ordner anzeigen",@@ -278,7 +279,10 @@ export const de = {"hoverCardSpace": "Arbeitsbereich","hoverCardUpdatedAt": "Aktualisiert {{when}}","hoverCardTemporarySpace": "Temporär",- "hoverCardBranchAria": "Zweig {{name}}"+ "hoverCardBranchAria": "Zweig {{name}}",+ "dangerZone": "Gefahrenbereich",+ "batchSelectionHint": "{{count}} Sitzungen ausgewählt",+ "viewOptions": "Ansicht",},"sessionCollaboration": {"statusIdle": "Inaktiv",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex d6cf547cb..5ac6a6362 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -1,5 +1,6 @@export const en = {worktree: {+ menu: { group: "Git" },newIsolatedSession: "New isolated session",uncommittedNotIncluded: "Uncommitted changes in the project are not included in the isolated session.",reveal: "Show worktree folder",@@ -286,6 +287,9 @@ export const en = {hoverCardUpdatedAt: "Updated {{when}}",hoverCardTemporarySpace: "Temporary",hoverCardBranchAria: "Branch {{name}}",+ dangerZone: "Danger zone",+ batchSelectionHint: "{{count}} sessions selected",+ viewOptions: "View",},sessionCollaboration: {statusIdle: "Idle",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 3b434a2a8..537806011 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -2,6 +2,7 @@ import { en, type EnglishCatalog } from "../en/index.js";export const es = {"worktree": {+ "menu": { "group": "Git" },"newIsolatedSession": "Nueva sesión aislada","uncommittedNotIncluded": "Los cambios sin confirmar del proyecto no se incluyen en la sesión aislada.","reveal": "Mostrar carpeta del worktree",@@ -278,7 +279,10 @@ export const es = {"hoverCardSpace": "Espacio de trabajo","hoverCardUpdatedAt": "Actualizado {{when}}","hoverCardTemporarySpace": "Temporal",- "hoverCardBranchAria": "Rama {{name}}"+ "hoverCardBranchAria": "Rama {{name}}",+ "dangerZone": "Zona de riesgo",+ "batchSelectionHint": "{{count}} sesiones seleccionadas",+ "viewOptions": "Vista",},"sessionCollaboration": {"statusIdle": "Inactivo",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 8cad1aa64..f6979aacf 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -2,6 +2,7 @@ import { en, type EnglishCatalog } from "../en/index.js";export const fr = {"worktree": {+ "menu": { "group": "Git" },"newIsolatedSession": "Nouvelle session isolée","uncommittedNotIncluded": "Les modifications non validées du projet ne sont pas incluses dans la session isolée.","reveal": "Afficher le dossier du worktree",@@ -278,7 +279,10 @@ export const fr = {"hoverCardSpace": "Espace de travail","hoverCardUpdatedAt": "{{when}} mis à jour","hoverCardTemporarySpace": "Temporaire",- "hoverCardBranchAria": "Branche {{name}}"+ "hoverCardBranchAria": "Branche {{name}}",+ "dangerZone": "Zone sensible",+ "batchSelectionHint": "{{count}} sessions sélectionnées",+ "viewOptions": "Affichage",},"sessionCollaboration": {"statusIdle": "Inactif",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 68559465d..b34385e9f 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -2,6 +2,7 @@ import { en, type EnglishCatalog } from "../en/index.js";export const ko = {worktree: {+ menu: { group: "Git" },newIsolatedSession: "새 격리 세션",uncommittedNotIncluded: "프로젝트의 커밋되지 않은 변경 사항은 격리 세션에 포함되지 않습니다.",reveal: "worktree 폴더 보기",@@ -288,6 +289,9 @@ export const ko = {hoverCardUpdatedAt: "{{when}} 업데이트됨",hoverCardTemporarySpace: "임시",hoverCardBranchAria: "브랜치 {{name}}",+ dangerZone: "위험 구역",+ batchSelectionHint: "{{count}}개 세션 선택됨",+ viewOptions: "보기",},sessionCollaboration: {statusIdle: "대기",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 58491bc13..5ce8e240d 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -2,6 +2,7 @@ import { en, type EnglishCatalog } from "../en/index.js";export const ptBR = {worktree: {+ menu: { group: "Git" },newIsolatedSession: "Nova sessão isolada",uncommittedNotIncluded: "Alterações não confirmadas do projeto não são incluídas na sessão isolada.",reveal: "Mostrar pasta do worktree",@@ -277,7 +278,10 @@ export const ptBR = {hoverCardSpace: "Espaço de trabalho",hoverCardUpdatedAt: "Atualizado {{when}}",hoverCardTemporarySpace: "Temporário",- hoverCardBranchAria: "Ramificação {{name}}"+ hoverCardBranchAria: "Ramificação {{name}}",+ dangerZone: "Zona de risco",+ batchSelectionHint: "{{count}} sessões selecionadas",+ viewOptions: "Visualização",},sessionCollaboration: {statusIdle: "Ocioso",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 63a08e057..abc665e24 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -2,6 +2,7 @@ import { en, type EnglishCatalog } from "../en/index.js";export const tr = {worktree: {+ menu: { group: "Git" },newIsolatedSession: "Yeni yalıtılmış oturum",uncommittedNotIncluded: "Projedeki commit edilmemiş değişiklikler yalıtılmış oturuma dahil edilmez.",reveal: "Worktree klasörünü göster",@@ -288,6 +289,9 @@ export const tr = {hoverCardUpdatedAt: "Güncellendi {{when}}",hoverCardTemporarySpace: "Geçici",hoverCardBranchAria: "Dal {{name}}",+ dangerZone: "Tehlikeli bölge",+ batchSelectionHint: "{{count}} oturum seçildi",+ viewOptions: "Görünüm",},sessionCollaboration: {statusIdle: "Boşta",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 11df7b16f..f59f45403 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -2,6 +2,7 @@ import { en, type EnglishCatalog } from "../en/index.js";export const zhCN = {worktree: {+ menu: { group: "Git" },newIsolatedSession: "新建隔离会话",uncommittedNotIncluded: "项目中未提交的改动不会带入隔离会话。",reveal: "显示 worktree 文件夹",@@ -281,6 +282,9 @@ export const zhCN = {hoverCardUpdatedAt: "更新于 {{when}}",hoverCardTemporarySpace: "临时对话",hoverCardBranchAria: "分支 {{name}}",+ dangerZone: "危险操作",+ batchSelectionHint: "已选择 {{count}} 个会话",+ viewOptions: "显示",},sessionCollaboration: {statusIdle: "空闲",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 27467e44b..04cb1dbb7 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -2,6 +2,7 @@ import { en, type EnglishCatalog } from "../en/index.js";export const zhTW = {worktree: {+ menu: { group: "Git" },newIsolatedSession: "新增隔離工作階段",uncommittedNotIncluded: "專案中未提交的變更不會帶入隔離工作階段。",reveal: "顯示 worktree 資料夾",@@ -281,6 +282,9 @@ export const zhTW = {hoverCardUpdatedAt: "更新於 {{when}}",hoverCardTemporarySpace: "臨時對話",hoverCardBranchAria: "分支 {{name}}",+ dangerZone: "危險操作",+ batchSelectionHint: "已選取 {{count}} 個工作階段",+ viewOptions: "顯示",},sessionCollaboration: {statusIdle: "閒置",