diff --git a/tests/e2e/chat-adapters-ui-providers.spec.ts b/tests/e2e/chat-adapters-ui-providers.spec.ts index 687b5a6f1d4..3542b1c135b 100644 --- a/tests/e2e/chat-adapters-ui-providers.spec.ts +++ b/tests/e2e/chat-adapters-ui-providers.spec.ts @@ -509,7 +509,6 @@ test.describe("iMessage Photon setup and management", () => { await group.click(); await expect(group).toBeChecked(); await page.setViewportSize({ width: 390, height: 844 }); - await page.getByRole("button", { name: "Open sidebar" }).click(); await page.getByRole("navigation", { name: "Chat connection" }).getByRole("link", { name: "Activity", exact: true }).click(); await page.getByText("Connection health and controls", { exact: true }).click(); await expect( diff --git a/ui/src/components/AgentContextualSidebar.tsx b/ui/src/components/AgentContextualSidebar.tsx index c1f96978061..ffef28a8ead 100644 --- a/ui/src/components/AgentContextualSidebar.tsx +++ b/ui/src/components/AgentContextualSidebar.tsx @@ -1,3 +1,4 @@ +import { useMemo } from "react"; import { useQuery } from "@tanstack/react-query"; import { Activity, @@ -21,6 +22,7 @@ import { agentsApi } from "@/api/agents"; import { useCompany } from "@/context/CompanyContext"; import { queryKeys } from "@/lib/queryKeys"; import { ContextualSidebarFrame } from "./ContextualSidebarFrame"; +import { MobileContextualNav, type MobileContextualNavGroup } from "./MobileContextualNav"; import { SidebarNavItem } from "./SidebarNavItem"; import { contextualSidebarStyles } from "./contextual-sidebar-styles"; import { @@ -47,17 +49,19 @@ const localIcons = { budgets: Gauge, } satisfies Record; -export function AgentContextualSidebar({ - agentRef, - agentId, - agentName, - labels, -}: { +interface AgentContextualNavigationProps { agentRef: string; agentId?: string; agentName?: string; labels?: Partial>; -}) { +} + +function useAgentContextualNavigation({ + agentRef, + agentId, + agentName, + labels, +}: AgentContextualNavigationProps) { const { selectedCompanyId } = useCompany(); const shouldResolveAgent = !agentId || !agentName; const { data: resolvedAgent } = useQuery({ @@ -66,10 +70,52 @@ export function AgentContextualSidebar({ enabled: shouldResolveAgent && Boolean(agentRef && selectedCompanyId), }); const resolvedId = agentId ?? resolvedAgent?.id; - const { slots: declaredTabs } = usePluginSlots({ slotTypes: ["detailTab"], entityType: "agent", companyId: resolvedAgent?.companyId ?? selectedCompanyId, enabled: Boolean(resolvedId) }); - const { slots: pluginTabs } = useAgentEnvironmentSlots(declaredTabs, resolvedId, resolvedAgent?.companyId ?? selectedCompanyId); + const { slots: declaredTabs } = usePluginSlots({ + slotTypes: ["detailTab"], + entityType: "agent", + companyId: resolvedAgent?.companyId ?? selectedCompanyId, + enabled: Boolean(resolvedId), + }); + const { slots: pluginTabs } = useAgentEnvironmentSlots( + declaredTabs, + resolvedId, + resolvedAgent?.companyId ?? selectedCompanyId, + ); const resolvedName = agentName ?? resolvedAgent?.name ?? "Agent"; + const groups = useMemo(() => { + const result: MobileContextualNavGroup[] = []; + for (const section of AGENT_DETAIL_NAVIGATION) { + if (section.label === "Audit" && pluginTabs.length > 0) { + result.push({ + key: "Apps", + items: pluginTabs.map((slot) => ({ + key: `plugin:${slot.pluginKey}:${slot.id}`, + to: `/agents/${encodeURIComponent(agentRef)}/${encodeURIComponent(`plugin:${slot.pluginKey}:${slot.id}`)}`, + label: slot.displayName, + icon: Wrench, + })), + }); + } + result.push({ + key: section.label, + items: section.items.map((item) => ({ + key: item.value, + to: agentDetailHref(agentRef, item.value), + label: labels?.[item.value] ?? item.label, + icon: localIcons[item.value], + })), + }); + } + return result; + }, [agentRef, labels, pluginTabs]); + + return { resolvedName, groups }; +} + +export function AgentContextualSidebar(props: AgentContextualNavigationProps) { + const { resolvedName, groups } = useAgentContextualNavigation(props); + return ( - {AGENT_DETAIL_NAVIGATION.map((section) => ( -
- {section.label === "Audit" && pluginTabs.length > 0 ? ( -
-

Apps

-
- {pluginTabs.map(slot => )} -
-
- ) : null} -
-

- {section.label} -

-
- {section.items.map((item) => ( - - ))} -
+ {groups.map((section) => ( +
+

+ {section.key} +

+
+ {section.items.map((item) => ( + + ))}
))} @@ -114,3 +150,15 @@ export function AgentContextualSidebar({ ); } + +export function AgentContextualMobileNav(props: AgentContextualNavigationProps) { + const { resolvedName, groups } = useAgentContextualNavigation(props); + + return ( + + ); +} diff --git a/ui/src/components/AgentConversationSidebar.tsx b/ui/src/components/AgentConversationSidebar.tsx index 5ba4957d10a..5f1b93bba22 100644 --- a/ui/src/components/AgentConversationSidebar.tsx +++ b/ui/src/components/AgentConversationSidebar.tsx @@ -1,5 +1,5 @@ import { useId, useMemo, useRef, useState, type ReactNode } from "react"; -import { PanelLeftOpen, Plus, Search, Users, X } from "lucide-react"; +import { ChevronsUpDown, PanelLeftOpen, Plus, Search, Users, X } from "lucide-react"; import { SortablePinnedList, SortablePinnedRow } from "./PinnedNavigationList"; import { Badge } from "./ui/badge"; import type { Agent } from "@paperclipai/shared"; @@ -13,10 +13,12 @@ import { agentRouteRef, cn } from "@/lib/utils"; export interface AgentConversationSidebarProps { agents: Agent[]; compact?: boolean; + mobileSwitcher?: boolean; /** Agents with a saved conversation; defaults to every listed agent. */ existingChatAgentIds?: readonly string[]; availableAgents?: Agent[]; activeId?: string; + activeAgent?: Agent; previews?: Record; unreadAgentIds?: readonly string[]; unreadMessageCounts?: ReadonlyMap; @@ -40,7 +42,7 @@ const NO_PINNED_AGENTS: readonly string[] = []; const contactRowClassName = "agent-pin-row agent-contact-pin-row group/agent-pin relative rounded-md"; /** Searchable navigation for one conversation per agent. */ -export function AgentConversationSidebar({ agents, compact = false, existingChatAgentIds, availableAgents = agents, activeId, previews = {}, unreadAgentIds = [], unreadMessageCounts, loading = false, error, onRetry, initialSearch = "", onSelect, onBrowse, onAddChat, historyLoading, historyError, onRetryHistory, onCreateAgent, renderAgentAction, pinnedAgentIds = NO_PINNED_AGENTS, onReorderPins }: AgentConversationSidebarProps) { +export function AgentConversationSidebar({ agents, compact = false, mobileSwitcher = false, existingChatAgentIds, availableAgents = agents, activeId, activeAgent: providedActiveAgent, previews = {}, unreadAgentIds = [], unreadMessageCounts, loading = false, error, onRetry, initialSearch = "", onSelect, onBrowse, onAddChat, historyLoading, historyError, onRetryHistory, onCreateAgent, renderAgentAction, pinnedAgentIds = NO_PINNED_AGENTS, onReorderPins }: AgentConversationSidebarProps) { const navigate = useNavigate(); const [pickerOpen, setPickerOpen] = useState(false); const [search, setSearch] = useState(initialSearch); @@ -48,10 +50,54 @@ export function AgentConversationSidebar({ agents, compact = false, existingChat const headingId = useId(); const unreadIds = useMemo(() => new Set(unreadAgentIds), [unreadAgentIds]); const pinnedIds = useMemo(() => new Set(pinnedAgentIds), [pinnedAgentIds]); - const picker = + const activeAgent = useMemo(() => { + if (!mobileSwitcher) return undefined; + if (providedActiveAgent !== undefined) return providedActiveAgent; + return activeId ? agents.find((agent) => agent.id === activeId) : undefined; + }, [activeId, agents, mobileSwitcher, providedActiveAgent]); + const otherUnreadCount = useMemo(() => { + if (!mobileSwitcher || !unreadMessageCounts) return 0; + let total = 0; + for (const [id, count] of unreadMessageCounts) { + if (id !== activeId && count > 0) total += count; + } + return total; + }, [activeId, mobileSwitcher, unreadMessageCounts]); + const pickerTrigger = compact ? ( + : undefined} + + ) : mobileSwitcher ? ( + + ) : undefined; + const picker = agent.id)} loading={loading} error={error} onRetry={onRetry} renderAgentIcon={agent => } @@ -62,6 +108,23 @@ export function AgentConversationSidebar({ agents, compact = false, existingChat if (!signal?.aborted) setSearch(""); }} />; if (compact) return picker; + if (mobileSwitcher) { + return ( +
+ {picker} + {historyError ? ( +
+

Some chat history couldn’t load.

+ {onRetryHistory ? ( + + ) : null} +
+ ) : null} +
+ ); + } const query = search.trim().toLocaleLowerCase(); const matching = agents.filter(agent => `${agent.name} ${agent.title ?? ""} ${agent.role}`.toLocaleLowerCase().includes(query)); const byId = new Map(matching.map(agent => [agent.id, agent])); diff --git a/ui/src/components/AgentConversationsSidebar.tsx b/ui/src/components/AgentConversationsSidebar.tsx index 24624b3778a..17642f1b103 100644 --- a/ui/src/components/AgentConversationsSidebar.tsx +++ b/ui/src/components/AgentConversationsSidebar.tsx @@ -1,4 +1,5 @@ import { useMemo } from "react"; +import type { Agent } from "@paperclipai/shared"; import { AgentConversationSidebar } from "./AgentConversationSidebar"; import { queryViewKind } from "./QueryView"; import { useAgentChatNavigation, useOpenAgentChat } from "@/hooks/useAgentChatNavigation"; @@ -12,8 +13,10 @@ import { resourceMembershipState, useResourceMemberships } from "@/hooks/useReso import { useDialogActions } from "@/context/DialogContext"; import { AgentChatPin, agentChatPinKey, useAgentChatPins } from "./AgentChatPin"; +const EMPTY_AGENTS: Agent[] = []; + /** Account- and company-scoped data for the secondary chat navigation. */ -export function AgentConversationsSidebar({ compact = false }: { compact?: boolean } = {}) { +export function AgentConversationsSidebar({ compact = false, mobileSwitcher = false }: { compact?: boolean; mobileSwitcher?: boolean } = {}) { const { companyId, userId, agents, chats, session } = useAgentChatNavigation(); const agentChatPins = useAgentChatPins(); const unreadMessageCounts = useMemo(() => new Map((chats.data ?? []) @@ -26,16 +29,38 @@ export function AgentConversationsSidebar({ compact = false }: { compact?: boole const { isMobile, setSidebarOpen } = useSidebar(); const { pathname } = useLocation(); const activeRef = pathname.split("/chats/")[1]?.split("/")[0]; - const roster = agents.data ?? []; - const byId = new Map(roster.map(agent => [agent.id, agent])); - // The active roster excludes terminated agents, but their history remains readable. - const missingIds = agents.isSuccess ? [...new Set((chats.data ?? []) - .flatMap(chat => chat.conversationAgentId && !byId.has(chat.conversationAgentId) ? [chat.conversationAgentId] : []))] : []; + const roster = agents.data ?? EMPTY_AGENTS; + const missingIds = useMemo(() => { + if (!agents.isSuccess) return []; + const rosterIds = new Set(roster.map(agent => agent.id)); + return [...new Set((chats.data ?? []) + .flatMap(chat => chat.conversationAgentId && !rosterIds.has(chat.conversationAgentId) ? [chat.conversationAgentId] : []))]; + }, [agents.isSuccess, chats.data, roster]); const historyAgents = useQueries({ queries: missingIds.map(id => ({ queryKey: queryKeys.agents.detail(id), queryFn: () => agentsApi.get(id, companyId!), })) }); - for (const result of historyAgents) if (result.data) byId.set(result.data.id, result.data); - const active = [...byId.values()].find(agent => agent.id === activeRef || (agent.status !== "terminated" && encodeURIComponent(agentRouteRef(agent)) === activeRef)); + const historyAgentsSignature = historyAgents + .map(result => `${result.data?.id ?? ""}:${String(result.data?.updatedAt ?? "")}`) + .join("|"); + const { active, orderedAgents } = useMemo(() => { + const byId = new Map(roster.map(agent => [agent.id, agent])); + for (const result of historyAgents) if (result.data) byId.set(result.data.id, result.data); + const resolvedActive = [...byId.values()].find(agent => agent.id === activeRef || (agent.status !== "terminated" && encodeURIComponent(agentRouteRef(agent)) === activeRef)); + const conversations = (chats.data ?? []).flatMap(chat => { + const agent = chat.conversationAgentId ? byId.get(chat.conversationAgentId) : undefined; + return agent ? [agent] : []; + }); + if (resolvedActive && !conversations.some(agent => agent.id === resolvedActive.id)) conversations.unshift(resolvedActive); + const listedIds = new Set(conversations.map(agent => agent.id)); + const teammates = roster + .filter(agent => !listedIds.has(agent.id) && agent.status !== "terminated" + && (!memberships.isSuccess || resourceMembershipState(memberships.data, "agent", agent.id) !== "left")) + .sort((left, right) => left.name.localeCompare(right.name, undefined, { sensitivity: "base" })); + return { + active: resolvedActive, + orderedAgents: [...conversations, ...teammates], + }; + }, [roster, chats.data, activeRef, historyAgentsSignature, memberships.isSuccess, memberships.data]); const activeId = active?.id; const existingChatAgentIds = useMemo(() => { const ids = (chats.data ?? []).flatMap(chat => chat.conversationAgentId ? [chat.conversationAgentId] : []); @@ -44,30 +69,19 @@ export function AgentConversationsSidebar({ compact = false }: { compact?: boole }, [chats.data, activeId]); const unreadAgentIds = useMemo(() => (chats.data ?? []) .flatMap(chat => chat.isUnreadForMe && chat.conversationAgentId ? [chat.conversationAgentId] : []), [chats.data]); - const conversations = (chats.data ?? []).flatMap(chat => { - const agent = chat.conversationAgentId ? byId.get(chat.conversationAgentId) : undefined; - return agent ? [agent] : []; - }); - if (active && !conversations.some(agent => agent.id === active.id)) conversations.unshift(active); - // Everyone you can chat with is listed, not only agents you've already - // talked to: conversations first by recent activity, then the rest of the - // roster alphabetically. Same eligibility rule as the Agents nav section — - // terminated agents and agents you've left are omitted. - const listedIds = new Set(conversations.map(agent => agent.id)); - const teammates = roster - .filter(agent => !listedIds.has(agent.id) && agent.status !== "terminated" - && (!memberships.isSuccess || resourceMembershipState(memberships.data, "agent", agent.id) !== "left")) - .sort((left, right) => left.name.localeCompare(right.name, undefined, { sensitivity: "base" })); - const previews = Object.fromEntries((chats.data ?? []).filter(chat => chat.conversationState === "active") - .map(chat => [chat.conversationAgentId!, "Working…"])); + const previews = useMemo(() => Object.fromEntries((chats.data ?? []).filter(chat => chat.conversationState === "active") + .map(chat => [chat.conversationAgentId!, "Working…"])), [chats.data]); const pinnedAgentIds = useMemo(() => { const prefix = `agent-chat:${companyId}:`; return agentChatPins.orderedKeys.filter(key => key.startsWith(prefix)).map(key => key.slice(prefix.length)); }, [companyId, agentChatPins.orderedKeys]); - return result.isPending)} historyError={historyAgents.find(result => queryViewKind(result) === "error")?.error} onRetryHistory={() => { historyAgents.filter(result => result.isError).forEach(result => { void result.refetch(); }); }} - onAddChat={compact ? undefined : openChat} + onAddChat={compact || mobileSwitcher ? undefined : openChat} onSelect={agent => { navigate(`/chats/${encodeURIComponent(agent.status === "terminated" ? agent.id : agentRouteRef(agent))}`); if (isMobile) setSidebarOpen(false); diff --git a/ui/src/components/AppConnectionSidebar.tsx b/ui/src/components/AppConnectionSidebar.tsx index e146ebb930b..404c276f6d9 100644 --- a/ui/src/components/AppConnectionSidebar.tsx +++ b/ui/src/components/AppConnectionSidebar.tsx @@ -24,6 +24,7 @@ import { type AppGalleryDisplayEntry, } from "@/pages/apps/app-definition-display"; import { SidebarNavItem } from "./SidebarNavItem"; +import { MobileContextualNav } from "./MobileContextualNav"; import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; import { cn } from "@/lib/utils"; @@ -31,9 +32,8 @@ type AppDetailSidebarProps = | { kind: "connection"; connectionId: string } | { kind: "application"; applicationId: string }; -export function AppDetailSidebar(props: AppDetailSidebarProps) { +function useAppDetailNavigation(props: AppDetailSidebarProps) { const { selectedCompanyId } = useCompany(); - const { isMobile, setSidebarOpen } = useSidebar(); const connectionQuery = useQuery({ queryKey: queryKeys.tools.connection(props.kind === "connection" ? props.connectionId : "__none__"), @@ -83,6 +83,32 @@ export function AppDetailSidebar(props: AppDetailSidebarProps) { (reviewCountsQuery.data?.pendingActionRequestCount ?? 0) + ((reviewCountsQuery.data?.quarantinedCatalogEntryCount ?? 0) > 0 ? 1 : 0); + const visibleTabs = APP_TABS + .filter((tab) => !poolPluginKey || tab.key === "permissions") + .map((tab) => ({ + key: tab.key, + to: tabHref(props, tab.key), + label: poolPluginKey ? "Settings" : tab.label, + icon: tab.icon, + end: true, + badge: tab.key === "review" && reviewCount > 0 ? reviewCount : undefined, + badgeTone: "danger" as const, + badgeLabel: "needing review", + })); + + return { + appName, + brandKey, + logoEntry, + applicationsPending: applicationsQuery.isPending, + visibleTabs, + }; +} + +export function AppDetailSidebar(props: AppDetailSidebarProps) { + const { isMobile, setSidebarOpen } = useSidebar(); + const { appName, brandKey, logoEntry, applicationsPending, visibleTabs } = useAppDetailNavigation(props); + return ( ); } + +export function AppsMobileNav() { + const { pathname } = useLocation(); + const developerTabs = useAppsDeveloperTabs(); + + if (isChatConnectPath(pathname)) return null; + const chatDetail = pathname.match(CHAT_DETAIL_PATH_RE); + if (chatDetail) return ; + if (developerTabs.length === 0) return null; + + return ( + ({ + key: tab.key, + to: advancedTabHref(tab.key), + label: tab.label, + icon: tab.icon, + end: true, + })), + }, + ]} + /> + ); +} diff --git a/ui/src/components/Layout.mobile.test.tsx b/ui/src/components/Layout.mobile.test.tsx new file mode 100644 index 00000000000..cd5a1282823 --- /dev/null +++ b/ui/src/components/Layout.mobile.test.tsx @@ -0,0 +1,273 @@ +// @vitest-environment jsdom + +import { flushSync } from "react-dom"; +import { createRoot, type Root } from "react-dom/client"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { Layout } from "./Layout"; +import { queryKeys } from "@/lib/queryKeys"; + +const mockSidebarState = { + sidebarOpen: true, + setSidebarOpen: vi.fn(), + toggleSidebar: vi.fn(), + isMobile: true, +}; + +const mockUsePluginSlots = vi.fn(); + +vi.mock("../context/SidebarContext", () => ({ + useSidebar: () => mockSidebarState, +})); + +vi.mock("../context/CompanyContext", () => ({ + useCompany: () => ({ + companies: [{ id: "company-1", name: "Paperclip", issuePrefix: "PAP", status: "active" }], + loading: false, + selectedCompany: { id: "company-1", name: "Paperclip", issuePrefix: "PAP", status: "active" }, + selectedCompanyId: "company-1", + selectionSource: "manual", + setSelectedCompanyId: vi.fn(), + }), +})); + +vi.mock("../context/DialogContext", () => ({ + useDialogActions: () => ({ openNewIssue: vi.fn(), openOnboarding: vi.fn() }), +})); + +vi.mock("../context/PanelContext", () => ({ + usePanel: () => ({ + panelContent: null, + panelVisible: false, + panelShowsArtifact: false, + togglePanelVisible: vi.fn(), + setPanelVisible: vi.fn(), + }), +})); + +vi.mock("../context/ToastContext", () => ({ + useOptionalToastActions: () => null, +})); + +vi.mock("@/context/DesignSandboxContext", () => ({ + useDesignSandbox: () => false, +})); + +vi.mock("@/hooks/useCoordinatorWorkspaceEnabled", () => ({ + useCoordinatorWorkspaceEnabled: () => ({ enabled: false, userId: "user-1" }), +})); + +vi.mock("@/hooks/useBrowserTimeZoneSync", () => ({ + useBrowserTimeZoneSync: () => {}, +})); + +vi.mock("../hooks/useStreamlinedUiEnabled", () => ({ + useStreamlinedUiEnabled: () => ({ enabled: true }), +})); + +vi.mock("../hooks/useCompanyPageMemory", () => ({ + useCompanyPageMemory: () => {}, +})); + +vi.mock("../hooks/useKeyboardShortcuts", () => ({ + useKeyboardShortcuts: () => {}, +})); + +vi.mock("../hooks/useMobileNavVisibility", () => ({ + useMobileNavVisibility: () => true, +})); + +vi.mock("../hooks/useMobileVisualViewport", () => ({ + useMobileVisualViewport: () => ({ current: null }), +})); + +vi.mock("../hooks/useAgentChatEnabled", () => ({ + useAgentChatEnabled: () => ({ enabled: true }), +})); + +vi.mock("../plugins/slots", () => ({ + PluginSlotMount: () =>
Plugin Sidebar
, + resolveRouteSidebarSlot: (slots: Array<{ id: string; displayName: string }>) => slots[0] ?? null, + usePluginSlots: (...args: unknown[]) => mockUsePluginSlots(...args), +})); + +vi.mock("./Sidebar", () => ({ + Sidebar: () => , +})); + +vi.mock("./AgentContextualSidebar", () => ({ + AgentContextualSidebar: ({ agentRef }: { agentRef: string }) => ( +
Agent Sidebar: {agentRef}
+ ), + AgentContextualMobileNav: ({ agentRef }: { agentRef: string }) => ( + + ), +})); + +vi.mock("./CompanySettingsSidebar", () => ({ + CompanySettingsSidebar: () =>
Settings Sidebar
, +})); + +vi.mock("./access/CompanySettingsNav", () => ({ + CompanySettingsNav: () =>
Settings Mobile Nav
, +})); + +vi.mock("./AppsSidebar", () => ({ + AppsSidebar: () =>
Apps Sidebar
, + AppsMobileNav: () =>
Apps Mobile Nav
, + appsRouteHasMobileNav: (pathname: string, hasDeveloperTabs: boolean) => { + if (pathname.replace(/\/+$/, "").endsWith("/apps/chat/connect")) return false; + if (/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|conversations|activity)|\/reviews(?:\/[^/]+)?)?\/?$/.test(pathname)) { + return true; + } + return hasDeveloperTabs; + }, + useAppsDeveloperTabs: () => [], +})); + +vi.mock("./AppConnectionSidebar", () => ({ + AppDetailSidebar: () =>
App Detail Sidebar
, + AppDetailMobileNav: () =>
App Detail Mobile Nav
, +})); + +vi.mock("./AgentConversationsSidebar", () => ({ + AgentConversationsSidebar: ({ mobileSwitcher }: { mobileSwitcher?: boolean }) => ( +
+ {mobileSwitcher ? "Chat Switcher" : "Chat Sidebar"} +
+ ), +})); + +vi.mock("./MobileBottomNav", () => ({ + MobileBottomNav: ({ visible }: { visible: boolean }) => ( + + ), +})); + +vi.mock("./BreadcrumbBar", () => ({ + BreadcrumbBar: () =>
Breadcrumb
, +})); + +vi.mock("./PropertiesPanel", () => ({ PropertiesPanel: () => null })); +vi.mock("./CommandPalette", () => ({ CommandPalette: () => null })); +vi.mock("./KeyboardShortcutsCheatsheet", () => ({ KeyboardShortcutsCheatsheet: () => null })); +vi.mock("./ToastViewport", () => ({ ToastViewport: () => null })); +vi.mock("./AnnouncementWell", () => ({ AnnouncementWell: () => null })); +vi.mock("./PluginAppShellOverlays", () => ({ PluginAppShellOverlays: () => null })); +vi.mock("./WorktreeBanner", () => ({ WorktreeBanner: () => null })); +vi.mock("./DevRestartBanner", () => ({ DevRestartBanner: () => null })); +vi.mock("./StandaloneBrowserControls", () => ({ StandaloneBrowserControls: () => null })); +vi.mock("./SidebarAccountMenu", () => ({ SidebarAccountMenu: () =>
})); +vi.mock("./BoardDialogs", () => ({ BoardDialogs: () => null })); +vi.mock("./CloudTrialGate", () => ({ CloudTrialGate: () => null })); + +describe("Layout mobile drawer & contextual navigation", () => { + let container: HTMLDivElement; + let root: Root | null = null; + + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + mockSidebarState.sidebarOpen = true; + mockSidebarState.isMobile = true; + mockUsePluginSlots.mockReturnValue({ slots: [] }); + }); + + afterEach(() => { + flushSync(() => root?.unmount()); + root = null; + container.remove(); + vi.clearAllMocks(); + }); + + function renderAt(path: string) { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + queryClient.setQueryData(queryKeys.health, { status: "ok", deploymentMode: "local_trusted" }); + root = createRoot(container); + flushSync(() => { + root!.render( + + + + }> + Agent Page
} /> + Chat Connect Page
} /> + Plugin Page
} /> + + + + , + ); + }); + } + + it("renders inline mobile tabs on Agent Detail, opens drawer to global Workspace nav, and layers drawer backdrop above hidden MobileBottomNav", () => { + renderAt("/PAP/agents/codexcoder/overview"); + + expect(container.querySelector('[data-testid="agent-contextual-mobile-nav"]')).not.toBeNull(); + expect(container.querySelector('[data-testid="global-workspace-sidebar"]')).not.toBeNull(); + + const switcher = container.querySelector('[data-slot="mobile-drawer-switcher"]'); + expect(switcher).not.toBeNull(); + const buttons = Array.from(switcher!.querySelectorAll("button")); + expect(buttons.map((b) => b.textContent)).toEqual(["Workspace", "Agent"]); + + flushSync(() => { + buttons[1]!.click(); + }); + expect(container.querySelector('[data-testid="agent-contextual-sidebar"]')).not.toBeNull(); + + flushSync(() => { + buttons[0]!.click(); + }); + expect(container.querySelector('[data-testid="global-workspace-sidebar"]')).not.toBeNull(); + + const bottomNav = container.querySelector('[data-testid="mobile-bottom-nav"]'); + const backdrop = container.querySelector('[data-slot="mobile-drawer-backdrop"]'); + const drawer = container.querySelector('[data-mobile-drawer="true"]'); + expect(bottomNav?.getAttribute("data-visible")).toBe("false"); + expect(backdrop).not.toBeNull(); + expect(drawer).not.toBeNull(); + expect(Boolean(bottomNav!.compareDocumentPosition(backdrop!) & Node.DOCUMENT_POSITION_FOLLOWING)).toBe(true); + expect(Boolean(backdrop!.compareDocumentPosition(drawer!) & Node.DOCUMENT_POSITION_FOLLOWING)).toBe(true); + }); + + it("never traps mobile drawer on plugin routeSidebar routes without inline nav: provides Workspace escape button", () => { + mockUsePluginSlots.mockReturnValue({ + slots: [{ id: "custom-sidebar", displayName: "Wiki" }], + }); + renderAt("/PAP/custom-plugin"); + + expect(container.querySelector('[data-testid="plugin-sidebar-slot"]')).not.toBeNull(); + + const workspaceBtn = Array.from( + container.querySelectorAll('[data-slot="mobile-drawer-switcher"] button'), + ).find((b) => b.textContent?.includes("Workspace")) as HTMLButtonElement; + expect(workspaceBtn).toBeDefined(); + + flushSync(() => { + workspaceBtn.click(); + }); + expect(container.querySelector('[data-testid="global-workspace-sidebar"]')).not.toBeNull(); + }); + + it("opens the mobile drawer to the contextual setup sidebar on /apps/chat/connect where no inline bar is rendered", () => { + renderAt("/PAP/apps/chat/connect?provider=slack"); + + expect(container.querySelector('[data-testid="apps-mobile-nav"]')).toBeNull(); + expect(container.querySelector('[data-testid="apps-sidebar"]')).not.toBeNull(); + + const workspaceBtn = Array.from( + container.querySelectorAll('[data-slot="mobile-drawer-switcher"] button'), + ).find((b) => b.textContent?.includes("Workspace")) as HTMLButtonElement; + expect(workspaceBtn).toBeDefined(); + + flushSync(() => { + workspaceBtn.click(); + }); + expect(container.querySelector('[data-testid="global-workspace-sidebar"]')).not.toBeNull(); + }); +}); diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsx index a442f15373d..2c62acf5d73 100644 --- a/ui/src/components/Layout.tsx +++ b/ui/src/components/Layout.tsx @@ -8,15 +8,16 @@ import { BoardDialogs } from "./BoardDialogs"; import { CloudTrialGate } from "./CloudTrialGate"; import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react"; +import { ArrowLeft } from "lucide-react"; import { useQuery } from "@tanstack/react-query"; import { Outlet, useLocation, useNavigate, useNavigationType, useParams } from "@/lib/router"; import { Sidebar } from "./Sidebar"; import { CompanySettingsSidebar } from "./CompanySettingsSidebar"; import { CompanySettingsNav } from "./access/CompanySettingsNav"; -import { AppsSidebar, useAppsDeveloperTabs } from "./AppsSidebar"; +import { AppsMobileNav, AppsSidebar, appsRouteHasMobileNav, useAppsDeveloperTabs } from "./AppsSidebar"; import { appsRouteHasRail } from "../pages/apps/apps-rail"; -import { AppDetailSidebar } from "./AppConnectionSidebar"; -import { AgentContextualSidebar } from "./AgentContextualSidebar"; +import { AppDetailMobileNav, AppDetailSidebar } from "./AppConnectionSidebar"; +import { AgentContextualMobileNav, AgentContextualSidebar } from "./AgentContextualSidebar"; import { SkillsContextualSidebar } from "./SkillsContextualSidebar"; import { BreadcrumbBar } from "./BreadcrumbBar"; import { PropertiesPanel } from "./PropertiesPanel"; @@ -236,6 +237,34 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) { ) : sharedSecondarySidebar; const hasSecondarySidebar = secondarySidebar != null; + const mobileContextualNav = !isMobile ? null : isCompanySettingsRoute ? ( +
+ +
+ ) : isAgentChatRoute ? ( + + ) : shellRoute.builtInContextualSurface === "agent" && agentId ? ( + + ) : appDetailApplicationId ? ( + + ) : appsRouteHasRail(companyPathSegments, appsDeveloperTabs.length > 0) + && appsRouteHasMobileNav(location.pathname, appsDeveloperTabs.length > 0) ? ( + + ) : null; + const mobileDrawerContextualLabel = isAgentChatRoute + ? "Chats" + : shellRoute.builtInContextualSurface === "agent" + ? "Agent" + : isCompanySettingsRoute + ? "Settings" + : appDetailApplicationId || isAppsRoute || isToolsRoute + ? "Apps" + : shellRoute.builtInContextualSurface === "skills" + ? "Skills" + : routeSidebarSlot?.displayName ?? "Section"; + const defaultMobileDrawerPane: "workspace" | "contextual" = + hasSecondarySidebar && mobileContextualNav == null ? "contextual" : "workspace"; + const [mobileDrawerPane, setMobileDrawerPane] = useState<"workspace" | "contextual">(defaultMobileDrawerPane); const keepsPrimarySidebar = streamlinedUiEnabled && hasSecondarySidebar && ( isAgentChatRoute || shellRoute.builtInContextualSurface === "agent" @@ -249,6 +278,14 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) { : routeSidebarSlot && !shellRoute.builtInContextualSurface ? `plugin:${routeSidebarSlot.id}` : shellRoute.builtInContextualSurface; + useEffect(() => { + setMobileDrawerPane(defaultMobileDrawerPane); + }, [contextualSurface, defaultMobileDrawerPane]); + useEffect(() => { + if (!sidebarOpen) { + setMobileDrawerPane(defaultMobileDrawerPane); + } + }, [sidebarOpen, defaultMobileDrawerPane]); const previousShellRoute = useRef<{ pathname: string; surface: ContextualSidebarSurface | null; @@ -515,36 +552,7 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
- {isMobile && sidebarOpen && ( -
- {isMobile && } + {isMobile && } + {isMobile && sidebarOpen && ( + + + + ) : null} +
+
+ {hasSecondarySidebar && mobileDrawerPane === "contextual" ? ( + {secondarySidebar} + ) : ( + {sidebarSections} + )} +
+
+ + + ) : null} diff --git a/ui/src/components/MobileBottomNav.test.tsx b/ui/src/components/MobileBottomNav.test.tsx new file mode 100644 index 00000000000..7a9df283447 --- /dev/null +++ b/ui/src/components/MobileBottomNav.test.tsx @@ -0,0 +1,76 @@ +// @vitest-environment jsdom + +import { flushSync } from "react-dom"; +import { createRoot, type Root } from "react-dom/client"; +import { MemoryRouter } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { MobileBottomNav } from "./MobileBottomNav"; + +vi.mock("../context/CompanyContext", () => ({ + useCompany: () => ({ selectedCompanyId: "company-1", selectedCompany: { issuePrefix: "PAP" } }), +})); + +vi.mock("../context/DialogContext", () => ({ + useDialogActions: () => ({ openNewIssue: vi.fn() }), +})); + +vi.mock("@/hooks/useAgentChatEnabled", () => ({ + useAgentChatEnabled: () => ({ enabled: false }), +})); + +vi.mock("@/hooks/useCoordinatorWorkspaceEnabled", () => ({ + useCoordinatorWorkspaceEnabled: () => ({ enabled: true }), +})); + +vi.mock("@/hooks/useCombinedInboxTasksEnabled", () => ({ + useCombinedInboxTasksEnabled: () => ({ enabled: false }), +})); + +vi.mock("@/hooks/useCompanyHomePath", () => ({ + useCompanyHomePath: () => ({ path: "/dashboard" }), +})); + +vi.mock("@/hooks/useResponsibilitiesEnabled", () => ({ + useResponsibilitiesEnabled: () => ({ enabled: false }), +})); + +vi.mock("../hooks/useInboxBadge", () => ({ + useInboxBadge: () => ({ inbox: 96 }), +})); + +vi.mock("@/hooks/useCoordinatorAttentionCount", () => ({ + useCoordinatorAttentionCount: () => 96, +})); + +describe("MobileBottomNav", () => { + let container: HTMLDivElement; + let root: Root | null = null; + + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + }); + + afterEach(() => { + flushSync(() => root?.unmount()); + root = null; + container.remove(); + }); + + it("anchors the unread badge to the top-right edge so two-digit counts expand outward without covering the icon center", () => { + root = createRoot(container); + flushSync(() => { + root!.render( + + + , + ); + }); + + const badge = container.querySelector('[data-slot="mobile-nav-badge"]'); + expect(badge).not.toBeNull(); + expect(badge?.textContent).toBe("96"); + expect(badge?.className).toContain("left-3"); + expect(badge?.className).not.toContain("-right-2"); + }); +}); diff --git a/ui/src/components/MobileBottomNav.tsx b/ui/src/components/MobileBottomNav.tsx index 9bf33d76d5d..e45c77d56ed 100644 --- a/ui/src/components/MobileBottomNav.tsx +++ b/ui/src/components/MobileBottomNav.tsx @@ -155,10 +155,14 @@ export function MobileBottomNav({ visible }: MobileBottomNavProps) { > {({ isActive }) => ( <> - + {item.badge != null && item.badge > 0 && ( - + {item.badge > 99 ? "99+" : item.badge} )} diff --git a/ui/src/components/MobileContextualNav.test.tsx b/ui/src/components/MobileContextualNav.test.tsx new file mode 100644 index 00000000000..ee0fdd15e2e --- /dev/null +++ b/ui/src/components/MobileContextualNav.test.tsx @@ -0,0 +1,420 @@ +// @vitest-environment jsdom + +import { flushSync } from "react-dom"; +import { createRoot, type Root } from "react-dom/client"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { AgentContextualMobileNav } from "./AgentContextualSidebar"; +import { AppDetailMobileNav } from "./AppConnectionSidebar"; +import { AppsMobileNav, appsRouteHasMobileNav } from "./AppsSidebar"; +import { ChatDetailMobileNav } from "./chat/ChatDetailSidebar"; +import { AgentConversationSidebar } from "./AgentConversationSidebar"; +import { MobileContextualNav } from "./MobileContextualNav"; +import { queryKeys } from "@/lib/queryKeys"; + +const mockUsePluginSlots = vi.fn(); +const mockUseAgentEnvironmentSlots = vi.fn(); +const mockUseSmokeLabEnabled = vi.fn(); + +vi.mock("@/context/CompanyContext", () => ({ + useCompany: () => ({ + selectedCompanyId: "company-1", + selectedCompany: { id: "company-1", issuePrefix: "PAP", name: "Paperclip" }, + }), +})); + +vi.mock("@/context/SidebarContext", () => ({ + useSidebar: () => ({ isMobile: true, sidebarOpen: false, setSidebarOpen: vi.fn(), toggleSidebar: vi.fn() }), +})); + +vi.mock("@/plugins/slots", () => ({ + usePluginSlots: (...args: unknown[]) => mockUsePluginSlots(...args), +})); + +vi.mock("@/plugins/useAgentEnvironmentSlots", () => ({ + useAgentEnvironmentSlots: (...args: unknown[]) => mockUseAgentEnvironmentSlots(...args), +})); + +vi.mock("@/hooks/useSmokeLabEnabled", () => ({ + useSmokeLabEnabled: () => mockUseSmokeLabEnabled(), +})); + +describe("Mobile contextual section switchers", () => { + let container: HTMLDivElement; + let root: Root | null = null; + + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + mockUsePluginSlots.mockReturnValue({ slots: [] }); + mockUseAgentEnvironmentSlots.mockImplementation((slots: unknown[]) => ({ slots })); + mockUseSmokeLabEnabled.mockReturnValue({ enabled: true }); + }); + + afterEach(() => { + flushSync(() => root?.unmount()); + root = null; + container.remove(); + vi.clearAllMocks(); + }); + + it("renders all 10 built-in Agent Detail views plus plugin detailTab slots inline on mobile", () => { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + mockUsePluginSlots.mockReturnValue({ + slots: [ + { + id: "memory-tab", + pluginKey: "paperclip.memory", + displayName: "Memory", + }, + ], + }); + + root = createRoot(container); + flushSync(() => { + root!.render( + + + + } + /> + + + , + ); + }); + + const nav = container.querySelector('[data-mobile-contextual-nav="agent"]'); + expect(nav).not.toBeNull(); + const links = Array.from(nav!.querySelectorAll("a")); + const labels = links.map((link) => link.textContent); + expect(labels).toEqual([ + "Overview", + "Identity", + "Harness / Runtime", + "Secrets & variables", + "Permissions / Trust", + "Advanced", + "Memory", + "Activity", + "Runs", + "Costs", + "Budgets", + ]); + expect(links[0]?.getAttribute("aria-current")).toBe("page"); + expect(links[6]?.getAttribute("href")).toBe("/PAP/agents/codexcoder/plugin%3Apaperclip.memory%3Amemory-tab"); + }); + + it("renders AppDetail inline switcher with Permissions and Review tabs plus review badge", () => { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + queryClient.setQueryData(queryKeys.tools.connection("conn-1"), { + id: "conn-1", + name: "GitHub", + applicationId: "app-1", + status: "connected", + }); + queryClient.setQueryData(queryKeys.tools.applications("company-1"), { applications: [] }); + queryClient.setQueryData(queryKeys.apps.gallery("company-1"), { apps: [] }); + queryClient.setQueryData(queryKeys.apps.connectionReviewCounts("company-1", "conn-1"), { + pendingActionRequestCount: 3, + quarantinedCatalogEntryCount: 0, + }); + + root = createRoot(container); + flushSync(() => { + root!.render( + + + + } + /> + + + , + ); + }); + + const nav = container.querySelector('[data-mobile-contextual-nav="app-detail"]'); + expect(nav).not.toBeNull(); + const links = Array.from(nav!.querySelectorAll("a")); + expect(links.map((a) => a.getAttribute("href"))).toEqual([ + "/PAP/apps/conn-1/permissions", + "/PAP/apps/conn-1/review", + ]); + expect(links[1]?.textContent).toContain("Review"); + expect(links[1]?.textContent).toContain("3"); + }); + + it("renders ChatEndpointDetail inline switcher including GitHub Reviews tab", () => { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + queryClient.setQueryData(queryKeys.chatEndpoints.detail("ep-1"), { + id: "ep-1", + provider: "github", + }); + + root = createRoot(container); + flushSync(() => { + root!.render( + + + + } + /> + + + , + ); + }); + + const nav = container.querySelector('[data-mobile-contextual-nav="chat-detail"]'); + expect(nav).not.toBeNull(); + const labels = Array.from(nav!.querySelectorAll("a")).map((a) => a.textContent); + expect(labels).toEqual(["Settings", "Access", "Reviews", "Conversations", "Activity"]); + }); + + it("renders AppsMobileNav developer tabs when smoke lab is enabled", () => { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + + root = createRoot(container); + flushSync(() => { + root!.render( + + + + } /> + + + , + ); + }); + + const nav = container.querySelector('[data-mobile-contextual-nav="apps"]'); + expect(nav).not.toBeNull(); + const labels = Array.from(nav!.querySelectorAll("a")).map((a) => a.textContent); + expect(labels).toEqual(["All plugins", "Smoke Lab"]); + expect(appsRouteHasMobileNav("/PAP/apps/chat/connect", false)).toBe(false); + expect(appsRouteHasMobileNav("/PAP/apps/chat/connect/", true)).toBe(false); + expect(appsRouteHasMobileNav("/PAP/apps/chat/ep-1/settings", false)).toBe(true); + expect(appsRouteHasMobileNav("/PAP/apps/advanced/smoke-lab", true)).toBe(true); + expect(appsRouteHasMobileNav("/PAP/apps/advanced/smoke-lab", false)).toBe(false); + }); + + it("renders inline mobile switcher trigger for AgentConversationSidebar with active agent and other unread count", () => { + const agents = [ + { id: "a1", name: "Chief of Staff", role: "ceo", status: "active", companyId: "company-1" }, + { id: "a2", name: "CodexCoder", role: "engineer", status: "active", companyId: "company-1" }, + ] as Parameters[0]["agents"]; + + root = createRoot(container); + flushSync(() => { + root!.render( + + + , + ); + }); + + const trigger = container.querySelector('[data-mobile-contextual-nav="agent-chat"]'); + expect(trigger).not.toBeNull(); + expect(trigger?.getAttribute("aria-label")).toBe("Browse chats"); + expect(trigger?.textContent).toContain("Chief of Staff"); + expect(trigger?.textContent).toContain("5"); + }); + + it("renders chat history error and retry button in AgentConversationSidebar mobileSwitcher mode", () => { + const onRetryHistory = vi.fn(); + const agents = [ + { id: "a1", name: "Chief of Staff", role: "ceo", status: "active", companyId: "company-1" }, + ] as Parameters[0]["agents"]; + + root = createRoot(container); + flushSync(() => { + root!.render( + + + , + ); + }); + + const alert = container.querySelector('[role="alert"]'); + expect(alert?.textContent).toContain("Some chat history couldn’t load."); + const retryBtn = Array.from(alert!.querySelectorAll("button")).find((btn) => + btn.textContent?.includes("Retry chat history"), + ) as HTMLButtonElement; + expect(retryBtn).toBeDefined(); + flushSync(() => { + retryBtn.click(); + }); + expect(onRetryHistory).toHaveBeenCalledTimes(1); + }); + + it("scrolls newly loaded active tabs into view when items arrive within an existing group", () => { + const scrollIntoView = vi.fn(); + Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { + configurable: true, + value: scrollIntoView, + }); + + root = createRoot(container); + flushSync(() => { + root!.render( + + + + } + /> + + , + ); + }); + expect(scrollIntoView).not.toHaveBeenCalled(); + + flushSync(() => { + root!.render( + + + + } + /> + + , + ); + }); + expect(scrollIntoView).toHaveBeenCalledWith({ inline: "nearest", block: "nearest" }); + }); + + it("keeps mobileSwitcher activeAgent and unread count work bounded across unchanged rerenders at realistic roster size", () => { + const rosterSize = 250; + let nonActiveIdLookups = 0; + const maxNonActiveLookups = rosterSize; + const agents = Array.from({ length: rosterSize }, (_, index) => { + const id = `agent-${index}`; + return Object.defineProperty( + { name: `Agent ${index}`, role: "engineer", status: "active", companyId: "company-1" }, + "id", + { + enumerable: true, + get() { + if (index < rosterSize - 1) { + nonActiveIdLookups += 1; + if (nonActiveIdLookups > maxNonActiveLookups) { + throw new Error(`Exceeded lookup bound: ${nonActiveIdLookups}`); + } + } + return id; + }, + }, + ); + }) as Parameters[0]["agents"]; + + let unreadIterations = 0; + const unreadMap = new Map( + Array.from({ length: rosterSize }, (_, index) => [`agent-${index}`, index % 3 === 0 ? 1 : 0]), + ); + const originalIterator = unreadMap[Symbol.iterator].bind(unreadMap); + unreadMap[Symbol.iterator] = function countedIterator() { + unreadIterations += 1; + if (unreadIterations > 2) { + throw new Error(`Exceeded unread iteration bound: ${unreadIterations}`); + } + return originalIterator(); + }; + + const existingChatAgentIds: string[] = []; + const targetId = `agent-${rosterSize - 1}`; + root = createRoot(container); + for (let pass = 0; pass < 5; pass += 1) { + flushSync(() => { + root!.render( + + + , + ); + }); + } + + expect(nonActiveIdLookups).toBe(rosterSize - 1); + expect(unreadIterations).toBe(1); + const trigger = container.querySelector('[data-mobile-contextual-nav="agent-chat"]'); + expect(trigger?.textContent).toContain(`Agent ${rosterSize - 1}`); + + const providedAgent = { + id: targetId, + name: `Agent ${rosterSize - 1}`, + role: "engineer", + status: "active", + companyId: "company-1", + } as Parameters[0]["agents"][number]; + for (let pass = 0; pass < 5; pass += 1) { + flushSync(() => { + root!.render( + + + , + ); + }); + } + expect(nonActiveIdLookups).toBe(rosterSize - 1); + expect(unreadIterations).toBe(1); + }); +}); diff --git a/ui/src/components/MobileContextualNav.tsx b/ui/src/components/MobileContextualNav.tsx new file mode 100644 index 00000000000..53f3b2b9893 --- /dev/null +++ b/ui/src/components/MobileContextualNav.tsx @@ -0,0 +1,102 @@ +import { Fragment, useEffect, useRef } from "react"; +import type { LucideIcon } from "lucide-react"; +import { NavLink, useLocation } from "@/lib/router"; +import { Badge } from "@/components/ui/badge"; +import { SIDEBAR_SCROLL_RESET_STATE } from "@/lib/navigation-scroll"; +import { cn } from "@/lib/utils"; + +export interface MobileContextualNavItem { + key: string; + to: string; + label: string; + icon?: LucideIcon; + end?: boolean; + badge?: number; + badgeTone?: "default" | "danger"; + badgeLabel?: string; +} + +export interface MobileContextualNavGroup { + key: string; + items: readonly MobileContextualNavItem[]; +} + +export function MobileContextualNav({ + surface, + ariaLabel, + groups, + className, +}: { + surface: string; + ariaLabel: string; + groups: readonly MobileContextualNavGroup[]; + className?: string; +}) { + const location = useLocation(); + const navRef = useRef(null); + const visibleGroups = groups.filter((group) => group.items.length > 0); + const itemSignature = visibleGroups + .flatMap((group) => group.items.map((item) => item.to)) + .join("|"); + + useEffect(() => { + const nav = navRef.current; + if (!nav) return; + const active = nav.querySelector('[aria-current="page"]'); + if (typeof active?.scrollIntoView === "function") { + active.scrollIntoView({ inline: "nearest", block: "nearest" }); + } + }, [location.pathname, itemSignature]); + + if (visibleGroups.length === 0) return null; + + return ( +
+ +
+ ); +} diff --git a/ui/src/components/PageTabBar.test.tsx b/ui/src/components/PageTabBar.test.tsx new file mode 100644 index 00000000000..47b71b6a9d2 --- /dev/null +++ b/ui/src/components/PageTabBar.test.tsx @@ -0,0 +1,92 @@ +// @vitest-environment jsdom + +import { flushSync } from "react-dom"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { PageTabBar } from "./PageTabBar"; + +const mockUseSidebar = vi.fn(); + +vi.mock("../context/SidebarContext", () => ({ + useSidebar: () => mockUseSidebar(), +})); + +describe("PageTabBar mobile select", () => { + let container: HTMLDivElement; + let root: Root | null = null; + + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + mockUseSidebar.mockReturnValue({ isMobile: true }); + }); + + afterEach(() => { + flushSync(() => root?.unmount()); + root = null; + container.remove(); + vi.clearAllMocks(); + }); + + it("extracts readable text from JSX labels for mobile