Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): worktree switcher submenu, live refresh, count (#2473)
Andrew Mikofalvy03dd0ca2e0e0
diff --git a/.changeset/worktree-list-live-refresh.md b/.changeset/worktree-list-live-refresh.mdnew file mode 100644index 000000000..b07b034ff--- /dev/null+++ b/.changeset/worktree-list-live-refresh.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Fixed the project switcher's worktree list not refreshing until an app restart. A worktree created outside the current window — a `git worktree add` in a terminal, or a create in another OpenKnowledge window — now appears when the window regains focus, instead of staying hidden until you quit and reopen. The cached worktree model now revalidates on window focus / tab-visible, the same signal the file list and graph already use to recover from stale data.diff --git a/packages/app/src/components/ProjectSwitcher.dom.test.tsx b/packages/app/src/components/ProjectSwitcher.dom.test.tsxindex 94cf9026c..a0af8f40c 100644--- a/packages/app/src/components/ProjectSwitcher.dom.test.tsx+++ b/packages/app/src/components/ProjectSwitcher.dom.test.tsx@@ -1,6 +1,6 @@import { beforeEach, describe, expect, mock, test } from 'bun:test';import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';-import type { ReactNode } from 'react';+import { createContext, type ReactNode, use } from 'react';import { ProjectSwitcher } from './ProjectSwitcher';type MenuProps = {@@ -19,6 +19,14 @@ let lastDropdownOpenChange: ((open: boolean) => void) | null = null;let keydownBubbleCount = 0;let createDialogProps: Array<{ open: boolean; bridge: unknown }> = [];+// The worktree flyout in RecentProjectsMenu (rendered live here) is a real+// DropdownMenuSub; model it via a shared { open, onOpenChange } context so the+// flyout opens on trigger click/hover and closes on onOpenChange(false) — enough+// to exercise ProjectSwitcher's hoisted flyout state + close-on-scroll wiring.+const SubStateContext = createContext<{ open: boolean; onOpenChange: (o: boolean) => void }>({+ open: false,+ onOpenChange: () => {},+});mock.module('@/components/ui/dropdown-menu', () => ({DropdownMenu: ({ children, onOpenChange }: MenuProps) => {lastDropdownOpenChange = onOpenChange ?? null;@@ -37,6 +45,50 @@ mock.module('@/components/ui/dropdown-menu', () => ({DropdownMenuLabel: ({ children, ...props }: ItemProps) => <div {...props}>{children}</div>,DropdownMenuSeparator: () => <hr />,DropdownMenuTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,+ DropdownMenuSub: ({ children, open, onOpenChange }: MenuProps) => (+ <SubStateContext value={{ open: !!open, onOpenChange: onOpenChange ?? (() => {}) }}>+ {children}+ </SubStateContext>+ ),+ DropdownMenuSubTrigger: ({+ children,+ onClick,+ onKeyDown,+ ...props+ }: ItemProps & {+ onClick?: (e: React.MouseEvent) => void;+ onKeyDown?: (e: React.KeyboardEvent) => void;+ }) => {+ const { onOpenChange } = use(SubStateContext);+ // Model Radix composition: our handler runs first; the sub opens only if we+ // did not preventDefault. The row's onClick / Enter+Space preventDefault to+ // navigate to the project, so hover (and ArrowRight) is what opens the flyout.+ return (+ <div+ role="menuitem"+ tabIndex={-1}+ onMouseEnter={() => onOpenChange(true)}+ onClick={(e) => {+ onClick?.(e);+ if (!e.defaultPrevented) onOpenChange(true);+ }}+ onKeyDown={(e) => {+ onKeyDown?.(e);+ if (e.defaultPrevented) return;+ if (e.key === 'ArrowRight' || e.key === 'Enter' || e.key === ' ') onOpenChange(true);+ else if (e.key === 'ArrowLeft' || e.key === 'Escape') onOpenChange(false);+ }}+ {...props}+ >+ {children}+ </div>+ );+ },+ DropdownMenuSubContent: ({ children, sideOffset: _sideOffset, ...props }: ItemProps) => {+ const { open } = use(SubStateContext);+ if (!open) return null;+ return <div {...props}>{children}</div>;+ },}));mock.module('@/components/ui/input-group', () => ({@@ -361,7 +413,7 @@ describe('ProjectSwitcher dropdown behavior', () => {await openMenu();// Open the current project's worktree flyout, type a non-matching name.- fireEvent.click(screen.getByTestId('project-switcher-toggle-/projects/current'));+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/projects/current'));const searchBox = (await screen.findByTestId('project-switcher-flyout-search-/projects/current',)) as HTMLInputElement;@@ -380,6 +432,45 @@ describe('ProjectSwitcher dropdown behavior', () => {expect(newWorktreeProps.at(-1)?.initialBranchName).toBe('shiny-feature');});+ test('scrolling the recents list closes an open worktree flyout (submenu does not follow the row off-screen)', async () => {+ // Same git-enriched current project with a worktree so its submenu renders.+ const bridge = createBridge();+ bridge.project.listRecent = mock(() =>+ Promise.resolve([+ {+ name: 'current',+ path: '/projects/current',+ gitCommonDir: '/projects/current/.git',+ mainRoot: '/projects/current',+ isLinkedWorktree: false,+ branch: 'main',+ lastOpenedAt: '2026-07-01',+ },+ {+ name: 'has-worktree',+ path: '/projects/current/.ok/worktrees/has-worktree',+ gitCommonDir: '/projects/current/.git',+ mainRoot: '/projects/current',+ isLinkedWorktree: true,+ branch: 'has-worktree',+ lastOpenedAt: '2026-07-01',+ },+ ]),+ );+ render(<ProjectSwitcher bridge={bridge as never} />);+ await openMenu();++ // Open the flyout, then scroll the recents viewport — the flyout closes so+ // it can't trail its trigger row off-screen (Radix anchors it to the row).+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/projects/current'));+ await screen.findByTestId('project-switcher-flyout-/projects/current');++ fireEvent.scroll(screen.getByTestId('project-switcher-scroll'));+ await waitFor(() => {+ expect(screen.queryByTestId('project-switcher-flyout-/projects/current')).toBeNull();+ });+ });+test('threads branches and the already-has-a-worktree set from the cached model to the dialog', async () => {const bridge = createBridge();render(<ProjectSwitcher bridge={bridge as never} />);diff --git a/packages/app/src/components/ProjectSwitcher.tsx b/packages/app/src/components/ProjectSwitcher.tsxindex 7e3322963..6425f85df 100644--- a/packages/app/src/components/ProjectSwitcher.tsx+++ b/packages/app/src/components/ProjectSwitcher.tsx@@ -322,11 +322,19 @@ export function ProjectSwitcher({ bridge }: ProjectSwitcherProps) {</InputGroup><DropdownMenuSeparator />{/* Only the items list scrolls — the search field above and the- New / Switch / Open actions below stay pinned. Each group row's- worktree Popover flyout portals out of this wrapper, so the- scroll clip doesn't cut it off. overscroll-contain stops scroll- chaining to the page behind the dropdown at the list edges. */}- <div className="max-h-64 overflow-x-hidden overflow-y-auto overscroll-contain subtle-scrollbar scroll-fade-mask">+ New / Switch / Open actions below stay pinned. overscroll-contain+ stops scroll chaining to the page behind the dropdown at the list+ edges. Radix anchors each group's worktree submenu to its trigger+ row; if the row scrolls out of this viewport the submenu would+ follow it off into empty space, so close the open flyout on+ scroll — it re-opens anchored correctly on the next hover. */}+ <div+ className="max-h-64 overflow-x-hidden overflow-y-auto overscroll-contain subtle-scrollbar scroll-fade-mask"+ data-testid="project-switcher-scroll"+ onScroll={() => {+ if (flyoutPath !== null) setFlyoutPath(null);+ }}+ ><RecentProjectsMenubridge={bridge}recents={menuRecents}diff --git a/packages/app/src/components/RecentProjectsMenu.dom.test.tsx b/packages/app/src/components/RecentProjectsMenu.dom.test.tsxindex ca953c94c..1b7ede0c9 100644--- a/packages/app/src/components/RecentProjectsMenu.dom.test.tsx+++ b/packages/app/src/components/RecentProjectsMenu.dom.test.tsx@@ -1,16 +1,7 @@import { beforeEach, describe, expect, mock, test } from 'bun:test';import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core';import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';-import {- cloneElement,- createContext,- isValidElement,- type ReactElement,- type ReactNode,- use,- useEffect,- useState,-} from 'react';+import { createContext, type ReactNode, use, useState } from 'react';import type { RecentProjectEntry } from '@/lib/desktop-bridge-types';import { RecentProjectsMenu } from './RecentProjectsMenu';@@ -22,9 +13,21 @@ type ItemProps = {};// DropdownMenuItem is a div (role=menuitem), matching reality — the real one is-// not a <button>, so the nested toggle Button composes cleanly. onSelect fires on-// click; a nested Button that stopPropagations its click keeps onSelect from-// firing (the two-target behavior).+// not a <button>. onSelect fires on click; onKeyDown (from props) drives the+// flyout list's manual roving focus.+//+// The worktree flyout is a real DropdownMenuSub, modeled here through a shared+// { open, onOpenChange } context: SubTrigger opens on click / mouseenter /+// ArrowRight and closes on ArrowLeft / Escape / mouseleave; SubContent renders+// only while open and closes on mouseleave. Radix's safe-triangle + close-on-+// leave-both geometry can't run in jsdom, so the mock models the onOpenChange+// contract the component wires to (asserting the flyout closes when Radix+// reports hover-out). Focus-into-search on open is the component's own effect,+// not simulated here.+const SubStateContext = createContext<{ open: boolean; onOpenChange: (o: boolean) => void }>({+ open: false,+ onOpenChange: () => {},+});mock.module('@/components/ui/dropdown-menu', () => ({DropdownMenuItem: ({ children, onSelect, ...props }: ItemProps) => (<div@@ -38,44 +41,7 @@ mock.module('@/components/ui/dropdown-menu', () => ({</div>),DropdownMenuLabel: ({ children, ...props }: ItemProps) => <div {...props}>{children}</div>,-}));-mock.module('@/components/ui/button', () => ({- Button: ({- children,- onClick,- onMouseDown,- ...props- }: ItemProps & {- onClick?: (e: unknown) => void;- onMouseDown?: (e: unknown) => void;- }) => (- <button- type="button"- onClick={(e) => onClick?.(e)}- onMouseDown={(e) => onMouseDown?.(e)}- {...props}- >- {children}- </button>- ),-}));--// Popover: controlled by `open` (driven by the hoisted flyoutPath). Content-// renders only when open, matching Radix (PopoverContent is absent from the DOM-// while closed). The real Radix Popover portals + gates open on pointerdown-// (which the Electron renderer lacks — the reason for choosing Popover over-// DropdownMenuSub), neither of which jsdom drives, so the mock flattens it to a-// context-carried { open, onOpenChange }. PopoverTrigger clones its asChild-// child (the expander Button) to add an onClick that calls onOpenChange(!open)-// — exactly what Radix's asChild Trigger does — so the click lands on the real-// interactive Button and the Button's own onClick stopPropagation keeps the-// row's onSelect from firing. That models the two-target row exactly.-const PopoverStateContext = createContext<{ open: boolean; onOpenChange: (o: boolean) => void }>({- open: false,- onOpenChange: () => {},-});-mock.module('@/components/ui/popover', () => ({- Popover: ({+ DropdownMenuSub: ({children,open,onOpenChange,@@ -84,42 +50,60 @@ mock.module('@/components/ui/popover', () => ({open?: boolean;onOpenChange?: (o: boolean) => void;}) => (- <PopoverStateContext value={{ open: !!open, onOpenChange: onOpenChange ?? (() => {}) }}>+ <SubStateContext value={{ open: !!open, onOpenChange: onOpenChange ?? (() => {}) }}>{children}- </PopoverStateContext>+ </SubStateContext>),- PopoverTrigger: ({ children }: { children?: ReactNode }) => {- const { open, onOpenChange } = use(PopoverStateContext);- if (!isValidElement(children)) return <>{children}</>;- const child = children as ReactElement<{ onClick?: (e: unknown) => void }>;- return cloneElement(child, {- onClick: (e: unknown) => {- child.props.onClick?.(e);- onOpenChange(!open);- },- });+ DropdownMenuSubTrigger: ({+ children,+ onClick,+ onKeyDown,+ ...props+ }: ItemProps & {+ onClick?: (e: React.MouseEvent) => void;+ onKeyDown?: (e: React.KeyboardEvent) => void;+ }) => {+ const { onOpenChange } = use(SubStateContext);+ // Model Radix's SubTrigger composition: our handler runs first, and Radix+ // opens the sub only if we did NOT preventDefault. The component's onClick /+ // Enter+Space preventDefault (they navigate to the project instead), so those+ // do NOT open the flyout; hover and ArrowRight still do.+ return (+ <div+ role="menuitem"+ tabIndex={-1}+ onMouseEnter={() => onOpenChange(true)}+ onMouseLeave={() => onOpenChange(false)}+ onClick={(e) => {+ onClick?.(e);+ if (!e.defaultPrevented) onOpenChange(true);+ }}+ onKeyDown={(e) => {+ onKeyDown?.(e);+ if (e.defaultPrevented) return;+ if (e.key === 'ArrowRight' || e.key === 'Enter' || e.key === ' ') onOpenChange(true);+ else if (e.key === 'ArrowLeft' || e.key === 'Escape') onOpenChange(false);+ }}+ {...props}+ >+ {children}+ </div>+ );},- PopoverContent: ({+ DropdownMenuSubContent: ({children,- // Strip Radix-only positioning/dismiss props so React doesn't warn about- // unknown DOM attributes on the plain div the mock renders.- side: _side,- align: _align,sideOffset: _sideOffset,- onPointerDownOutside: _onPointerDownOutside,- onFocusOutside: _onFocusOutside,- onOpenAutoFocus,...props- }: ItemProps & { onOpenAutoFocus?: (e: Event) => void }) => {- const { open } = use(PopoverStateContext);- // Radix fires onOpenAutoFocus when the content opens. Simulate it here (hook- // runs unconditionally, before the closed early-return) so the flyout's- // focus-into-search behavior is exercised in the mock.- useEffect(() => {- if (open) onOpenAutoFocus?.(new Event('focus'));- }, [open, onOpenAutoFocus]);+ }: ItemProps & { sideOffset?: number }) => {+ const { open, onOpenChange } = use(SubStateContext);if (!open) return null;- return <div {...props}>{children}</div>;+ // role="menu" mirrors the real DropdownMenuSubContent and satisfies the+ // static-interactive-element lint on the hover-out handler.+ return (+ <div role="menu" onMouseLeave={() => onOpenChange(false)} {...props}>+ {children}+ </div>+ );},}));@@ -265,7 +249,7 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {expect(row.querySelector('svg')).toBeNull();});- test('the expander opens the worktree flyout (does not open the project)', async () => {+ test('clicking a worktree-bearing row opens the PROJECT (root) directly, not the flyout', async () => {const { bridge } = renderMenu({recents: [main('/repo', '/repo/.git'),@@ -278,23 +262,28 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {expect(groupRow.textContent).toContain('/repo');expect(screen.queryByTestId('project-switcher-flyout-/repo')).toBeNull();- // The expander row carries the pluralized worktree count ("1 worktree" at- // one; "N worktrees" otherwise) plus a trailing chevron only — no leading- // GitBranch icon, since "worktrees" already says what the chip is.+ // The count chip carries the pluralized worktree count ("1 worktree" at one;+ // "N worktrees" otherwise) with no icon of its own — the disclosure chevron+ // is the DropdownMenuSubTrigger's built-in (not rendered by the mock).const toggle = screen.getByTestId('project-switcher-toggle-/repo');- expect(toggle.querySelectorAll('svg').length).toBe(1);+ expect(toggle.querySelectorAll('svg').length).toBe(0);expect(toggle.textContent).toContain('1 worktree');expect(toggle.textContent).not.toContain('1 worktrees');- // Clicking the expander opens the flyout — and does NOT open the project.- fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));+ // Two-target row: a direct CLICK opens the bare project (root) in one click,+ // and does NOT open the flyout (the click preventDefaults Radix's open).+ fireEvent.click(screen.getByTestId('project-switcher-group-/repo'));await waitFor(() => {- expect(screen.getByTestId('project-switcher-flyout-/repo')).not.toBeNull();+ expect(bridge.project.open).toHaveBeenCalledWith({+ path: '/repo',+ target: 'new-window',+ entryPoint: 'recents',+ });});- expect(bridge.project.open).not.toHaveBeenCalled();+ expect(screen.queryByTestId('project-switcher-flyout-/repo')).toBeNull();});- test('hovering the expander opens the flyout (hover-open, not click-only) without opening the project', async () => {+ test('hovering the submenu row opens the flyout (hover-open, not click-only) without opening the project', async () => {const { bridge } = renderMenu({recents: [main('/repo', '/repo/.git'),@@ -302,15 +291,36 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {],});expect(screen.queryByTestId('project-switcher-flyout-/repo')).toBeNull();- // Mouse-enter (which fires on the Electron renderer, unlike pointerdown)- // opens the flyout on hover.- fireEvent.mouseEnter(screen.getByTestId('project-switcher-toggle-/repo'));+ // DropdownMenuSub opens the submenu on hover of its trigger row (Radix+ // safe-triangle hover); the mock models that onOpenChange(true) wiring.+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));await waitFor(() => {expect(screen.getByTestId('project-switcher-flyout-/repo')).not.toBeNull();});expect(bridge.project.open).not.toHaveBeenCalled();});+ test('the flyout closes when the pointer leaves both the row and the flyout (close-on-hover-out)', async () => {+ renderMenu({+ recents: [+ main('/repo', '/repo/.git'),+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),+ ],+ });+ // Hover the row → flyout opens.+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));+ const flyout = await screen.findByTestId('project-switcher-flyout-/repo');+ // Leaving the flyout content (the pointer is now inside neither the trigger+ // nor the content) → Radix reports onOpenChange(false) and the flyout closes.+ // The safe-triangle / leave-BOTH geometry is Radix-native (verified live on+ // the Electron POC); the mock exercises the onOpenChange(false) wiring that+ // RecentProjectsMenu hooks up via the hoisted flyout state.+ fireEvent.mouseLeave(flyout);+ await waitFor(() => {+ expect(screen.queryByTestId('project-switcher-flyout-/repo')).toBeNull();+ });+ });+test('keyboard: ArrowRight on the group row opens its flyout; ArrowLeft and Escape close it (a11y C7)', async () => {const { bridge } = renderMenu({recents: [@@ -354,6 +364,33 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {});});+ test('keyboard: Enter (and Space) on the group row opens the PROJECT, not the flyout (two-target)', async () => {+ const { bridge } = renderMenu({+ recents: [+ main('/repo', '/repo/.git'),+ worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),+ ],+ });+ const row = screen.getByTestId('project-switcher-group-/repo');++ // Enter opens the bare project (the SUB_OPEN key is preventDefaulted so Radix+ // does not open the submenu instead) and leaves the flyout closed.+ fireEvent.keyDown(row, { key: 'Enter' });+ await waitFor(() => {+ expect(bridge.project.open).toHaveBeenCalledWith({+ path: '/repo',+ target: 'new-window',+ entryPoint: 'recents',+ });+ });+ expect(screen.queryByTestId('project-switcher-flyout-/repo')).toBeNull();++ // Space behaves identically.+ fireEvent.keyDown(row, { key: ' ' });+ await waitFor(() => expect(bridge.project.open).toHaveBeenCalledTimes(2));+ expect(screen.queryByTestId('project-switcher-flyout-/repo')).toBeNull();+ });+test('the flyout lists the default (main) first, then the opened worktree; opening one opens its window', async () => {const { bridge } = renderMenu({recents: [@@ -361,7 +398,7 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),],});- fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));// main (default, pinned) is entry /repo; the dev worktree follows.const mainEntry = await screen.findByTestId('project-switcher-flyout-entry-/repo');@@ -377,8 +414,9 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {expect(mainEntry.querySelector('svg')).toBeNull();expect(devEntry.querySelector('svg')).toBeNull();const flyoutSearch = screen.getByTestId('project-switcher-flyout-search-/repo');- // Search magnifier (leading) + branch icon (trailing) = two icons on the field.- expect(flyoutSearch.parentElement?.querySelectorAll('svg').length).toBe(2);+ // Search magnifier (leading) is the only icon on the field — the trailing+ // branch icon was removed as unnecessary.+ expect(flyoutSearch.parentElement?.querySelectorAll('svg').length).toBe(1);fireEvent.click(devEntry);await waitFor(() => {@@ -402,7 +440,7 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {expect(screen.getByTestId('project-switcher-toggle-/repo').textContent).toContain('2 worktrees',);- fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));const flyout = await screen.findByTestId('project-switcher-flyout-/repo');const ids = [...flyout.querySelectorAll('[data-testid^="project-switcher-flyout-entry-"]')].map(@@ -416,6 +454,39 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {]);});+ test('count chip + flyout affordance single-source from the builder: a model-known opened worktree not in Recents still counts', async () => {+ // The current project's git model knows an opened worktree ("ghost") that+ // Recents never listed. The count chip and the flyout gate both derive from+ // buildWorktreeFlyoutEntries (which merges the model for the current+ // project), so this worktree surfaces the submenu affordance and is counted+ // — where the old Recents-only count would have shown a plain row with none.+ renderMenu({+ recents: [main('/repo', '/repo/.git')],+ currentPath: '/repo',+ worktreeModel: model([+ { branch: 'main', worktreePath: '/repo', isCurrent: true, isMain: true, locked: false },+ {+ branch: 'ghost',+ worktreePath: '/repo/.ok/worktrees/ghost',+ isCurrent: false,+ isMain: false,+ locked: false,+ },+ ]),+ });+ // Submenu row (not a plain row), and the chip counts the one opened, non-main+ // worktree — the pinned "default" (main) is not itself counted.+ expect(screen.getByTestId('project-switcher-group-/repo')).not.toBeNull();+ expect(screen.getByTestId('project-switcher-toggle-/repo').textContent).toContain('1 worktree');++ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));+ await screen.findByTestId('project-switcher-flyout-/repo');+ // The list shows the same worktree the count implies.+ expect(+ screen.getByTestId('project-switcher-flyout-entry-/repo/.ok/worktrees/ghost'),+ ).not.toBeNull();+ });+test('the flyout search filters that project’s worktrees + branches; a create-on-demand branch creates its worktree', async () => {const { bridge } = renderMenu({recents: [@@ -435,7 +506,7 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {{ branch: 'feature-x', worktreePath: null, isCurrent: false, isMain: false, locked: false },]),});- fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));await screen.findByTestId('project-switcher-flyout-/repo');// The un-opened branch is present (create-on-demand) and flagged "create".@@ -496,7 +567,7 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {]),openNewWorktreeWith,});- fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));await screen.findByTestId('project-switcher-flyout-/repo');// A query matching no worktree/branch. The empty label stays, AND a clickable@@ -535,7 +606,7 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {},]),});- fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));await screen.findByTestId('project-switcher-flyout-/repo');const searchBox = screen.getByTestId('project-switcher-flyout-search-/repo',@@ -568,7 +639,7 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {'/elsewhere',),});- fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));await screen.findByTestId('project-switcher-flyout-/repo');const searchBox = screen.getByTestId('project-switcher-flyout-search-/repo',@@ -602,7 +673,7 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {'/elsewhere',),});- fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));const flyout = await screen.findByTestId('project-switcher-flyout-/repo');// main + dev only; the other project's branch does not appear.expect(flyout.textContent).not.toContain('other-branch');@@ -612,15 +683,22 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {).not.toBeNull();});- test('clicking the project name opens the bare project (root), not the flyout', async () => {+ test('the flyout’s pinned "default" entry also opens the project root (secondary path to the same action)', async () => {+ // Row-click is the primary one-click open (covered above); the repo's+ // default/main checkout is also the pinned first flyout entry, opening the+ // same bare root with the `recents` entry point.const { bridge } = renderMenu({recents: [main('/repo', '/repo/.git'),worktree('/repo/.ok/worktrees/dev', '/repo/.git', '/repo', 'dev'),],});- // The name row opens the project directly (separate target from the expander).- fireEvent.click(screen.getByTestId('project-switcher-group-/repo'));+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));+ // Hover opened the flyout — it did NOT open the project directly.+ const mainEntry = await screen.findByTestId('project-switcher-flyout-entry-/repo');+ expect(bridge.project.open).not.toHaveBeenCalled();++ fireEvent.click(mainEntry);await waitFor(() => {expect(bridge.project.open).toHaveBeenCalledWith({path: '/repo',@@ -661,7 +739,7 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {// the worktree flyout.const groupRow = screen.getByTestId('project-switcher-group-/repo');expect(groupRow.textContent).toContain('/repo');- fireEvent.click(screen.getByTestId('project-switcher-toggle-/repo'));+ fireEvent.mouseEnter(screen.getByTestId('project-switcher-group-/repo'));// Synthesized project has no pinned main entry (never opened); the dev// worktree is present.await screen.findByTestId('project-switcher-flyout-/repo');diff --git a/packages/app/src/components/RecentProjectsMenu.tsx b/packages/app/src/components/RecentProjectsMenu.tsxindex 0b904fc16..7db0e33b8 100644--- a/packages/app/src/components/RecentProjectsMenu.tsx+++ b/packages/app/src/components/RecentProjectsMenu.tsx@@ -1,23 +1,28 @@/*** The recents + worktrees body of the ProjectSwitcher dropdown. Two modes:* - No query: recents grouped by repo. A project with opened worktrees is a- * row with two click targets — the name/path opens the bare project (root- * git workspace), the right-side worktree-icon + count + chevron opens a- * side-flyout listing that project's worktrees + branches. A project with- * none is a plain row.+ * two-target submenu row: HOVERING it (or ArrowRight) opens a side-flyout+ * listing that project's worktrees + branches, while CLICKING it (or+ * Enter/Space) opens the bare project (root git workspace) directly — one+ * click, same as a flat row. A project with no opened worktrees is a plain+ * row that opens it directly.* - Query: a flat list of matches across recent projects, their opened* worktrees, and the CURRENT project's branches (from the cached store, so* an un-opened branch is reachable by typing its name — create-on-demand).*- * The per-project worktree list is a Radix `Popover` side-flyout, NOT an inline- * disclosure and NOT a Radix `DropdownMenuSub`: the Electron renderer delivers- * no real `pointerdown`, so Radix submenus never open on click OR hover there- * (the same missing-pointer-event family as the v1 top-level menu). A Popover- * opens on click, which works. Its open-state is HOISTED to ProjectSwitcher- * (one "which row's flyout is open" value) so the flyout renders as a single- * controlled overlay rather than one deeply-nested overlay per menu item — two- * stacked non-modal Radix overlays otherwise fight focus-return / outside-click- * dismiss. See ProjectSwitcher for the hoist + the menu-vs-flyout dismiss guard.+ * The per-project worktree list is a Radix `DropdownMenuSub` (shadcn+ * `DropdownMenuSub`/`SubTrigger`/`SubContent`) — a real submenu of the project+ * dropdown, so mouse traversal gets Radix's safe-triangle hover and the flyout+ * closes when the pointer leaves both the row and the flyout. An earlier+ * revision used a Popover here on the theory that the Electron renderer's+ * missing `pointerdown` broke Radix submenus; live testing showed submenus open+ * on `pointermove`/`click` (only drag-region title-bar triggers are affected,+ * and this trigger sits inside the portaled, non-drag menu). Its open-state is+ * still HOISTED to ProjectSwitcher (one "which row's flyout is open" value) so+ * only one is open at a time and the parent can force-close it on menu dismiss+ * and on parent-menu scroll — Radix anchors the submenu to its trigger and would+ * otherwise follow the row off-screen. See ProjectSwitcher for the hoist + the+ * scroll-close.** Opening a worktree reuses `project.open({ entryPoint: 'worktree' })`; creating* one for a branch that has no window yet goes through `worktree.create` first,@@ -27,14 +32,18 @@import type { WorktreeSelectorEntry, WorktreeSelectorModel } from '@inkeep/open-knowledge-core';import { Plural, Trans, useLingui } from '@lingui/react/macro';-import { Check, ChevronRight, GitBranch, Plus, Search } from 'lucide-react';+import { Check, GitBranch, Plus, Search } from 'lucide-react';import type * as React from 'react';-import { useRef, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { toast } from 'sonner';-import { Button } from '@/components/ui/button';-import { DropdownMenuItem, DropdownMenuLabel } from '@/components/ui/dropdown-menu';+import {+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+} from '@/components/ui/dropdown-menu';import { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group';-import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';import type { OkDesktopBridge, RecentProjectEntry } from '@/lib/desktop-bridge-types';import { cn } from '@/lib/utils';import { refreshWorktrees } from '@/lib/worktree-store';@@ -64,7 +73,7 @@ interface RecentProjectsMenuProps {* the parent can force-close it when the menu dismisses.*/flyoutPath: string | null;- setFlyoutPath: (path: string | null) => void;+ setFlyoutPath: React.Dispatch<React.SetStateAction<string | null>>;/*** Opens the New Worktree dialog pre-filled with `name` (the flyout's typed* query). Wired from the current project's flyout no-match "Create worktree …"@@ -166,7 +175,14 @@ export function RecentProjectsMenu({currentPath={currentPath}worktreeModel={worktreeModel}flyoutOpen={flyoutPath === group.project.path}- setFlyoutOpen={(next) => setFlyoutPath(next ? group.project.path : null)}+ // Native hover-out-close can fire a sibling's A-close and this row's+ // B-open in the same tick; a functional update guards against a stale+ // close clobbering a fresh open (only clear if THIS row is the open one).+ setFlyoutOpen={(next) =>+ setFlyoutPath((cur) =>+ next ? group.project.path : cur === group.project.path ? null : cur,+ )+ }onPickProject={() => {if (group.project.path === currentPath) {closeMenu();@@ -206,7 +222,18 @@ function GroupRow({}) {const projectIsCurrent = group.project.path === currentPath;- if (group.worktrees.length === 0) {+ // Single source for BOTH the count chip and the flyout affordance: the same+ // builder rows the flyout list is built from, so the chip and the list can't+ // drift apart on which worktrees exist. We count opened, non-main worktrees —+ // the main checkout is pinned in the flyout as "default" and isn't itself a+ // switchable worktree — which matches the pre-migration `group.worktrees.length`+ // semantic while sourcing it from the git model (an opened worktree the model+ // knows about but Recents doesn't now surfaces the affordance). Hoisted here so+ // the builder runs once per group.+ const flyoutEntries = buildWorktreeFlyoutEntries(group, worktreeModel, currentPath);+ const openedWorktreeCount = flyoutEntries.filter((e) => e.opened && !e.isMain).length;++ if (openedWorktreeCount === 0) {return (<DropdownMenuItemonSelect={(e) => {@@ -233,6 +260,8 @@ function GroupRow({currentPath={currentPath}containsCurrent={containsCurrent}worktreeModel={worktreeModel}+ flyoutEntries={flyoutEntries}+ openedWorktreeCount={openedWorktreeCount}flyoutOpen={flyoutOpen}setFlyoutOpen={setFlyoutOpen}onPickProject={onPickProject}@@ -248,6 +277,8 @@ function FlyoutGroup({currentPath,containsCurrent,worktreeModel,+ flyoutEntries,+ openedWorktreeCount,flyoutOpen,setFlyoutOpen,onPickProject,@@ -259,6 +290,10 @@ function FlyoutGroup({currentPath: string;containsCurrent: boolean;worktreeModel: WorktreeSelectorModel | null;+ /** Builder rows, hoisted from GroupRow so the builder runs once per group. */+ flyoutEntries: WorktreeFlyoutEntry[];+ /** Opened, non-main worktree count from the same builder — drives the chip. */+ openedWorktreeCount: number;flyoutOpen: boolean;setFlyoutOpen: (open: boolean) => void;onPickProject: () => void;@@ -269,30 +304,32 @@ function FlyoutGroup({const { t } = useLingui();const projectIsCurrent = group.project.path === currentPath;+ // Two-target row on a real submenu (restores the pre-migration ergonomics):+ // - HOVER anywhere on the row opens the worktree flyout (native Radix+ // safe-triangle + close-on-leave-both), and ArrowRight opens it by keyboard.+ // - CLICK / Enter / Space open the PROJECT (its root) directly — one click,+ // same as a flat row. Radix's SubTrigger opens the submenu on click and on+ // the SUB_OPEN_KEYS (Enter/Space/ArrowRight); it bails when our handler+ // already called preventDefault (onClick: `if (event.defaultPrevented) return`;+ // onKeyDown: composed with checkForDefaultPrevented), so preventing default+ // on click + Enter/Space suppresses the open and lets navigation win while+ // ArrowRight still falls through to open the flyout. guardStaleSelect+ // swallows the Electron menu-open click fall-through, as on the flat rows.+ const openProjectFromRow = (nativeEvent: Event): void => {+ if (guardStaleSelect(nativeEvent)) return;+ onPickProject();+ };return (- <Popover open={flyoutOpen} onOpenChange={setFlyoutOpen}>- <DropdownMenuItem- onSelect={(e) => {- if (guardStaleSelect(e)) return;- // Clicking the name/path opens the bare project (root git workspace);- // the expander (its own click target below) opens the worktree flyout.- onPickProject();+ <DropdownMenuSub open={flyoutOpen} onOpenChange={setFlyoutOpen}>+ <DropdownMenuSubTrigger+ onClick={(e) => {+ e.preventDefault();+ openProjectFromRow(e.nativeEvent);}}- // Keyboard access to the flyout (the count-chip trigger is tabIndex=-1,- // out of the menu's roving focus). Standard submenu keys off the focused- // row: Right opens the flyout (focus moves into its search input via the- // Popover's open-autofocus), Left/Escape closes it. Only swallow- // Left/Escape while the flyout is OPEN so a closed-flyout Escape still- // bubbles to close the whole menu. This row only renders when the group- // has worktrees, so a flyout always exists here.onKeyDown={(e) => {- if (e.key === 'ArrowRight') {+ if (e.key === 'Enter' || e.key === ' ') {e.preventDefault();- setFlyoutOpen(true);- } else if ((e.key === 'ArrowLeft' || e.key === 'Escape') && flyoutOpen) {- e.preventDefault();- e.stopPropagation();- setFlyoutOpen(false);+ openProjectFromRow(e.nativeEvent);}}}className="flex w-full min-w-0 items-start gap-2"@@ -317,77 +354,57 @@ function FlyoutGroup({className="mt-0.5 size-3.5 shrink-0 text-muted-foreground"/>) : null}- {/* Separate click target: worktree icon + count + chevron opens the- side-flyout. The PopoverTrigger IS this button. stopPropagation keeps- the row's open-project select from also firing. tabIndex=-1 keeps it- out of the menu's roving focus. */}- <PopoverTrigger asChild>- <Button- type="button"- variant="ghost"- size="sm"- tabIndex={-1}- aria-label={flyoutOpen ? t`Hide worktrees` : t`Show worktrees`}- aria-expanded={flyoutOpen}- onMouseDown={(e) => {- e.stopPropagation();- }}- onClick={(e) => {- e.stopPropagation();- }}- // Open the flyout on HOVER, not just click. Mouse-enter DOES fire on- // the Electron renderer (unlike pointerdown), so this works here. Only- // OPEN on hover — deliberately NO onMouseLeave close: leaving the chip- // to reach the portaled flyout must not dismiss it (that was the v1- // "closes when I move my mouse" bug). It closes by hovering another- // project's chip (single hoisted flyout switches), clicking the chip- // again, Escape, picking an entry, or the menu closing.- onMouseEnter={() => {- setFlyoutOpen(true);- }}- data-testid={`project-switcher-toggle-${group.project.path}`}- className="-my-1 -mr-1 h-auto shrink-0 gap-1 rounded-md px-1.5 py-1 text-muted-foreground hover:bg-accent-foreground/15 hover:text-foreground hover:ring-1 hover:ring-border hover:ring-inset"- >- {/* Worktree count + pluralized label ("3 worktrees" / "1 worktree").- The digit stays tabular-nums so the count column doesn't jitter.- No leading icon here — "worktrees" already says what this is. */}- <span className="text-xs">- <span className="tabular-nums">{group.worktrees.length}</span>{' '}- <Plural value={group.worktrees.length} one="worktree" other="worktrees" />- </span>- <ChevronRight aria-hidden="true" className="size-3.5" />- </Button>- </PopoverTrigger>- </DropdownMenuItem>+ {/* Opened, non-main worktree count + pluralized label ("3 worktrees" /+ "1 worktree"), counted off the same builder rows the flyout list is+ built from (so the chip tracks the same worktree set the list shows;+ the list additionally renders the pinned "default" + create-on-demand+ branches, which the chip deliberately doesn't count). The digit stays+ tabular-nums so the count column doesn't jitter; the disclosure chevron+ is supplied by DropdownMenuSubTrigger. No leading icon — "worktrees"+ already says what this is. */}+ <span+ className="mt-0.5 shrink-0 text-muted-foreground text-xs"+ data-testid={`project-switcher-toggle-${group.project.path}`}+ >+ <span className="tabular-nums">{openedWorktreeCount}</span>{' '}+ <Plural value={openedWorktreeCount} one="worktree" other="worktrees" />+ </span>+ </DropdownMenuSubTrigger><WorktreeFlyoutgroup={group}- currentPath={currentPath}+ open={flyoutOpen}worktreeModel={worktreeModel}+ entries={flyoutEntries}onPickFlyoutEntry={onPickFlyoutEntry}guardStaleSelect={guardStaleSelect}openNewWorktreeWith={openNewWorktreeWith}/>- </Popover>+ </DropdownMenuSub>);}/*** The side-flyout content for one project: a search box over that project's- * worktrees + local branches, then the ordered list (main- * pinned, opened worktrees by recency, create-on-demand branches last). Portals- * out of the menu's scroll container so it isn't clipped.+ * worktrees + local branches, then the ordered list (main pinned, opened+ * worktrees by recency, create-on-demand branches last). Rendered as a+ * DropdownMenuSubContent — a real submenu, so it isn't clipped by the parent+ * menu's scroll container (Radix positions it fixed against the trigger).*/function WorktreeFlyout({group,- currentPath,+ open,worktreeModel,+ entries,onPickFlyoutEntry,guardStaleSelect,openNewWorktreeWith,}: {group: RecentRepoGroup;- currentPath: string;+ /** Hoisted open state — drives the focus-into-search effect on open. */+ open: boolean;worktreeModel: WorktreeSelectorModel | null;+ /** Builder rows, hoisted from GroupRow so the builder runs once per group. */+ entries: WorktreeFlyoutEntry[];onPickFlyoutEntry: (entry: WorktreeFlyoutEntry) => void;guardStaleSelect: (event: Event) => boolean;openNewWorktreeWith: (name: string) => void;@@ -397,13 +414,25 @@ function WorktreeFlyout({const searchRef = useRef<HTMLInputElement | null>(null);const listRef = useRef<HTMLDivElement | null>(null);- // Manual roving focus over the entry rows. These rows are Radix- // DropdownMenuItems inside a PORTALED PopoverContent — NOT a real DropdownMenu- // roving-focus context — so Radix's built-in arrow-key roving does not reach- // them. We drive focus ourselves off the live DOM (`[role="menuitem"]` in the- // list container) rather than a parallel ref array, so it stays correct as the- // search filters the list. ArrowDown out of the search input enters the list;- // ArrowUp off the first row returns to the search input.+ // Move focus onto the search input when the submenu opens so the list + the+ // "Create worktree" option are keyboard-reachable. DropdownMenuSubContent+ // hardcodes its own onOpenAutoFocus (a passed one is ignored), so drive focus+ // from the open transition instead. The content — and this input — only mounts+ // while open, so searchRef is live by the time this runs, and it lands after+ // Radix's own focus so the input wins. `preventScroll` so focusing the input+ // can't nudge the parent recents scroll container, whose onScroll close would+ // otherwise self-dismiss the flyout the instant it opens.+ useEffect(() => {+ if (open) searchRef.current?.focus({ preventScroll: true });+ }, [open]);++ // Manual roving focus over the entry rows. `preventDefault` + `stopPropagation`+ // on the keys we own keeps the enclosing DropdownMenuSubContent's native+ // roving/typeahead from also acting on them; ArrowLeft / Escape are left to+ // bubble so Radix closes the submenu. We drive focus off the live DOM+ // (`[role="menuitem"]` in the list container) rather than a parallel ref array,+ // so it stays correct as the search filters the list. ArrowDown out of the+ // search input enters the list; ArrowUp off the first row returns to it.function focusableRows(): HTMLElement[] {const container = listRef.current;if (container === null) return [];@@ -415,27 +444,29 @@ function WorktreeFlyout({}// Roving handler shared by every list row: Up/Down move between rows, Up off// the first row returns to the search input, Enter fires the row's action.- // Escape / ArrowLeft are intentionally NOT handled so the Popover's own- // Escape-to-close (and the group row's keys) keep working.+ // Escape / ArrowLeft are intentionally NOT handled so DropdownMenuSubContent's+ // native ArrowLeft/Escape (close the submenu, close the menu) keep working.function onRowKeyDown(e: React.KeyboardEvent, onEnter: () => void): void {if (e.key === 'ArrowDown') {e.preventDefault();+ e.stopPropagation();const rows = focusableRows();const i = rows.indexOf(e.currentTarget as HTMLElement);focusRowAt(Math.min(i + 1, rows.length - 1));} else if (e.key === 'ArrowUp') {e.preventDefault();+ e.stopPropagation();const rows = focusableRows();const i = rows.indexOf(e.currentTarget as HTMLElement);if (i <= 0) searchRef.current?.focus();else focusRowAt(i - 1);} else if (e.key === 'Enter') {e.preventDefault();+ e.stopPropagation();onEnter();}}- const entries = buildWorktreeFlyoutEntries(group, worktreeModel, currentPath);const q = flyoutQuery.trim().toLowerCase();const visible =q === '' ? entries : entries.filter((e) => (e.branch ?? '').toLowerCase().includes(q));@@ -450,34 +481,9 @@ function WorktreeFlyout({const canCreate = isCurrentProject && typedName.length > 0;return (- <PopoverContent- side="right"- align="start"+ <DropdownMenuSubContentsideOffset={4}className="flex max-h-80 w-96 flex-col gap-1 overflow-hidden p-1"- // Two stacked non-modal Radix overlays (menu + this flyout) otherwise- // fight over outside-click dismiss: a click inside this portaled flyout- // reads as "outside the menu" and closes both. Stopping the pointerdown- // here keeps the flyout interactive without collapsing the menu behind it.- // (Live dismiss behavior is only verifiable on the Electron renderer.)- onPointerDownOutside={(e) => e.preventDefault()}- // The flyout lives inside a Radix DropdownMenuItem; the parent menu focuses- // whatever row the pointer moves over (menus focus-on-hover), pulling focus- // OUT of this flyout — which would dismiss it the instant the mouse leaves- // the trigger, making it impossible to mouse in. Preventing the focus-outside- // dismiss keeps it open; it still closes on trigger re-click, Escape, picking- // an entry, or the menu closing (hoisted flyout state).- onFocusOutside={(e) => e.preventDefault()}- // Keyboard access: when the flyout opens (via ArrowRight on the- // group row, or click), move focus INTO it — onto the search input — so the- // list + "Create worktree" option are keyboard-reachable. Preventing Radix's- // default auto-focus lets us pick the target deterministically. Focus lands- // INSIDE the flyout, so the onFocusOutside guard above never fires (it stays- // open); Escape from here is handled by the Popover (close + return focus).- onOpenAutoFocus={(e) => {- e.preventDefault();- searchRef.current?.focus();- }}data-testid={`project-switcher-flyout-${group.project.path}`}><InputGroup className="mb-1 h-8 shrink-0">@@ -495,9 +501,10 @@ function WorktreeFlyout({onChange={(e) => setFlyoutQuery(e.target.value)}// ArrowDown steps from the search box into the entry list (focus the// first row); typing still filters. Intercept BEFORE stopPropagation —- // the stop keeps the parent menu's typeahead from stealing the keys,- // but would also swallow ArrowDown, so nav has to run first. Escape /- // ArrowLeft are left to the Popover / group row, unchanged.+ // the stop keeps the enclosing submenu's typeahead/roving from stealing+ // the keys, but would also swallow ArrowDown, so nav has to run first.+ // Escape still closes (Radix's document-level dismiss ignores React+ // stopPropagation); ArrowLeft stays a cursor move inside the input.onKeyDown={(e) => {if (e.key === 'ArrowDown') {e.preventDefault();@@ -507,11 +514,6 @@ function WorktreeFlyout({}}data-testid={`project-switcher-flyout-search-${group.project.path}`}/>- {/* Branch icon trails as the worktree-context cue (kept per design),- alongside the leading search magnifier. */}- <InputGroupAddon align="inline-end">- <GitBranch aria-hidden="true" />- </InputGroupAddon></InputGroup><divref={listRef}@@ -586,7 +588,7 @@ function WorktreeFlyout({}))}</div>- </PopoverContent>+ </DropdownMenuSubContent>);}diff --git a/packages/app/src/lib/worktree-store.test.ts b/packages/app/src/lib/worktree-store.test.tsindex 4b869f8cb..98298554f 100644--- a/packages/app/src/lib/worktree-store.test.ts+++ b/packages/app/src/lib/worktree-store.test.ts@@ -104,4 +104,111 @@ describe('createWorktreeStore', () => {await flush();expect(store.getSnapshot()?.mainRoot).toBe('/repo');});++ test('revalidation re-fetches so an out-of-band worktree surfaces without a refresh() call', async () => {+ let next = model('/repo');+ const fetchModel = mock(() => Promise.resolve(next));+ // Capture the store's revalidation callback so the test can fire a+ // focus/visible signal by hand (no DOM).+ let fireRevalidate: (() => void) | null = null;+ const subscribeRevalidate = mock((onRevalidate: () => void) => {+ fireRevalidate = onRevalidate;+ return () => {+ fireRevalidate = null;+ };+ });+ const store = createWorktreeStore({ fetchModel, subscribeRevalidate });+ const listener = mock(() => {});+ store.subscribe(listener);+ await flush();+ expect(fetchModel).toHaveBeenCalledTimes(1);+ expect(subscribeRevalidate).toHaveBeenCalledTimes(1);++ // A worktree was created out-of-band (terminal / other window); the window+ // regains focus → the store re-fetches WITHOUT any explicit refresh().+ next = model('/repo-with-new-worktree');+ fireRevalidate?.();+ await flush();+ expect(fetchModel).toHaveBeenCalledTimes(2);+ expect(store.getSnapshot()?.mainRoot).toBe('/repo-with-new-worktree');+ });++ test('attaches the revalidation trigger once and detaches it when the last subscriber leaves', async () => {+ const fetchModel = mock(() => Promise.resolve(model('/repo')));+ let attached = 0;+ let detached = 0;+ const subscribeRevalidate = mock((_onRevalidate: () => void) => {+ attached += 1;+ return () => {+ detached += 1;+ };+ });+ const store = createWorktreeStore({ fetchModel, subscribeRevalidate });++ const unsubA = store.subscribe(() => {});+ const unsubB = store.subscribe(() => {});+ await flush();+ // Attached exactly once for the first subscriber; the second reuses it.+ expect(attached).toBe(1);+ expect(detached).toBe(0);++ // Still one subscriber left → trigger stays attached (no leak, no premature+ // teardown).+ unsubA();+ expect(detached).toBe(0);++ // Last subscriber leaves → the trigger is detached so the DOM listener can't+ // outlive the store's consumers.+ unsubB();+ expect(detached).toBe(1);+ });++ test('re-attaches the revalidation trigger when a new subscriber arrives after the store went quiet', async () => {+ const fetchModel = mock(() => Promise.resolve(model('/repo')));+ let attached = 0;+ const subscribeRevalidate = mock((_onRevalidate: () => void) => {+ attached += 1;+ return () => {};+ });+ const store = createWorktreeStore({ fetchModel, subscribeRevalidate });++ store.subscribe(() => {})();+ await flush();+ expect(attached).toBe(1);++ // A later subscriber (e.g. the switcher remounts) must re-arm revalidation.+ store.subscribe(() => {});+ await flush();+ expect(attached).toBe(2);+ });++ test('a revalidation firing mid-flight is coalesced into one follow-up load', async () => {+ let resolveFirst: ((m: WorktreeSelectorModel) => void) | null = null;+ let call = 0;+ const fetchModel = mock(() => {+ call += 1;+ if (call === 1) {+ return new Promise<WorktreeSelectorModel>((r) => {+ resolveFirst = r;+ });+ }+ return Promise.resolve(model('/repo-revalidated'));+ });+ let fireRevalidate: (() => void) | null = null;+ const subscribeRevalidate = mock((onRevalidate: () => void) => {+ fireRevalidate = onRevalidate;+ return () => {};+ });+ const store = createWorktreeStore({ fetchModel, subscribeRevalidate });+ store.subscribe(() => {});+ await flush();+ // Bootstrap load is in-flight; a focus revalidation lands mid-flight.+ fireRevalidate?.();+ resolveFirst?.(model('/repo'));+ await flush();+ await flush();+ // The queued reload ran once after the first settled — not an unbounded storm.+ expect(fetchModel).toHaveBeenCalledTimes(2);+ expect(store.getSnapshot()?.mainRoot).toBe('/repo-revalidated');+ });});diff --git a/packages/app/src/lib/worktree-store.ts b/packages/app/src/lib/worktree-store.tsindex e9ef2ebb4..e02572479 100644--- a/packages/app/src/lib/worktree-store.ts+++ b/packages/app/src/lib/worktree-store.ts@@ -8,9 +8,19 @@* runs once and every consumer reads the same snapshot via `useSyncExternalStore`.* First subscription kicks off the fetch; the cached model is returned* synchronously thereafter, so rendering never blocks and repeat opens are- * instant. `refresh()` re-fetches after a worktree is created (the topology+ * instant. `refresh()` re-fetches after an in-app worktree create (the topology* changed). A failed fetch keeps the prior cache rather than clearing it.*+ * Out-of-band topology changes — a `git worktree add` in a terminal, or a+ * create in ANOTHER OK window (a separate BrowserWindow, hence a separate+ * module instance with its own cache) — never call `refresh()` here, so the+ * cache would otherwise stay frozen for the window's lifetime (the "new worktree+ * only shows after a restart" bug). `subscribeRevalidate` closes that gap: it+ * re-fetches on window focus / tab-visible, the same reactive signal+ * `PageListContext` / `FileTree` / `GraphView` use to recover from stale list+ * data. There's no cheap push for git worktree topology, so focus/visibility is+ * the proportionate invalidation trigger.+ ** Consumers render from the (possibly `null`) snapshot into a stable region, so* the async arrival fills that region without reflowing the primary list.*/@@ -27,6 +37,16 @@ export interface WorktreeStore {interface WorktreeStoreDeps {/** Resolves the current window's worktree model, or `null` when unavailable. */fetchModel: () => Promise<WorktreeSelectorModel | null>;+ /**+ * Register an external revalidation trigger — invoked whenever a signal+ * suggests the git worktree topology may have changed out-of-band (window+ * regains focus, tab becomes visible). Each call re-fetches the model.+ * Returns an unsubscribe. Wired to the subscriber lifecycle: attached when the+ * first consumer subscribes, detached when the last unsubscribes, so it never+ * fires — or leaks a listener — while nothing is mounted. Optional (omitted in+ * SSR and in tests that don't exercise revalidation).+ */+ subscribeRevalidate?: (onRevalidate: () => void) => () => void;}export function createWorktreeStore(deps: WorktreeStoreDeps): WorktreeStore {@@ -38,6 +58,10 @@ export function createWorktreeStore(deps: WorktreeStoreDeps): WorktreeStore {// dropped — otherwise a just-created worktree could miss the current window's// cache until remount.let reloadQueued = false;+ // Live only while at least one consumer is subscribed — ref-counted off+ // `listeners` so a focus event never re-fetches (or holds a DOM listener)+ // while the store is unmounted.+ let revalidateUnsub: (() => void) | null = null;const listeners = new Set<() => void>();function emit(): void {@@ -77,8 +101,22 @@ export function createWorktreeStore(deps: WorktreeStoreDeps): WorktreeStore {bootstrapped = true;void load();}+ // Attach the revalidation trigger on the first live subscriber. `load()`'s+ // in-flight coalescing bounds a burst of focus events to at most one+ // follow-up fetch, so no throttle is needed here.+ if (deps.subscribeRevalidate && revalidateUnsub === null) {+ revalidateUnsub = deps.subscribeRevalidate(() => {+ void load();+ });+ }return () => {listeners.delete(listener);+ // Detach when the last subscriber leaves so the DOM listener can't+ // outlive the store's consumers.+ if (listeners.size === 0 && revalidateUnsub !== null) {+ revalidateUnsub();+ revalidateUnsub = null;+ }};},refresh() {@@ -94,11 +132,35 @@ async function fetchWorktreeModel(): Promise<WorktreeSelectorModel | null> {return result.ok ? result.model : null;}+/**+ * Browser revalidation trigger: re-fetch when the window regains focus or the+ * tab becomes visible — the moment a worktree created out-of-band (a terminal+ * `git worktree add`, or another OK window) should surface without an app+ * restart. Mirrors the focus/visibilitychange revalidation in `PageListContext`+ * / `FileTree` / `GraphView`. The `visibilityState === 'visible'` gate drops the+ * hide half of `visibilitychange` (only re-fetch on show), and `visibilitychange`+ * is attached on `window` (it bubbles up from `document`) to match those callers.+ */+function subscribeBrowserRevalidate(onRevalidate: () => void): () => void {+ const handleResume = (): void => {+ if (document.visibilityState === 'visible') onRevalidate();+ };+ window.addEventListener('focus', handleResume);+ window.addEventListener('visibilitychange', handleResume);+ return () => {+ window.removeEventListener('focus', handleResume);+ window.removeEventListener('visibilitychange', handleResume);+ };+}+const productionStore: WorktreeStore =typeof window === 'undefined'? // SSR / non-browser: nothing to fetch. Consumers render their empty state.{ getSnapshot: () => null, subscribe: () => () => {}, refresh: () => {} }- : createWorktreeStore({ fetchModel: fetchWorktreeModel });+ : createWorktreeStore({+ fetchModel: fetchWorktreeModel,+ subscribeRevalidate: subscribeBrowserRevalidate,+ });export const subscribeToWorktrees = productionStore.subscribe;export const getWorktreesSnapshot = productionStore.getSnapshot;diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 1788b67c8..fd97de360 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -444,6 +444,7 @@"AE7BY3": ["The terminal session ended."],"AIn2Yv": [["displayName"], " CLI, ", ["hint"]],"AItsE5": ["Open it there"],+ "AKxFtn": [["openedWorktreeCount", "plural", { "one": ["worktree"], "other": ["worktrees"] }]],"ALhMYW": ["Terminal"],"AQ-Lfg": ["Couldn't load templates"],"AQGtjK": [@@ -467,7 +468,6 @@"This project lives only on this computer. Connect it to GitHub to back it up and share it with other people."],"Aif3E7": ["Enable semantic search"],- "Aj1D9r": ["Hide worktrees"],"Am78jY": ["Drag ", ["keyName"], " to reorder"],"Aq-O0x": ["status"],"AqnqMJ": ["API key set"],@@ -1210,7 +1210,6 @@"UYcGIW": ["Connecting — waiting for collab server"],"Ua78MH": ["no response"],"UaDyeb": ["Hide selection preview"],- "UaRsDu": ["Show worktrees"],"Uay5NL": ["This ",["targetNoun"],@@ -1793,7 +1792,6 @@"idD8Ev": ["Saved"],"ig5vUe": ["Failed to load file"],"iilQXA": ["Folder duplicated"],- "ij5sBu": [["0", "plural", { "one": ["worktree"], "other": ["worktrees"] }]],"ijLc3m": ["Bullet list"],"ipn17C": ["The <0>type</0> every document created from this template gets (e.g. <1>research-note</1>). Keeps new docs Open Knowledge Format–conformant."diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex f08e74932..bb3a18839 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -145,11 +145,6 @@ msgstr "{0, plural, one {File} other {Files}}"msgid "{0, plural, one {Folder} other {Folders}}"msgstr "{0, plural, one {Folder} other {Folders}}"-#. placeholder {0}: group.worktrees.length-#: src/components/RecentProjectsMenu.tsx-msgid "{0, plural, one {worktree} other {worktrees}}"-msgstr "{0, plural, one {worktree} other {worktrees}}"-#. placeholder {0}: templates.length#: src/components/empty-state/CreateView.tsxmsgid "{0} templates available"@@ -372,6 +367,10 @@ msgstr "{name} CLI"msgid "{nodeCount, plural, one {# node} other {# nodes}}"msgstr "{nodeCount, plural, one {# node} other {# nodes}}"+#: src/components/RecentProjectsMenu.tsx+msgid "{openedWorktreeCount, plural, one {worktree} other {worktrees}}"+msgstr "{openedWorktreeCount, plural, one {worktree} other {worktrees}}"+#: src/components/PublishToGitHubDialog.tsxmsgid "{owner}/{name} already exists"msgstr "{owner}/{name} already exists"@@ -3463,10 +3462,6 @@ msgstr "Hide this file"msgid "Hide thumbnails"msgstr "Hide thumbnails"-#: src/components/RecentProjectsMenu.tsx-msgid "Hide worktrees"-msgstr "Hide worktrees"-#: src/lib/keyboard-shortcuts.tsmsgid "Highlight"msgstr "Highlight"@@ -6328,10 +6323,6 @@ msgstr "Show terminal"msgid "Show thumbnails"msgstr "Show thumbnails"-#: src/components/RecentProjectsMenu.tsx-msgid "Show worktrees"-msgstr "Show worktrees"-#: src/components/CommandPalette.tsxmsgid "Showing results for \"{semanticResultsLabel}\""msgstr "Showing results for \"{semanticResultsLabel}\""diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 53c8bb33e..af02b67c1 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -444,6 +444,7 @@"AE7BY3": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď."],"AIn2Yv": [["displayName"], " ĆĹĨ, ", ["hint"]],"AItsE5": ["Ōƥēń ĩţ ţĥēŕē"],+ "AKxFtn": [["openedWorktreeCount", "plural", { "one": ["ŵōŕķţŕēē"], "other": ["ŵōŕķţŕēēś"] }]],"ALhMYW": ["Ţēŕḿĩńàĺ"],"AQ-Lfg": ["Ćōũĺďń'ţ ĺōàď ţēḿƥĺàţēś"],"AQGtjK": [@@ -467,7 +468,6 @@"Ţĥĩś ƥŕōĴēćţ ĺĩvēś ōńĺŷ ōń ţĥĩś ćōḿƥũţēŕ. Ćōńńēćţ ĩţ ţō ĜĩţĤũƀ ţō ƀàćķ ĩţ ũƥ àńď śĥàŕē ĩţ ŵĩţĥ ōţĥēŕ ƥēōƥĺē."],"Aif3E7": ["Ēńàƀĺē śēḿàńţĩć śēàŕćĥ"],- "Aj1D9r": ["Ĥĩďē ŵōŕķţŕēēś"],"Am78jY": ["Ďŕàĝ ", ["keyName"], " ţō ŕēōŕďēŕ"],"Aq-O0x": ["śţàţũś"],"AqnqMJ": ["ÀƤĨ ķēŷ śēţ"],@@ -1210,7 +1210,6 @@"UYcGIW": ["Ćōńńēćţĩńĝ — ŵàĩţĩńĝ ƒōŕ ćōĺĺàƀ śēŕvēŕ"],"Ua78MH": ["ńō ŕēśƥōńśē"],"UaDyeb": ["Ĥĩďē śēĺēćţĩōń ƥŕēvĩēŵ"],- "UaRsDu": ["Śĥōŵ ŵōŕķţŕēēś"],"Uay5NL": ["Ţĥĩś ",["targetNoun"],@@ -1793,7 +1792,6 @@"idD8Ev": ["Śàvēď"],"ig5vUe": ["Ƒàĩĺēď ţō ĺōàď ƒĩĺē"],"iilQXA": ["Ƒōĺďēŕ ďũƥĺĩćàţēď"],- "ij5sBu": [["0", "plural", { "one": ["ŵōŕķţŕēē"], "other": ["ŵōŕķţŕēēś"] }]],"ijLc3m": ["ßũĺĺēţ ĺĩśţ"],"ipn17C": ["Ţĥē <0>ţŷƥē</0> ēvēŕŷ ďōćũḿēńţ ćŕēàţēď ƒŕōḿ ţĥĩś ţēḿƥĺàţē ĝēţś (ē.ĝ. <1>ŕēśēàŕćĥ-ńōţē</1>). Ķēēƥś ńēŵ ďōćś Ōƥēń Ķńōŵĺēďĝē Ƒōŕḿàţ–ćōńƒōŕḿàńţ."diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex dfacb6117..eb8558d82 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -145,11 +145,6 @@ msgstr ""msgid "{0, plural, one {Folder} other {Folders}}"msgstr ""-#. placeholder {0}: group.worktrees.length-#: src/components/RecentProjectsMenu.tsx-msgid "{0, plural, one {worktree} other {worktrees}}"-msgstr ""-#. placeholder {0}: templates.length#: src/components/empty-state/CreateView.tsxmsgid "{0} templates available"@@ -372,6 +367,10 @@ msgstr ""msgid "{nodeCount, plural, one {# node} other {# nodes}}"msgstr ""+#: src/components/RecentProjectsMenu.tsx+msgid "{openedWorktreeCount, plural, one {worktree} other {worktrees}}"+msgstr ""+#: src/components/PublishToGitHubDialog.tsxmsgid "{owner}/{name} already exists"msgstr ""@@ -3458,10 +3457,6 @@ msgstr ""msgid "Hide thumbnails"msgstr ""-#: src/components/RecentProjectsMenu.tsx-msgid "Hide worktrees"-msgstr ""-#: src/lib/keyboard-shortcuts.tsmsgid "Highlight"msgstr ""@@ -6323,10 +6318,6 @@ msgstr ""msgid "Show thumbnails"msgstr ""-#: src/components/RecentProjectsMenu.tsx-msgid "Show worktrees"-msgstr ""-#: src/components/CommandPalette.tsxmsgid "Showing results for \"{semanticResultsLabel}\""msgstr ""