Files
PaperClipAI/ui/src/components/SidebarCompanyMenu.tsx
T
7b9334cd10 Draft: Build agent-ready design proposal system (#16875)
## Thinking Path

> - Paperclip helps people manage AI agents and their work.
> - People need consistent UI patterns to review and control that work.
> - The current board uses related layouts and controls with different
spacing, type, and behavior.
> - That drift makes it hard for a designer or an agent to build a new
page from a reliable reference.
> - Storybook can show the shared patterns and the states they need to
support.
> - This pull request adds design proposals, a local sandbox, and
reusable UI controls so people can compare the patterns in context.
> - The benefit is a clearer design system that agents can use to build
consistent UI.

## Linked Issues or Issue Description

**Subsystem affected**

`ui/` — React board UI and Storybook.

**Problem or motivation**

Board pages repeat visual and interaction decisions. Storybook did not
provide a complete reference for task views, conversation states,
typography, toolbars, tabs, and light/dark colors. People could not
compare a proposed pattern with the running board in one place.

**Proposed solution**

Add a staged Design Proposals catalog with foundations, components,
layouts, and page specimens. Add an opt-in sandbox. Reuse production
components where possible. Include synthetic conversation states and
shared controls so reviewers can compare and refine them.

**Alternatives considered**

Separate static mockups would not show keyboard behavior, responsive
layout, or real component states. Rebuilding each page only in Storybook
would allow the reference to drift from the board.

**Roadmap alignment**

This improves existing board UI and Skills Manager surfaces. It does not
add a new control-plane capability.

## What Changed

- Added dark and light color references, typography and conversation
specimens, and component stories for buttons, tabs, toolbars, sidebar,
popovers, activity, and task lists.
- Added a local design sandbox with synthetic task conversation playback
and representative states.
- Shared collection toolbars and navigation patterns across task, agent,
project, routine, skill, connector, and artifact pages.
- Added the streamlined Skills tabs and a My Skills collection that uses
the shared skill cards.
- Restored saved-thread access during synthetic playback, kept connector
searchbox semantics, and updated reproduction checks after moving trial
stories.
- Documented the proposed patterns and added focused UI, catalog, and
browser checks.

## Verification

- `pnpm check:token-gates`, `node scripts/check-maps.mjs`, and `node
scripts/storybook-catalog.mjs --check` passed.
- Full workspace `pnpm -r typecheck` and `pnpm build` passed after
merging master. After the review fixes, focused UI typecheck, `pnpm
build-storybook`, 23 Skills Sources tests, and all 15 Storybook
typography browser tests passed.
- Focused task-thread and system-notice suites passed: 251 tests.
Connector Browse passed 84 tests; the connector, attachment, recovery,
and Storybook flyout browser journeys passed locally.
- A local full Vitest run hit one intermittent chat-channels integration
failure; that test passed in isolation. GitHub CI
[39347996059](https://github.com/paperclipai/paperclip/actions/runs/39347996059)
passed on the exact latest commit: 55 successful checks and two skipped
draft-only Storybook jobs.
- Greptile reviewed the exact latest commit at 5/5 with no new comments
or open review threads. GitHub reports the branch as cleanly mergeable.

## Risks

- This PR changes 206 files and exceeds the repository's 100-file review
target. Review by commit and consider a scoped split before merge.
- Design Proposals are staged references. Fixture interactions do not
prove API behavior, permissions, or provider execution.
- UI changes to shared controls may affect pages outside the proposal
sandbox. Focused browser checks and the full CI matrix passed.

## Model Used

- OpenAI Codex, GPT-6 family. The exact runtime model ID and context
window are not exposed in this session. The model used reasoning, code
execution, browser inspection, and local tests. Earlier branch commits
were also AI-assisted in this Codex conversation.

## 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 available in this session)
- [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 where applicable
- [x] I have either linked existing issues or described the issue in-PR
following the relevant issue template
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] My branch name describes the change and contains no internal
ticket id
- [x] I have run focused 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 risks above
- [x] All Paperclip CI gates are green
- [x] 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: Scott Tong <scott@scotts-mbp-m5-max.local>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-19 17:45:26 -07:00

418 lines
16 KiB
TypeScript

import { useCallback, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
Check,
ChevronsUpDown,
GripVertical,
LogOut,
Plus,
RefreshCw,
UserPlus,
} from "lucide-react";
import {
DndContext,
MouseSensor,
TouchSensor,
closestCenter,
type DragEndEvent,
useSensor,
useSensors,
} from "@dnd-kit/core";
import { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { hidesCompanyPage, type Company } from "@paperclipai/shared";
import { Link, useLocation, useNavigate } from "@/lib/router";
import { authApi } from "@/api/auth";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useCompany } from "@/context/CompanyContext";
import { useDialogActions } from "@/context/DialogContext";
import { useCloudInstance } from "@/hooks/useCloudInstance";
import { useHiddenSettings } from "@/hooks/useHiddenSettings";
import { useCompanyOrder } from "@/hooks/useCompanyOrder";
import { useSignOut } from "@/hooks/useSignOut";
import { queryKeys } from "@/lib/queryKeys";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "@/lib/utils";
import { useSidebar } from "../context/SidebarContext";
import { CompanyPatternIcon } from "./CompanyPatternIcon";
import { TruncatedText } from "./TruncatedText";
import { FlyoutHeader, FlyoutOptions } from "./ui/flyout";
import { PluginOrganizationSwitcher } from "./PluginOrganizationSwitcher";
interface SidebarCompanyMenuProps {
open?: boolean;
onOpenChange?: (open: boolean) => void;
showChevron?: boolean;
}
const TRIGGER_WORKSPACE_ICON_CLASS = "size-5 shrink-0 rounded-md text-(length:--text-micro)";
const POPOVER_WORKSPACE_ICON_CLASS =
"size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)";
const ORGANIZATION_ROW_CLASS =
"h-(--organization-popover-company-row-height) min-w-0 gap-(--organization-popover-row-gap) rounded-lg px-2.5 py-0 text-(length:--text-compact) focus:bg-accent/50 focus:text-foreground";
const ORGANIZATION_ACTION_CLASS =
"h-(--organization-popover-action-row-height) gap-(--organization-popover-row-gap) rounded-lg px-2.5 py-0 text-(length:--text-compact) font-medium leading-(--organization-popover-action-line-height) text-foreground focus:bg-accent/50 focus:text-foreground";
function WorkspaceIcon({ company, inPopover = false }: { company: Company; inPopover?: boolean }) {
return (
<CompanyPatternIcon
companyName={company.name}
logoUrl={company.logoUrl}
className={inPopover ? POPOVER_WORKSPACE_ICON_CLASS : TRIGGER_WORKSPACE_ICON_CLASS}
/>
);
}
function SortableCompanyItem({
company,
isEditing,
isSelected,
onSelect,
}: {
company: Company;
isEditing: boolean;
isSelected: boolean;
onSelect: (company: Company) => void;
}) {
const {
attributes,
listeners,
setActivatorNodeRef,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: company.id, disabled: !isEditing });
return (
<DropdownMenuItem
ref={setNodeRef}
data-selected={isSelected || undefined}
style={{
transform: CSS.Transform.toString(transform),
transition,
zIndex: isDragging ? 10 : undefined,
}}
onSelect={(event) => {
if (isEditing) {
event.preventDefault();
return;
}
onSelect(company);
}}
className={cn(
ORGANIZATION_ROW_CLASS,
isEditing && "cursor-grab",
isDragging && "opacity-80",
)}
>
<WorkspaceIcon company={company} inPopover />
<span className="min-w-0 flex-1">
<TruncatedText className="block truncate font-medium leading-(--organization-popover-name-line-height)">
{company.name}
</TruncatedText>
{isEditing ? null : (
<TruncatedText className="block truncate text-(length:--text-nano) leading-(--organization-popover-prefix-line-height) text-muted-foreground">
{company.issuePrefix}
</TruncatedText>
)}
</span>
{isEditing ? (
<button
type="button"
ref={setActivatorNodeRef}
aria-label={`Reorder ${company.name}`}
className="inline-flex size-8 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-(length:--rad-2) focus-visible:ring-ring"
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
}}
{...attributes}
{...listeners}
>
<GripVertical className="size-4" aria-hidden="true" />
</button>
) : (
<span className="flex size-5 shrink-0 items-center justify-center">
{isSelected ? <Check className="size-4 text-foreground" /> : null}
</span>
)}
</DropdownMenuItem>
);
}
export function SidebarCompanyMenu({ showChevron, ...props }: SidebarCompanyMenuProps = {}) {
return (
<PluginOrganizationSwitcher {...props}>
<BuiltinCompanyMenu {...props} showChevron={showChevron} />
</PluginOrganizationSwitcher>
);
}
function BuiltinCompanyMenu({ open: controlledOpen, onOpenChange, showChevron = true }: SidebarCompanyMenuProps) {
const [internalOpen, setInternalOpen] = useState(false);
const [isEditingOrder, setIsEditingOrder] = useState(false);
const { companies, selectedCompany, setSelectedCompanyId, companyListUnavailable, retryCompanies } =
useCompany();
const { openOnboarding } = useDialogActions();
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const location = useLocation();
const navigate = useNavigate();
const open = controlledOpen ?? internalOpen;
const setOpen = onOpenChange ?? setInternalOpen;
const sensors = useSensors(
useSensor(MouseSensor, {
activationConstraint: { distance: 8 },
}),
useSensor(TouchSensor, {
activationConstraint: { delay: 180, tolerance: 6 },
}),
);
const sidebarCompanies = useMemo(
() => companies.filter((company) => company.status !== "archived"),
[companies],
);
const { data: session } = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
retry: false,
});
const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;
const { orderedCompanies, persistOrder } = useCompanyOrder({
companies: sidebarCompanies,
userId: currentUserId,
});
// Keep invitation links hidden until the operator policy is known.
const { hidden: hiddenSettings, loaded: hiddenSettingsLoaded } = useHiddenSettings();
const showInvitePeople =
hiddenSettingsLoaded &&
!hidesCompanyPage(hiddenSettings, "company.members") &&
!hidesCompanyPage(hiddenSettings, "company.invites");
const switcherNoun = "organization";
const currentName = selectedCompany?.name ?? null;
// Managed hosts forbid local company creation. Their extension owns that action.
const companyCreationManaged = Boolean(useCloudInstance());
const signOutMutation = useSignOut({ onSignedOut: closeNavigationChrome });
function handleOpenChange(nextOpen: boolean) {
if (!nextOpen) setIsEditingOrder(false);
setOpen(nextOpen);
}
function closeNavigationChrome() {
setOpen(false);
setIsEditingOrder(false);
if (isMobile) setSidebarOpen(false);
}
function selectCompany(company: Company) {
const pathPrefix = location.pathname.split("/")[1]?.toUpperCase();
const isCompanyRoute = sidebarCompanies.some((sidebarCompany) => (
sidebarCompany.issuePrefix.toUpperCase() === pathPrefix
));
const shouldLeaveCurrentRoute = company.id !== selectedCompany?.id
&& (location.pathname.startsWith("/instance/") || isCompanyRoute);
setSelectedCompanyId(company.id);
setOpen(false);
if (isMobile) setSidebarOpen(false);
if (shouldLeaveCurrentRoute) {
navigate(`/${company.issuePrefix}/dashboard`);
}
}
function addCompany() {
if (companyCreationManaged) return;
setOpen(false);
if (isMobile) setSidebarOpen(false);
// Skip the front-door "how would you like to get started?" choice and land
// directly on "Name your organization" — this entry point is unambiguously
// "create a new company" (PAP-431).
openOnboarding({ initialStep: 1 });
}
const handleDragEnd = useCallback(
(event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
const ids = orderedCompanies.map((company) => company.id);
const oldIndex = ids.indexOf(active.id as string);
const newIndex = ids.indexOf(over.id as string);
if (oldIndex === -1 || newIndex === -1) return;
persistOrder(arrayMove(ids, oldIndex, newIndex));
},
[orderedCompanies, persistOrder],
);
return (
<DropdownMenu open={open} onOpenChange={handleOpenChange}>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
// The nav icon column sits at nav px-3 + item mx-2 + item px-2.
// Match that inset with wrapper px-3 + trigger px-4. Override the
// Button's direct-SVG padding too so the expanded chevron cannot pull
// the avatar four pixels left of the nav icons.
// `min-w-0` on every link of the flex chain (button → label row → label)
// is what lets the name truncate: a flex item's default `min-width:auto`
// floors it at its content width, so without it a long name widens the
// trigger past the sidebar and pushes the chevron out of bounds.
className="h-9 min-w-0 flex-1 justify-start gap-2 px-4 text-left hover:bg-sidebar-accent hover:text-sidebar-accent-foreground has-[>svg]:px-4 dark:hover:bg-sidebar-accent dark:hover:text-sidebar-accent-foreground"
aria-label={
currentName
? `Open ${currentName} ${switcherNoun} switcher`
: `Open ${switcherNoun} switcher`
}
>
<span className="flex min-w-0 flex-1 items-center gap-2">
{selectedCompany ? <WorkspaceIcon company={selectedCompany} /> : null}
{/* The header has room for ~110px of name beside the collapse
control (~142px on mobile, which hides it) — search moved to
the nav to buy that width. A name that still
truncates stays hover-recoverable via title. */}
<TruncatedText
marqueeResetKey={open}
className={cn(
"min-w-0 truncate text-sm font-bold text-foreground",
rail && SIDEBAR_RAIL_HIDDEN_LABEL,
)}
title={currentName ?? undefined}
>
{currentName ?? `Select ${switcherNoun}`}
</TruncatedText>
</span>
{!rail && showChevron && <ChevronsUpDown className="size-3.5 shrink-0 text-muted-foreground" />}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="start"
sideOffset={8}
className="ml-2 w-(--organization-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)"
>
<FlyoutHeader className="flex h-(--organization-popover-header-height) items-center justify-between gap-2 px-3.5">
<DropdownMenuLabel className="p-0 text-(length:--text-compact) font-semibold text-foreground">
Organizations
</DropdownMenuLabel>
<button
type="button"
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setIsEditingOrder((current) => !current);
}}
className="rounded px-1.5 py-0.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
{isEditingOrder ? "Done" : "Edit"}
</button>
</FlyoutHeader>
<FlyoutOptions className="flex max-h-96 flex-col gap-0.5 overflow-y-auto px-2.5 pb-2 pt-1">
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={orderedCompanies.map((company) => company.id)}
strategy={verticalListSortingStrategy}
>
{orderedCompanies.map((company) => (
<SortableCompanyItem
key={company.id}
company={company}
isEditing={isEditingOrder}
isSelected={company.id === selectedCompany?.id}
onSelect={selectCompany}
/>
))}
</SortableContext>
</DndContext>
{orderedCompanies.length === 0 ? (
// "No companies" is a claim about the account. After a failed
// list request it is one we cannot make, and this menu is the
// only place the customer can act on it — say what happened and
// offer the way back.
companyListUnavailable ? (
<>
<DropdownMenuItem disabled>Couldn&apos;t load organizations</DropdownMenuItem>
<DropdownMenuItem
onSelect={(event) => {
// Keep the menu open so the result of the retry is visible.
event.preventDefault();
void retryCompanies();
}}
>
<RefreshCw className="h-4 w-4 mr-2" />
Try again
</DropdownMenuItem>
</>
) : (
<DropdownMenuItem disabled>No organizations</DropdownMenuItem>
)
) : null}
</FlyoutOptions>
<FlyoutOptions className="flex flex-col gap-0.5 border-t border-border px-2.5 pb-2.5 pt-2">
{!companyCreationManaged && (
<DropdownMenuItem
onClick={addCompany}
className={ORGANIZATION_ACTION_CLASS}
disabled={isEditingOrder}
>
<span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground">
<Plus className="size-4" />
</span>
<TruncatedText className="min-w-0 flex-1 truncate">Create organization</TruncatedText>
</DropdownMenuItem>
)}
{showInvitePeople ? (
<DropdownMenuItem asChild disabled={isEditingOrder} className={ORGANIZATION_ACTION_CLASS}>
<Link
to="/company/settings/members?tab=invites"
onClick={(event) => {
if (isEditingOrder) {
event.preventDefault();
return;
}
closeNavigationChrome();
}}
>
<span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground">
<UserPlus className="size-4" />
</span>
<TruncatedText className="min-w-0 flex-1 truncate">
{currentName ? `Invite people to ${currentName}` : "Invite people"}
</TruncatedText>
</Link>
</DropdownMenuItem>
) : null}
{session?.session ? (
<DropdownMenuItem
className={ORGANIZATION_ACTION_CLASS}
onClick={() => signOutMutation.mutate()}
disabled={isEditingOrder || signOutMutation.isPending}
>
<span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground">
<LogOut className="size-4" />
</span>
<TruncatedText className="min-w-0 flex-1 truncate">
{signOutMutation.isPending ? "Signing out..." : "Sign out"}
</TruncatedText>
</DropdownMenuItem>
) : null}
</FlyoutOptions>
</DropdownMenuContent>
</DropdownMenu>
);
}