Files
PaperClipAI/ui/src/components/AgentConversationSidebar.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

208 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useId, useMemo, useRef, useState, type ReactNode } from "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";
import { AgentChatPicker } from "@/components/AgentChatPicker";
import { AgentAvatar } from "@/components/AgentAvatar";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Link, useNavigate } from "@/lib/router";
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<string, string>;
unreadAgentIds?: readonly string[];
unreadMessageCounts?: ReadonlyMap<string, number>;
loading?: boolean;
error?: Error | null;
onRetry?: () => void;
initialSearch?: string;
onSelect?: (agent: Agent, signal?: AbortSignal) => void | Promise<void>;
onBrowse?: () => void;
onAddChat?: (agent: Agent, signal?: AbortSignal) => void | Promise<void>;
historyLoading?: boolean;
historyError?: Error | null;
onRetryHistory?: () => void;
onCreateAgent?: () => void;
renderAgentAction?: (agent: Agent) => ReactNode;
pinnedAgentIds?: readonly string[];
onReorderPins?: (ids: string[]) => void;
}
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, 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);
const searchRef = useRef<HTMLInputElement>(null);
const headingId = useId();
const unreadIds = useMemo(() => new Set(unreadAgentIds), [unreadAgentIds]);
const pinnedIds = useMemo(() => new Set(pinnedAgentIds), [pinnedAgentIds]);
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 ? (
<Button variant="ghost" size="icon-sm" className="text-muted-foreground" aria-label="Browse chats" title="Browse chats">
<PanelLeftOpen className="size-4" aria-hidden />
</Button>
) : mobileSwitcher ? (
<Button
variant="ghost"
size="sm"
data-mobile-contextual-nav="agent-chat"
aria-label="Browse chats"
className="h-8 w-full max-w-full justify-between gap-2 px-2 text-xs font-medium text-foreground"
>
<span className="flex min-w-0 items-center gap-2">
{activeAgent ? (
<AgentAvatar agent={activeAgent} size={20} />
) : (
<Users className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
)}
<span className="truncate">{activeAgent ? activeAgent.name : "Choose an agent"}</span>
</span>
<span className="flex shrink-0 items-center gap-1.5 text-muted-foreground">
{otherUnreadCount > 0 ? (
<Badge
variant="ghost"
className="bg-primary px-1.5 py-0 text-(length:--text-nano) leading-tight font-mono tabular-nums text-primary-foreground"
>
{otherUnreadCount > 99 ? "99+" : otherUnreadCount}
</Badge>
) : null}
<ChevronsUpDown className="size-3.5 shrink-0" aria-hidden="true" />
</span>
</Button>
) : undefined;
const picker = <AgentChatPicker agents={compact || mobileSwitcher ? agents : availableAgents} open={pickerOpen} onOpenChange={setPickerOpen}
trigger={pickerTrigger}
unreadMessageCounts={unreadMessageCounts}
existingChatAgentIds={existingChatAgentIds ?? agents.map(agent => agent.id)} loading={loading} error={error} onRetry={onRetry}
renderAgentIcon={agent => <AgentAvatar agent={agent} size={32} />}
onSelect={async (agent, signal) => {
if (onAddChat) await onAddChat(agent, signal);
else if (onSelect) await onSelect(agent, signal);
else navigate(`/chats/${encodeURIComponent(agentRouteRef(agent))}`);
if (!signal?.aborted) setSearch("");
}} />;
if (compact) return picker;
if (mobileSwitcher) {
return (
<div className="flex flex-col gap-1.5 border-b border-border bg-background px-3 py-1.5">
{picker}
{historyError ? (
<div role="alert" className="flex flex-wrap items-center justify-between gap-2 px-2 py-1">
<p className="text-xs text-muted-foreground">Some chat history couldn’t load.</p>
{onRetryHistory ? (
<Button variant="outline" size="sm" onClick={onRetryHistory}>
Retry chat history
</Button>
) : null}
</div>
) : null}
</div>
);
}
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]));
const pins = pinnedAgentIds.flatMap(id => {
const agent = byId.get(id);
return agent ? [agent] : [];
});
const visible = [...pins, ...matching.filter(agent => !pinnedIds.has(agent.id))];
const visiblePinnedIds = pins.map(agent => agent.id);
function focusSearch() {
setSearch("");
searchRef.current?.focus();
}
return <aside aria-labelledby={headingId} className="flex h-full min-h-0 flex-col border-r border-border bg-background">
<h2 id={headingId} className="sr-only">Chat contacts</h2>
<div className="flex shrink-0 items-center gap-2 px-3 pb-3 pt-5">
<div className="relative min-w-0 flex-1">
<Search aria-hidden="true" className="pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
<Input ref={searchRef} aria-label="Search chats" placeholder="Search chats" value={search} onChange={event => setSearch(event.target.value)}
onKeyDown={event => { if (event.key === "Escape") { event.stopPropagation(); setSearch(""); } }}
className="h-9 pl-8 pr-8 text-xs md:text-xs" />
{search && <Button variant="ghost" size="icon-xs" aria-label="Clear search" className="absolute right-1 top-1/2 -translate-y-1/2" onClick={focusSearch}><X className="size-3" /></Button>}
</div>
</div>
<div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 pb-3 scrollbar-auto-hide">
<span role="status" className="sr-only">{loading ? "Loading agents" : `${visible.length} ${visible.length === 1 ? "agent" : "agents"}`}</span>
{historyLoading && <p role="status" className="px-2 text-xs text-muted-foreground">Loading chat history…</p>}
{historyError && <div role="alert" className="flex flex-col items-start gap-2 px-2 py-3">
<p className="text-xs text-muted-foreground">Some chat history couldn’t load.</p>
<Button variant="outline" size="sm" onClick={onRetryHistory}>Retry chat history</Button>
</div>}
{error ? <div role="alert" className="flex flex-col items-start gap-2 px-2 py-6"><p className="text-sm">Couldn’t load your chats.</p><Button variant="outline" size="sm" onClick={onRetry}>Try again</Button></div> : loading ? <div aria-hidden="true" className="flex flex-col gap-1">
{[0, 1, 2, 3].map(index => <div key={index} className="flex items-center gap-3 rounded-md px-2 py-3 motion-safe:animate-pulse">
<div className="size-8 shrink-0 rounded-lg bg-muted" />
<div className="flex flex-1 flex-col gap-2"><div className="h-3 w-2/3 rounded-sm bg-muted" /><div className="h-2 w-full rounded-sm bg-muted" /></div>
</div>)}
</div> : visible.length ? <nav aria-label="Agent conversations" className="flex flex-col gap-1">
<SortablePinnedList keys={visiblePinnedIds} onReorder={onReorderPins}>
{visible.map(agent => {
const unreadCount = unreadMessageCounts?.get(agent.id) ?? 0;
const hasUnread = unreadCount > 0 || unreadIds.has(agent.id);
const canReorder = pinnedIds.has(agent.id) && !!onReorderPins;
const content = <><Link to={`/chats/${encodeURIComponent(agent.status === "terminated" ? agent.id : agentRouteRef(agent))}`}
aria-current={activeId === agent.id ? "page" : undefined}
title={`${agent.name}${agent.title ? ` · ${agent.title}` : ""}`}
onClick={event => { if (onSelect) { event.preventDefault(); onSelect(agent); } }}
className={cn("agent-contact-row flex min-w-0 items-center gap-3 rounded-md px-2.5 py-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring", renderAgentAction && hasUnread && "pr-12", canReorder && "pr-20", activeId === agent.id ? "bg-accent text-accent-foreground" : "group-hover/agent-pin:bg-accent/60 group-focus-within/agent-pin:bg-accent/60")}>
<AgentAvatar agent={agent} size={40} />
<span className="agent-pin-text flex min-w-0 flex-1 flex-col gap-0.5">
<span className="truncate text-sm font-medium">{agent.name}</span>
<span className="truncate text-xs text-muted-foreground">{agent.status === "terminated" ? "Terminated" : agent.title ?? agent.role}</span>
</span>
{unreadCount > 0 ? <Badge variant="ghost" aria-label={`${unreadCount} unread ${unreadCount === 1 ? "message" : "messages"} from ${agent.name}`} className="shrink-0 bg-primary font-mono tabular-nums text-primary-foreground">{unreadCount}</Badge>
: unreadIds.has(agent.id) && <span role="img" aria-label={`Unread messages from ${agent.name}`} className="size-2 shrink-0 rounded-full bg-primary" />}
</Link>{renderAgentAction?.(agent)}</>;
return <SortablePinnedRow key={agent.id} id={agent.id} label={agent.name} disabled={!canReorder} className={contactRowClassName}
data-selected={activeId === agent.id || undefined} data-has-unread={hasUnread || undefined}
handleClassName="agent-chat-pin right-2 size-8 focus-visible:outline-none group-hover/agent-pin:opacity-100 group-focus-within/agent-pin:opacity-100" handleIconClassName="size-4">{content}</SortablePinnedRow>;
})}
</SortablePinnedList>
</nav> : !agents.length && (historyLoading || historyError) ? null : <div className="flex flex-col items-start gap-2 px-2 py-6">
<p className="text-sm font-medium">{agents.length ? "No agents found" : "No chats yet"}</p>
<p className="text-xs leading-relaxed text-muted-foreground">{agents.length ? "Try another name or role." : "Choose an agent to start a conversation."}</p>
{!agents.length && <Button variant="outline" size="sm" onClick={() => setPickerOpen(true)}>Choose an agent</Button>}
{agents.length > 0 && <Button variant="outline" size="sm" onClick={focusSearch}>Clear search</Button>}
</div>}
{onCreateAgent && !loading && !error && <button type="button" onClick={onCreateAgent}
className="flex min-w-0 items-center gap-3 rounded-md px-2.5 py-3 text-left hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
<span aria-hidden className="flex size-10 shrink-0 items-center justify-center"><span className="agent-contact-create flex size-8 items-center justify-center bg-muted"><Plus className="size-5 text-foreground" /></span></span>
<span className="text-sm font-medium">Create a new agent</span>
</button>}
</div>
{onBrowse && <div className="shrink-0 px-3 py-4">
<Button variant="ghost" size="sm" className="w-full justify-start gap-2 px-2 text-muted-foreground" onClick={onBrowse}>
<Users className="size-4" />Browse all agents
</Button>
</div>}
{picker}
</aside>;
}