Files
PaperClipAI/ui/src/components/Layout.mobile.test.tsx
T
DottaandPaperclip 99203b9f95 fix(ui): add mobile contextual navigation, drawer escape, and shell nav polish (#23047)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The board UI uses contextual sidebars in `Layout` to switch sections
on Agent Detail, App Detail, Chat Endpoint Detail, Apps developer tools,
Agent Chat, and Company Settings pages.
> - On mobile viewports (`< 768px`), `Layout` hides the adjacent
secondary sidebar without rendering an inline section switcher for most
contextual routes, traps the mobile drawer inside the contextual sidebar
without a Workspace back path, leaks a half-masked `MobileBottomNav`
beside the open drawer, overlaps the `MobileBottomNav` unread badge over
the icon center, and misaligns the `PageTabBar` native `<select>`
chevron while dropping readable text from JSX tab labels.
> - Operators on mobile cannot reach agent configuration views
(`Identity`, `Harness / Runtime`, `Secrets & variables`, `Permissions /
Trust`, `Advanced`, `Activity`, `Runs`, `Costs`, `Budgets`, and plugin
`detailTab` slots) or leave contextual drawers cleanly.
> - This pull request adds inline mobile section switchers for all
contextual-sidebar routes, adds a non-trapping `Workspace | <Section>`
switcher to the mobile drawer, fixes `MobileBottomNav` badge alignment
and drawer z-index layering, adds `companySettingsPluginSlots` support
to `CompanySettingsNav`, and fixes `PageTabBar` mobile `<select>`
chevron alignment and JSX `<option>` text extraction.
> - The benefit is full mobile navigation parity across agent
configuration and contextual shell surfaces without breaking desktop
layouts.

## Linked Issues or Issue Description

**What happened?**

On mobile viewports (`< 768px`), opening an Agent Detail page
(`/agents/:agentId/overview`) showed no on-page tabs for the 10 built-in
views or plugin `detailTab` slots, and opening the mobile sidebar drawer
replaced global Workspace navigation with only the agent links and no
back link. The same inline-nav gap affected `AppDetail`,
`ChatEndpointDetail`, `AppsSidebar`, and `AgentChat`. In addition,
`CompanySettingsNav` omitted `companySettingsPluginSlots`, `PageTabBar`
stretched its mobile `<select>` wrapper inside `<Tabs>` so the
`<ChevronDown>` icon floated on the far right while falling back to raw
values for JSX labels, and `MobileBottomNav` overlapped two-digit unread
badges over the Inbox icon while peeking out beside the open mobile
drawer.

**Expected behavior**

Mobile operators see an accessible inline section switcher on Agent
Detail (all 10 built-in views plus plugin `detailTab` slots),
`AppDetail`, `ChatEndpointDetail`, `AppsSidebar`, and `AgentChat`.
Opening the mobile drawer always provides immediate access to global
Workspace navigation and cleanly layers above `MobileBottomNav`.
`CompanySettingsNav` aligns with `CompanySettingsSidebar` including
plugin settings slots and `/company/export`. `PageTabBar` aligns its
chevron inside the `<select>` box and renders readable plain text from
JSX tab labels. `MobileBottomNav` places unread counts cleanly at the
top-right corner of the icon.

**Steps to reproduce**

1. Resize the board UI to a mobile viewport (`390x844`, `< 768px`).
2. Open an Agent Detail page (`/agents/:agentId/overview`), an App
Detail page, a Chat Endpoint Detail page, an Agent Chat page, and
Company Settings.
3. Observe missing inline section controls on contextual routes, the
trapped mobile drawer, the misaligned `PageTabBar` chevron, and the
overlapping `MobileBottomNav` unread badge and open-drawer layering.

**Paperclip version or commit**

`85ad16b47e` (`master`)

**Deployment mode**

Local dev (`pnpm dev`) / Storybook responsive verification

## What Changed

- Added reusable token-backed `MobileContextualNav`
(`ui/src/components/MobileContextualNav.tsx`) with horizontal scroll,
group dividers, active pill auto-scroll, and optional danger/secondary
badges.
- Added `AgentContextualMobileNav`
(`ui/src/components/AgentContextualSidebar.tsx`), `AppDetailMobileNav`
(`ui/src/components/AppConnectionSidebar.tsx`), `ChatDetailMobileNav`
(`ui/src/components/chat/ChatDetailSidebar.tsx`), `AppsMobileNav`
(`ui/src/components/AppsSidebar.tsx`), and `mobileSwitcher` mode on
`AgentConversationsSidebar` / `AgentConversationSidebar` so all
contextual-sidebar routes render inline mobile navigation below
`BreadcrumbBar` in `Layout.tsx`.
- Updated `Layout.tsx` mobile drawer to never trap users: routes with
inline mobile nav default the drawer to global `<Sidebar>`, all
contextual routes expose a `Workspace | <Section>` switcher (with `←
Workspace` when viewing the contextual pane), and the drawer backdrop
(`z-40`) and drawer (`z-50`, `inert` when closed) mount at shell root
after `MobileBottomNav` (`z-30`, `visible={mobileNavVisible &&
!sidebarOpen}`).
- Updated `MobileBottomNav.tsx` badge positioning (`-top-1.5 left-3
min-w-4`) so two-digit (`96`) and `99+` badges anchor to the top-right
edge and expand outward without covering the icon center.
- Updated `CompanySettingsNav.tsx` to match `CompanySettingsSidebar.tsx`
ordering and routes (including `/company/export`) and to render and
match `companySettingsPluginSlots`.
- Updated `PageTabBar.tsx` mobile `<select>` wrapper (`w-fit max-w-full
self-start` + `w-full appearance-none bg-none`) to eliminate stray
far-right and duplicate chevrons, and added `extractTabOptionText` to
extract readable text from JSX `item.label` nodes.
- Removed unused `PageTabBar` and `Tabs` imports in
`ui/src/pages/AgentDetail.tsx` and added `flex-wrap` to the left-agent
membership notice banner.
- Added responsive mobile Storybook views (`AgentOverviewMobile`,
`AgentRuntimeMobile` in `agent-persona-pages.stories.tsx`;
`MobileSettingsAndBottomNav`, `MobileAgentDrawerOpen` in
`navigation-layout.stories.tsx`) and 5 new Vitest unit/component suites.

## Verification

- Targeted Vitest (`pnpm --filter @paperclipai/ui exec vitest run
src/components/PageTabBar.test.tsx
src/components/access/CompanySettingsNav.test.tsx
src/components/MobileBottomNav.test.tsx
src/components/MobileContextualNav.test.tsx
src/components/Layout.mobile.test.tsx src/lib/shell-navigation.test.ts
src/pages/agent-detail-navigation.test.ts
src/pages/apps/apps-rail.test.ts src/context/SidebarContext.test.tsx
src/lib/mobile-nav-scroll.test.ts
src/components/contextual-sidebar-styles.test.ts`): 11/11 files, 38/38
tests passed.
- Replay masking check (`pnpm --filter @paperclipai/ui exec vitest run
src/lib/analytics/replay-masking.test.tsx`): 220/220 tests passed.
- Typecheck (`pnpm --filter @paperclipai/ui typecheck`): passed with 0
errors.
- Design token gates (`pnpm check:token-gates`): all 4 gates CLEAN and
cliplab character in sync.
- Storybook catalog and map checks (`node scripts/storybook-catalog.mjs
--check && node --test scripts/check-maps.test.mjs
scripts/storybook-catalog.test.mjs
scripts/storybook-feature-index.test.mjs`): passed (372 files, 3490
stories; 30/30 tests passed).

## Risks

- Low risk: desktop layouts (`isMobile === false`) and desktop
sidebar/rail behavior remain unchanged.
- On mobile, hiding `MobileBottomNav` while `sidebarOpen` is true uses
the existing `data-visible="false"` + `inert` transition while
preserving `--tc-composer-bottom` so background page content does not
shift when opening or closing the drawer.

## Model Used

- Model Used: Gemini 4 Neon (High) — agentic coding assistant with
reasoning, code editing, shell execution, and local test verification.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-27 14:00:55 +00:00

274 lines
10 KiB
TypeScript

// @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: () => <div data-testid="plugin-sidebar-slot">Plugin Sidebar</div>,
resolveRouteSidebarSlot: (slots: Array<{ id: string; displayName: string }>) => slots[0] ?? null,
usePluginSlots: (...args: unknown[]) => mockUsePluginSlots(...args),
}));
vi.mock("./Sidebar", () => ({
Sidebar: () => <nav data-testid="global-workspace-sidebar">Global Workspace Sidebar</nav>,
}));
vi.mock("./AgentContextualSidebar", () => ({
AgentContextualSidebar: ({ agentRef }: { agentRef: string }) => (
<div data-testid="agent-contextual-sidebar">Agent Sidebar: {agentRef}</div>
),
AgentContextualMobileNav: ({ agentRef }: { agentRef: string }) => (
<nav data-testid="agent-contextual-mobile-nav">Agent Mobile Tabs: {agentRef}</nav>
),
}));
vi.mock("./CompanySettingsSidebar", () => ({
CompanySettingsSidebar: () => <div data-testid="settings-sidebar">Settings Sidebar</div>,
}));
vi.mock("./access/CompanySettingsNav", () => ({
CompanySettingsNav: () => <div data-testid="settings-mobile-nav">Settings Mobile Nav</div>,
}));
vi.mock("./AppsSidebar", () => ({
AppsSidebar: () => <div data-testid="apps-sidebar">Apps Sidebar</div>,
AppsMobileNav: () => <div data-testid="apps-mobile-nav">Apps Mobile Nav</div>,
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: () => <div data-testid="app-detail-sidebar">App Detail Sidebar</div>,
AppDetailMobileNav: () => <div data-testid="app-detail-mobile-nav">App Detail Mobile Nav</div>,
}));
vi.mock("./AgentConversationsSidebar", () => ({
AgentConversationsSidebar: ({ mobileSwitcher }: { mobileSwitcher?: boolean }) => (
<div data-testid={mobileSwitcher ? "agent-chat-mobile-switcher" : "agent-chat-sidebar"}>
{mobileSwitcher ? "Chat Switcher" : "Chat Sidebar"}
</div>
),
}));
vi.mock("./MobileBottomNav", () => ({
MobileBottomNav: ({ visible }: { visible: boolean }) => (
<nav data-testid="mobile-bottom-nav" data-visible={String(visible)}>
Bottom Nav
</nav>
),
}));
vi.mock("./BreadcrumbBar", () => ({
BreadcrumbBar: () => <div data-testid="breadcrumb-bar">Breadcrumb</div>,
}));
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: () => <div data-testid="account-menu" /> }));
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(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/:companyPrefix" element={<Layout />}>
<Route path="agents/:agentId/:tab" element={<div>Agent Page</div>} />
<Route path="apps/chat/connect" element={<div>Chat Connect Page</div>} />
<Route path="custom-plugin" element={<div>Plugin Page</div>} />
</Route>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
});
}
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();
});
});