From 4b5203788db3fe53f922218bc73c211c74266348 Mon Sep 17 00:00:00 2001 From: Aulma <37032612+Aulma@users.noreply.github.com> Date: Tue, 4 Aug 2026 18:55:54 +0200 Subject: [PATCH] feat(web): drive navigation surfaces from one manifest (#2233) --- .../app-sidebar/app-sidebar-footer.test.tsx | 15 ++ .../app-sidebar/app-sidebar-footer.tsx | 27 ++- .../app-sidebar/app-sidebar-nav-item.tsx | 4 +- .../sections/integrations-section.test.tsx | 144 +++++++------- .../sections/integrations-section.tsx | 110 ++++------- apps/web/components/global-commands.test.tsx | 111 +++++++++++ apps/web/components/global-commands.tsx | 135 ++++++++----- .../integrations/integrations-menu.test.ts | 66 +------ .../integrations/integrations-menu.tsx | 181 +++-------------- .../components/kanban/mobile-menu-sheet.tsx | 24 +-- .../navigation/destination-rows.test.tsx | 73 +++++++ .../navigation/destination-rows.tsx | 83 ++++++++ .../plugins/mobile-plugin-nav-section.tsx | 43 ++-- .../plugins/plugin-nav-items.test.tsx | 13 ++ .../components/plugins/plugin-nav-items.tsx | 27 ++- .../mobile-integrations-nav.spec.ts | 4 +- .../e2e/tests/layout/mobile-stats-nav.spec.ts | 36 ++++ apps/web/hooks/use-app-destinations.test.tsx | 96 +++++++++ apps/web/hooks/use-app-destinations.ts | 93 +++++++++ apps/web/hooks/use-nav-availability.test.ts | 109 ++++++++++ apps/web/hooks/use-nav-availability.ts | 73 +++++++ .../lib/navigation/core-destinations.test.ts | 186 ++++++++++++++++++ apps/web/lib/navigation/core-destinations.ts | 171 ++++++++++++++++ .../navigation/plugin-destinations.test.ts | 149 ++++++++++++++ .../web/lib/navigation/plugin-destinations.ts | 55 ++++++ .../navigation/resolve-destinations.test.ts | 123 ++++++++++++ .../lib/navigation/resolve-destinations.ts | 101 ++++++++++ apps/web/lib/navigation/surface-policy.ts | 71 +++++++ apps/web/lib/navigation/types.ts | 123 ++++++++++++ apps/web/lib/plugins/registry.test.ts | 12 ++ apps/web/lib/plugins/registry.ts | 20 ++ ...26-08-04-navigation-manifest-boundaries.md | 69 +++++++ docs/decisions/INDEX.md | 1 + docs/public/feature-status.md | 2 +- 34 files changed, 2081 insertions(+), 469 deletions(-) create mode 100644 apps/web/components/global-commands.test.tsx create mode 100644 apps/web/components/navigation/destination-rows.test.tsx create mode 100644 apps/web/components/navigation/destination-rows.tsx create mode 100644 apps/web/e2e/tests/layout/mobile-stats-nav.spec.ts create mode 100644 apps/web/hooks/use-app-destinations.test.tsx create mode 100644 apps/web/hooks/use-app-destinations.ts create mode 100644 apps/web/hooks/use-nav-availability.test.ts create mode 100644 apps/web/hooks/use-nav-availability.ts create mode 100644 apps/web/lib/navigation/core-destinations.test.ts create mode 100644 apps/web/lib/navigation/core-destinations.ts create mode 100644 apps/web/lib/navigation/plugin-destinations.test.ts create mode 100644 apps/web/lib/navigation/plugin-destinations.ts create mode 100644 apps/web/lib/navigation/resolve-destinations.test.ts create mode 100644 apps/web/lib/navigation/resolve-destinations.ts create mode 100644 apps/web/lib/navigation/surface-policy.ts create mode 100644 apps/web/lib/navigation/types.ts create mode 100644 docs/decisions/2026-08-04-navigation-manifest-boundaries.md diff --git a/apps/web/components/app-sidebar/app-sidebar-footer.test.tsx b/apps/web/components/app-sidebar/app-sidebar-footer.test.tsx index 5f61957707..acf66de6c2 100644 --- a/apps/web/components/app-sidebar/app-sidebar-footer.test.tsx +++ b/apps/web/components/app-sidebar/app-sidebar-footer.test.tsx @@ -1,5 +1,6 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { TooltipProvider } from "@kandev/ui/tooltip"; +import { IconChartBar } from "@tabler/icons-react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ @@ -43,6 +44,20 @@ vi.mock("@/hooks/domains/features/use-feature", () => ({ useFeature: (name: string) => (name === "office" ? officeEnabled : appStatusBarEnabled), })); +// The footer renders its insight buttons from the navigation manifest; the +// manifest itself is covered in `lib/navigation/core-destinations.test.ts`. +vi.mock("@/hooks/use-app-destinations", () => ({ + useStaticDestinations: () => [ + { + id: "stats", + label: "Stats", + icon: IconChartBar, + section: "insights", + href: "/stats", + }, + ], +})); + vi.mock("@/hooks/use-release-notes", () => ({ useReleaseNotes: () => ({ unseenEntries: [], diff --git a/apps/web/components/app-sidebar/app-sidebar-footer.tsx b/apps/web/components/app-sidebar/app-sidebar-footer.tsx index de4d05d01a..19c1c35c54 100644 --- a/apps/web/components/app-sidebar/app-sidebar-footer.tsx +++ b/apps/web/components/app-sidebar/app-sidebar-footer.tsx @@ -5,14 +5,14 @@ import { useTranslation } from "react-i18next"; import { useRouter, usePathname } from "@/lib/routing/client-router"; import { IconBuildings, - IconChartBar, IconLayoutKanban, IconSettings, IconSparkles, IconStethoscope, IconWifiOff, } from "@tabler/icons-react"; -import type { Icon as TablerIcon } from "@tabler/icons-react"; +import { useStaticDestinations } from "@/hooks/use-app-destinations"; +import type { DestinationIcon } from "@/lib/navigation/types"; import { Button } from "@kandev/ui/button"; import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; import { ImproveKandevDialog } from "@/components/improve-kandev-dialog"; @@ -42,7 +42,7 @@ type AppSidebarFooterProps = { }; type FooterIconButtonProps = { - icon: TablerIcon; + icon: DestinationIcon; label: string; collapsed: boolean; onClick?: () => void; @@ -210,6 +210,10 @@ export function AppSidebarFooter({ collapsed, onToggleSettingsMode }: AppSidebar }; const officeEnabled = useFeature("office"); const appStatusBarEnabled = useFeature("appStatusBar"); + // Stats today, and anything else the manifest adds to the insights section. + // The gear below stays bespoke: it toggles the sidebar's settings takeover as + // well as navigating, so it is an action, not a plain destination. + const insightDestinations = useStaticDestinations("sidebar", "insights"); const releaseNotes = useReleaseNotes(); const [improveOpen, setImproveOpen] = useState(false); const authMode = useAppStore((s) => s.auth.mode); @@ -231,13 +235,16 @@ export function AppSidebarFooter({ collapsed, onToggleSettingsMode }: AppSidebar active={settingsMode} testId="sidebar-settings-gear" /> - router.push("/stats")} - testId="sidebar-stats-button" - /> + {insightDestinations.map((destination) => ( + router.push(destination.href)} + testId={`sidebar-${destination.id}-button`} + /> + ))} ({ pathname: "/", @@ -11,12 +14,7 @@ const collapsibleMock = vi.hoisted(() => ({ open: false, })); -const linksMock = vi.hoisted(() => - vi.fn(() => [ - { id: "github", label: "GitHub", href: "/github" }, - { id: "jira", label: "Jira", href: "/jira" }, - ]), -); +const destinationsMock = vi.hoisted(() => vi.fn()); const storeState = { appSidebar: { @@ -36,24 +34,11 @@ vi.mock("@/components/state-provider", () => ({ useAppStore: (selector: (state: typeof storeState) => unknown) => selector(storeState), })); -vi.mock("@/components/integrations/integrations-menu", () => ({ - useConfiguredIntegrationLinks: linksMock, -})); - -const pluginsMock = vi.hoisted(() => ({ - navItems: [] as Array<{ - id: string; - label: string; - path: string; - icon?: string; - section?: string; - }>, -})); - -vi.mock("@/lib/plugins/registry", () => ({ - usePluginRegistry: () => ({ - getNavItems: () => pluginsMock.navItems, - }), +// The section renders whatever the navigation manifest resolves for the sidebar's +// integrations group; availability gating and plugin merging are covered in +// `lib/navigation/core-destinations.test.ts`. +vi.mock("@/hooks/use-app-destinations", () => ({ + useAppDestinations: destinationsMock, })); vi.mock("@kandev/ui/collapsible", () => ({ @@ -67,6 +52,39 @@ vi.mock("@kandev/ui/collapsible", () => ({ import { IntegrationsSection } from "./integrations-section"; +function destination( + id: string, + label: string, + icon: ResolvedDestination["icon"], +): ResolvedDestination { + return { id, label, icon, section: "integrations", href: `/${id}` }; +} + +/** Plugin entries arrive namespaced, with the raw item id kept for test ids. */ +function pluginDestination( + itemId: string, + label: string, + icon: ResolvedDestination["icon"], +): ResolvedDestination { + return { + id: `plugin:${itemId}`, + pluginItemId: itemId, + label, + icon, + section: "integrations", + href: `/${itemId}`, + source: "plugin", + }; +} + +const AZURE = destination("azure-devops", "Azure DevOps", AzureDevOpsIcon); +const GITHUB = destination("github", "GitHub", IconBrandGithub); +const GITLAB = destination("gitlab", "GitLab", IconBrandGitlab); +const JIRA = destination("jira", "Jira", IconHexagon); +const LINEAR = destination("linear", "Linear", IconHexagon); +const PLUGIN_PAGE = pluginDestination("cost-per-model", "Cost per Model", IconChartBar); +const PLUGIN_TEST_ID = `plugin-nav-item-${PLUGIN_PAGE.pluginItemId}`; + function renderSection() { return render( @@ -81,110 +99,86 @@ describe("IntegrationsSection", () => { storeState.appSidebar.sectionExpanded.integrations = false; storeState.toggleAppSidebarSection.mockClear(); storeState.setAppSidebarCollapsed.mockClear(); - linksMock.mockReturnValue([ - { id: "github", label: "GitHub", href: "/github" }, - { id: "jira", label: "Jira", href: "/jira" }, - ]); - pluginsMock.navItems = []; + destinationsMock.mockReturnValue([GITHUB, JIRA]); }); afterEach(() => cleanup()); it("keeps integration shortcuts visible while the section accordion is closed", () => { - linksMock.mockReturnValue([ - { id: "github", label: "GitHub", href: "/github" }, - { id: "gitlab", label: "GitLab", href: "/gitlab" }, - { id: "jira", label: "Jira", href: "/jira" }, - { id: "linear", label: "Linear", href: "/linear" }, - { id: "sentry", label: "Sentry", href: "/sentry" }, - ]); + destinationsMock.mockReturnValue([AZURE, GITHUB, GITLAB, JIRA, LINEAR]); renderSection(); const shortcuts = screen.getAllByTestId("integration-header-shortcut"); expect(shortcuts.map((shortcut) => shortcut.getAttribute("aria-label"))).toEqual([ + "Azure DevOps", "GitHub", "GitLab", "Jira", - "Linear", ]); expect(shortcuts.map((shortcut) => shortcut.getAttribute("href"))).toEqual([ + "/azure-devops", "/github", "/gitlab", "/jira", - "/linear", ]); - expect(screen.queryByRole("link", { name: "Sentry" })).toBeNull(); + expect(screen.queryByRole("link", { name: "Linear" })).toBeNull(); }); it("limits shortcuts to four integrations and leaves the full list in the expanded section", () => { storeState.appSidebar.sectionExpanded.integrations = true; - linksMock.mockReturnValue([ - { id: "github", label: "GitHub", href: "/github" }, - { id: "gitlab", label: "GitLab", href: "/gitlab" }, - { id: "jira", label: "Jira", href: "/jira" }, - { id: "linear", label: "Linear", href: "/linear" }, - { id: "sentry", label: "Sentry", href: "/sentry" }, - ]); + destinationsMock.mockReturnValue([AZURE, GITHUB, GITLAB, JIRA, LINEAR]); renderSection(); expect(screen.getAllByTestId("integration-header-shortcut")).toHaveLength(4); - expect(screen.getByRole("link", { name: "Sentry" })).toBeTruthy(); + expect(screen.getByRole("link", { name: "Linear" })).toBeTruthy(); }); it("uses the Azure DevOps product mark for Azure links", () => { storeState.appSidebar.sectionExpanded.integrations = true; - linksMock.mockReturnValue([ - { id: "azure-devops", label: "Azure DevOps", href: "/azure-devops" }, - ]); + destinationsMock.mockReturnValue([AZURE]); renderSection(); expect(screen.getAllByTestId("azure-devops-icon")).toHaveLength(2); }); - const costPerModelItem = { - id: "cost-per-model", - label: "Cost per Model", - path: "/cost-per-model", - icon: "chart", - section: "integrations", - }; - const costPerModelTestId = `plugin-nav-item-${costPerModelItem.id}`; - - it("renders plugin nav items registered with section integrations after the first-party links", () => { + it("renders plugin nav items after the first-party links, with their own test id", () => { storeState.appSidebar.sectionExpanded.integrations = true; - pluginsMock.navItems = [ - costPerModelItem, - { id: "hello", label: "Hello", path: "/hello", section: "main" }, - ]; + destinationsMock.mockReturnValue([GITHUB, PLUGIN_PAGE]); renderSection(); - const pluginRow = screen.getByTestId(costPerModelTestId); - expect(pluginRow.getAttribute("href")).toBe(costPerModelItem.path); - expect(screen.queryByRole("link", { name: "Hello" })).toBeNull(); + const pluginRow = screen.getByTestId(PLUGIN_TEST_ID); + expect(pluginRow.getAttribute("href")).toBe(PLUGIN_PAGE.href); + expect(pluginRow.textContent).toContain(PLUGIN_PAGE.label); }); - it("shows the section when only plugin integration items exist, with no empty header-action slot", () => { - storeState.appSidebar.sectionExpanded.integrations = true; - linksMock.mockReturnValue([]); - pluginsMock.navItems = [costPerModelItem]; + it("keeps plugin items out of the header shortcut strip", () => { + destinationsMock.mockReturnValue([PLUGIN_PAGE]); const { container } = renderSection(); - expect(screen.getByTestId(costPerModelTestId)).toBeTruthy(); // Regression for the empty headerAction slot: AppSidebarSection renders // a "shrink-0 mr-1 flex items-center" wrapper whenever headerAction is // non-null, even with zero shortcuts inside it. + expect(screen.queryAllByTestId("integration-header-shortcut")).toEqual([]); expect(container.querySelector(".shrink-0.mr-1")).toBeNull(); }); - it("hides the section entirely when neither first-party links nor plugin items exist", () => { + it("shows the section when only plugin integration items exist", () => { storeState.appSidebar.sectionExpanded.integrations = true; - linksMock.mockReturnValue([]); - pluginsMock.navItems = []; + destinationsMock.mockReturnValue([PLUGIN_PAGE]); + + renderSection(); + + expect(screen.getByTestId(PLUGIN_TEST_ID)).toBeTruthy(); + }); + + it("hides the section entirely when the manifest resolves no destinations", () => { + storeState.appSidebar.sectionExpanded.integrations = true; + destinationsMock.mockReturnValue([]); const { container } = renderSection(); diff --git a/apps/web/components/app-sidebar/sections/integrations-section.tsx b/apps/web/components/app-sidebar/sections/integrations-section.tsx index 26a70af660..de03ee604b 100644 --- a/apps/web/components/app-sidebar/sections/integrations-section.tsx +++ b/apps/web/components/app-sidebar/sections/integrations-section.tsx @@ -3,18 +3,10 @@ import Link from "@/components/routing/app-link"; import { useTranslation } from "react-i18next"; import { usePathname } from "@/lib/routing/client-router"; -import type { ComponentType } from "react"; -import { - IconBrandGithub, - IconBrandGitlab, - IconHexagon, - IconPlugConnected, - IconTicket, -} from "@tabler/icons-react"; +import { IconPlugConnected } from "@tabler/icons-react"; import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; -import { useConfiguredIntegrationLinks } from "@/components/integrations/integrations-menu"; -import { resolvePluginIcon } from "@/lib/plugins/icons"; -import { usePluginRegistry } from "@/lib/plugins/registry"; +import { useAppDestinations } from "@/hooks/use-app-destinations"; +import type { DestinationIcon, ResolvedDestination } from "@/lib/navigation/types"; import { cn } from "@/lib/utils"; import { APP_SIDEBAR_SECTION_IDS, @@ -22,47 +14,31 @@ import { SIDEBAR_ITEM_INACTIVE, } from "../app-sidebar-constants"; import { AppSidebarSection } from "../app-sidebar-section"; -import { AzureDevOpsIcon } from "@/components/icons/azure-devops-icon"; type IntegrationsSectionProps = { collapsed: boolean; }; -type IntegrationIcon = ComponentType<{ className?: string }>; - -const INTEGRATION_ICONS: Record = { - "azure-devops": AzureDevOpsIcon, - github: IconBrandGithub, - gitlab: IconBrandGitlab, - jira: IconTicket, - linear: IconHexagon, -}; - const MAX_HEADER_SHORTCUTS = 4; -type ConfiguredIntegrationLink = ReturnType[number]; - -function IntegrationHeaderShortcuts({ links }: { links: ConfiguredIntegrationLink[] }) { +function IntegrationHeaderShortcuts({ links }: { links: ResolvedDestination[] }) { return (
- {links.slice(0, MAX_HEADER_SHORTCUTS).map(({ id, label, href }) => { - const Icon = INTEGRATION_ICONS[id] ?? IconPlugConnected; - return ( - - - - - - - {label} - - ); - })} + {links.slice(0, MAX_HEADER_SHORTCUTS).map(({ id, label, href, icon: Icon }) => ( + + + + + + + {label} + + ))}
); } @@ -70,7 +46,7 @@ function IntegrationHeaderShortcuts({ links }: { links: ConfiguredIntegrationLin type IntegrationRowProps = { href: string; label: string; - icon: IntegrationIcon; + icon: DestinationIcon; active: boolean; testId?: string; }; @@ -94,14 +70,15 @@ function IntegrationRow({ href, label, icon: Icon, active, testId }: Integration export function IntegrationsSection({ collapsed }: IntegrationsSectionProps) { const { t } = useTranslation(); const pathname = usePathname(); - const links = useConfiguredIntegrationLinks(); - // Plugin-registered nav items that target this section - // (`registerNavItem({ section: "integrations" })`), rendered after the - // first-party links. - const registry = usePluginRegistry(); - const pluginItems = registry.getNavItems().filter((item) => item.section === "integrations"); + // First-party integration links and plugin-registered nav items that target + // this section (`registerNavItem({ section: "integrations" })`) both come from + // the navigation manifest, already in render order. + const destinations = useAppDestinations("sidebar", "integrations"); + // Header shortcuts stay first-party: they are a fixed-width strip, and a + // plugin should not push a configured integration out of it. + const firstPartyLinks = destinations.filter((destination) => destination.source !== "plugin"); - if (links.length === 0 && pluginItems.length === 0) return null; + if (destinations.length === 0) return null; return ( 0 ? : undefined} + headerAction={ + firstPartyLinks.length > 0 ? ( + + ) : undefined + } headerActionVisibility="always" > - {links.map(({ id, label, href }) => ( + {destinations.map((destination) => ( - ))} - {pluginItems.map((item) => ( - ))} diff --git a/apps/web/components/global-commands.test.tsx b/apps/web/components/global-commands.test.tsx new file mode 100644 index 0000000000..ac20d62cac --- /dev/null +++ b/apps/web/components/global-commands.test.tsx @@ -0,0 +1,111 @@ +import { cleanup, render } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { CommandItem } from "@/lib/commands/types"; +import { GlobalCommands } from "./global-commands"; + +const mocks = vi.hoisted(() => { + const translations: Record = {}; + return { + commands: [] as CommandItem[], + destinations: [ + { + id: "stats", + label: "Stats", + icon: () => null, + section: "insights" as const, + href: "/stats", + palette: { + id: "nav-stats", + labelKey: "common:commandGoToStats", + keywordsKey: "common:commandGoToStatsKeywords", + }, + }, + ], + push: vi.fn(), + quickChat: vi.fn(), + setTheme: vi.fn(), + translations, + translate: vi.fn((key: string) => translations[key] ?? key), + }; +}); + +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: mocks.translate }), +})); +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (state: unknown) => unknown) => + selector({ + userSettings: { keyboardShortcuts: {} }, + workspaces: { activeId: "workspace-1" }, + }), +})); +vi.mock("@/components/theme/app-theme", () => ({ + useTheme: () => ({ resolvedTheme: "dark", setTheme: mocks.setTheme }), +})); +vi.mock("@/hooks/use-app-destinations", () => ({ + useStaticDestinations: () => mocks.destinations.map((destination) => ({ ...destination })), +})); +vi.mock("@/hooks/use-app-shortcuts", () => ({ useAppShortcuts: vi.fn() })); +vi.mock("@/hooks/use-keyboard-shortcut", () => ({ useKeyboardShortcut: vi.fn() })); +vi.mock("@/hooks/use-plugin-shortcuts", () => ({ usePluginShortcuts: vi.fn() })); +vi.mock("@/hooks/use-quick-chat-launcher", () => ({ + useQuickChatLauncher: () => mocks.quickChat, +})); +vi.mock("@/hooks/use-register-commands", () => ({ + useRegisterCommands: (commands: CommandItem[]) => { + mocks.commands = commands; + }, +})); +vi.mock("@/lib/keyboard/shortcut-overrides", () => ({ getShortcut: () => undefined })); +vi.mock("@/lib/routing/client-router", () => ({ + useRouter: () => ({ push: mocks.push }), +})); + +function navigationCommand(): CommandItem { + const command = mocks.commands.find((item) => item.id === "nav-stats"); + if (!command) throw new Error("Missing Stats navigation command"); + return command; +} + +beforeEach(() => { + mocks.commands = []; + mocks.push.mockReset(); + mocks.translations["common:commandGroupNavigation"] = "Navigation"; + mocks.translations["common:commandGoToStatsKeywords"] = "stats, metrics"; +}); + +afterEach(cleanup); + +describe("GlobalCommands navigation commands", () => { + it("maps destinations to commands and navigation actions", () => { + render(); + + const command = navigationCommand(); + expect(command).toMatchObject({ + id: "nav-stats", + label: "Stats", + group: "Navigation", + keywords: ["stats", "metrics"], + }); + + command.action?.(); + expect(mocks.push).toHaveBeenCalledWith("/stats"); + }); + + it("keeps command identity until a translated command value changes", () => { + const { rerender } = render(); + const first = navigationCommand(); + + rerender(); + expect(navigationCommand()).toBe(first); + + mocks.translations["common:commandGroupNavigation"] = "Navigation pseudo"; + mocks.translations["common:commandGoToStatsKeywords"] = "statistiques, mesures"; + rerender(); + + const translated = navigationCommand(); + expect(translated).not.toBe(first); + expect(translated.group).toBe("Navigation pseudo"); + expect(translated.keywords).toEqual(["statistiques", "mesures"]); + }); +}); diff --git a/apps/web/components/global-commands.tsx b/apps/web/components/global-commands.tsx index fa0303e380..5597267e48 100644 --- a/apps/web/components/global-commands.tsx +++ b/apps/web/components/global-commands.tsx @@ -1,15 +1,11 @@ "use client"; -import { useMemo } from "react"; +import { useMemo, useRef } from "react"; import { useTranslation } from "react-i18next"; import type { TFunction } from "i18next"; import { useRouter } from "@/lib/routing/client-router"; import { useTheme } from "@/components/theme/app-theme"; import { - IconHome, - IconList, - IconSettings, - IconChartBar, IconSun, IconMoon, IconRobot, @@ -17,8 +13,9 @@ import { IconFolder, IconMessageCircle, IconSparkles, - IconBrandGithub, } from "@tabler/icons-react"; +import { useStaticDestinations } from "@/hooks/use-app-destinations"; +import { PALETTE_NAVIGATION_GROUP_KEY } from "@/lib/navigation/surface-policy"; import { useRegisterCommands } from "@/hooks/use-register-commands"; import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut"; import { useAppShortcuts } from "@/hooks/use-app-shortcuts"; @@ -26,14 +23,13 @@ import { usePluginShortcuts } from "@/hooks/use-plugin-shortcuts"; import { useAppStore } from "@/components/state-provider"; import { useQuickChatLauncher } from "@/hooks/use-quick-chat-launcher"; import { getShortcut } from "@/lib/keyboard/shortcut-overrides"; -import { linkToTaskOverview } from "@/lib/links"; import type { CommandItem } from "@/lib/commands/types"; type PushFn = ReturnType["push"]; // Catalog keys, not copy — safe at module scope (no `t()` call here). The // palette groups by this resolved value, so every producer must use these. -const GROUP_NAVIGATION = "common:commandGroupNavigation"; +const GROUP_NAVIGATION = PALETTE_NAVIGATION_GROUP_KEY; const GROUP_SETTINGS = "common:commandGroupSettings"; const GROUP_ACTIONS = "common:commandGroupActions"; @@ -50,48 +46,74 @@ function searchKeywords(t: TFunction, key: string): string[] { .filter(Boolean); } -function buildNavigationCommands(push: PushFn, t: TFunction): CommandItem[] { +/** + * The Navigation group comes from the navigation manifest + * (`lib/navigation/core-destinations.ts`), so a destination cannot reach the palette + * without also being offered on the surfaces it declares. Command ids and copy + * live in each destination's `palette` block — they are stable API for tests and + * telemetry. The Settings group below stays hand-written: those are deep links + * into one destination, not destinations of their own. + */ +function useNavigationCommands(push: PushFn, t: TFunction): CommandItem[] { + // `useStaticDestinations`, not `useAppDestinations`: this component is mounted + // for the whole session, and the palette's one gated entry (GitHub) opts out of + // the availability check, so subscribing to integration polling here would add + // background requests for nothing. + const destinations = useStaticDestinations("palette"); + // Cached on a value signature so the command array keeps its identity across + // unrelated re-renders — `useRegisterCommands` re-registers whenever the array + // changes. Same render-time cache pattern as `use-responsive-breakpoint.ts`; + // a `useMemo` cannot work here because the resolved list is rebuilt each render. + const group = t(GROUP_NAVIGATION); + const resolved = destinations.map((destination) => ({ + destination, + keywords: destination.palette?.keywordsKey + ? searchKeywords(t, destination.palette.keywordsKey) + : [], + })); + const signature = JSON.stringify( + resolved.map(({ destination, keywords }) => [ + destination.id, + destination.palette?.id, + destination.href, + destination.label, + group, + keywords, + ]), + ); + const cacheRef = useRef<{ + signature: string; + push: PushFn; + commands: CommandItem[]; + } | null>(null); + + if ( + !cacheRef.current || + cacheRef.current.signature !== signature || + cacheRef.current.push !== push + ) { + cacheRef.current = { + signature, + push, + commands: resolved.map(({ destination, keywords }) => { + const Icon = destination.icon; + return { + id: destination.palette?.id ?? `nav-${destination.id}`, + label: destination.label, + group, + icon: , + keywords, + action: () => push(destination.href), + }; + }), + }; + } + + return cacheRef.current.commands; +} + +function buildSettingsCommands(push: PushFn, t: TFunction): CommandItem[] { return [ - { - id: "nav-home", - label: t("common:commandGoToHome"), - group: t(GROUP_NAVIGATION), - icon: , - keywords: searchKeywords(t, "common:commandGoToHomeKeywords"), - action: () => push(linkToTaskOverview()), - }, - { - id: "nav-tasks", - label: t("common:commandGoToAllTasks"), - group: t(GROUP_NAVIGATION), - icon: , - keywords: searchKeywords(t, "common:commandGoToAllTasksKeywords"), - action: () => push("/tasks"), - }, - { - id: "nav-settings", - label: t("common:commandGoToSettings"), - group: t(GROUP_NAVIGATION), - icon: , - keywords: searchKeywords(t, "common:commandGoToSettingsKeywords"), - action: () => push("/settings/general"), - }, - { - id: "nav-stats", - label: t("common:commandGoToStats"), - group: t(GROUP_NAVIGATION), - icon: , - keywords: searchKeywords(t, "common:commandGoToStatsKeywords"), - action: () => push("/stats"), - }, - { - id: "nav-github", - label: t("common:commandGoToGitHubDashboard"), - group: t(GROUP_NAVIGATION), - icon: , - keywords: searchKeywords(t, "common:commandGoToGitHubDashboardKeywords"), - action: () => push("/github"), - }, { id: "settings-agents", label: t("common:commandAgentsSettings"), @@ -180,14 +202,25 @@ export function GlobalCommands() { [handleOpenConfigChat, t], ); + const navigationCommands = useNavigationCommands(router.push, t); + const commands = useMemo( () => [ - ...buildNavigationCommands(router.push, t), + ...navigationCommands, + ...buildSettingsCommands(router.push, t), buildThemeCommand(resolvedTheme, setTheme, t), quickChatCommand, configChatCommand, ], - [router.push, resolvedTheme, setTheme, quickChatCommand, configChatCommand, t], + [ + navigationCommands, + router.push, + resolvedTheme, + setTheme, + quickChatCommand, + configChatCommand, + t, + ], ); useRegisterCommands(commands); diff --git a/apps/web/components/integrations/integrations-menu.test.ts b/apps/web/components/integrations/integrations-menu.test.ts index fd995da66f..8f39e360e8 100644 --- a/apps/web/components/integrations/integrations-menu.test.ts +++ b/apps/web/components/integrations/integrations-menu.test.ts @@ -2,8 +2,6 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { createElement } from "react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { - getAvailableIntegrationLinks, - getGitHubIntegrationStatus, IntegrationsMenu, IntegrationsTopbarLinks, MobileIntegrationsSection, @@ -42,10 +40,14 @@ vi.mock("@/components/state-provider", () => ({ useAppStore: ( selector: (state: { workspaces: { activeId: string | null; items: Array<{ id: string }> }; + // The navigation manifest resolves hrefs against the active mode, so + // `useInOffice` (and through it `useFeature`) now runs in this tree. + features: Record; }) => unknown, ) => selector({ workspaces: { activeId: activeWorkspaceRef.id, items: activeWorkspaceRef.items }, + features: { office: false }, }), })); @@ -87,62 +89,10 @@ afterEach(() => { activeWorkspaceRef.items = []; }); -describe("getGitHubIntegrationStatus", () => { - it("shows checking while GitHub status is loading and not configured", () => { - expect(getGitHubIntegrationStatus(status({}), true)).toEqual({ - ready: false, - label: "Checking", - }); - }); - - it("treats a configured token as ready even before live auth is green", () => { - expect(getGitHubIntegrationStatus(status({ token_configured: true }), false)).toEqual({ - ready: true, - label: "Configured", - }); - }); - - it("uses the GitHub page for authenticated status", () => { - expect(getGitHubIntegrationStatus(status({ authenticated: true }), false)).toEqual({ - ready: true, - label: "Connected", - }); - }); - - it("shows setup only when no auth or token is configured", () => { - expect(getGitHubIntegrationStatus(status({}), false)).toEqual({ - ready: false, - label: "Setup", - }); - }); -}); - -describe("getAvailableIntegrationLinks", () => { - it("returns only configured integration destinations", () => { - expect( - getAvailableIntegrationLinks({ - githubReady: true, - gitlabReady: false, - jiraAvailable: false, - linearAvailable: true, - }), - ).toEqual([ - { id: "github", label: "GitHub", href: "/github" }, - { id: "linear", label: "Linear", href: "/linear" }, - ]); - }); - - it("returns no setup destinations when integrations are unavailable", () => { - expect( - getAvailableIntegrationLinks({ - githubReady: false, - gitlabReady: false, - jiraAvailable: false, - linearAvailable: false, - }), - ).toEqual([]); - }); -}); +// `getGitHubIntegrationStatus` now lives in `hooks/use-nav-availability` with the +// rest of the manifest's availability gating, and the link table moved into +// `lib/navigation/`. Their unit coverage moved with them — see +// `hooks/use-nav-availability.test.ts` and `lib/navigation/*.test.ts`. describe("IntegrationsMenu", () => { it("opens configured integration links on hover", async () => { diff --git a/apps/web/components/integrations/integrations-menu.tsx b/apps/web/components/integrations/integrations-menu.tsx index 4a9bdda4ea..c25ef497c1 100644 --- a/apps/web/components/integrations/integrations-menu.tsx +++ b/apps/web/components/integrations/integrations-menu.tsx @@ -1,6 +1,6 @@ "use client"; -import { useEffect, useRef, useState, type ComponentType } from "react"; +import { useEffect, useRef, useState } from "react"; import Link from "@/components/routing/app-link"; import { Button } from "@kandev/ui/button"; import { @@ -11,122 +11,27 @@ import { DropdownMenuTrigger, } from "@kandev/ui/dropdown-menu"; import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; -import { - IconBrandGithub, - IconBrandGitlab, - IconHexagon, - IconPlugConnected, - IconTicket, -} from "@tabler/icons-react"; -import { useJiraAvailable } from "@/hooks/domains/jira/use-jira-availability"; -import { useLinearAvailable } from "@/hooks/domains/linear/use-linear-availability"; -import { useAzureDevOpsAvailable } from "@/hooks/domains/azure-devops/use-azure-devops-availability"; -import { useGitHubStatus } from "@/hooks/domains/github/use-github-status"; -import { useGitLabAvailable } from "@/hooks/domains/gitlab/use-task-mr"; -import { useAppStore } from "@/components/state-provider"; -import { resolvePluginIcon } from "@/lib/plugins/icons"; -import { usePluginRegistry } from "@/lib/plugins/registry"; -import type { GitHubStatus } from "@/lib/types/github"; -import { AzureDevOpsIcon } from "@/components/icons/azure-devops-icon"; +import { IconPlugConnected } from "@tabler/icons-react"; +import { DestinationRows } from "@/components/navigation/destination-rows"; +import { useAppDestinations } from "@/hooks/use-app-destinations"; type MobileIntegrationsSectionProps = { onNavigate: () => void; }; -type IntegrationId = "azure-devops" | "github" | "gitlab" | "jira" | "linear"; - -type IntegrationLink = { - id: IntegrationId; - label: string; - href: string; -}; - -type IntegrationAvailability = { - azureDevOpsAvailable?: boolean; - githubReady: boolean; - gitlabReady: boolean; - jiraAvailable: boolean; - linearAvailable: boolean; -}; - -const INTEGRATION_LINKS: IntegrationLink[] = [ - { id: "azure-devops", label: "Azure DevOps", href: "/azure-devops" }, - { id: "github", label: "GitHub", href: "/github" }, - { id: "gitlab", label: "GitLab", href: "/gitlab" }, - { id: "jira", label: "Jira", href: "/jira" }, - { id: "linear", label: "Linear", href: "/linear" }, -]; - -const INTEGRATION_ICONS = { - "azure-devops": AzureDevOpsIcon, - github: IconBrandGithub, - gitlab: IconBrandGitlab, - jira: IconTicket, - linear: IconHexagon, -} satisfies Record>; - const HOVER_CLOSE_DELAY_MS = 180; -export function getAvailableIntegrationLinks({ - azureDevOpsAvailable, - githubReady, - gitlabReady, - jiraAvailable, - linearAvailable, -}: IntegrationAvailability): IntegrationLink[] { - return INTEGRATION_LINKS.filter((link) => { - if (link.id === "azure-devops") return !!azureDevOpsAvailable; - if (link.id === "github") return githubReady; - if (link.id === "gitlab") return gitlabReady; - if (link.id === "jira") return jiraAvailable; - return linearAvailable; - }); -} - -function getStatusLabel(loading: boolean | undefined): string { - return loading ? "Checking" : "Setup"; -} - -export function getGitHubIntegrationStatus(status: GitHubStatus | null, loading: boolean) { - if (status?.authenticated) return { ready: true, label: "Connected" }; - if (status?.token_configured) return { ready: true, label: "Configured" }; - return { ready: false, label: getStatusLabel(loading) }; -} - -export function useConfiguredIntegrationLinks(): IntegrationLink[] { - // Jira and Linear are per-workspace integrations, so their availability must - // be checked against the active workspace. Omitting the id makes the backend - // fall back to a legacy default-workspace resolver that can point at the - // wrong workspace, hiding a configured integration from the sidebar. GitHub, - // Jira, and Linear all follow the active workspace; GitLab remains install-wide. - const activeWorkspaceId = useAppStore((s) => s.workspaces.activeId); - const activeWorkspaceExists = useAppStore((s) => - s.workspaces.items.some((item) => item.id === s.workspaces.activeId), - ); - // Guard against a stale active id: if the active workspace was removed but - // activeId was not reconciled (e.g. setWorkspaces keeps a non-null id), - // scoping to the deleted id would return no config and hide the links even - // when another workspace is configured. Fall back to null so the backend's - // default-workspace resolution applies instead. - const scopedWorkspaceId = activeWorkspaceExists ? activeWorkspaceId : null; - const { status, loading } = useGitHubStatus(); - const gitlabAvailable = useGitLabAvailable(); - const jiraAvailable = useJiraAvailable(scopedWorkspaceId); - const linearAvailable = useLinearAvailable(scopedWorkspaceId); - const azureDevOpsAvailable = useAzureDevOpsAvailable(scopedWorkspaceId); - const githubStatus = getGitHubIntegrationStatus(status, loading); - - return getAvailableIntegrationLinks({ - azureDevOpsAvailable, - githubReady: githubStatus.ready, - gitlabReady: gitlabAvailable, - jiraAvailable, - linearAvailable, - }); +/** + * Configured integration destinations, in manifest order. Ids, labels, hrefs and + * icons come from `lib/navigation/core-destinations.ts`; availability comes from + * `useNavAvailability` through `useAppDestinations`. + */ +function useIntegrationDestinations() { + return useAppDestinations("sidebar", "integrations"); } export function IntegrationsMenu() { - const links = useConfiguredIntegrationLinks(); + const links = useIntegrationDestinations(); const [open, setOpen] = useState(false); const closeTimeoutRef = useRef | null>(null); @@ -181,7 +86,7 @@ export function IntegrationsMenu() { > Integrations {links.map((link) => { - const Icon = INTEGRATION_ICONS[link.id]; + const Icon = link.icon; return ( @@ -197,13 +102,13 @@ export function IntegrationsMenu() { } export function IntegrationsTopbarLinks() { - const links = useConfiguredIntegrationLinks(); + const links = useIntegrationDestinations(); if (links.length === 0) return null; return ( <> {links.map((link) => { - const Icon = INTEGRATION_ICONS[link.id]; + const Icon = link.icon; return ( @@ -221,65 +126,27 @@ export function IntegrationsTopbarLinks() { ); } -function MobileIntegrationRow({ - href, - label, - icon: Icon, - testId, - onNavigate, -}: { - href: string; - label: string; - icon: ComponentType<{ className?: string }>; - testId?: string; - onNavigate: () => void; -}) { - return ( - - ); -} - /** * Mobile counterpart to the desktop sidebar Integrations section: the * hamburger-sheet surface that exposes the first-party integration links plus * any plugin-registered nav items targeting this section * (`registerNavItem({ section: "integrations" })`), matching the desktop - * `IntegrationsSection`. + * `IntegrationsSection`. Both come from the navigation manifest, so the two + * surfaces cannot drift apart. */ export function MobileIntegrationsSection({ onNavigate }: MobileIntegrationsSectionProps) { - const links = useConfiguredIntegrationLinks(); - const registry = usePluginRegistry(); - const pluginItems = registry.getNavItems().filter((item) => item.section === "integrations"); + const destinations = useAppDestinations("mobileMenu", "integrations"); - if (links.length === 0 && pluginItems.length === 0) return null; + if (destinations.length === 0) return null; return (
Integrations
- {links.map((link) => ( - - ))} - {pluginItems.map((item) => ( - - ))} +
); } diff --git a/apps/web/components/kanban/mobile-menu-sheet.tsx b/apps/web/components/kanban/mobile-menu-sheet.tsx index b3af3921df..b49f007f96 100644 --- a/apps/web/components/kanban/mobile-menu-sheet.tsx +++ b/apps/web/components/kanban/mobile-menu-sheet.tsx @@ -1,7 +1,6 @@ "use client"; import { type ReactNode, type RefObject, useRef, useState } from "react"; import { useRouter } from "@/lib/routing/client-router"; -import Link from "@/components/routing/app-link"; import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@kandev/ui/sheet"; import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@kandev/ui/drawer"; import { Button } from "@kandev/ui/button"; @@ -13,13 +12,15 @@ import { IconActivity, IconLayoutKanban, IconList, - IconSettings, IconStethoscope, IconTimeline, } from "@tabler/icons-react"; import { AppSidebarWorkspacePicker } from "@/components/app-sidebar/app-sidebar-workspace-picker"; import { MobileIntegrationsSection } from "@/components/integrations/integrations-menu"; +import { DestinationRows } from "@/components/navigation/destination-rows"; import { MobilePluginNavSection } from "@/components/plugins/mobile-plugin-nav-section"; +import { useStaticDestinations } from "@/hooks/use-app-destinations"; +import { MOBILE_MENU_UTILITY_SECTIONS } from "@/lib/navigation/surface-policy"; import { TaskSearchInput } from "./task-search-input"; import { MobileTasksListOptions, @@ -293,6 +294,10 @@ function MobileUtilityActions({ }) { const { enabled: statusDrawerEnabled, issueSeverity, openStatusDrawer } = useAppStatusDrawer(); const issueDetails = useConnectionIssueCopy(issueSeverity); + // Stats, Settings, and anything else added to the manifest's insight/utility + // sections. Before the manifest, this block hardcoded a Settings link and + // Stats had no phone entry point at all. + const destinations = useStaticDestinations("mobileMenu", MOBILE_MENU_UTILITY_SECTIONS); const closeSheet = () => onOpenChange(false); const openHealth = () => { closeSheet(); @@ -330,16 +335,11 @@ function MobileUtilityActions({ )} )} - + + ); +} diff --git a/apps/web/components/plugins/mobile-plugin-nav-section.tsx b/apps/web/components/plugins/mobile-plugin-nav-section.tsx index 07cc4a73c8..586764d857 100644 --- a/apps/web/components/plugins/mobile-plugin-nav-section.tsx +++ b/apps/web/components/plugins/mobile-plugin-nav-section.tsx @@ -1,8 +1,8 @@ "use client"; -import { Button } from "@kandev/ui/button"; -import Link from "@/components/routing/app-link"; -import { resolvePluginIcon } from "@/lib/plugins/icons"; +import { DestinationRows } from "@/components/navigation/destination-rows"; +import { resolveDestinations } from "@/lib/navigation/resolve-destinations"; +import { NO_WORKSPACE_CONTEXT } from "@/lib/navigation/surface-policy"; import { usePluginRegistry } from "@/lib/plugins/registry"; type MobilePluginNavSectionProps = { @@ -20,33 +20,26 @@ type MobilePluginNavSectionProps = { */ export function MobilePluginNavSection({ onNavigate }: MobilePluginNavSectionProps) { const registry = usePluginRegistry(); - const items = registry.getNavItems().filter((item) => (item.section ?? "main") === "main"); + // Resolved directly rather than through `useStaticDestinations`: this group's + // hrefs are static plugin paths, so it needs neither workspace context nor the + // availability subscription. Matches the desktop rail in `plugin-nav-items.tsx`. + const destinations = resolveDestinations({ + surface: "mobileMenu", + section: "plugins", + ctx: NO_WORKSPACE_CONTEXT, + pluginItems: registry.getNavRegistrations(), + }); - if (items.length === 0) return null; + if (destinations.length === 0) return null; return (
Plugins
- {items.map((item) => { - const Icon = resolvePluginIcon(item.icon); - return ( - - ); - })} +
); } diff --git a/apps/web/components/plugins/plugin-nav-items.test.tsx b/apps/web/components/plugins/plugin-nav-items.test.tsx index 259603015b..54790038e2 100644 --- a/apps/web/components/plugins/plugin-nav-items.test.tsx +++ b/apps/web/components/plugins/plugin-nav-items.test.tsx @@ -60,6 +60,19 @@ describe("PluginNavItems", () => { expect(screen.queryByTestId("plugin-nav-item-settings-item")).toBeNull(); }); + it("keeps integration items out of the main plugin rail", () => { + pluginRegistry.forPlugin("plugin-a").registerNavItem({ + id: "integration-item", + label: "Integration Item", + path: "/plugins/integration-item", + section: "integrations", + }); + + renderNavItems(); + + expect(screen.queryByTestId("plugin-nav-item-integration-item")).toBeNull(); + }); + it("renders the named curated icon, falling back to the puzzle glyph", () => { pluginRegistry .forPlugin("plugin-a") diff --git a/apps/web/components/plugins/plugin-nav-items.tsx b/apps/web/components/plugins/plugin-nav-items.tsx index 8be97ad8dc..a9254da97a 100644 --- a/apps/web/components/plugins/plugin-nav-items.tsx +++ b/apps/web/components/plugins/plugin-nav-items.tsx @@ -1,7 +1,8 @@ "use client"; import { AppSidebarNavItem } from "@/components/app-sidebar/app-sidebar-nav-item"; -import { resolvePluginIcon } from "@/lib/plugins/icons"; +import { resolveDestinations } from "@/lib/navigation/resolve-destinations"; +import { NO_WORKSPACE_CONTEXT } from "@/lib/navigation/surface-policy"; import { usePluginRegistry } from "@/lib/plugins/registry"; type PluginNavItemsProps = { @@ -15,21 +16,31 @@ type PluginNavItemsProps = { * string resolves against the curated map in `lib/plugins/icons.ts`; * unknown/missing names fall back to a generic puzzle-piece glyph. Renders * nothing while the registry holds no "main"-section items. + * + * Section routing and icon resolution come from the navigation manifest, so this + * rail and the mobile menu's plugin group cannot disagree about which items + * belong here. Resolved directly rather than through `useStaticDestinations`: + * plugin paths are static, so there is no reason to read workspace context. */ export function PluginNavItems({ collapsed }: PluginNavItemsProps) { const registry = usePluginRegistry(); - const items = registry.getNavItems().filter((item) => (item.section ?? "main") === "main"); + const destinations = resolveDestinations({ + surface: "sidebar", + section: "plugins", + ctx: NO_WORKSPACE_CONTEXT, + pluginItems: registry.getNavRegistrations(), + }); return ( <> - {items.map((item) => ( + {destinations.map((destination) => ( ))} diff --git a/apps/web/e2e/tests/integrations/mobile-integrations-nav.spec.ts b/apps/web/e2e/tests/integrations/mobile-integrations-nav.spec.ts index 4192802f98..a0c5a0e6ba 100644 --- a/apps/web/e2e/tests/integrations/mobile-integrations-nav.spec.ts +++ b/apps/web/e2e/tests/integrations/mobile-integrations-nav.spec.ts @@ -16,8 +16,8 @@ test.describe("Integrations section on mobile", () => { testPage, apiClient, }) => { - // Make GitHub report authenticated so useConfiguredIntegrationLinks yields - // the GitHub link before the page loads its status. + // Make GitHub report authenticated so the navigation manifest resolves the + // GitHub destination before the page loads its status. await apiClient.mockGitHubReset(); await apiClient.mockGitHubSetUser("test-user"); diff --git a/apps/web/e2e/tests/layout/mobile-stats-nav.spec.ts b/apps/web/e2e/tests/layout/mobile-stats-nav.spec.ts new file mode 100644 index 0000000000..d2180465a4 --- /dev/null +++ b/apps/web/e2e/tests/layout/mobile-stats-nav.spec.ts @@ -0,0 +1,36 @@ +import { test, expect } from "../../fixtures/test-base"; +import { MobileKanbanPage } from "../../pages/mobile-kanban-page"; + +/** + * Mobile reachability for `/stats`. The route's only entry points used to be the + * desktop-only sidebar footer (`hidden md:block`) and a keyboard-only command + * palette entry, so on a phone the page could only be reached by typing the URL. + * It is now a navigation-manifest destination (`lib/navigation/core-destinations.ts`), + * which puts it in the hamburger sheet's utility group. + */ +test.describe("Stats on mobile", () => { + test("exposes Stats in the hamburger sheet and navigates", async ({ testPage }) => { + const kanban = new MobileKanbanPage(testPage); + await kanban.goto(); + + await kanban.mobileMenuButton.click(); + + // Scope to the open menu sheet so we never match the display:none desktop + // sidebar, which carries the same "Stats" accessible name. + const sheet = testPage.getByRole("dialog"); + const statsLink = sheet.getByRole("link", { name: "Stats" }); + await expect(statsLink).toBeVisible({ timeout: 10_000 }); + expect(await statsLink.getAttribute("href")).toBe("/stats"); + + await statsLink.click(); + + await expect(testPage).toHaveURL(/\/stats$/); + await expect(sheet).toBeHidden(); + // Assert content unique to the rendered stats page. The "Statistics" topbar + // title also renders for the no-workspace and error states, so it would pass + // on a page that never loaded. + await expect(testPage.getByRole("button", { name: "Copy Stats" })).toBeVisible({ + timeout: 15_000, + }); + }); +}); diff --git a/apps/web/hooks/use-app-destinations.test.tsx b/apps/web/hooks/use-app-destinations.test.tsx new file mode 100644 index 0000000000..6015f94a9a --- /dev/null +++ b/apps/web/hooks/use-app-destinations.test.tsx @@ -0,0 +1,96 @@ +import { renderHook } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"; + +const availabilitySpy = vi.hoisted(() => vi.fn(() => ({ github: true }))); + +vi.mock("@/hooks/use-nav-availability", () => ({ + useNavAvailability: availabilitySpy, +})); + +vi.mock("@/components/state-provider", () => ({ + useAppStore: ( + selector: (state: { + workspaces: { activeId: string | null }; + features: Record; + }) => unknown, + ) => selector({ workspaces: { activeId: "ws-1" }, features: { office: false } }), +})); + +vi.mock("@/lib/routing/client-router", () => ({ + usePathname: () => "/", +})); + +vi.mock("@/lib/plugins/registry", () => ({ + usePluginRegistry: () => ({ getNavRegistrations: () => [] }), +})); + +import { useAppDestinations, useStaticDestinations } from "./use-app-destinations"; + +describe("useStaticDestinations", () => { + beforeEach(() => availabilitySpy.mockClear()); + afterEach(() => vi.clearAllMocks()); + + it("rejects availability-gated sections at compile time", () => { + type StaticSection = NonNullable[1]>; + + expectTypeOf<"insights">().toExtend(); + expectTypeOf<"integrations">().not.toExtend(); + }); + + it("requires an explicit section on every surface but the palette", () => { + // Omitting the section resolves gated sections too, against an empty + // availability map — harmless for the palette (its gated entry opts out), + // but on any other surface it would silently drop unconfigured integrations. + expectTypeOf(useStaticDestinations).toBeCallableWith("palette"); + const offPalette = () => { + // @ts-expect-error - a non-palette surface must name its sections + useStaticDestinations("sidebar"); + }; + + expect(offPalette).toBeTypeOf("function"); + }); + + /** + * The regression this guards: every per-integration auth probe runs its own + * 90s `setInterval` per consumer, so a surface that renders no gated + * destination must not subscribe to availability just to draw a static link. + */ + it("does not subscribe to integration availability", () => { + renderHook(() => useStaticDestinations("sidebar", "insights")); + + expect(availabilitySpy).not.toHaveBeenCalled(); + }); + + it("still resolves the ungated destinations it is asked for", () => { + const { result } = renderHook(() => useStaticDestinations("sidebar", "insights")); + + expect(result.current.map((destination) => destination.id)).toEqual(["stats"]); + }); + + it("resolves the palette without availability, including the opted-out GitHub entry", () => { + const { result } = renderHook(() => useStaticDestinations("palette")); + + expect(availabilitySpy).not.toHaveBeenCalled(); + expect(result.current.map((destination) => destination.palette?.id)).toContain("nav-github"); + }); +}); + +describe("useAppDestinations", () => { + beforeEach(() => availabilitySpy.mockClear()); + afterEach(() => vi.clearAllMocks()); + + it("only accepts availability-gated sections at compile time", () => { + type GatedSection = Parameters[1]; + + expectTypeOf<"integrations">().toExtend(); + expectTypeOf<"insights">().not.toExtend(); + }); + + it("subscribes to availability so gated sections can be filtered", () => { + const { result } = renderHook(() => useAppDestinations("sidebar", "integrations")); + + expect(availabilitySpy).toHaveBeenCalled(); + // Only GitHub is configured in the mocked availability map. + expect(result.current.map((destination) => destination.id)).toEqual(["github"]); + }); +}); diff --git a/apps/web/hooks/use-app-destinations.ts b/apps/web/hooks/use-app-destinations.ts new file mode 100644 index 0000000000..6c8e6b46f7 --- /dev/null +++ b/apps/web/hooks/use-app-destinations.ts @@ -0,0 +1,93 @@ +"use client"; + +import { useTranslation } from "react-i18next"; +import { useAppStore } from "@/components/state-provider"; +import { useInOffice } from "@/hooks/use-in-office"; +import { useNavAvailability } from "@/hooks/use-nav-availability"; +import { resolveDestinations } from "@/lib/navigation/resolve-destinations"; +import { usePluginRegistry } from "@/lib/plugins/registry"; +import type { + GatedNavSection, + NavContext, + NavSurface, + ResolvedDestination, + StaticNavSection, +} from "@/lib/navigation/types"; + +/** Active workspace and mode, the inputs a destination href may depend on. */ +export function useNavContext(): NavContext { + const workspaceId = useAppStore((s) => s.workspaces.activeId); + const inOffice = useInOffice(); + return { workspaceId, inOffice }; +} + +/** + * Destinations for a surface that renders availability-gated sections — today + * that means the integrations groups (see `GATED_SECTIONS`). + * + * Subscribes to `useNavAvailability`, and therefore to the per-integration auth + * probes: Jira, Linear and Azure DevOps each run a fetch plus a 90s + * `setInterval` per mounted consumer + * (`hooks/domains/integrations/use-integration-availability.ts`). Use + * `useStaticDestinations` for ungated sections so a nav surface doesn't add + * background polling just to render a static link. + * + * Not memoized: the availability map is rebuilt each render, so a `useMemo` here + * would never hit. Consumers map the result straight into JSX. + */ +export function useAppDestinations( + surface: NavSurface, + section: GatedNavSection | GatedNavSection[], +): ResolvedDestination[] { + const { t } = useTranslation(); + const ctx = useNavContext(); + const availability = useNavAvailability(); + const registry = usePluginRegistry(); + + return resolveDestinations({ + surface, + ...(section ? { section } : {}), + ctx, + availability, + translate: t, + pluginItems: registry.getNavRegistrations(), + }); +} + +/** + * Destinations for a surface whose sections carry no availability gate — the + * sidebar footer, the mobile menu's utility group, and the command palette + * (whose one gated entry opts out via `palette.ignoreRequires`). + * + * Identical to `useAppDestinations` minus the availability subscription, so + * these surfaces cost no background requests. `core-destinations.test.ts` enforces + * the invariant that makes this safe: nothing outside `GATED_SECTIONS` declares + * `requires`, and every palette entry is either ungated or opted out. + * + * Only the palette may omit `section` (first overload). Omitting it resolves + * every section, gated ones included, against an empty availability map — which + * is correct only because the palette's single gated entry opts out via + * `palette.ignoreRequires`. On any other surface that would silently drop every + * unconfigured integration, so the section is required there. + */ +export function useStaticDestinations(surface: "palette"): ResolvedDestination[]; +export function useStaticDestinations( + surface: NavSurface, + section: StaticNavSection | StaticNavSection[], +): ResolvedDestination[]; +export function useStaticDestinations( + surface: NavSurface, + section?: StaticNavSection | StaticNavSection[], +): ResolvedDestination[] { + const { t } = useTranslation(); + const ctx = useNavContext(); + const registry = usePluginRegistry(); + + return resolveDestinations({ + surface, + ...(section ? { section } : {}), + ctx, + translate: t, + pluginItems: registry.getNavRegistrations(), + }); +} diff --git a/apps/web/hooks/use-nav-availability.test.ts b/apps/web/hooks/use-nav-availability.test.ts new file mode 100644 index 0000000000..c8f7aadb79 --- /dev/null +++ b/apps/web/hooks/use-nav-availability.test.ts @@ -0,0 +1,109 @@ +import { renderHook } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { getGitHubIntegrationStatus } from "./use-nav-availability"; +import type { GitHubStatus } from "@/lib/types/github"; + +const mocks = vi.hoisted(() => { + const workspaceId = "workspace-1"; + return { + workspaceId, + state: { + workspaces: { + activeId: workspaceId as string | null, + items: [{ id: workspaceId }], + }, + }, + azureDevOpsAvailable: vi.fn(() => false), + gitlabAvailable: vi.fn(() => false), + jiraAvailable: vi.fn(() => false), + linearAvailable: vi.fn(() => false), + }; +}); + +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (state: typeof mocks.state) => unknown) => selector(mocks.state), +})); +vi.mock("@/hooks/domains/azure-devops/use-azure-devops-availability", () => ({ + useAzureDevOpsAvailable: mocks.azureDevOpsAvailable, +})); +vi.mock("@/hooks/domains/github/use-github-status", () => ({ + useGitHubStatus: () => ({ status: null, loading: false }), +})); +vi.mock("@/hooks/domains/gitlab/use-task-mr", () => ({ + useGitLabAvailable: mocks.gitlabAvailable, +})); +vi.mock("@/hooks/domains/jira/use-jira-availability", () => ({ + useJiraAvailable: mocks.jiraAvailable, +})); +vi.mock("@/hooks/domains/linear/use-linear-availability", () => ({ + useLinearAvailable: mocks.linearAvailable, +})); + +import { useNavAvailability } from "./use-nav-availability"; + +function status(overrides: Partial): GitHubStatus { + return { + authenticated: false, + username: "", + auth_method: "none", + token_configured: false, + required_scopes: [], + ...overrides, + }; +} + +describe("getGitHubIntegrationStatus", () => { + it("shows checking while GitHub status is loading and not configured", () => { + expect(getGitHubIntegrationStatus(status({}), true)).toEqual({ + ready: false, + label: "Checking", + }); + }); + + it("treats a configured token as ready even before live auth is green", () => { + expect(getGitHubIntegrationStatus(status({ token_configured: true }), false)).toEqual({ + ready: true, + label: "Configured", + }); + }); + + it("uses the Connected label for authenticated status", () => { + expect(getGitHubIntegrationStatus(status({ authenticated: true }), false)).toEqual({ + ready: true, + label: "Connected", + }); + }); + + it("shows setup only when no auth or token is configured", () => { + expect(getGitHubIntegrationStatus(status({}), false)).toEqual({ + ready: false, + label: "Setup", + }); + }); +}); + +describe("useNavAvailability", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.state.workspaces.activeId = mocks.workspaceId; + mocks.state.workspaces.items = [{ id: mocks.workspaceId }]; + }); + + it("scopes workspace integrations to the active workspace", () => { + renderHook(() => useNavAvailability()); + + expect(mocks.jiraAvailable).toHaveBeenCalledWith(mocks.workspaceId); + expect(mocks.linearAvailable).toHaveBeenCalledWith(mocks.workspaceId); + expect(mocks.azureDevOpsAvailable).toHaveBeenCalledWith(mocks.workspaceId); + }); + + it("falls back to default workspace resolution for a stale active id", () => { + mocks.state.workspaces.items = [{ id: "workspace-2" }]; + + renderHook(() => useNavAvailability()); + + expect(mocks.jiraAvailable).toHaveBeenCalledWith(null); + expect(mocks.linearAvailable).toHaveBeenCalledWith(null); + expect(mocks.azureDevOpsAvailable).toHaveBeenCalledWith(null); + }); +}); diff --git a/apps/web/hooks/use-nav-availability.ts b/apps/web/hooks/use-nav-availability.ts new file mode 100644 index 0000000000..a08208869f --- /dev/null +++ b/apps/web/hooks/use-nav-availability.ts @@ -0,0 +1,73 @@ +"use client"; + +import { useAppStore } from "@/components/state-provider"; +import { useAzureDevOpsAvailable } from "@/hooks/domains/azure-devops/use-azure-devops-availability"; +import { useGitHubStatus } from "@/hooks/domains/github/use-github-status"; +import { useGitLabAvailable } from "@/hooks/domains/gitlab/use-task-mr"; +import { useJiraAvailable } from "@/hooks/domains/jira/use-jira-availability"; +import { useLinearAvailable } from "@/hooks/domains/linear/use-linear-availability"; +import type { AvailabilityMap } from "@/lib/navigation/types"; +import type { GitHubStatus } from "@/lib/types/github"; + +function getStatusLabel(loading: boolean | undefined): string { + return loading ? "Checking" : "Setup"; +} + +export function getGitHubIntegrationStatus(status: GitHubStatus | null, loading: boolean) { + if (status?.authenticated) return { ready: true, label: "Connected" }; + if (status?.token_configured) return { ready: true, label: "Configured" }; + return { ready: false, label: getStatusLabel(loading) }; +} + +/** + * Availability map the navigation manifest filters on + * (`lib/navigation/`) — currently which integrations are + * configured. Extend here when a destination gains a gate. + * + * Extracted from `useConfiguredIntegrationLinks` so the sidebar link list and the + * mobile menu gate on one implementation instead of each calling the five domain + * hooks themselves. + * + * Availability is **not** deduplicated across consumers. GitHub and GitLab are + * store-backed, but Jira, Linear and Azure DevOps go through + * `useIntegrationAuthed`, which owns a fetch plus a 90s `setInterval` per mounted + * consumer (`hooks/domains/integrations/use-integration-availability.ts`). So each + * mounted caller of this hook may add its own polling subscription: keep the + * callers to the surfaces that render gated sections, and use + * `useStaticDestinations` everywhere else. Deduplicating this properly means + * hoisting the probes into the store, which is a change to those domain hooks + * rather than to the navigation manifest. + * + * Not to be confused with `hooks/domains/integrations/use-integration-availability`, + * which is the generic per-integration primitive these hooks are built on. + */ +export function useNavAvailability(): AvailabilityMap { + // Jira and Linear are per-workspace integrations, so their availability must + // be checked against the active workspace. Omitting the id makes the backend + // fall back to a legacy default-workspace resolver that can point at the + // wrong workspace, hiding a configured integration from the sidebar. GitHub, + // Jira, and Linear all follow the active workspace; GitLab remains install-wide. + const activeWorkspaceId = useAppStore((s) => s.workspaces.activeId); + const activeWorkspaceExists = useAppStore((s) => + s.workspaces.items.some((item) => item.id === s.workspaces.activeId), + ); + // Guard against a stale active id: if the active workspace was removed but + // activeId was not reconciled (e.g. setWorkspaces keeps a non-null id), + // scoping to the deleted id would return no config and hide the links even + // when another workspace is configured. Fall back to null so the backend's + // default-workspace resolution applies instead. + const scopedWorkspaceId = activeWorkspaceExists ? activeWorkspaceId : null; + const { status, loading } = useGitHubStatus(); + const gitlabAvailable = useGitLabAvailable(); + const jiraAvailable = useJiraAvailable(scopedWorkspaceId); + const linearAvailable = useLinearAvailable(scopedWorkspaceId); + const azureDevOpsAvailable = useAzureDevOpsAvailable(scopedWorkspaceId); + + return { + "azure-devops": !!azureDevOpsAvailable, + github: getGitHubIntegrationStatus(status, loading).ready, + gitlab: gitlabAvailable, + jira: jiraAvailable, + linear: linearAvailable, + }; +} diff --git a/apps/web/lib/navigation/core-destinations.test.ts b/apps/web/lib/navigation/core-destinations.test.ts new file mode 100644 index 0000000000..58322b3808 --- /dev/null +++ b/apps/web/lib/navigation/core-destinations.test.ts @@ -0,0 +1,186 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { APP_DESTINATIONS } from "./core-destinations"; +import { resolveDestinations } from "./resolve-destinations"; +import { + MOBILE_MENU_EXEMPTIONS, + MOBILE_MENU_SECTIONS, + NO_WORKSPACE_CONTEXT, +} from "./surface-policy"; +import { GATED_SECTIONS, type AvailabilityMap } from "./types"; + +const ALL_INTEGRATIONS: AvailabilityMap = { + "azure-devops": true, + github: true, + gitlab: true, + jira: true, + linear: true, +}; + +function ids(destinations: { id: string }[]): string[] { + return destinations.map((destination) => destination.id); +} + +describe("manifest invariants", () => { + it("gives every destination a unique id", () => { + expect(new Set(ids(APP_DESTINATIONS)).size).toBe(APP_DESTINATIONS.length); + }); + + it("gives every destination exactly one of label or labelKey", () => { + // Also a compile error (`DestinationCopy`); kept as a runtime check because + // an entry can still reach this array through a cast. + for (const destination of APP_DESTINATIONS) { + expect( + Boolean(destination.label) !== Boolean(destination.labelKey), + `${destination.id} must set either label (brand name) or labelKey (translated copy)`, + ).toBe(true); + } + }); + + it("declares at least one surface per destination", () => { + for (const destination of APP_DESTINATIONS) { + expect(destination.surfaces.length, `${destination.id} is offered nowhere`).toBeGreaterThan( + 0, + ); + } + }); + + it("gives every palette destination a command id and copy", () => { + const paletteDestinations = APP_DESTINATIONS.filter((destination) => + destination.surfaces.includes("palette"), + ); + + expect(paletteDestinations.length).toBeGreaterThan(0); + for (const destination of paletteDestinations) { + expect(destination.palette?.id, `${destination.id} needs a stable command id`).toBeTruthy(); + expect(destination.palette?.labelKey, `${destination.id} needs command copy`).toBeTruthy(); + } + }); +}); + +/** + * The guardrails that make the manifest worth having. Both encode bugs the app + * actually had: `/stats` reachable only from the desktop sidebar, and new routes + * shipping with no navigation entry at all. + */ +describe("navigation coverage guardrails", () => { + it("offers every destination in the mobile menu unless it is explicitly exempt", () => { + // Deliberately stricter than "sidebar destinations must also be mobile": + // a palette-only destination is just as unreachable on a phone, so every + // omission has to be justified in MOBILE_MENU_EXEMPTIONS. + const missing = APP_DESTINATIONS.filter( + (destination) => + !destination.surfaces.includes("mobileMenu") && !(destination.id in MOBILE_MENU_EXEMPTIONS), + ); + + expect( + ids(missing), + "the sidebar is hidden below md, so a destination that is not in the mobile menu is unreachable on a phone — add the mobileMenu surface, or record the mobile affordance that owns it in MOBILE_MENU_EXEMPTIONS", + ).toEqual([]); + }); + + it("keeps the exemption list honest", () => { + for (const [id, reason] of Object.entries(MOBILE_MENU_EXEMPTIONS)) { + const destination = APP_DESTINATIONS.find((entry) => entry.id === id); + expect(destination, `${id} is exempt but is not a destination`).toBeTruthy(); + expect( + destination?.surfaces.includes("mobileMenu"), + `${id} is offered in the mobile menu, so it should not be exempt`, + ).toBe(false); + expect(reason.length, `${id} needs a reason naming the surface that owns it`).toBeGreaterThan( + 10, + ); + } + }); + + it("confines availability gates to the sections that resolve availability", () => { + // `useStaticDestinations` skips the availability subscription (which polls + // per consumer). That is only safe while gates stay inside GATED_SECTIONS. + const strays = APP_DESTINATIONS.filter( + (destination) => + destination.requires && !GATED_SECTIONS.some((section) => section === destination.section), + ); + + expect( + ids(strays), + `a gated destination outside ${GATED_SECTIONS.join(", ")} would silently disappear on surfaces that use useStaticDestinations`, + ).toEqual([]); + }); + + it("keeps every palette destination resolvable without availability", () => { + // The palette resolves statically, so a gated entry must opt out explicitly. + const unresolvable = APP_DESTINATIONS.filter( + (destination) => + destination.surfaces.includes("palette") && + destination.requires && + !destination.palette?.ignoreRequires, + ); + + expect( + ids(unresolvable), + "a gated palette entry needs palette.ignoreRequires, or the palette must switch to useAppDestinations", + ).toEqual([]); + }); + + it("puts every mobile-menu destination in a section the mobile menu renders", () => { + const unrendered = APP_DESTINATIONS.filter( + (destination) => + destination.surfaces.includes("mobileMenu") && + !MOBILE_MENU_SECTIONS.includes(destination.section), + ); + + expect( + ids(unrendered), + `mobileMenu destinations must live in one of: ${MOBILE_MENU_SECTIONS.join(", ")}`, + ).toEqual([]); + }); + + it("covers every first-class top-level route with a destination", () => { + // Pre-auth routes: the SPA shell bounces them, so they are never navigation + // targets. `/` (the kanban catch-all) and the nested `/settings` and + // `/office` trees are not part of this switch; Office is still owned by the + // sidebar footer's mode toggle rather than a manifest destination. + const NOT_NAVIGABLE = ["/login", "/setup", "/invite"]; + + // Source-scanned rather than imported: the route table is a `switch` over + // string literals, so there is no route list to read at runtime. Typed route + // ids shared by routing and navigation would replace this — see the + // open-decisions note in `surface-policy.ts`. Until then the length floor + // below turns a restructured switch into a failure rather than a silent pass. + const here = path.dirname(fileURLToPath(import.meta.url)); + const source = readFileSync(path.join(here, "../../src/spa-routes.tsx"), "utf8"); + const topLevelRoutes = [...source.matchAll(/case "(\/[a-z0-9-]*)":/g)].map((match) => match[1]); + + expect( + topLevelRoutes.length, + "no top-level routes were found in src/spa-routes.tsx — the switch was restructured, so this guardrail needs updating rather than passing vacuously", + ).toBeGreaterThan(5); + + const covered = new Set( + resolveDestinations({ + surface: "sidebar", + ctx: NO_WORKSPACE_CONTEXT, + availability: ALL_INTEGRATIONS, + }) + .concat( + resolveDestinations({ + surface: "palette", + ctx: NO_WORKSPACE_CONTEXT, + availability: ALL_INTEGRATIONS, + }), + ) + .map((destination) => destination.href.split("?")[0]), + ); + + const uncovered = topLevelRoutes.filter( + (route) => !NOT_NAVIGABLE.includes(route) && !covered.has(route), + ); + + expect( + uncovered, + "every first-class route needs a navigation manifest entry (or an explicit NOT_NAVIGABLE reason)", + ).toEqual([]); + }); +}); diff --git a/apps/web/lib/navigation/core-destinations.ts b/apps/web/lib/navigation/core-destinations.ts new file mode 100644 index 0000000000..6f3ebc4026 --- /dev/null +++ b/apps/web/lib/navigation/core-destinations.ts @@ -0,0 +1,171 @@ +/** + * The app's first-party navigation catalog: one declaration per top-level + * destination, in the order surfaces should offer them. + * + * Why this exists: each surface used to hardcode its own list. Adding a + * destination meant editing three unrelated files, and forgetting one silently + * dropped it from that surface — `/stats` was reachable only from the + * desktop-only sidebar footer and a keyboard-only palette command, so it had no + * phone entry point at all. `core-destinations.test.ts` now fails when a + * first-class route has no manifest entry, or when a destination is missing from + * the mobile menu without a recorded reason. + * + * What this manifest currently drives: the sidebar's integrations section and + * footer insight buttons, the sidebar and mobile plugin nav groups, the mobile + * menu's integrations and utility groups, and the command palette's Navigation + * group. + * + * What it does not drive yet (deliberately, see the notes below): the sidebar's + * primary nav and the mobile header/View-toggle affordances for Home and Tasks, + * action-shaped controls (New task, Inbox, quick chat, the settings gear, the + * Office↔Kanban switch), the settings tree, and Office's own navigation section. + * Those stay bespoke until the shared-shell work lands. + */ +import { + IconBrandGithub, + IconBrandGitlab, + IconChartBar, + IconHexagon, + IconHome, + IconList, + IconSettings, + IconTicket, +} from "@tabler/icons-react"; +import { AzureDevOpsIcon } from "@/components/icons/azure-devops-icon"; +import { linkToTaskOverview, linkToTasks } from "@/lib/links"; +import { EVERYWHERE, MENU_AND_PALETTE, PALETTE_ONLY, SIDEBAR_AND_MENU } from "./surface-policy"; +import type { Destination } from "./types"; + +/** + * Not listed here, on purpose: + * - Home/Inbox/New task in the sidebar's primary nav and the Office↔Kanban + * toggle — those carry badge counts, quick-chat launches, or `localStorage` + * side effects. They are actions, not plain destinations; folding actions in + * is a follow-up that should reuse the command registry. + * - `/settings/
` deep links (the palette's Settings group) — those are + * shortcuts into one destination, not destinations of their own. + * - `/login`, `/setup`, `/invite` — pre-auth routes, intentionally unlisted. + */ +export const APP_DESTINATIONS: Destination[] = [ + { + id: "home", + labelKey: "sidebar:home", + icon: IconHome, + section: "primary", + href: (ctx) => + ctx.inOffice ? "/office" : linkToTaskOverview({ workspaceId: ctx.workspaceId ?? undefined }), + // Palette-only: the sidebar's primary nav and the mobile header's brand link + // already own "go home", so a second entry would duplicate them. + surfaces: PALETTE_ONLY, + palette: { + id: "nav-home", + labelKey: "common:commandGoToHome", + keywordsKey: "common:commandGoToHomeKeywords", + // The palette has always sent users to the workspace-less overview; a + // manifest refactor is the wrong place to change where a command lands. + href: () => linkToTaskOverview(), + }, + }, + { + id: "tasks", + labelKey: "sidebar:tasks", + icon: IconList, + section: "primary", + href: (ctx) => linkToTasks(ctx.workspaceId ?? undefined), + // Palette-only: the sidebar's Tasks section and the mobile menu's View + // toggle are the established ways to reach the task list. + surfaces: PALETTE_ONLY, + palette: { + id: "nav-tasks", + labelKey: "common:commandGoToAllTasks", + keywordsKey: "common:commandGoToAllTasksKeywords", + href: "/tasks", + }, + }, + { + id: "stats", + labelKey: "sidebar:stats", + icon: IconChartBar, + section: "insights", + href: "/stats", + surfaces: EVERYWHERE, + palette: { + id: "nav-stats", + labelKey: "common:commandGoToStats", + keywordsKey: "common:commandGoToStatsKeywords", + }, + }, + { + id: "settings", + labelKey: "common:settings", + icon: IconSettings, + section: "utilities", + href: "/settings", + // The sidebar's gear also toggles the sidebar's settings takeover, so it + // stays bespoke; this entry serves the mobile menu and the palette. + surfaces: MENU_AND_PALETTE, + palette: { + id: "nav-settings", + labelKey: "common:commandGoToSettings", + keywordsKey: "common:commandGoToSettingsKeywords", + href: "/settings/general", + }, + }, + { + id: "azure-devops", + label: "Azure DevOps", + icon: AzureDevOpsIcon, + section: "integrations", + href: "/azure-devops", + // Integrations other than GitHub have no palette command yet: the palette + // needs "Go to " copy, and adding it means new catalog keys. Adding + // `palette` here plus an override block is all it takes. + surfaces: SIDEBAR_AND_MENU, + requires: "azure-devops", + }, + { + id: "github", + label: "GitHub", + icon: IconBrandGithub, + section: "integrations", + href: "/github", + surfaces: EVERYWHERE, + requires: "github", + palette: { + id: "nav-github", + labelKey: "common:commandGoToGitHubDashboard", + keywordsKey: "common:commandGoToGitHubDashboardKeywords", + // The GitHub command predates per-workspace availability checks and has + // always been listed unconditionally; the dashboard itself explains how to + // connect. Kept as-is so this refactor changes no behavior. + ignoreRequires: true, + }, + }, + { + id: "gitlab", + label: "GitLab", + icon: IconBrandGitlab, + section: "integrations", + href: "/gitlab", + surfaces: SIDEBAR_AND_MENU, + requires: "gitlab", + }, + { + id: "jira", + label: "Jira", + icon: IconTicket, + section: "integrations", + href: "/jira", + surfaces: SIDEBAR_AND_MENU, + requires: "jira", + }, + { + id: "linear", + label: "Linear", + icon: IconHexagon, + section: "integrations", + href: "/linear", + surfaces: SIDEBAR_AND_MENU, + requires: "linear", + }, +]; diff --git a/apps/web/lib/navigation/plugin-destinations.test.ts b/apps/web/lib/navigation/plugin-destinations.test.ts new file mode 100644 index 0000000000..22a2544e77 --- /dev/null +++ b/apps/web/lib/navigation/plugin-destinations.test.ts @@ -0,0 +1,149 @@ +import { describe, expect, it } from "vitest"; +import { pluginDestinationId } from "./plugin-destinations"; +import { resolveDestinations } from "./resolve-destinations"; +import { NO_WORKSPACE_CONTEXT } from "./surface-policy"; +import type { AvailabilityMap, NavContext } from "./types"; +import type { PluginNavRegistration } from "@/lib/plugins/registry"; + +const ALL_INTEGRATIONS: AvailabilityMap = { + "azure-devops": true, + github: true, + gitlab: true, + jira: true, + linear: true, +}; + +const KANBAN: NavContext = { workspaceId: "ws-1", inOffice: false }; + +const pluginItems: PluginNavRegistration[] = [ + { pluginId: "acme", id: "hello", label: "Hello", path: "/plugins/hello" }, + { + pluginId: "acme", + id: "explicit-main", + label: "Explicit", + path: "/plugins/explicit", + section: "main", + }, + { + pluginId: "acme", + id: "tracker", + label: "Tracker", + path: "/plugins/tracker", + section: "integrations", + }, + { + pluginId: "acme", + id: "prefs", + label: "Prefs", + path: "/settings/plugins/p", + section: "settings", + }, +]; + +function ids(destinations: { id: string }[]): string[] { + return destinations.map((destination) => destination.id); +} + +function pluginsIn(surface: "sidebar" | "mobileMenu", items: PluginNavRegistration[]) { + return resolveDestinations({ + surface, + section: "plugins", + ctx: NO_WORKSPACE_CONTEXT, + pluginItems: items, + }); +} + +describe("plugin destinations", () => { + it("routes main-section items (explicit or omitted) to the plugins group", () => { + const resolved = pluginsIn("mobileMenu", pluginItems); + + expect(ids(resolved)).toEqual(["plugin:acme:hello", "plugin:acme:explicit-main"]); + expect(resolved.every((destination) => destination.source === "plugin")).toBe(true); + }); + + it("keeps the raw item id available for test ids", () => { + const [hello] = pluginsIn("mobileMenu", pluginItems); + + expect(hello).toMatchObject({ id: "plugin:acme:hello", pluginItemId: "hello" }); + }); + + it("routes integration-section items alongside the first-party integrations", () => { + const resolved = resolveDestinations({ + surface: "sidebar", + section: "integrations", + ctx: KANBAN, + availability: { github: true }, + pluginItems, + }); + + // First-party links keep precedence; plugin items follow. + expect(ids(resolved)).toEqual(["github", "plugin:acme:tracker"]); + }); + + it("never renders settings-section items as destinations", () => { + const resolved = resolveDestinations({ + surface: "mobileMenu", + ctx: NO_WORKSPACE_CONTEXT, + availability: ALL_INTEGRATIONS, + pluginItems, + }); + + expect(ids(resolved)).not.toContain("plugin:acme:prefs"); + }); + + it("keeps plugin items off the palette, which plugins reach via shortcuts", () => { + const resolved = resolveDestinations({ surface: "palette", ctx: KANBAN, pluginItems }); + + expect(ids(resolved)).not.toContain("plugin:acme:hello"); + }); +}); + +/** + * Destination ids are the React keys every nav surface renders with, and plugin + * item ids come from third-party manifests — plugin-local, never coordinated. + */ +describe("plugin destination identity", () => { + it("keeps a plugin from colliding with a first-party id", () => { + const resolved = resolveDestinations({ + surface: "sidebar", + section: "integrations", + ctx: KANBAN, + availability: { github: true }, + // A plugin is free to register `id: "github"` in this very section. + pluginItems: [ + { + pluginId: "acme", + id: "github", + label: "GitHub Extras", + path: "/plugins/github-extras", + section: "integrations", + }, + ], + }); + + expect(ids(resolved)).toEqual(["github", "plugin:acme:github"]); + expect(resolved[1]).toMatchObject({ pluginItemId: "github", label: "GitHub Extras" }); + }); + + it("keeps two plugins that pick the same item id apart", () => { + const resolved = pluginsIn("sidebar", [ + { pluginId: "acme", id: "dashboard", label: "Acme", path: "/plugins/acme" }, + { pluginId: "globex", id: "dashboard", label: "Globex", path: "/plugins/globex" }, + ]); + + expect(ids(resolved)).toEqual(["plugin:acme:dashboard", "plugin:globex:dashboard"]); + expect(new Set(ids(resolved)).size).toBe(resolved.length); + // Both keep the raw id, which is what `plugin-nav-item-` test ids use. + expect(resolved.map((destination) => destination.pluginItemId)).toEqual([ + "dashboard", + "dashboard", + ]); + }); + + it("encodes both segments so the separator cannot be forged", () => { + // Without encoding, ("a:b", "c") and ("a", "b:c") would both read as + // "plugin:a:b:c" — a collision the namespace exists to prevent. + expect(pluginDestinationId("a:b", "c")).not.toBe(pluginDestinationId("a", "b:c")); + expect(pluginDestinationId("a:b", "c")).toBe("plugin:a%3Ab:c"); + }); +}); diff --git a/apps/web/lib/navigation/plugin-destinations.ts b/apps/web/lib/navigation/plugin-destinations.ts new file mode 100644 index 0000000000..1612abfc39 --- /dev/null +++ b/apps/web/lib/navigation/plugin-destinations.ts @@ -0,0 +1,55 @@ +/** + * Maps plugin-registered nav items onto destinations so plugin and first-party + * entries render through the same components. + * + * Identity is the whole reason this is its own module: nav items arrive from + * third-party manifests, and a resolved destination id is what every surface + * uses as its React key. Two plugins may each register `id: "dashboard"`, and a + * plugin may register an id a first-party destination already uses, so the id a + * surface sees is built from the owning pluginId as well as the item id. + */ +import { resolvePluginIcon } from "@/lib/plugins/icons"; +import { SIDEBAR_AND_MENU } from "./surface-policy"; +// Type-only: keeps this module free of the registry's React subscription. +import type { PluginNavRegistration } from "@/lib/plugins/registry"; +import type { Destination } from "./types"; + +/** + * Id namespace for plugin-registered entries. Matches the `plugin::…` + * convention the app-status-bar slot ordering ids already use. + */ +const PLUGIN_ID_PREFIX = "plugin:"; + +/** + * Owner-namespaced destination id for a plugin nav item. + * + * Both segments are percent-encoded so the separator stays unambiguous: without + * it a plugin id of `a:b` with item `c` and a plugin id of `a` with item `b:c` + * would produce the same id, which is exactly the collision the namespace is + * there to prevent. The raw item id travels separately on `pluginItemId`, + * because the `plugin-nav-item-` test ids are public contract. + */ +export function pluginDestinationId(pluginId: string, itemId: string): string { + return `${PLUGIN_ID_PREFIX}${encodeURIComponent(pluginId)}:${encodeURIComponent(itemId)}`; +} + +/** + * `section: "settings"` items are skipped — those render in the settings tree's + * `PluginSlot`, not as destinations. + */ +export function pluginDestinations(items: PluginNavRegistration[]): Destination[] { + return items + .filter((item) => (item.section ?? "main") !== "settings") + .map((item) => ({ + id: pluginDestinationId(item.pluginId, item.id), + pluginItemId: item.id, + label: item.label, + icon: resolvePluginIcon(item.icon), + section: item.section === "integrations" ? ("integrations" as const) : ("plugins" as const), + href: item.path, + // Plugins reach the palette through `registerShortcut`, not as nav + // commands, so plugin destinations stay off that surface. + surfaces: SIDEBAR_AND_MENU, + source: "plugin" as const, + })); +} diff --git a/apps/web/lib/navigation/resolve-destinations.test.ts b/apps/web/lib/navigation/resolve-destinations.test.ts new file mode 100644 index 0000000000..68b9a89c1e --- /dev/null +++ b/apps/web/lib/navigation/resolve-destinations.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it } from "vitest"; +import { APP_DESTINATIONS } from "./core-destinations"; +import { resolveDestinations } from "./resolve-destinations"; +import { MOBILE_MENU_UTILITY_SECTIONS } from "./surface-policy"; +import type { AvailabilityMap, NavContext } from "./types"; + +const ALL_INTEGRATIONS: AvailabilityMap = { + "azure-devops": true, + github: true, + gitlab: true, + jira: true, + linear: true, +}; + +const KANBAN: NavContext = { workspaceId: "ws-1", inOffice: false }; +const OFFICE: NavContext = { workspaceId: "ws-office", inOffice: true }; + +function ids(destinations: { id: string }[]): string[] { + return destinations.map((destination) => destination.id); +} + +describe("resolveDestinations", () => { + it("offers the sidebar's insight and integration destinations, in manifest order", () => { + const resolved = resolveDestinations({ + surface: "sidebar", + ctx: KANBAN, + availability: ALL_INTEGRATIONS, + }); + + expect(ids(resolved)).toEqual(["stats", "azure-devops", "github", "gitlab", "jira", "linear"]); + }); + + it("hides integrations that are not configured", () => { + const resolved = resolveDestinations({ + surface: "sidebar", + section: "integrations", + ctx: KANBAN, + availability: { github: true, linear: true }, + }); + + expect(ids(resolved)).toEqual(["github", "linear"]); + expect(resolved.map((destination) => destination.href)).toEqual(["/github", "/linear"]); + }); + + it("offers no integrations when none are configured", () => { + const resolved = resolveDestinations({ + surface: "sidebar", + section: "integrations", + ctx: KANBAN, + availability: {}, + }); + + expect(resolved).toEqual([]); + }); + + it("accepts several sections, which is how the mobile menu's utility group resolves", () => { + const resolved = resolveDestinations({ + surface: "mobileMenu", + section: MOBILE_MENU_UTILITY_SECTIONS, + ctx: KANBAN, + }); + + expect(ids(resolved)).toEqual(["stats", "settings"]); + }); + + it("resolves workspace-dependent hrefs from the nav context", () => { + const [home] = resolveDestinations({ surface: "palette", section: "primary", ctx: KANBAN }); + + expect(home?.href).toBe("/?home=overview"); + }); + + it("follows the active mode for destinations whose href depends on it", () => { + // Home is palette-only, so assert the context wiring through the manifest + // entry itself rather than a surface that does not offer it. + const home = APP_DESTINATIONS.find((destination) => destination.id === "home"); + const href = home?.href; + + expect(typeof href).toBe("function"); + expect(typeof href === "function" ? href(OFFICE) : null).toBe("/office"); + expect(typeof href === "function" ? href(KANBAN) : null).toBe( + "/?home=overview&workspaceId=ws-1", + ); + }); + + it("resolves labels through the injected translator, leaving brand names alone", () => { + const resolved = resolveDestinations({ + surface: "sidebar", + ctx: KANBAN, + availability: ALL_INTEGRATIONS, + translate: (key) => `t(${key})`, + }); + + expect(resolved[0]).toMatchObject({ id: "stats", label: "t(sidebar:stats)" }); + expect(resolved.find((destination) => destination.id === "github")?.label).toBe("GitHub"); + }); + + it("applies palette overrides for id, copy and href", () => { + const resolved = resolveDestinations({ surface: "palette", ctx: KANBAN }); + const settings = resolved.find((destination) => destination.id === "settings"); + + expect(settings?.href).toBe("/settings/general"); + expect(settings?.label).toBe("common:commandGoToSettings"); + expect(settings?.palette?.id).toBe("nav-settings"); + }); + + it("keeps the surface-agnostic href outside the palette", () => { + const [settings] = resolveDestinations({ + surface: "mobileMenu", + section: "utilities", + ctx: KANBAN, + }); + + expect(settings).toMatchObject({ id: "settings", href: "/settings" }); + }); + + it("keeps the GitHub command listed when GitHub is unconfigured, unlike the sidebar link", () => { + const palette = resolveDestinations({ surface: "palette", ctx: KANBAN, availability: {} }); + const sidebar = resolveDestinations({ surface: "sidebar", ctx: KANBAN, availability: {} }); + + expect(ids(palette)).toContain("github"); + expect(ids(sidebar)).not.toContain("github"); + }); +}); diff --git a/apps/web/lib/navigation/resolve-destinations.ts b/apps/web/lib/navigation/resolve-destinations.ts new file mode 100644 index 0000000000..380e0e806f --- /dev/null +++ b/apps/web/lib/navigation/resolve-destinations.ts @@ -0,0 +1,101 @@ +/** + * The one function every navigation surface calls. Filters the manifest by + * surface, section and availability, then resolves hrefs and copy. + * + * Kept separate from the catalog (`core-destinations.ts`) so surfaces depend on + * the resolution rules rather than on the data, and so the rules can be tested + * against fixture destinations. + */ +import { APP_DESTINATIONS } from "./core-destinations"; +import { pluginDestinations } from "./plugin-destinations"; +import type { PluginNavRegistration } from "@/lib/plugins/registry"; +import type { + AvailabilityMap, + Destination, + DestinationHref, + NavContext, + NavSection, + NavSurface, + PaletteOverride, + ResolvedDestination, +} from "./types"; + +export function resolveHref(href: DestinationHref, ctx: NavContext): string { + return typeof href === "function" ? href(ctx) : href; +} + +export function isAvailable(destination: Destination, availability: AvailabilityMap): boolean { + if (!destination.requires) return true; + return availability[destination.requires] === true; +} + +export type ResolveOptions = { + surface: NavSurface; + /** One section, several (a surface group that renders more than one), or all. */ + section?: NavSection | NavSection[]; + ctx: NavContext; + availability?: AvailabilityMap; + /** i18n lookup for `labelKey` entries; identity-safe for tests. */ + translate?: (key: string) => string; + /** + * Plugin-registered nav items to merge in, already in registry order — as + * `pluginRegistry.getNavRegistrations()` returns them, owner included. + */ + pluginItems?: PluginNavRegistration[]; +}; + +export function resolveDestinations({ + surface, + section, + ctx, + availability = {}, + translate, + pluginItems = [], +}: ResolveOptions): ResolvedDestination[] { + const sections = section === undefined ? null : [section].flat(); + const all = [...APP_DESTINATIONS, ...pluginDestinations(pluginItems)]; + return all + .filter((destination) => destination.surfaces.includes(surface)) + .filter((destination) => !sections || sections.includes(destination.section)) + .filter((destination) => isOfferedOnSurface(destination, surface, availability)) + .map((destination) => toResolved(destination, surface, ctx, translate)); +} + +function isOfferedOnSurface( + destination: Destination, + surface: NavSurface, + availability: AvailabilityMap, +): boolean { + if (surface === "palette" && destination.palette?.ignoreRequires) return true; + return isAvailable(destination, availability); +} + +function toResolved( + destination: Destination, + surface: NavSurface, + ctx: NavContext, + translate?: (key: string) => string, +): ResolvedDestination { + const palette = surface === "palette" ? destination.palette : undefined; + const href = resolveHref(palette?.href ?? destination.href, ctx); + return { + id: destination.id, + label: destinationLabel(destination, palette, translate), + icon: destination.icon, + section: destination.section, + href, + ...(destination.source ? { source: destination.source } : {}), + ...(destination.pluginItemId ? { pluginItemId: destination.pluginItemId } : {}), + ...(destination.palette ? { palette: destination.palette } : {}), + }; +} + +function destinationLabel( + destination: Destination, + palette: PaletteOverride | undefined, + translate?: (key: string) => string, +): string { + const key = palette?.labelKey ?? destination.labelKey; + if (key) return translate ? translate(key) : key; + return destination.label ?? destination.id; +} diff --git a/apps/web/lib/navigation/surface-policy.ts b/apps/web/lib/navigation/surface-policy.ts new file mode 100644 index 0000000000..fe3acd6aa1 --- /dev/null +++ b/apps/web/lib/navigation/surface-policy.ts @@ -0,0 +1,71 @@ +/** + * Per-surface navigation policy: which surface tuples destinations reuse, which + * sections each surface actually draws, and the exemptions that keep the mobile + * coverage guardrail honest. Split out from the catalog so a policy change is + * reviewable on its own. + * + * Open decisions recorded here rather than encoded; see + * `docs/decisions/2026-08-04-navigation-manifest-boundaries.md` for the durable + * contract and tradeoffs: + * + * - **Per-surface ordering.** Catalog array position is currently the render + * order on all three surfaces at once. That is intentional while the surfaces + * agree; the moment one needs its own order (e.g. the palette ranking by + * recency, or the mobile menu promoting Settings), add a per-surface + * `order`/`priority` instead of reshuffling the array and silently moving rows + * on the other two surfaces. + * - **Plugin path ownership.** `NavItem.path` is used verbatim as the row href, + * so a plugin can point a nav row at a first-party page. It cannot *serve* + * one: `resolvePluginRoute` in `src/spa-routes.tsx` runs after every static and + * nested route, so a plugin route can never shadow a first-class path. Adding + * a link-side ownership check needs the first-party route list as data — the + * same typed-route-id work the coverage guardrail wants (see + * `core-destinations.test.ts`) — and has to keep the legitimate case working, + * where a plugin links to its own `/settings/plugins/` page. + */ +import type { NavContext, NavSection, NavSurface, StaticNavSection } from "./types"; + +// Surface tuples are shared so the same literal isn't repeated per entry (the +// duplicate-string lint counts occurrences, not intent). +export const EVERYWHERE: NavSurface[] = ["sidebar", "mobileMenu", "palette"]; +export const SIDEBAR_AND_MENU: NavSurface[] = ["sidebar", "mobileMenu"]; +export const MENU_AND_PALETTE: NavSurface[] = ["mobileMenu", "palette"]; +export const PALETTE_ONLY: NavSurface[] = ["palette"]; + +/** + * Sections the mobile menu renders, across its plugin group + * (`MobilePluginNavSection`), its integrations group (`MobileIntegrationsSection`) + * and its utility group (`MOBILE_MENU_UTILITY_SECTIONS`). A destination that + * declares the `mobileMenu` surface must belong to one of these, or it would + * claim a surface that never draws it — `core-destinations.test.ts` enforces that. + */ +export const MOBILE_MENU_SECTIONS: NavSection[] = [ + "plugins", + "integrations", + "insights", + "utilities", +]; + +/** Sections the mobile menu's utility group renders, in order. */ +export const MOBILE_MENU_UTILITY_SECTIONS: StaticNavSection[] = ["insights", "utilities"]; + +/** + * Destinations deliberately not offered in the mobile menu, each with the mobile + * affordance that owns it instead. Everything else must be offered there: the + * sidebar is hidden below `md`, so an omission means unreachable on a phone — + * which is exactly how `/stats` ended up with no phone entry point. + * `core-destinations.test.ts` fails on any omission that is not listed here. + */ +export const MOBILE_MENU_EXEMPTIONS: Record = { + home: "the mobile header's brand link is the phone's home affordance", + tasks: "the mobile menu's View toggle switches between Kanban and List", +}; + +/** Catalog key the palette groups navigation commands under. */ +export const PALETTE_NAVIGATION_GROUP_KEY = "common:commandGroupNavigation"; + +/** + * Context for surfaces whose destinations carry static hrefs (the plugins group) + * — lets them resolve without pulling workspace/mode hooks they don't need. + */ +export const NO_WORKSPACE_CONTEXT: NavContext = { workspaceId: null, inOffice: false }; diff --git a/apps/web/lib/navigation/types.ts b/apps/web/lib/navigation/types.ts new file mode 100644 index 0000000000..bade928683 --- /dev/null +++ b/apps/web/lib/navigation/types.ts @@ -0,0 +1,123 @@ +/** + * Shape of the navigation manifest — the vocabulary every other module in + * `lib/navigation/` and every nav surface speaks. + * + * The catalog itself lives in `core-destinations.ts`, the plugin mapping in + * `plugin-destinations.ts`, the per-surface constants in `surface-policy.ts`, and + * the one filter/resolve entry point in `resolve-destinations.ts`. All of it is + * deliberately pure — no React, no hooks, no `t()`. Availability (integration + * configured?) and copy resolution are injected by + * `hooks/use-app-destinations.ts`, which keeps the manifest unit-testable. + */ +import type { ComponentType } from "react"; + +/** + * Where a destination may be offered; every destination lists its surfaces + * explicitly rather than defaulting, so an omission is visible in review. + * + * - `sidebar` — desktop navigation chrome: the `AppSidebar` sections and footer, + * plus the integration dropdown/topbar shortcuts that mirror them. All of it is + * hidden below the `md` breakpoint. + * - `mobileMenu` — the phone/tablet hamburger sheet, which is the only navigation + * surface below `md`. + * - `palette` — the command panel's Navigation group (keyboard-only today). + */ +export type NavSurface = "sidebar" | "mobileMenu" | "palette"; + +/** + * Grouping within a surface. `plugins` and `integrations` keep their own group + * headings in the mobile menu and their own sidebar sections; `insights` and + * `utilities` render together in the mobile menu's utility block. + */ +export type NavSection = "primary" | "plugins" | "integrations" | "insights" | "utilities"; + +/** + * Sections that may contain availability-gated destinations. Only surfaces + * rendering these sections need `useAppDestinations`; everything else can use + * `useStaticDestinations` and skip the integration availability subscription, + * which polls per consumer. `core-destinations.test.ts` enforces that no + * destination outside these sections declares `requires`. + * + * A value rather than a plain union because both the type and the runtime + * guardrail derive from it. + */ +export const GATED_SECTIONS = ["integrations"] as const satisfies readonly NavSection[]; + +export type GatedNavSection = (typeof GATED_SECTIONS)[number]; +export type StaticNavSection = Exclude; + +/** Keys the availability map may carry. Extend when a gated destination is added. */ +export type AvailabilityKey = "azure-devops" | "github" | "gitlab" | "jira" | "linear"; + +export type DestinationIcon = ComponentType<{ className?: string }>; + +/** Resolved at render time so hrefs can follow the active workspace / mode. */ +export type NavContext = { + workspaceId: string | null; + inOffice: boolean; +}; + +export type DestinationHref = string | ((ctx: NavContext) => string); + +/** Palette-specific overrides. Command ids are stable API — tests select by them. */ +export type PaletteOverride = { + id: string; + labelKey: string; + keywordsKey?: string; + /** Palette href when it differs from the surface-agnostic one. */ + href?: DestinationHref; + /** Offered even when `requires` is unmet (preserves pre-manifest behavior). */ + ignoreRequires?: boolean; +}; + +/** + * Brand and product names are never translated (see apps/web/AGENTS.md), so + * integrations and plugin entries carry a literal `label` while first-party copy + * carries a catalog `labelKey`. Encoded as a union so "exactly one of the two" + * is a compile error rather than only a test failure. + */ +export type DestinationCopy = + | { label: string; labelKey?: never } + | { label?: never; labelKey: string }; + +type DestinationBase = { + /** + * Stable identity, unique across the manifest and the merged plugin entries. + * Plugin ids are owner-namespaced (`plugin::`, see + * `pluginDestinationId`) so neither a first-party id nor another plugin's item + * id can collide with them. Consumers use this as the React key. + */ + id: string; + /** Raw `NavItem.id` for plugin entries; never set on first-party entries. */ + pluginItemId?: string; + icon: DestinationIcon; + section: NavSection; + href: DestinationHref; + /** + * Surfaces that may offer this destination. Array position in the catalog is + * the render order on every surface today; see the open-decisions note in + * `surface-policy.ts` if a surface ever needs its own order. + */ + surfaces: NavSurface[]; + /** Availability gate; omitted means always offered. */ + requires?: AvailabilityKey; + palette?: PaletteOverride; + /** "plugin" entries get surface-specific test ids; see `pluginDestinations`. */ + source?: "plugin"; +}; + +export type Destination = DestinationBase & DestinationCopy; + +export type ResolvedDestination = { + id: string; + label: string; + icon: DestinationIcon; + section: NavSection; + href: string; + source?: "plugin"; + /** Raw `NavItem.id` for plugin entries — the id e2e test ids are built from. */ + pluginItemId?: string; + palette?: PaletteOverride; +}; + +export type AvailabilityMap = Partial>; diff --git a/apps/web/lib/plugins/registry.test.ts b/apps/web/lib/plugins/registry.test.ts index 10b71bd921..93228a5967 100644 --- a/apps/web/lib/plugins/registry.test.ts +++ b/apps/web/lib/plugins/registry.test.ts @@ -43,6 +43,18 @@ describe("pluginRegistry", () => { }); }); + it("reports the owning plugin for each nav item", () => { + // Nav item ids are plugin-local, so navigation needs the owner to build a + // unique identity (`lib/navigation/plugin-destinations.ts`). + pluginRegistry.forPlugin("plugin-a").registerNavItem({ id: "nav", label: "A", path: "/a" }); + pluginRegistry.forPlugin("plugin-b").registerNavItem({ id: "nav", label: "B", path: "/b" }); + + expect(pluginRegistry.getNavRegistrations()).toEqual([ + { pluginId: "plugin-a", id: "nav", label: "A", path: "/a" }, + { pluginId: "plugin-b", id: "nav", label: "B", path: "/b" }, + ]); + }); + it("registers and returns a settings route", () => { const scoped = pluginRegistry.forPlugin("plugin-a"); function Settings() { diff --git a/apps/web/lib/plugins/registry.ts b/apps/web/lib/plugins/registry.ts index b00b2625ea..e39dee1918 100644 --- a/apps/web/lib/plugins/registry.ts +++ b/apps/web/lib/plugins/registry.ts @@ -43,6 +43,16 @@ export interface PluginRouteRegistration extends RouteRegistration { pluginId: string; } +/** + * Nav item plus the owning pluginId — what `getNavRegistrations()` returns. + * Navigation needs the owner because `NavItem.id` is plugin-local: two plugins + * may register the same id, and the navigation manifest builds its React keys + * from it (`lib/navigation/plugin-destinations.ts`). + */ +export interface PluginNavRegistration extends NavItem { + pluginId: string; +} + interface SlotRegistration { registrationId: string; orderingId: string; @@ -185,10 +195,20 @@ class PluginRegistryStore { return this.settingsRoutes.map((entry) => entry.value); } + /** + * Nav items without their owner. Use `getNavRegistrations()` for anything that + * needs a globally unique identity; this stays for callers that only read the + * item's own fields (e.g. deriving a page title from a path). + */ getNavItems(): NavItem[] { return this.navItems.map((entry) => entry.value); } + /** Nav items plus the pluginId that registered each one, in registration order. */ + getNavRegistrations(): PluginNavRegistration[] { + return this.navItems.map((entry) => ({ ...entry.value, pluginId: entry.pluginId })); + } + getSlotComponents(slot: string): SlotComponent[] { return this.getSlotRegistrations(slot).map((registration) => registration.Component); } diff --git a/docs/decisions/2026-08-04-navigation-manifest-boundaries.md b/docs/decisions/2026-08-04-navigation-manifest-boundaries.md new file mode 100644 index 0000000000..4ad3fc5fb1 --- /dev/null +++ b/docs/decisions/2026-08-04-navigation-manifest-boundaries.md @@ -0,0 +1,69 @@ +# ADR-2026-08-04-navigation-manifest-boundaries: Centralize Navigation and Namespace Plugin Destinations + +**Status:** accepted +**Date:** 2026-08-04 +**Area:** frontend + +## Context + +The sidebar, mobile menu, and command palette previously declared overlapping +destination lists independently. That made navigation coverage difficult to +review and allowed `/stats` to remain unreachable on phones. The first shared +manifest fixed that gap, but its catalog, types, plugin mapping, surface policy, +and resolution rules initially lived in one growing module. + +Plugin navigation introduced a second boundary problem. `NavItem.id` is local to +the plugin that registered it, while resolved destination IDs are React keys. +Using only the item ID allowed two plugins, or a plugin and a first-party +destination, to collide. + +## Decision + +- Keep one compact first-party catalog in `core-destinations.ts`. Destinations + explicitly declare the surfaces on which they may appear. +- Keep shared vocabulary in `types.ts`, plugin conversion and identity in + `plugin-destinations.ts`, filtering and copy/href resolution in + `resolve-destinations.ts`, and cross-surface policy in `surface-policy.ts`. +- Preserve plugin ownership through `PluginNavRegistration`. Build internal + plugin destination IDs as + `plugin::` and keep + the raw item ID separately only for compatibility selectors. +- Keep availability-gated and static consumers distinct. Static consumers must + not mount integration polling merely to render ungated links. + +The following concerns remain explicit follow-up decisions rather than fields or +validation added before a concrete requirement exists: + +- Catalog order is shared across surfaces. Add per-surface order or priority + only when two surfaces need different ordering. +- Plugin nav paths remain links supplied by plugins. Static and nested routes + resolve before plugin routes, so plugins cannot serve or shadow first-party + pages, but link ownership is not yet validated. +- Route coverage continues to inspect the current route switch. Typed route IDs + shared by routing and navigation should replace that source scan before path + ownership validation is introduced. +- Jira, Linear, and Azure DevOps availability polling remains per mounted gated + consumer. Deduplication belongs in shared integration state, not navigation. + +## Consequences + +- Adding a first-party destination has one catalog entry and testable mobile + coverage rules, while mechanics can evolve without growing the catalog file. +- Plugin destination React keys are globally stable across owners without + changing existing plugin test IDs. +- New navigation consumers must choose the gated or static hook deliberately. +- Future ordering, path ownership, and typed-route work has a discoverable + decision boundary instead of relying on comments in one implementation file. + +## Alternatives Considered + +- **Keep one navigation module until it reaches the line limit.** Rejected + because the catalog and its mechanics change for different reasons and were + already approaching the frontend file-size limit. +- **Use only `NavItem.id` for plugin destinations.** Rejected because plugin IDs + are not globally coordinated and resolved IDs are React keys. +- **Add priorities and path validation immediately.** Rejected because all + surfaces currently agree on order, while reliable path ownership depends on a + typed route catalog that does not yet exist. +- **Centralize integration polling in this change.** Rejected because polling is + owned by integration domain hooks and is independent of manifest structure. diff --git a/docs/decisions/INDEX.md b/docs/decisions/INDEX.md index b4beeeff0f..462a8c79b4 100644 --- a/docs/decisions/INDEX.md +++ b/docs/decisions/INDEX.md @@ -113,3 +113,4 @@ Read individual ADRs for full context. Create new ones via `/record decision` or | 2026-08-02-isolate-replaceable-session-stream-traffic | [Isolate Replaceable Session Stream Traffic](2026-08-02-isolate-replaceable-session-stream-traffic.md) | accepted | backend, frontend, protocol | 2026-08-02 | | 2026-08-03-backend-owned-cancellation-progress | [Keep Cancellation Progress Backend Owned](2026-08-03-backend-owned-cancellation-progress.md) | accepted | backend, frontend, protocol | 2026-08-03 | | 2026-08-03-separate-message-queue-provenance-cancellation-and-capacity | [Separate Message Queue Provenance, Cancellation, and Capacity](2026-08-03-separate-message-queue-provenance-cancellation-and-capacity.md) | accepted | backend, frontend, protocol, security | 2026-08-03 | +| 2026-08-04-navigation-manifest-boundaries | [Centralize Navigation and Namespace Plugin Destinations](2026-08-04-navigation-manifest-boundaries.md) | accepted | frontend | 2026-08-04 | diff --git a/docs/public/feature-status.md b/docs/public/feature-status.md index fd25f2bd97..6d7a974ebf 100644 --- a/docs/public/feature-status.md +++ b/docs/public/feature-status.md @@ -121,7 +121,7 @@ Released builds can lag this page. Check **Settings > System > About** or `kande | CLI/browser runtime, Linux/macOS service, Docker deployment, and remote hosting | Dependency-bound | Platform, filesystem, browser, systemd/launchd, container, reverse-proxy, and network configuration determine availability. The web app, API, WebSocket, and external MCP add no Kandev user-login boundary; protect the whole remotely reachable origin. | | Native desktop app | Dependency-bound | macOS, Windows, and Linux artifacts and a Tauri shell are implemented. Signing trust and update behavior differ by platform and release artifact. | | Kubernetes deployment guide | Experimental | The guide describes one deployment approach; Kandev does not ship a Kubernetes executor or operator. | -| Statistics and host resource metrics | Supported | Workspace stats and on-demand CPU/memory/disk display are shipped. Execution-environment metrics depend on executor/runtime support. | +| Statistics and host resource metrics | Supported | Workspace stats and on-demand CPU/memory/disk display are shipped. Open **Stats** from the desktop sidebar or from **Menu → Utilities → Stats** on phones. Execution-environment metrics depend on executor/runtime support. | | SQLite backups, database maintenance, status, and logs | Supported | Backups use SQLite `VACUUM INTO` snapshots under the data root. Retention, free space, file permissions, and off-host copies remain operator responsibilities. | | Update checking and applying updates | Dependency-bound | Checking is shipped. Package-manager installs update through their package manager; backend self-update is service-install-specific; desktop updater support varies by artifact/platform. | | Feature Toggle settings | Supported | The page exposes Office and Debug overrides, environment locks, and restart-required state. Debug is high risk because logs/endpoints can expose prompt, file, and tool data. A toggle being present does not promote its target feature to supported. |