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>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-27 14:00:55 +00:00
1 parent 26c72ed7ca
commit 99203b9f95
20 files changed
+1791 -218

No files matched your search

@@ -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(
+81 -33
View File
@@ -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<AgentLocalDetailView, typeof Sparkles>;
export function AgentContextualSidebar({
agentRef,
agentId,
agentName,
labels,
}: {
interface AgentContextualNavigationProps {
agentRef: string;
agentId?: string;
agentName?: string;
labels?: Partial<Record<AgentLocalDetailView, string>>;
}) {
}
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<MobileContextualNavGroup[]>(() => {
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 (
<ContextualSidebarFrame
surface="agent"
@@ -83,30 +129,20 @@ export function AgentContextualSidebar({
data-slot="contextual-sidebar-nav"
className={contextualSidebarStyles.nav}
>
{AGENT_DETAIL_NAVIGATION.map((section) => (
<div key={section.label} className="contents">
{section.label === "Audit" && pluginTabs.length > 0 ? (
<div data-slot="contextual-sidebar-section" className={contextualSidebarStyles.section}>
<p className={contextualSidebarStyles.sectionLabel}>Apps</p>
<div className={contextualSidebarStyles.group}>
{pluginTabs.map(slot => <SidebarNavItem key={`${slot.pluginKey}:${slot.id}`} to={`/agents/${encodeURIComponent(agentRef)}/${encodeURIComponent(`plugin:${slot.pluginKey}:${slot.id}`)}`} label={slot.displayName} icon={Wrench} />)}
</div>
</div>
) : null}
<div data-slot="contextual-sidebar-section" className={contextualSidebarStyles.section}>
<p data-slot="contextual-sidebar-section-label" className={contextualSidebarStyles.sectionLabel}>
{section.label}
</p>
<div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>
{section.items.map((item) => (
<SidebarNavItem
key={item.value}
to={agentDetailHref(agentRef, item.value)}
label={labels?.[item.value] ?? item.label}
icon={localIcons[item.value]}
/>
))}
</div>
{groups.map((section) => (
<div key={section.key} data-slot="contextual-sidebar-section" className={contextualSidebarStyles.section}>
<p data-slot="contextual-sidebar-section-label" className={contextualSidebarStyles.sectionLabel}>
{section.key}
</p>
<div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>
{section.items.map((item) => (
<SidebarNavItem
key={item.key}
to={item.to}
label={item.label}
icon={item.icon ?? Wrench}
/>
))}
</div>
</div>
))}
@@ -114,3 +150,15 @@ export function AgentContextualSidebar({
</ContextualSidebarFrame>
);
}
export function AgentContextualMobileNav(props: AgentContextualNavigationProps) {
const { resolvedName, groups } = useAgentContextualNavigation(props);
return (
<MobileContextualNav
surface="agent"
ariaLabel={`${resolvedName} navigation`}
groups={groups}
/>
);
}
+68 -5
View File
@@ -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<string, string>;
unreadAgentIds?: readonly string[];
unreadMessageCounts?: ReadonlyMap<string, number>;
@@ -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 = <AgentChatPicker agents={compact ? agents : availableAgents} open={pickerOpen} onOpenChange={setPickerOpen}
trigger={compact ? <Button variant="ghost" size="icon-sm" className="text-muted-foreground" aria-label="Browse chats" title="Browse chats">
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> : undefined}
</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} />}
@@ -62,6 +108,23 @@ export function AgentConversationSidebar({ agents, compact = false, existingChat
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]));
+41 -27
View File
@@ -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 <AgentConversationSidebar key={`${companyId}:${userId}`} agents={[...conversations, ...teammates]} availableAgents={roster}
return <AgentConversationSidebar key={`${companyId}:${userId}`} agents={orderedAgents} availableAgents={roster}
compact={compact}
mobileSwitcher={mobileSwitcher}
existingChatAgentIds={existingChatAgentIds}
activeId={active?.id} previews={previews}
activeId={active?.id}
activeAgent={active}
previews={previews}
unreadAgentIds={unreadAgentIds}
unreadMessageCounts={unreadMessageCounts}
pinnedAgentIds={pinnedAgentIds}
@@ -82,7 +96,7 @@ export function AgentConversationsSidebar({ compact = false }: { compact?: boole
historyLoading={historyAgents.some(result => 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);
+49 -10
View File
@@ -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 (
<aside className="flex h-full min-h-0 w-full flex-col border-r border-border bg-background">
<div className="flex shrink-0 flex-col gap-3 px-3 py-3">
@@ -101,7 +127,7 @@ export function AppDetailSidebar(props: AppDetailSidebarProps) {
name={appName}
brandKey={brandKey}
logoUrl={appDefinitionLogoUrl(logoEntry)}
allowRemoteFallback={!applicationsQuery.isPending}
allowRemoteFallback={!applicationsPending}
darkLogoUrl={appDefinitionDarkLogoUrl(logoEntry)}
size={28}
/>
@@ -111,16 +137,16 @@ export function AppDetailSidebar(props: AppDetailSidebarProps) {
<nav className="scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-3 py-2">
<div className="flex flex-col gap-0.5">
{APP_TABS.filter(tab => !poolPluginKey || tab.key === "permissions").map((tab) => (
{visibleTabs.map((tab) => (
<SidebarNavItem
key={tab.key}
to={tabHref(props, tab.key)}
label={poolPluginKey ? "Settings" : tab.label}
to={tab.to}
label={tab.label}
icon={tab.icon}
end
badge={tab.key === "review" && reviewCount > 0 ? reviewCount : undefined}
badgeTone="danger"
badgeLabel="needing review"
end={tab.end}
badge={tab.badge}
badgeTone={tab.badgeTone}
badgeLabel={tab.badgeLabel}
/>
))}
</div>
@@ -129,6 +155,19 @@ export function AppDetailSidebar(props: AppDetailSidebarProps) {
);
}
export function AppDetailMobileNav(props: AppDetailSidebarProps) {
const { appName, visibleTabs } = useAppDetailNavigation(props);
if (visibleTabs.length <= 1) return null;
return (
<MobileContextualNav
surface="app-detail"
ariaLabel={`${appName} navigation`}
groups={[{ key: "tabs", items: visibleTabs }]}
/>
);
}
function tabHref(props: AppDetailSidebarProps, tab: AppTabKey): string {
return props.kind === "connection"
? appTabHref(props.connectionId, tab)
+49 -3
View File
@@ -1,12 +1,25 @@
import { useLocation } from "@/lib/router";
import { ChatDetailSidebar } from "./chat/ChatDetailSidebar";
import { ChatDetailMobileNav, ChatDetailSidebar } from "./chat/ChatDetailSidebar";
import { ChatSetupSidebar } from "./chat/ChatSetupNavigation";
import { Store } from "lucide-react";
import { DEVELOPER_TABS, advancedTabHref, isExperimentalToolTab } from "@/pages/tools/tool-tabs";
import { useSmokeLabEnabled } from "@/hooks/useSmokeLabEnabled";
import { MobileContextualNav } from "./MobileContextualNav";
import { SidebarNavItem } from "./SidebarNavItem";
import { contextualSidebarStyles } from "./contextual-sidebar-styles";
const CHAT_DETAIL_PATH_RE = /\/apps\/chat\/([^/]+)(?:\/(?:settings|access|conversations|activity)|\/reviews(?:\/[^/]+)?)?\/?$/;
function isChatConnectPath(pathname: string): boolean {
return pathname.replace(/\/+$/, "").endsWith("/apps/chat/connect");
}
export function appsRouteHasMobileNav(pathname: string, hasDeveloperTabs: boolean): boolean {
if (isChatConnectPath(pathname)) return false;
if (CHAT_DETAIL_PATH_RE.test(pathname)) return true;
return hasDeveloperTabs;
}
/** Developer tabs that are switched on for this instance; Gateways and Profiles stay hidden until they ship. */
export function useAppsDeveloperTabs() {
const { enabled: smokeLabEnabled } = useSmokeLabEnabled();
@@ -25,8 +38,8 @@ export function AppsSidebar() {
const { pathname } = useLocation();
const developerTabs = useAppsDeveloperTabs();
if (pathname.endsWith("/apps/chat/connect")) return <ChatSetupSidebar />;
const chatDetail = pathname.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|conversations|activity)|\/reviews(?:\/[^/]+)?)?\/?$/);
if (isChatConnectPath(pathname)) return <ChatSetupSidebar />;
const chatDetail = pathname.match(CHAT_DETAIL_PATH_RE);
if (chatDetail) return <ChatDetailSidebar endpointId={chatDetail[1]} />;
return (
@@ -70,3 +83,36 @@ export function AppsSidebar() {
</aside>
);
}
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 <ChatDetailMobileNav endpointId={chatDetail[1]} />;
if (developerTabs.length === 0) return null;
return (
<MobileContextualNav
surface="apps"
ariaLabel="Plugins"
groups={[
{
key: "plugins",
items: [{ key: "all-plugins", to: "/apps", label: "All plugins", icon: Store, end: true }],
},
{
key: "developer",
items: developerTabs.map((tab) => ({
key: tab.key,
to: advancedTabHref(tab.key),
label: tab.label,
icon: tab.icon,
end: true,
})),
},
]}
/>
);
}
+273
View File
@@ -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: () => <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();
});
});
+112 -40
View File
@@ -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 }) {
<AgentContextualSidebar agentRef={agentId} />
) : sharedSecondarySidebar;
const hasSecondarySidebar = secondarySidebar != null;
const mobileContextualNav = !isMobile ? null : isCompanySettingsRoute ? (
<div className="border-b border-border px-4 pb-3">
<CompanySettingsNav />
</div>
) : isAgentChatRoute ? (
<AgentConversationsSidebar mobileSwitcher />
) : shellRoute.builtInContextualSurface === "agent" && agentId ? (
<AgentContextualMobileNav agentRef={agentId} />
) : appDetailApplicationId ? (
<AppDetailMobileNav kind="application" applicationId={appDetailApplicationId} />
) : appsRouteHasRail(companyPathSegments, appsDeveloperTabs.length > 0)
&& appsRouteHasMobileNav(location.pathname, appsDeveloperTabs.length > 0) ? (
<AppsMobileNav />
) : 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 }) {
<WorktreeBanner />
<DevRestartBanner devServer={health?.devServer} />
<div className={cn("app-main-row min-h-0 flex-1", isMobile ? "w-full" : "flex overflow-clip")}>
{isMobile && sidebarOpen && (
<button
type="button"
className="fixed inset-0 z-40 bg-black/50"
onClick={() => setSidebarOpen(false)}
aria-label="Close sidebar"
/>
)}
{isMobile ? (
<div
className={cn(
"fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",
sidebarOpen ? "translate-x-0" : "-translate-x-full"
)}
>
<div className="flex flex-1 min-h-0 overflow-hidden">
<div className="w-60 shrink-0 overflow-hidden">
{hasSecondarySidebar ? (
<SecondarySidebar>{secondarySidebar}</SecondarySidebar>
) : (
<Sidebar>{sidebarSections}</Sidebar>
)}
</div>
</div>
<SidebarAccountMenu
deploymentMode={health?.deploymentMode}
/>
</div>
) : (
{!isMobile ? (
<SidebarShell
open={sidebarOpen}
resizable
@@ -566,7 +574,7 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
/>
</>}
</SidebarShell>
)}
) : null}
{!isMobile && !isAgentChatRoute && ((showsAdjacentSecondarySidebar && !keepsPrimarySidebar) || (designSandbox && replacesPrimarySidebar)) ? (
<SecondarySidebar className="w-60 shrink-0">
@@ -584,11 +592,7 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
>
<StandaloneBrowserControls mobile={isMobile} />
<BreadcrumbBar showPropertiesToggle={isAgentChatRoute} toolbarAction={chatListCollapsed ? <AgentConversationsSidebar compact /> : undefined} />
{isMobile && isCompanySettingsRoute ? (
<div className="border-b border-border px-4 pb-3">
<CompanySettingsNav />
</div>
) : null}
{mobileContextualNav}
</div>
<div className={cn(
"app-content-row",
@@ -672,7 +676,75 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
</div>
</div>
</div>
{isMobile && <MobileBottomNav visible={mobileNavVisible} />}
{isMobile && <MobileBottomNav visible={mobileNavVisible && !sidebarOpen} />}
{isMobile && sidebarOpen && (
<button
type="button"
data-slot="mobile-drawer-backdrop"
className="fixed inset-0 z-40 bg-black/50"
onClick={() => setSidebarOpen(false)}
aria-label="Close sidebar"
/>
)}
{isMobile ? (
<div
data-mobile-drawer="true"
inert={!sidebarOpen}
className={cn(
"fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden bg-background pt-(--sz-safe-top) transition-transform duration-100 ease-out",
sidebarOpen ? "translate-x-0" : "-translate-x-full",
)}
>
{hasSecondarySidebar ? (
<div
data-slot="mobile-drawer-switcher"
className="flex w-60 shrink-0 items-center gap-1 border-b border-r border-border bg-muted p-2"
>
<button
type="button"
aria-pressed={mobileDrawerPane === "workspace"}
onClick={() => setMobileDrawerPane("workspace")}
className={cn(
"flex min-w-0 flex-1 items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
mobileDrawerPane === "workspace"
? "bg-background text-foreground shadow-xs"
: "text-muted-foreground hover:bg-background/60 hover:text-foreground",
)}
>
{mobileDrawerPane === "contextual" ? (
<ArrowLeft className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
) : null}
<span className="truncate">Workspace</span>
</button>
<button
type="button"
aria-pressed={mobileDrawerPane === "contextual"}
onClick={() => setMobileDrawerPane("contextual")}
className={cn(
"flex min-w-0 flex-1 items-center justify-center rounded-md px-2 py-1.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
mobileDrawerPane === "contextual"
? "bg-background text-foreground shadow-xs"
: "text-muted-foreground hover:bg-background/60 hover:text-foreground",
)}
>
<span className="truncate">{mobileDrawerContextualLabel}</span>
</button>
</div>
) : null}
<div className="flex flex-1 min-h-0 overflow-hidden">
<div className="w-60 shrink-0 overflow-hidden">
{hasSecondarySidebar && mobileDrawerPane === "contextual" ? (
<SecondarySidebar>{secondarySidebar}</SecondarySidebar>
) : (
<Sidebar>{sidebarSections}</Sidebar>
)}
</div>
</div>
<SidebarAccountMenu
deploymentMode={health?.deploymentMode}
/>
</div>
) : null}
<CommandPalette />
<BoardDialogs />
<CloudTrialGate />
@@ -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(
<MemoryRouter initialEntries={["/PAP/issues"]}>
<MobileBottomNav visible />
</MemoryRouter>,
);
});
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");
});
});
+6 -2
View File
@@ -155,10 +155,14 @@ export function MobileBottomNav({ visible }: MobileBottomNavProps) {
>
{({ isActive }) => (
<>
<span className="relative">
<span className="relative inline-flex items-center justify-center">
<Icon className={cn("h-(--sz-18px) w-(--sz-18px)", isActive && "stroke-(length:--sw-2_3)")} />
{item.badge != null && item.badge > 0 && (
<Badge variant="ghost" className="absolute -right-2 -top-2 bg-primary px-1.5 text-(length:--text-nano) leading-none text-primary-foreground">
<Badge
variant="ghost"
data-slot="mobile-nav-badge"
className="pointer-events-none absolute -top-1.5 left-3 min-w-4 bg-primary px-1 py-0.5 text-(length:--text-nano) leading-none tabular-nums text-primary-foreground"
>
{item.badge > 99 ? "99+" : item.badge}
</Badge>
)}
@@ -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(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={["/PAP/agents/codexcoder/overview"]}>
<Routes>
<Route
path="/:companyPrefix/agents/:agentId/:tab"
element={<AgentContextualMobileNav agentRef="codexcoder" agentId="agent-1" agentName="CodexCoder" />}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
});
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(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={["/PAP/apps/conn-1/permissions"]}>
<Routes>
<Route
path="/:companyPrefix/apps/:connectionId/:tab"
element={<AppDetailMobileNav kind="connection" connectionId="conn-1" />}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
});
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(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={["/PAP/apps/chat/ep-1/settings"]}>
<Routes>
<Route
path="/:companyPrefix/apps/chat/:endpointId/:tab"
element={<ChatDetailMobileNav endpointId="ep-1" />}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
});
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(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={["/PAP/apps/advanced/smoke-lab"]}>
<Routes>
<Route path="/:companyPrefix/apps/advanced/:tab" element={<AppsMobileNav />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
});
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<typeof AgentConversationSidebar>[0]["agents"];
root = createRoot(container);
flushSync(() => {
root!.render(
<MemoryRouter initialEntries={["/PAP/chats/chief-of-staff"]}>
<AgentConversationSidebar
agents={agents}
activeId="a1"
unreadMessageCounts={new Map([["a1", 2], ["a2", 5]])}
mobileSwitcher
/>
</MemoryRouter>,
);
});
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<typeof AgentConversationSidebar>[0]["agents"];
root = createRoot(container);
flushSync(() => {
root!.render(
<MemoryRouter initialEntries={["/PAP/chats/chief-of-staff"]}>
<AgentConversationSidebar
agents={agents}
activeId="a1"
historyError={new Error("network failed")}
onRetryHistory={onRetryHistory}
mobileSwitcher
/>
</MemoryRouter>,
);
});
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(
<MemoryRouter initialEntries={["/PAP/apps/chat/ep-1/reviews"]}>
<Routes>
<Route
path="/:companyPrefix/apps/chat/:endpointId/:tab"
element={
<MobileContextualNav
surface="chat-detail"
ariaLabel="Chat connection"
groups={[
{
key: "chat-detail",
items: [
{ key: "settings", to: "/apps/chat/ep-1/settings", label: "Settings", end: true },
],
},
]}
/>
}
/>
</Routes>
</MemoryRouter>,
);
});
expect(scrollIntoView).not.toHaveBeenCalled();
flushSync(() => {
root!.render(
<MemoryRouter initialEntries={["/PAP/apps/chat/ep-1/reviews"]}>
<Routes>
<Route
path="/:companyPrefix/apps/chat/:endpointId/:tab"
element={
<MobileContextualNav
surface="chat-detail"
ariaLabel="Chat connection"
groups={[
{
key: "chat-detail",
items: [
{ key: "settings", to: "/apps/chat/ep-1/settings", label: "Settings", end: true },
{ key: "reviews", to: "/apps/chat/ep-1/reviews", label: "Reviews" },
],
},
]}
/>
}
/>
</Routes>
</MemoryRouter>,
);
});
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<typeof AgentConversationSidebar>[0]["agents"];
let unreadIterations = 0;
const unreadMap = new Map<string, number>(
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(
<MemoryRouter initialEntries={[`/PAP/chats/${targetId}`]}>
<AgentConversationSidebar
agents={agents}
existingChatAgentIds={existingChatAgentIds}
activeId={targetId}
unreadMessageCounts={unreadMap}
mobileSwitcher
/>
</MemoryRouter>,
);
});
}
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<typeof AgentConversationSidebar>[0]["agents"][number];
for (let pass = 0; pass < 5; pass += 1) {
flushSync(() => {
root!.render(
<MemoryRouter initialEntries={[`/PAP/chats/${targetId}`]}>
<AgentConversationSidebar
agents={agents}
existingChatAgentIds={existingChatAgentIds}
activeId={targetId}
activeAgent={providedAgent}
unreadMessageCounts={unreadMap}
mobileSwitcher
/>
</MemoryRouter>,
);
});
}
expect(nonActiveIdLookups).toBe(rosterSize - 1);
expect(unreadIterations).toBe(1);
});
});
+102
View File
@@ -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<HTMLElement | null>(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<HTMLElement>('[aria-current="page"]');
if (typeof active?.scrollIntoView === "function") {
active.scrollIntoView({ inline: "nearest", block: "nearest" });
}
}, [location.pathname, itemSignature]);
if (visibleGroups.length === 0) return null;
return (
<div className={cn("border-b border-border bg-background", className)}>
<nav
ref={navRef}
aria-label={ariaLabel}
data-mobile-contextual-nav={surface}
className="flex min-w-0 items-center gap-1 overflow-x-auto scrollbar-auto-hide px-3 py-1.5"
>
{visibleGroups.map((group, groupIndex) => (
<Fragment key={group.key}>
{groupIndex > 0 ? (
<span aria-hidden="true" className="mx-1 h-4 w-px shrink-0 bg-border" />
) : null}
{group.items.map((item) => {
const Icon = item.icon;
return (
<NavLink
key={item.key}
to={item.to}
end={item.end}
state={SIDEBAR_SCROLL_RESET_STATE}
className={({ isActive }) =>
cn(
"inline-flex min-h-8 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground",
)
}
>
{Icon ? <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden="true" /> : null}
<span>{item.label}</span>
{item.badge != null && item.badge > 0 ? (
<Badge
variant={item.badgeTone === "danger" ? "destructive" : "secondary"}
aria-label={item.badgeLabel ? `${item.badge} ${item.badgeLabel}` : undefined}
className="px-1.5 py-0 text-(length:--text-nano) leading-tight tabular-nums"
>
{item.badge > 99 ? "99+" : item.badge}
</Badge>
) : null}
</NavLink>
);
})}
</Fragment>
))}
</nav>
</div>
);
}
+92
View File
@@ -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 <option> elements", () => {
root = createRoot(container);
flushSync(() => {
root!.render(
<PageTabBar
value="proposals"
onValueChange={() => {}}
items={[
{
value: "secrets",
label: (
<span>
<svg aria-hidden="true"><title>Icon</title></svg>
Secrets
</span>
),
},
{
value: "proposals",
label: (
<span>
<span>Proposals</span>
<span>(4)</span>
</span>
),
},
{
value: "pending",
label: <>Pending <span>12</span></>,
},
]}
/>,
);
});
const options = Array.from(container.querySelectorAll("option")).map((el) => el.textContent);
expect(options).toEqual(["Secrets", "Proposals (4)", "Pending 12"]);
});
it("keeps the select wrapper self-sized with appearance-none so chevron aligns inside select", () => {
root = createRoot(container);
flushSync(() => {
root!.render(
<PageTabBar
value="general"
onValueChange={() => {}}
items={[
{ value: "general", label: "General" },
{ value: "members", label: "Members" },
]}
/>,
);
});
const select = container.querySelector("select");
expect(select).not.toBeNull();
expect(select?.className).toContain("appearance-none");
expect(select?.className).toContain("w-full");
expect(select?.parentElement?.className).toContain("w-fit");
expect(select?.parentElement?.className).toContain("self-start");
});
});
+43 -6
View File
@@ -1,4 +1,4 @@
import type { ReactNode } from "react";
import { isValidElement, type ReactNode } from "react";
import { ChevronDown } from "lucide-react";
import { TabBar, type TabSize } from "./TabBar";
import { useSidebar } from "../context/SidebarContext";
@@ -14,23 +14,60 @@ interface PageTabBarProps {
onValueChange?: (value: string) => void;
align?: "center" | "start";
size?: TabSize;
ariaLabel?: string;
}
export function PageTabBar({ items, value, onValueChange, align = "center", size = "standard" }: PageTabBarProps) {
function collectReadableText(node: ReactNode, out: string[]) {
if (node == null || typeof node === "boolean") return;
if (typeof node === "string" || typeof node === "number") {
const trimmed = String(node).trim();
if (trimmed) out.push(trimmed);
return;
}
if (Array.isArray(node)) {
for (const child of node) {
collectReadableText(child, out);
}
return;
}
if (isValidElement(node)) {
const props = node.props as { "aria-hidden"?: boolean | "true" | "false"; children?: ReactNode };
if (props["aria-hidden"] === true || props["aria-hidden"] === "true") {
return;
}
collectReadableText(props.children, out);
}
}
export function extractTabOptionText(label: ReactNode, fallback: string): string {
const parts: string[] = [];
collectReadableText(label, parts);
const text = parts.join(" ").replace(/\s+/g, " ").trim();
return text || fallback;
}
export function PageTabBar({
items,
value,
onValueChange,
align = "center",
size = "standard",
ariaLabel = "Page section",
}: PageTabBarProps) {
const { isMobile } = useSidebar();
if (isMobile && value !== undefined && onValueChange) {
return (
<div className="relative inline-flex">
<div className="relative inline-flex w-fit max-w-full self-start">
<select
value={value}
onChange={(e) => onValueChange(e.target.value)}
className="h-9 appearance-none rounded-md border border-border bg-background pl-3 pr-9 py-1 text-base focus:outline-none focus:ring-1 focus:ring-ring"
aria-label="Page section"
className="h-9 w-full max-w-full appearance-none rounded-md border border-border bg-background bg-none pl-3 pr-9 py-1 text-base focus:outline-none focus:ring-1 focus:ring-ring"
aria-label={ariaLabel}
>
{items.map((item) => (
<option key={item.value} value={item.value}>
{typeof item.label === "string" ? item.label : item.value}
{extractTabOptionText(item.label, item.value)}
</option>
))}
</select>
@@ -0,0 +1,130 @@
// @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 { CompanySettingsNav, getCompanySettingsTab } from "./CompanySettingsNav";
const mockNavigate = vi.fn();
const mockUseLocation = vi.fn();
const mockUseHiddenSettings = vi.fn();
const mockUseCloudInstance = vi.fn();
const mockUseCompany = vi.fn();
const mockUsePluginSlots = vi.fn();
vi.mock("@/lib/router", () => ({
useLocation: () => mockUseLocation(),
useNavigate: () => mockNavigate,
}));
vi.mock("@/hooks/useHiddenSettings", () => ({
useHiddenSettings: () => mockUseHiddenSettings(),
}));
vi.mock("@/hooks/useCloudInstance", () => ({
useCloudInstance: () => mockUseCloudInstance(),
}));
vi.mock("@/context/CompanyContext", () => ({
useCompany: () => mockUseCompany(),
}));
vi.mock("@/plugins/slots", () => ({
usePluginSlots: (...args: unknown[]) => mockUsePluginSlots(...args),
}));
vi.mock("@/context/SidebarContext", () => ({
useSidebar: () => ({ isMobile: true }),
}));
describe("CompanySettingsNav", () => {
let container: HTMLDivElement;
let root: Root | null = null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
mockUseLocation.mockReturnValue({ pathname: "/PAP/company/settings" });
mockUseHiddenSettings.mockReturnValue({ hidden: new Set<string>() });
mockUseCloudInstance.mockReturnValue(false);
mockUseCompany.mockReturnValue({ selectedCompanyId: "company-1" });
mockUsePluginSlots.mockReturnValue({
slots: [
{
id: "billing-settings",
pluginKey: "paperclip.billing",
displayName: "Billing",
routePath: "billing",
},
],
});
});
afterEach(() => {
flushSync(() => root?.unmount());
root = null;
container.remove();
vi.clearAllMocks();
});
it("includes companySettingsPluginSlots and navigates to their routes", () => {
root = createRoot(container);
flushSync(() => {
root!.render(<CompanySettingsNav />);
});
const select = container.querySelector("select") as HTMLSelectElement;
expect(select).not.toBeNull();
const optionTexts = Array.from(select.options).map((opt) => opt.textContent);
expect(optionTexts).toContain("Billing");
expect(optionTexts).toContain("Export");
const billingOption = Array.from(select.options).find((opt) => opt.textContent === "Billing");
expect(billingOption).toBeDefined();
flushSync(() => {
select.value = billingOption!.value;
select.dispatchEvent(new Event("change", { bubbles: true }));
});
expect(mockNavigate).toHaveBeenCalledWith("/company/settings/billing");
});
it("navigates Export to /company/export (not /company/settings/export)", () => {
root = createRoot(container);
flushSync(() => {
root!.render(<CompanySettingsNav />);
});
const select = container.querySelector("select") as HTMLSelectElement;
flushSync(() => {
select.value = "export";
select.dispatchEvent(new Event("change", { bubbles: true }));
});
expect(mockNavigate).toHaveBeenCalledWith("/company/export");
});
it("resolves plugin settings routes to the matching plugin tab without built-in prefix collisions", () => {
const slots = [
{
id: "billing-settings",
pluginKey: "paperclip.billing",
displayName: "Billing",
routePath: "billing",
},
{
id: "secrets-manager",
pluginKey: "acme.vault",
displayName: "Secrets Manager",
routePath: "secrets-manager",
},
];
expect(getCompanySettingsTab("/PAP/company/settings/billing", slots)).toBe(
"plugin:paperclip.billing:billing-settings",
);
expect(getCompanySettingsTab("/PAP/company/settings/secrets-manager", slots)).toBe(
"plugin:acme.vault:secrets-manager",
);
expect(getCompanySettingsTab("/PAP/company/settings/secrets", slots)).toBe("secrets");
expect(getCompanySettingsTab("/PAP/company/export/files/agent.md", slots)).toBe("export");
});
});
+112 -47
View File
@@ -1,116 +1,181 @@
import { useMemo } from "react";
import { PageTabBar } from "@/components/PageTabBar";
import { Tabs } from "@/components/ui/tabs";
import { useCompany } from "@/context/CompanyContext";
import { useCloudInstance } from "@/hooks/useCloudInstance";
import { useHiddenSettings } from "@/hooks/useHiddenSettings";
import { INSTANCE_SETTINGS_PATH_PREFIX } from "@/lib/instance-settings";
import { useLocation, useNavigate } from "@/lib/router";
import { usePluginSlots } from "@/plugins/slots";
const items = [
interface CompanySettingsPluginSlotLike {
id: string;
pluginKey: string;
displayName: string;
routePath?: string | null;
}
interface CompanySettingsNavItem {
value: string;
label: string;
href: string;
hiddenKey?: string;
hideOnCloud?: boolean;
}
const builtInPrefixItems: readonly CompanySettingsNavItem[] = [
{ value: "general", label: "General", href: "/company/settings" },
{ value: "export", label: "Export", href: "/company/export" },
{ value: "import", label: "Import", href: "/company/import" },
{ value: "members", label: "Members", href: "/company/settings/members" },
{ value: "secrets", label: "Secrets", href: "/company/settings/secrets" },
{ value: "instance-profile", label: "Profile", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/profile` },
{ value: "instance-environments", label: "Environments", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/environments` },
{ value: "instance-profile", label: "Profile", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/profile`, hiddenKey: "instance.profile" },
{ value: "members", label: "Members", href: "/company/settings/members", hiddenKey: "company.members" },
];
const builtInSuffixItems: readonly CompanySettingsNavItem[] = [
{ value: "secrets", label: "Secrets", href: "/company/settings/secrets", hiddenKey: "company.secrets" },
{ value: "instance-environments", label: "Environments", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/environments`, hiddenKey: "instance.environments" },
{ value: "connections", label: "Connections", href: "/company/settings/connections" },
{ value: "instance-access", label: "Access", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/access` },
{ value: "instance-experimental", label: "Experimental", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/experimental` },
{ value: "instance-plugins", label: "System plugins", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/plugins` },
{ value: "instance-adapters", label: "Adapters", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/adapters` },
] as const;
{ value: "instance-access", label: "Access", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/access`, hiddenKey: "instance.access" },
{ value: "export", label: "Export", href: "/company/export", hiddenKey: "company.export" },
{ value: "import", label: "Import", href: "/company/import", hiddenKey: "company.import", hideOnCloud: true },
{ value: "instance-experimental", label: "Experimental", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/experimental`, hiddenKey: "instance.experimental" },
{ value: "instance-plugins", label: "System plugins", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/plugins`, hiddenKey: "instance.plugins" },
{ value: "instance-adapters", label: "Adapters", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/adapters`, hiddenKey: "instance.adapters" },
];
type CompanySettingsTab = (typeof items)[number]["value"];
export type CompanySettingsTab =
| "general"
| "export"
| "import"
| "members"
| "secrets"
| "instance-profile"
| "instance-environments"
| "connections"
| "instance-access"
| "instance-experimental"
| "instance-plugins"
| "instance-adapters"
| `plugin:${string}:${string}`;
/** Tab values suppressed when their page is operator-hidden. */
const hiddenSettingKeyByTab: Partial<Record<CompanySettingsTab, string>> = {
export: "company.export",
import: "company.import",
members: "company.members",
secrets: "company.secrets",
"instance-profile": "instance.profile",
"instance-environments": "instance.environments",
"instance-access": "instance.access",
"instance-experimental": "instance.experimental",
"instance-plugins": "instance.plugins",
"instance-adapters": "instance.adapters",
};
function normalizePluginRoutePath(routePath: string | null | undefined): string {
return routePath?.replace(/^\/+|\/+$/g, "") ?? "";
}
export function getCompanySettingsTab(pathname: string): CompanySettingsTab {
if (pathname.includes("/company/settings/connections")) {
function matchesSettingsPath(normalizedPath: string, suffix: string): boolean {
return normalizedPath.endsWith(suffix) || normalizedPath.includes(`${suffix}/`);
}
export function getCompanySettingsTab(
pathname: string,
pluginSlots?: readonly CompanySettingsPluginSlotLike[],
): CompanySettingsTab {
const normalizedPath = pathname.replace(/\/+$/, "");
if (matchesSettingsPath(normalizedPath, "/company/settings/connections")) {
return "connections";
}
if (pathname.includes(`${INSTANCE_SETTINGS_PATH_PREFIX}/profile`)) {
if (matchesSettingsPath(normalizedPath, `${INSTANCE_SETTINGS_PATH_PREFIX}/profile`)) {
return "instance-profile";
}
if (pathname.includes(`${INSTANCE_SETTINGS_PATH_PREFIX}/environments`)) {
if (matchesSettingsPath(normalizedPath, `${INSTANCE_SETTINGS_PATH_PREFIX}/environments`)) {
return "instance-environments";
}
if (pathname.includes(`${INSTANCE_SETTINGS_PATH_PREFIX}/access`)) {
if (matchesSettingsPath(normalizedPath, `${INSTANCE_SETTINGS_PATH_PREFIX}/access`)) {
return "instance-access";
}
if (pathname.includes(`${INSTANCE_SETTINGS_PATH_PREFIX}/experimental`)) {
if (matchesSettingsPath(normalizedPath, `${INSTANCE_SETTINGS_PATH_PREFIX}/experimental`)) {
return "instance-experimental";
}
if (pathname.includes(`${INSTANCE_SETTINGS_PATH_PREFIX}/plugins`)) {
if (matchesSettingsPath(normalizedPath, `${INSTANCE_SETTINGS_PATH_PREFIX}/plugins`)) {
return "instance-plugins";
}
if (pathname.includes(`${INSTANCE_SETTINGS_PATH_PREFIX}/adapters`)) {
if (matchesSettingsPath(normalizedPath, `${INSTANCE_SETTINGS_PATH_PREFIX}/adapters`)) {
return "instance-adapters";
}
if (pathname.includes(`${INSTANCE_SETTINGS_PATH_PREFIX}/general`)) {
if (matchesSettingsPath(normalizedPath, `${INSTANCE_SETTINGS_PATH_PREFIX}/general`)) {
return "general";
}
if (pathname.includes("/company/settings/environments")) {
if (matchesSettingsPath(normalizedPath, "/company/settings/environments")) {
return "instance-environments";
}
if (pathname.includes("/company/export")) {
if (matchesSettingsPath(normalizedPath, "/company/export")) {
return "export";
}
if (pathname.includes("/company/import")) {
if (matchesSettingsPath(normalizedPath, "/company/import")) {
return "import";
}
if (pathname.includes("/company/settings/members") || pathname.includes("/company/settings/access")) {
if (
matchesSettingsPath(normalizedPath, "/company/settings/members")
|| matchesSettingsPath(normalizedPath, "/company/settings/access")
) {
return "members";
}
if (pathname.includes("/company/settings/invites")) {
// Invites live on the Members page now; the old URL redirects there.
if (matchesSettingsPath(normalizedPath, "/company/settings/invites")) {
return "members";
}
if (pathname.includes("/company/settings/secrets")) {
if (matchesSettingsPath(normalizedPath, "/company/settings/secrets")) {
return "secrets";
}
if (pluginSlots && pluginSlots.length > 0) {
for (const slot of pluginSlots) {
const routePath = normalizePluginRoutePath(slot.routePath);
if (!routePath) continue;
if (matchesSettingsPath(normalizedPath, `/company/settings/${routePath}`)) {
return `plugin:${slot.pluginKey}:${slot.id}`;
}
}
}
return "general";
}
export function CompanySettingsNav() {
const location = useLocation();
const navigate = useNavigate();
const { selectedCompanyId } = useCompany();
const { hidden: hiddenSettings } = useHiddenSettings();
// Import is floored server-side on cloud-managed instances (403 cloud_managed), so the
// tab is suppressed there rather than dead-ending.
const isCloud = Boolean(useCloudInstance());
const activeTab = getCompanySettingsTab(location.pathname);
const visibleItems = items.filter((item) => {
if (item.value === "import" && isCloud) return false;
const hiddenKey = hiddenSettingKeyByTab[item.value];
return !hiddenKey || !hiddenSettings.has(hiddenKey);
const { slots: companySettingsPluginSlots } = usePluginSlots({
slotTypes: ["companySettingsPage"],
companyId: selectedCompanyId,
enabled: !!selectedCompanyId,
});
const visibleItems = useMemo<CompanySettingsNavItem[]>(() => {
const pluginItems: CompanySettingsNavItem[] = companySettingsPluginSlots
.filter((slot) => Boolean(normalizePluginRoutePath(slot.routePath)))
.map((slot) => {
const routePath = normalizePluginRoutePath(slot.routePath);
return {
value: `plugin:${slot.pluginKey}:${slot.id}`,
label: slot.displayName,
href: `/company/settings/${routePath}`,
};
});
return [...builtInPrefixItems, ...pluginItems, ...builtInSuffixItems].filter((item) => {
if (item.hideOnCloud && isCloud) return false;
return !item.hiddenKey || !hiddenSettings.has(item.hiddenKey);
});
}, [companySettingsPluginSlots, hiddenSettings, isCloud]);
const activeTab = getCompanySettingsTab(location.pathname, companySettingsPluginSlots);
function handleTabChange(value: string) {
const nextTab = visibleItems.find((item) => item.value === value);
if (!nextTab || nextTab.value === activeTab) return;
+45 -34
View File
@@ -1,3 +1,4 @@
import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { chatEndpointsApi } from "@/api/chatEndpoints";
import { queryKeys } from "@/lib/queryKeys";
@@ -8,9 +9,32 @@ import {
Settings,
Users,
} from "lucide-react";
import { MobileContextualNav, type MobileContextualNavItem } from "../MobileContextualNav";
import { SidebarNavItem } from "../SidebarNavItem";
import { contextualSidebarStyles } from "../contextual-sidebar-styles";
function useChatDetailNavItems(endpointId: string): MobileContextualNavItem[] {
const endpoint = useQuery({
queryKey: queryKeys.chatEndpoints.detail(endpointId),
queryFn: () => chatEndpointsApi.get(endpointId),
enabled: Boolean(endpointId),
});
const isGitHub = endpoint.data?.provider === "github";
return useMemo<MobileContextualNavItem[]>(
() => [
{ key: "settings", to: `/apps/chat/${endpointId}/settings`, label: "Settings", icon: Settings, end: true },
{ key: "access", to: `/apps/chat/${endpointId}/access`, label: "Access", icon: Users, end: true },
...(isGitHub
? [{ key: "reviews", to: `/apps/chat/${endpointId}/reviews`, label: "Reviews", icon: GitPullRequest }]
: []),
{ key: "conversations", to: `/apps/chat/${endpointId}/conversations`, label: "Conversations", icon: MessageSquare, end: true },
{ key: "activity", to: `/apps/chat/${endpointId}/activity`, label: "Activity", icon: Activity, end: true },
],
[endpointId, isGitHub],
);
}
export function ChatDetailSidebar({
endpointId,
NavItem = SidebarNavItem,
@@ -18,11 +42,8 @@ export function ChatDetailSidebar({
endpointId: string;
NavItem?: typeof SidebarNavItem;
}) {
const endpoint = useQuery({
queryKey: queryKeys.chatEndpoints.detail(endpointId),
queryFn: () => chatEndpointsApi.get(endpointId),
enabled: Boolean(endpointId),
});
const items = useChatDetailNavItems(endpointId);
return (
<aside className="flex h-full min-h-0 w-full flex-col border-r border-border bg-background">
<nav
@@ -34,39 +55,29 @@ export function ChatDetailSidebar({
data-slot="contextual-sidebar-group"
className={contextualSidebarStyles.group}
>
<NavItem
to={`/apps/chat/${endpointId}/settings`}
label="Settings"
icon={Settings}
end
/>
<NavItem
to={`/apps/chat/${endpointId}/access`}
label="Access"
icon={Users}
end
/>
{endpoint.data?.provider === "github" && (
{items.map((item) => (
<NavItem
to={`/apps/chat/${endpointId}/reviews`}
label="Reviews"
icon={GitPullRequest}
key={item.key}
to={item.to}
label={item.label}
icon={item.icon ?? Settings}
end={item.end}
/>
)}
<NavItem
to={`/apps/chat/${endpointId}/conversations`}
label="Conversations"
icon={MessageSquare}
end
/>
<NavItem
to={`/apps/chat/${endpointId}/activity`}
label="Activity"
icon={Activity}
end
/>
))}
</div>
</nav>
</aside>
);
}
export function ChatDetailMobileNav({ endpointId }: { endpointId: string }) {
const items = useChatDetailNavItems(endpointId);
return (
<MobileContextualNav
surface="chat-detail"
ariaLabel="Chat connection"
groups={[{ key: "chat-detail", items }]}
/>
);
}
+1 -3
View File
@@ -76,8 +76,6 @@ import { cn } from "../lib/utils";
import { ProviderLimitMessage } from "../components/ProviderLimitMessage";
import { RunRetryDetails } from "../components/RunRetryDetails";
import { Button } from "@/components/ui/button";
import { Tabs } from "@/components/ui/tabs";
import { PageTabBar } from "../components/PageTabBar";
import { AuditFeed } from "./audit/AuditFeed";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
@@ -797,7 +795,7 @@ export function AgentDetail() {
return (
<div className={cn("agent-settings-content mx-auto max-w-5xl space-y-8", `agent-settings-${activeView}`, showConfigActionBar && "agent-settings-with-save-bar")}>
{showLeftAgentNotice ? (
<div className="flex items-center gap-3 border border-yellow-300/35 bg-yellow-300/10 px-3 py-2 text-sm text-yellow-900 dark:text-yellow-100">
<div className="flex flex-wrap items-center gap-3 border border-yellow-300/35 bg-yellow-300/10 px-3 py-2 text-sm text-yellow-900 dark:text-yellow-100">
<p className="min-w-0 flex-1">
You left this agent. It no longer appears in your sidebar.
</p>
@@ -64,7 +64,7 @@ function installPageFixtures() {
if (path.endsWith("/budgets/overview")) return json({ companyId, policies: [], activeIncidents: [], pausedAgentCount: 0, pausedProjectCount: 0, pendingApprovalCount: 0 });
if (path.includes("/heartbeat-runs/") && path.endsWith("/events")) return json([]);
// Reuse the preview's auth, company, adapter, issue-list and environment fixtures.
if (path === "/api/companies" || path.startsWith("/api/auth/") || path.includes("/adapters") || path.includes("/environments") || path.endsWith("/issues") || path.endsWith("/projects") || path.endsWith("/approvals") || path.endsWith("/sidebar-badges") || path.endsWith("/user-directory")) return previous(input, init);
if (path === "/api/companies" || path.startsWith("/api/auth/") || path.includes("/adapters") || path.includes("/environments") || path.includes("/ai-connections") || path.endsWith("/secrets") || path.endsWith("/user-secrets") || path.endsWith("/issues") || path.endsWith("/projects") || path.endsWith("/approvals") || path.endsWith("/sidebar-badges") || path.endsWith("/user-directory")) return previous(input, init);
if (path.includes("/settings")) return json({});
return json([]);
};
@@ -124,6 +124,16 @@ export default meta;
type Story = StoryObj;
export const AllAgents: Story = { render: () => <PersonaPage path="/PAP/agents/all" /> };
export const AgentOverview: Story = { render: () => <PersonaPage path="/PAP/agents/codexcoder/overview" /> };
export const AgentOverviewMobile: Story = {
render: () => <PersonaPage path="/PAP/agents/codexcoder/overview" />,
globals: { viewport: { value: "mobile", isRotated: false } },
parameters: { layout: "fullscreen", waitForViewport: true },
};
export const AgentRuntimeMobile: Story = {
render: () => <PersonaPage path="/PAP/agents/codexcoder/runtime" />,
globals: { viewport: { value: "mobile", isRotated: false } },
parameters: { layout: "fullscreen", waitForViewport: true },
};
export const Task: Story = { render: () => <PersonaPage path={`/PAP/issues/${issue.identifier}`} /> };
export const CompanyDashboard: Story = { name: "Dashboard", render: () => <PersonaPage path="/PAP/dashboard" /> };
export const MeetYourNextAgent: Story = { render: () => <PersonaPage path="/PAP/agents/all" meet /> };
@@ -1,5 +1,5 @@
import { useEffect, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import type { Meta, StoryObj } from "@storybook/react-vite";
import {
Bot,
@@ -14,6 +14,7 @@ import { BreadcrumbBar } from "@/components/BreadcrumbBar";
import { CommandPalette } from "@/components/CommandPalette";
import { CompanySwitcher } from "@/components/CompanySwitcher";
import { KeyboardShortcutsCheatsheetContent } from "@/components/KeyboardShortcutsCheatsheet";
import { Layout } from "@/components/Layout";
import { MobileBottomNav } from "@/components/MobileBottomNav";
import { PageTabBar } from "@/components/PageTabBar";
import { Sidebar } from "@/components/Sidebar";
@@ -33,10 +34,14 @@ import {
} from "@/components/ui/command";
import { Tabs } from "@/components/ui/tabs";
import { BreadcrumbProvider, useBreadcrumbs, type Breadcrumb } from "@/context/BreadcrumbContext";
import { useNavigate } from "@/lib/router";
import { useCompany } from "@/context/CompanyContext";
import { useSidebar } from "@/context/SidebarContext";
import { Route, Routes, useLocation, useNavigate } from "@/lib/router";
import { cn } from "@/lib/utils";
import { healthApi } from "@/api/health";
import { queryKeys } from "@/lib/queryKeys";
import { AgentDetail } from "@/pages/AgentDetail";
import { CompanySettings } from "@/pages/CompanySettings";
import { prepareFixtureApi } from "../../support/capability-gaps/api";
import {
storybookAgents,
@@ -145,10 +150,10 @@ function MobileBottomNavActiveStateMatrix() {
active ? "text-foreground" : "text-muted-foreground",
)}
>
<span className="relative">
<Icon className={cn("h-[18px] w-[18px]", active && "stroke-[2.3]")} />
<span className="relative inline-flex items-center justify-center">
<Icon className={cn("h-(--sz-18px) w-(--sz-18px)", active && "stroke-(length:--sw-2_3)")} />
{item.badge ? (
<span className="absolute -right-2 -top-2 rounded-full bg-primary px-1.5 py-0.5 text-[10px] leading-none text-primary-foreground">
<span className="pointer-events-none absolute -top-1.5 left-3 min-w-4 rounded-full bg-primary px-1 py-0.5 text-center text-(length:--text-nano) leading-none tabular-nums text-primary-foreground">
{item.badge}
</span>
) : null}
@@ -436,3 +441,72 @@ function SidebarIconAlignmentHarness() {
export const SidebarIconAlignment: Story = {
render: () => <SidebarIconAlignmentHarness />,
};
const MOBILE_STORY_COMPANY_ID = "company-storybook";
function MobileShellStoryHarness({
path,
openDrawer = false,
inboxCount = 96,
}: {
path: string;
openDrawer?: boolean;
inboxCount?: number;
}) {
const navigate = useNavigate();
const location = useLocation();
const queryClient = useQueryClient();
const { selectedCompanyId, setSelectedCompanyId } = useCompany();
const { isMobile, setSidebarOpen } = useSidebar();
const [ready, setReady] = useState(false);
const initializedPath = useRef<string | null>(null);
useEffect(() => {
if (initializedPath.current === path) return;
initializedPath.current = path;
queryClient.setQueryData(queryKeys.agents.list(MOBILE_STORY_COMPANY_ID), storybookAgents);
for (const agent of storybookAgents) {
for (const ref of [agent.id, agent.urlKey]) {
if (ref) queryClient.setQueryData([...queryKeys.agents.detail(ref), MOBILE_STORY_COMPANY_ID], agent);
}
}
queryClient.setQueryData(queryKeys.sidebarBadges(MOBILE_STORY_COMPANY_ID), {
...storybookSidebarBadges,
inbox: inboxCount,
});
setSelectedCompanyId(MOBILE_STORY_COMPANY_ID);
navigate(path, { replace: true });
setReady(true);
}, [inboxCount, navigate, path, queryClient, setSelectedCompanyId]);
useEffect(() => {
if (!ready || !isMobile) return;
setSidebarOpen(openDrawer);
return () => setSidebarOpen(false);
}, [isMobile, openDrawer, ready, setSidebarOpen]);
if (!ready || selectedCompanyId !== MOBILE_STORY_COMPANY_ID || location.pathname === "/PAP/storybook") {
return null;
}
return (
<Routes>
<Route path="/:companyPrefix" element={<Layout />}>
<Route path="company/settings" element={<CompanySettings />} />
<Route path="agents/:agentId/:tab?" element={<AgentDetail />} />
</Route>
</Routes>
);
}
export const MobileSettingsAndBottomNav: Story = {
render: () => <MobileShellStoryHarness path="/PAP/company/settings" inboxCount={96} />,
globals: { viewport: { value: "mobile", isRotated: false } },
parameters: { layout: "fullscreen", waitForViewport: true },
};
export const MobileAgentDrawerOpen: Story = {
render: () => <MobileShellStoryHarness path="/PAP/agents/codexcoder/overview" openDrawer inboxCount={96} />,
globals: { viewport: { value: "mobile", isRotated: false } },
parameters: { layout: "fullscreen", waitForViewport: true },
};