Files
PaperClipAI/ui/src/pages/Dashboard.tsx
DottaandPaperclip 26c72ed7ca fix(ui): polish mobile tables, popovers, PageTabBar callers, and settings (#23048)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Operators use the board UI on mobile viewports (`390x844`) to
inspect routines, members, costs, projects, dashboards, skills, and
settings
> - Wide tables overflowed the page horizontally, several `PageTabBar`
callers omitted `value`/`onValueChange` (breaking their mobile section
dropdowns), `w-96` popovers and floating save bars clipped or overlapped
the bottom nav, and key controls were hover-only or cramped on narrow
screens
> - Mobile operators could not scroll clipped columns, switch sections,
switch diff files, or tap hidden row actions on phones
> - This pull request constrains table scrollers and flex/grid
ancestors, wires all missing `PageTabBar` mobile callbacks, caps wide
popovers and floating save bars using existing viewport tokens, polishes
narrow layouts across collections and settings, and adds 390×844
Storybook views and Vitest regressions
> - The benefit is clean mobile layout without horizontal page overflow
and working touch controls across tables, tabs, popovers, dashboards,
and settings

## Linked Issues or Issue Description

Related mobile responsiveness PRs: #23045, #23046, #23047.

**What happened?**
On mobile viewports (`< 768px`, tested at `390x844`):
- Wide tables in Routines, Members, Costs, Connections, and tool profile
views caused horizontal page overflow or permanently clipped columns
(`overflow-hidden`).
- `AuditHub`, `Costs` (Providers/Billers), `Approvals`, `Inbox`, and
`LegacyInbox` omitted `value` and/or `onValueChange` on `PageTabBar`,
bypassing its mobile `<select>` section switcher.
- `w-96` popovers in `RoutinePage` and `WorkspaceServiceControlBar`
overflowed narrow viewports; the `CompanySkills` diff dialog hid its
file picker on `< md` and its floating save bar overlapped
`MobileBottomNav`.
- `ProjectDetail` task toolbars crushed the search field on `< sm`,
`Dashboard` charts rendered 2 cramped columns with uneven metric card
heights, `Agents` hid row `Chat` buttons on touch devices, and `Inbox`
hid nesting controls on `< sm`.

**Expected behavior**
Every collection, table, popover, dashboard, and settings screen stays
within the mobile viewport (`scrollWidth <= innerWidth`), wide tables
scroll horizontally inside their containers, mobile `PageTabBar`
dropdowns switch sections cleanly, and touch users can reach all row
actions, diff files, and nesting controls.

**Steps to reproduce**
1. Open the board UI at `390x844` (or the added Storybook `*Mobile`
stories).
2. Navigate to Routines, Settings → Members, Settings → Profile, Audit →
Costs, Approvals, Project Detail, Dashboard, and Company Skills diff
view.
3. Observe horizontal overflow, missing mobile tab switchers, hidden
diff file picker, and cramped toolbars/charts prior to this change.

**Paperclip version or commit**
`85ad16b47e` (`master`)

**Deployment mode**
Local dev (pnpm dev)

## What Changed

- **Horizontal table scroll containment & ancestor constraints**:
- Wrapped and constrained tables plus flex/grid ancestors
(`overflow-x-auto max-w-full`, `min-w-0`) in `RoutineTable.tsx`,
`Routines.tsx`, `CompanyAccess.tsx`, `CostByUserTable.tsx`, `Costs.tsx`,
`ProfileSettings.tsx`, `Connections.tsx`, `AgentToolsTab.tsx`,
`RoutineHistoryTab.tsx`, `RoutineVariablesEditor.tsx`,
`ProfilesTab.tsx`, `ProfileDetail.tsx`, `ProfilesIndex.tsx`, and
`SmokeLabTab.tsx`.
- Fixed `ProfileSettings.tsx` avatar upload `<label>` sizing
(`inline-block w-fit`) so the camera badge stays anchored to the avatar
circle.
- **Wired missing `PageTabBar` mobile callbacks**:
- Passed `value` and `onValueChange` to `PageTabBar` in `AuditHub.tsx`,
`Costs.tsx` (Providers and Billers), `Approvals.tsx`, `Inbox.tsx`, and
`LegacyInbox.tsx`.
- **Popovers & floating bars**:
- Capped `w-96` popovers in `RoutinePage.tsx` and
`WorkspaceServiceControlBar.tsx` with `max-w-(--sz-calc-4)` and wrapping
footer rows.
- Added a mobile file `<select>` (`md:hidden`) in the
`CompanySkills.tsx` version diff dialog and lifted its floating save bar
above `MobileBottomNav` (`bottom-20 md:bottom-6 max-w-(--sz-calc-4)
flex-wrap`).
- **Touch visibility & responsive layout polish**:
- Switched `ProjectDetail.tsx` task lists to
`toolbarPresentation="collection"` so the toolbar wraps cleanly on `<
sm`, and added `flex-wrap` to its left-membership notice banner.
- Made the `Agents.tsx` inline row `Chat` button touch-visible via
`pointer-coarse:opacity-100`.
- Exposed mobile parent-child nesting toggle and row expand chevrons in
`Inbox.tsx` and `LegacyInbox.tsx`.
- Stacked `Dashboard.tsx` chart cards to `grid-cols-1 sm:grid-cols-2`
and aligned the 2×2 summary metric cards with `auto-rows-fr
items-stretch`.
- Added responsive wrapping and width caps in `CompanySettings.tsx`,
`Secrets.tsx`, `SkillStudio.tsx`, `GrokBotSetupContent.tsx`, and
`ActionTestDialog.tsx`.
- **Storybook & Vitest coverage**:
- Added 390×844 mobile Storybook views for Routines
(`RoutinesListMobile`, `RoutineDetailMobile`), Members
(`MembersMobile`), Costs (`CostsMobile`), ProjectDetail
(`ProjectDetailMobile`), CompanySettings (`CompanySettingsMobile`), and
Dashboard (`DashboardMobile`).
  - Added `ui/src/pages/mobile-collections-responsive.test.tsx`.

## Verification

- `pnpm exec vitest run
ui/src/pages/mobile-collections-responsive.test.tsx
ui/src/pages/CompanyAccess.test.tsx ui/src/pages/Dashboard.test.ts` — 3
files, 35/35 passed
- `pnpm --filter @paperclipai/ui typecheck` — passed (0 errors)
- `pnpm check:token-gates` — all 4 gates CLEAN + cliplab character in
sync
- `node scripts/storybook-catalog.mjs --check` — passed (373 files, 3494
stories)
- `node --test scripts/check-maps.test.mjs
scripts/storybook-catalog.test.mjs
scripts/storybook-feature-index.test.mjs` — 30/30 passed

## Risks

- Low risk: layout-only responsive class updates, missing prop wiring on
`PageTabBar` callers, and additive mobile Storybook stories/tests.
Desktop breakpoints (`sm:` / `md:` / `lg:` / `xl:`) preserve existing
layouts.
- Several edited pages (`CompanySkills.tsx`, `Inbox.tsx`,
`LegacyInbox.tsx`, `Secrets.tsx`, `SkillStudio.tsx`, `Costs.tsx`,
`ProfilesTab.tsx`, `RoutineHistoryTab.tsx`, `ActionTestDialog.tsx`) were
already over 1,000 lines on `master`; this PR keeps edits minimal and
localized without introducing new subsystems into those files.

## Model Used

- Google Gemini 4 Neon (High) via Antigravity (tool use, code execution,
multi-agent code review)

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-27 13:41:45 +00:00

581 lines
25 KiB
TypeScript

import { companyProjectsQuery } from "@/lib/company-projects-query";
import { useAccountIdentity } from "@/api/companies-query";
import { AgentIdentity } from "../components/AgentIdentity";
import { TaskSummaryList } from "../components/TaskSummaryList";
import { useDesignSandbox } from "../context/DesignSandboxContext";
import { useEffect, useMemo, useRef, useState } from "react";
import { useAgentlessOnboardingAutoOpen } from "../hooks/useAgentlessOnboardingAutoOpen";
import { Link } from "@/lib/router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { dashboardApi } from "../api/dashboard";
import { activityApi } from "../api/activity";
import { accessApi } from "../api/access";
import { issuesApi } from "../api/issues";
import { agentsApi } from "../api/agents";
import { buildCompanyUserProfileMap } from "../lib/company-members";
import { useCompany } from "../context/CompanyContext";
import { useDialogActions } from "../context/DialogContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
import { MetricCard } from "../components/MetricCard";
import { EmptyState } from "../components/EmptyState";
import { StatusIcon } from "../components/StatusIcon";
import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";
import { ActivityRow } from "../components/ActivityRow";
import { ActivityList } from "../components/ActivityList";
import { timeAgo } from "../lib/timeAgo";
import { cn, formatCents } from "../lib/utils";
import { SHOW_TASK_PRIORITY_UI } from "../lib/ui-flags";
import { Bot, CircleDot, DollarSign, ShieldCheck, LayoutDashboard, PauseCircle } from "lucide-react";
import { ActiveAgentsPanel } from "../components/ActiveAgentsPanel";
import { ChartCard, RunActivityChart, PriorityChart, IssueStatusChart, SuccessRateChart } from "../components/ActivityCharts";
import { PageSkeleton } from "../components/PageSkeleton";
import { QueryErrorState, useQueryView } from "../components/QueryView";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { InlineBanner } from "../components/InlineBanner";
import type { Agent, CompactIssue, Issue, IssueSummary } from "@paperclipai/shared";
import { PluginSlotOutlet } from "@/plugins/slots";
import { SmokeLabDashboardCard } from "../components/SmokeLabDashboardCard";
import { taskStatusIconProps } from "@/lib/task-status-presentation";
const DASHBOARD_ACTIVITY_LIMIT = 10;
const DASHBOARD_RECENT_TASK_LIMIT = 10;
export function recentTaskIndexRows(issues: readonly CompactIssue[]): CompactIssue[] {
const recent: Array<{ issue: CompactIssue; at: number }> = [];
for (const issue of issues) {
const at = new Date(issue.updatedAt).getTime();
if (recent.length === DASHBOARD_RECENT_TASK_LIMIT && at <= recent[recent.length - 1]!.at) continue;
let index = recent.length;
while (index > 0 && recent[index - 1]!.at < at) index -= 1;
recent.splice(index, 0, { issue, at });
if (recent.length > DASHBOARD_RECENT_TASK_LIMIT) recent.pop();
}
return recent.map(entry => entry.issue);
}
export function withTaskSummaries(rows: readonly CompactIssue[], summaries: readonly IssueSummary[] | undefined): Issue[] {
const byId = new Map((summaries ?? []).map((summary) => [summary.id, summary]));
return rows.map((row) => {
const summary = byId.get(row.id);
return {
...row,
...(summary ? {
displayStatus: summary.displayStatus,
externalConversationState: summary.externalConversationState,
...(summary.blockerAttention ? { blockerAttention: summary.blockerAttention } : {}),
} : {}),
} as Issue;
});
}
export type PausedAgentBanner =
| { kind: "imported"; pausedImportedAgentIds: string[] }
| { kind: "all-paused" }
| null;
/**
* Which paused-agents banner the dashboard should show. Import-paused agents
* get the specific banner with a bulk resume (they were parked by the import
* safety default and stay parked until someone acts); otherwise a company
* whose agents are ALL paused gets a generic explanation, because from the
* outside it is indistinguishable from a broken company.
*/
export function derivePausedAgentBanner(agents: Agent[] | undefined): PausedAgentBanner {
if (!agents || agents.length === 0) return null;
const importedPaused = agents.filter(
(agent) => agent.status === "paused" && agent.pauseReason === "import",
);
if (importedPaused.length > 0) {
return { kind: "imported", pausedImportedAgentIds: importedPaused.map((agent) => agent.id) };
}
if (agents.every((agent) => agent.status === "paused")) return { kind: "all-paused" };
return null;
}
export function Dashboard() {
const designSandbox = useDesignSandbox();
const { selectedCompanyId, companies } = useCompany();
const { openOnboarding } = useDialogActions();
const { setBreadcrumbs } = useBreadcrumbs();
const [animatedActivityIds, setAnimatedActivityIds] = useState<Set<string>>(new Set());
const seenActivityIdsRef = useRef<Set<string>>(new Set());
const hydratedActivityRef = useRef(false);
const activityAnimationTimersRef = useRef<number[]>([]);
// `isFetching` is read alongside the data: a cached list is served while its
// refetch runs, and an empty one from before the first hire must not pass
// for the company's current state — see `shouldRouteAgentlessCompanyToOnboarding`.
const { data: agents, isFetching: agentsRefreshing } = useQuery({
queryKey: queryKeys.agents.list(selectedCompanyId!),
queryFn: () => agentsApi.list(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
// Bulk resume for agents parked by a company import. Sequential on purpose
// (mirrors the import page's activation checklist); a per-agent failure is
// tolerated so one bad agent never blocks the rest, and the refetch below
// re-renders the banner with whatever remains paused.
const queryClient = useQueryClient();
const resumeImportedAgents = useMutation({
mutationFn: async () => {
const targets = derivePausedAgentBanner(agents);
if (!targets || targets.kind !== "imported") return;
for (const agentId of targets.pausedImportedAgentIds) {
try {
await agentsApi.resume(agentId, selectedCompanyId ?? undefined);
} catch {
// Leave the agent paused; the banner re-renders with the remainder.
}
}
},
onSettled: async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(selectedCompanyId!) }),
queryClient.invalidateQueries({ queryKey: queryKeys.dashboard(selectedCompanyId!) }),
]);
},
});
// Opens onboarding once for a company with no agent (shared with the
// Responsibilities home page).
useAgentlessOnboardingAutoOpen();
useEffect(() => {
setBreadcrumbs([{ label: "Dashboard" }]);
}, [setBreadcrumbs]);
const dashboardQueryKey = queryKeys.dashboard(selectedCompanyId!);
const sharedDashboard = useSharedPollingQuery({
companyId: selectedCompanyId,
resourceKey: "dashboard",
queryKey: dashboardQueryKey,
enabled: !!selectedCompanyId,
});
const dashboardQuery = useQuery({
queryKey: dashboardQueryKey,
queryFn: () => dashboardApi.summary(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const { data, isLoading, dataUpdatedAt: dashboardUpdatedAt } = dashboardQuery;
const dashboardView = useQueryView(dashboardQuery);
usePublishSharedQueryData(sharedDashboard, data, dashboardUpdatedAt);
const activityQueryKey = [...queryKeys.activity(selectedCompanyId!), { limit: DASHBOARD_ACTIVITY_LIMIT }] as const;
const sharedActivity = useSharedPollingQuery({
companyId: selectedCompanyId,
resourceKey: `activity:limit:${DASHBOARD_ACTIVITY_LIMIT}`,
queryKey: activityQueryKey,
enabled: !!selectedCompanyId,
});
const { data: activity, dataUpdatedAt: activityUpdatedAt } = useQuery({
queryKey: activityQueryKey,
queryFn: () => activityApi.list(selectedCompanyId!, { limit: DASHBOARD_ACTIVITY_LIMIT }),
enabled: !!selectedCompanyId,
});
usePublishSharedQueryData(sharedActivity, activity, activityUpdatedAt);
const { data: issues } = useQuery({
queryKey: queryKeys.issues.listIndex(selectedCompanyId!),
queryFn: ({ signal }) => issuesApi.listCompact(selectedCompanyId!, { projection: "index" }, { signal }),
enabled: !!selectedCompanyId,
});
const { userId: accountUserId, settled: accountSettled } = useAccountIdentity();
const recentIndexRows = useMemo(() => recentTaskIndexRows(issues ?? []), [issues]);
const recentIds = useMemo(() => recentIndexRows.map((issue) => issue.id).sort(), [recentIndexRows]);
const { data: recentSummaries } = useQuery({
queryKey: queryKeys.issues.summaryBatch(selectedCompanyId!, accountUserId, recentIds),
queryFn: ({ signal }) => issuesApi.summaries(selectedCompanyId!, recentIds, { signal }),
enabled: !!selectedCompanyId && accountSettled && recentIds.length > 0,
});
const { data: projects } = useQuery({
...companyProjectsQuery(selectedCompanyId!, { includeArchived: true }),
enabled: !!selectedCompanyId,
});
const { data: companyMembers } = useQuery({
queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const userProfileMap = useMemo(
() => buildCompanyUserProfileMap(companyMembers?.users),
[companyMembers?.users],
);
const recentIssues = useMemo(
() => withTaskSummaries(recentIndexRows, recentSummaries),
[recentIndexRows, recentSummaries],
);
const recentActivity = useMemo(() => (activity ?? []).slice(0, 10), [activity]);
useEffect(() => {
for (const timer of activityAnimationTimersRef.current) {
window.clearTimeout(timer);
}
activityAnimationTimersRef.current = [];
seenActivityIdsRef.current = new Set();
hydratedActivityRef.current = false;
setAnimatedActivityIds(new Set());
}, [selectedCompanyId]);
useEffect(() => {
if (recentActivity.length === 0) return;
const seen = seenActivityIdsRef.current;
const currentIds = recentActivity.map((event) => event.id);
if (!hydratedActivityRef.current) {
for (const id of currentIds) seen.add(id);
hydratedActivityRef.current = true;
return;
}
const newIds = currentIds.filter((id) => !seen.has(id));
if (newIds.length === 0) {
for (const id of currentIds) seen.add(id);
return;
}
setAnimatedActivityIds((prev) => {
const next = new Set(prev);
for (const id of newIds) next.add(id);
return next;
});
for (const id of newIds) seen.add(id);
const timer = window.setTimeout(() => {
setAnimatedActivityIds((prev) => {
const next = new Set(prev);
for (const id of newIds) next.delete(id);
return next;
});
activityAnimationTimersRef.current = activityAnimationTimersRef.current.filter((t) => t !== timer);
}, 980);
activityAnimationTimersRef.current.push(timer);
}, [recentActivity]);
useEffect(() => {
return () => {
for (const timer of activityAnimationTimersRef.current) {
window.clearTimeout(timer);
}
};
}, []);
const agentMap = useMemo(() => {
const map = new Map<string, Agent>();
for (const a of agents ?? []) map.set(a.id, a);
return map;
}, [agents]);
const entityNameMap = useMemo(() => {
const map = new Map<string, string>();
for (const i of issues ?? []) map.set(`issue:${i.id}`, i.identifier ?? i.id.slice(0, 8));
for (const a of agents ?? []) map.set(`agent:${a.id}`, a.name);
for (const p of projects ?? []) map.set(`project:${p.id}`, p.name);
return map;
}, [issues, agents, projects]);
const entityTitleMap = useMemo(() => {
const map = new Map<string, string>();
for (const i of issues ?? []) map.set(`issue:${i.id}`, i.title);
return map;
}, [issues]);
const agentName = (id: string | null) => {
if (!id || !agents) return null;
return agents.find((a) => a.id === id)?.name ?? null;
};
if (!selectedCompanyId) {
if (companies.length === 0) {
return (
<EmptyState
icon={LayoutDashboard}
message="Welcome to Paperclip. Set up your first organization and agent to get started."
action="Get Started"
onAction={openOnboarding}
/>
);
}
return (
<EmptyState icon={LayoutDashboard} message="Create or select an organization to view the dashboard." />
);
}
// An outage before the first load shows the skeleton; loaded data stays on
// screen through a failed refetch, and only a real failure replaces it.
if (isLoading || dashboardView.kind === "reconnecting") {
return <PageSkeleton variant="dashboard" />;
}
if (dashboardView.kind === "error") {
return (
<QueryErrorState
size="page"
error={dashboardView.error}
action="load the dashboard"
onRetry={dashboardView.retry}
retrying={dashboardView.isFetching}
/>
);
}
// Same rule as the auto-offer above: a list still being refreshed may be the
// empty one cached before the first hire, and the banner's "Create one here"
// opens the same agent step the offer does.
const hasNoAgents = agents !== undefined && !agentsRefreshing && agents.length === 0;
const pausedBanner = derivePausedAgentBanner(agents);
const pausedImportedCount =
pausedBanner?.kind === "imported" ? pausedBanner.pausedImportedAgentIds.length : 0;
return (
<div className="space-y-6">
{pausedBanner?.kind === "imported" ? (
<InlineBanner
tone="warning"
icon={PauseCircle}
title={`${pausedImportedCount} imported agent${pausedImportedCount === 1 ? " is" : "s are"} paused and will not run.`}
actions={
<Button
size="sm"
onClick={() => resumeImportedAgents.mutate()}
disabled={resumeImportedAgents.isPending}
data-testid="dashboard-resume-imported-agents"
>
{resumeImportedAgents.isPending ? "Resuming…" : "Resume all"}
</Button>
}
>
Agents from an organization import arrive paused as a safety default. Resume them so assigned tasks can start.
</InlineBanner>
) : pausedBanner?.kind === "all-paused" ? (
<InlineBanner
tone="warning"
icon={PauseCircle}
title="All agents in this organization are paused — nothing will run."
actions={
<Button variant="ghost" size="sm" asChild>
<Link to="/agents">Review agents</Link>
</Button>
}
>
Resume at least one agent to let assigned tasks start.
</InlineBanner>
) : null}
{hasNoAgents && (
<div className="flex items-center justify-between gap-3 rounded-md border border-amber-300 bg-amber-50 px-4 py-3 dark:border-amber-500/25 dark:bg-amber-950/60">
<div className="flex items-center gap-2.5">
<Bot className="h-4 w-4 text-amber-600 dark:text-amber-400 shrink-0" />
<p className="text-sm text-amber-900 dark:text-amber-100">
You have no agents.
</p>
</div>
<button
onClick={() => openOnboarding({ initialStep: 3, companyId: selectedCompanyId! })}
className="text-sm font-medium text-amber-700 hover:text-amber-900 dark:text-amber-300 dark:hover:text-amber-100 underline underline-offset-2 shrink-0"
>
Create one here
</button>
</div>
)}
<ActiveAgentsPanel companyId={selectedCompanyId!} dedupeLinkedTasks />
{data && (
<>
{data.budgets.activeIncidents > 0 ? (
<div className="flex items-start justify-between gap-3 rounded-xl border border-red-500/20 bg-(image:--gradient-extract-1) px-4 py-3">
<div className="flex items-start gap-2.5">
<PauseCircle className="mt-0.5 h-4 w-4 shrink-0 text-red-700 dark:text-red-300" />
<div>
<p className="text-sm font-medium text-red-950 dark:text-red-50">
{data.budgets.activeIncidents} active budget incident{data.budgets.activeIncidents === 1 ? "" : "s"}
</p>
<p className="text-xs text-red-900/70 dark:text-red-100/70">
{data.budgets.pausedAgents} agents paused · {data.budgets.pausedProjects} projects paused · {data.budgets.pendingApprovals} pending budget approvals
</p>
</div>
</div>
<Link to="/costs" className="text-sm underline underline-offset-2 text-red-900 dark:text-red-100">
Open budgets
</Link>
</div>
) : null}
<div className={cn("grid auto-rows-fr grid-cols-2 items-stretch xl:grid-cols-4", designSandbox ? "gap-4" : "gap-1 sm:gap-2")}>
<MetricCard
appearance={designSandbox ? "card" : "plain"}
icon={Bot}
value={data.agents.active + data.agents.running + data.agents.paused + data.agents.error}
label="Agents Enabled"
to="/agents"
description={
<span>
{data.agents.running} running{", "}
{data.agents.paused} paused{", "}
{data.agents.error} errors
</span>
}
/>
<MetricCard
appearance={designSandbox ? "card" : "plain"}
icon={CircleDot}
value={data.tasks.inProgress}
label="Tasks In Progress"
to="/issues"
description={
<span>
{data.tasks.open} open{", "}
{data.tasks.blocked} blocked
</span>
}
/>
<MetricCard
appearance={designSandbox ? "card" : "plain"}
icon={DollarSign}
value={formatCents(data.costs.monthSpendCents)}
label="Month Spend"
to="/costs"
description={
<span>
{data.costs.monthBudgetCents > 0
? `${data.costs.monthUtilizationPercent}% of ${formatCents(data.costs.monthBudgetCents)} budget`
: "Unlimited budget"}
</span>
}
/>
<MetricCard
appearance={designSandbox ? "card" : "plain"}
icon={ShieldCheck}
value={data.pendingApprovals + data.budgets.pendingApprovals}
label="Pending Approvals"
to="/approvals"
description={
<span>
{data.budgets.pendingApprovals > 0
? `${data.budgets.pendingApprovals} budget overrides awaiting board review`
: "Awaiting board review"}
</span>
}
/>
</div>
<SmokeLabDashboardCard companyId={selectedCompanyId!} />
<div className={cn("grid grid-cols-1 gap-4 sm:grid-cols-2", SHOW_TASK_PRIORITY_UI ? "lg:grid-cols-4" : "lg:grid-cols-3")}>
<ChartCard title="Run Activity" subtitle="Last 14 days">
<RunActivityChart activity={data.runActivity} />
</ChartCard>
{/* PAP-411: "Tasks by Priority" chart hidden behind SHOW_TASK_PRIORITY_UI. */}
{SHOW_TASK_PRIORITY_UI && (
<ChartCard title="Tasks by Priority" subtitle="Last 14 days">
<PriorityChart issues={issues ?? []} />
</ChartCard>
)}
<ChartCard title="Tasks by Status" subtitle="Last 14 days">
<IssueStatusChart issues={issues ?? []} />
</ChartCard>
<ChartCard title="Success Rate" subtitle="Last 14 days">
<SuccessRateChart activity={data.runActivity} />
</ChartCard>
</div>
<PluginSlotOutlet
slotTypes={["dashboardWidget"]}
context={{ companyId: selectedCompanyId }}
className="grid gap-4 md:grid-cols-2"
// design-allow(card-pattern): class-string prop consumed by the plugin outlet; a component can't be passed here (C5a Run 3)
itemClassName="rounded-lg border bg-card p-4 shadow-sm"
/>
<div className="grid md:grid-cols-2 gap-4">
{/* Recent Activity */}
{recentActivity.length > 0 && (
<div className="min-w-0">
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3">
Recent Activity
</h3>
<Card className="@container block py-0 divide-y divide-border overflow-hidden">
{designSandbox ? <ActivityList events={recentActivity} agentMap={agentMap} userProfileMap={userProfileMap} entityNameMap={entityNameMap} entityTitleMap={entityTitleMap} rowClassName={event => animatedActivityIds.has(event.id) ? "activity-row-enter" : undefined} /> : recentActivity.map((event) => (
<ActivityRow
key={event.id}
event={event}
agentMap={agentMap}
userProfileMap={userProfileMap}
entityNameMap={entityNameMap}
entityTitleMap={entityTitleMap}
className={animatedActivityIds.has(event.id) ? "activity-row-enter" : undefined}
/>
))}
</Card>
</div>
)}
{/* Recent Tasks */}
<div className="min-w-0">
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3">
Recent Tasks
</h3>
{recentIssues.length === 0 ? (
<Card className="block p-4">
<p className="text-sm text-muted-foreground">No tasks yet.</p>
</Card>
) : (
designSandbox ? <Card className="block overflow-hidden py-0">
<TaskSummaryList issues={recentIssues.slice(0, 10)} />
</Card> : <Card className="@container block py-0 divide-y divide-border overflow-hidden">
{recentIssues.slice(0, 10).map((issue) => (
<Link
key={issue.id}
to={`/issues/${issue.identifier ?? issue.id}`}
className="dashboard-list-row text-sm cursor-pointer hover:bg-accent/50 transition-colors no-underline text-inherit block"
>
<div className="flex items-start gap-2 @xl:grid @xl:grid-cols-(--dashboard-task-list-columns) @xl:items-baseline">
<span className="flex size-6 shrink-0 items-center justify-end @xl:self-center">
<StatusIcon {...taskStatusIconProps(issue)} />
</span>
<span className="flex min-w-0 flex-1 flex-col gap-1 @xl:contents">
<span className="flex min-w-0 items-baseline gap-2 @xl:contents">
<span className="min-w-0 flex-1 truncate text-sm leading-6" title={issue.title}>
{issue.title}
</span>
<span className="ml-auto shrink-0 truncate text-right font-mono text-(length:--text-micro) text-muted-foreground @xl:col-start-4 @xl:row-start-1 @xl:w-(--dashboard-list-id-width)">
{issue.identifier ?? issue.id.slice(0, 8)}
</span>
</span>
<span className="flex min-h-6 min-w-0 items-center gap-2 @xl:contents">
<span className="flex min-w-0 flex-1 items-center @xl:col-start-3 @xl:row-start-1 @xl:self-center">
{issue.assigneeAgentId && (() => {
const name = agentName(issue.assigneeAgentId);
return name
? <AgentIdentity agent={agents?.find(agent => agent.id === issue.assigneeAgentId) ?? { id: issue.assigneeAgentId ?? undefined, name }} size="sm" className="max-w-32" />
: null;
})()}
</span>
<span className="ml-auto w-(--dashboard-list-time-width) shrink-0 whitespace-nowrap text-right text-xs text-muted-foreground">
{timeAgo(issue.updatedAt)}
</span>
</span>
</span>
</div>
</Link>
))}
</Card>
)}
</div>
</div>
</>
)}
</div>
);
}