Files
PaperClipAI/ui/src/components/SidebarCompanyMenu.tsx
T
43b2d8be22 feat(dashboard): add an experimental areas and responsibilities dashboard (#22069)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The dashboard is the first page a person sees in a company
> - The classic dashboard shows agents, runs, costs and recent tasks
> - It does not show what the person is responsible for, or if that work
goes well
> - People think in areas, such as Fundraising or Customers, and in the
things they own in each area
> - This pull request adds a dashboard built on areas and
responsibilities, behind an experimental setting that is off by default
> - The benefit is that a person sees what they own, how it is going,
and what agents do for it, on one page

## Linked Issues or Issue Description

No public issue exists for this work. The description follows the
feature request template.

**Subsystem affected**

Dashboard, navigation, the task conversation, routines, and the instance
experimental settings.

**Problem or motivation**

The classic dashboard counts agents and tasks. It does not say what a
person owns or if it goes well. People who run a company with agents
want to see their areas, the responsibilities in each area, the bar each
one must meet, and the agents and routines that serve it.

**Proposed solution**

A person owns responsibilities. Each responsibility belongs to an area
and has a bar, a number to reach. Projects, tasks and routines link to a
responsibility, and the page shows its status from those links. An agent
can interview the person and draft the dashboard. The person accepts or
declines each change, and any change can be undone from a saved version.

**Alternatives considered**

Add the same data to the classic dashboard. That page is a fixed set of
cards for company activity, so a second, person-centred page is clearer.
The setting lets a person pick one of the two.

**Roadmap alignment**

This is an experimental feature behind `enableResponsibilities`. It is
off by default and changes nothing for a person who leaves it off.

## What Changed

- Add the setting "Areas & Responsibilities dashboard"
(`enableResponsibilities`, off by default). On, Dashboard in the sidebar
opens the new page, and the classic dashboard link is not shown in the
sidebars or the command palette. Off, nothing changes.
- Add tables and migrations 0492 to 0497 for areas, responsibilities,
links to work, metrics, status reports, saved dashboard versions, and
model-call records for summaries.
- Add the API: areas, responsibilities, links, bars, metrics, status
reports, summaries, runs, automation, and the dashboard conversation
with versions and undo. Each route checks company access and writes to
the activity log.
- Add four task conversations with an agent: about a bar, about an
automation, about a routine, and about the whole dashboard. The agent
proposes a change. Nothing applies until a person accepts it.
- Add standing checks: routines that an agent carries out on its
heartbeat and reports.
- Add the Dashboard page: search, counts, areas that open and close, a
primary New area button, and a message box at the bottom of the page.
Add the responsibility page with its bar, metrics, work and routines.
- Add the Paperclip skill sections and runner API entries that let an
agent use these routes. The runner skill inventory is regenerated (166
to 174 rows).
- Keep the new runner API tests in their own file so
`runner-api.test.ts` stays at 985 lines.
- Onboarding is not changed. The onboarding changes that build on this
work are a separate pull request.

## Verification

- Type checks pass for `packages/db`, `packages/shared`, `server` (all
layers) and `ui`.
- `pnpm --filter @paperclipai/db check:migrations` passes. A new
`drizzle-kit generate` run produces no further change.
- Tests for every changed file pass: 26 server test files (3,009 tests),
116 UI test files (1,991 tests) and 28 shared test files (432 tests).
- The runner capability inventory checks pass.
- I started the app on a local database that already held earlier data.
Master's new migrations and these migrations applied without error. With
the setting on, the Dashboard and a responsibility page loaded with no
console or server errors. The More menu and the command palette show one
Dashboard.
- I did not run `pnpm verify`, the full local suite, or the browser
suites. Required CI covers them.
- The agent conversations are tested with simulated agents. No real
model has run them.

## Risks

- Medium. The change is large, and the setting is off by default. With
it off, the new routes refuse requests and the UI is unchanged.
- Migrations only add tables and columns. Two replace a CHECK
constraint, and one builds an index `CONCURRENTLY`. These two have the
`online_compatible` override with a reason in the file, and the second
one is listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`.
- Master can add migrations before this merges. The migrations then need
new numbers.
- `responsibilities.ts` (1,663 lines), `responsibility-summaries.ts`
(1,239 lines) and one Storybook fixture file (1,305 lines) are new files
over 1,000 lines. They each keep one cohesive unit together: the service
for one table family, the model-call path for summaries, and the
fixtures that the stories share. No existing file crosses 1,000 lines.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Anthropic Claude: Claude Fable 5.2 (`claude-fable-5-2`) wrote most of
the change, with Claude Sonnet 5.5 (`claude-sonnet-5-5`) for the final
steps. Both used tool use, code execution and browser checks.

## 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
- [ ] 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Scott Tong <scott@scottsmbpm5max.lan>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-17 20:45:44 -08:00

417 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 } from "@/lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { useSidebar } from "../context/SidebarContext";
import { CompanyPatternIcon } from "./CompanyPatternIcon";
import { TruncatedText } from "./TruncatedText";
import { FlyoutHeader, FlyoutOptions } from "./ui/flyout";
import { PluginOrganizationSwitcher } from "./PluginOrganizationSwitcher";
import { useCompanyHomePath } from "@/hooks/useCompanyHomePath";
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 } = useSidebar();
const location = useLocation();
const navigate = useNavigate();
const { path: homePath } = useCompanyHomePath();
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(),
});
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}${homePath}`);
}
}
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`
}
>
{/* Customer data: the organization name stays masked in session replay. */}
<span className={cn("flex min-w-0 flex-1 items-center gap-2", ANALYTICS_MASK_CLASS)}>
{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="min-w-0 truncate text-sm font-bold text-foreground"
title={currentName ?? undefined}
>
{currentName ?? `Select ${switcherNoun}`}
</TruncatedText>
</span>
{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>
);
}