feat(responsibilities): add routine filter and routine agent avatars (#23159)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The experimental Responsibilities dashboard (`outline_v2`) lists a
person's areas and responsibilities as a clean outline.
> - Today, operators cannot filter the Responsibilities outline by
whether a responsibility has routines, and rows do not show which agents
are assigned to those routines.
> - Operators need a quick visual signal of which responsibilities
already have agent-run routines and a fast way to focus on
responsibilities with or without routines.
> - This pull request adds `routineAgentIds` to `ResponsibilityRollup`,
adds the shared toolbar filter icon with "Has routines" and "No
routines" options (defaulting to either), and displays slightly
overlapping agent avatars on the right side of responsibility rows that
have assigned routines.
> - The benefit is faster scanning of routine coverage across
responsibilities without leaving the outline view.

## Linked Issues or Issue Description

**What existing behavior does this improve?**
The Responsibilities dashboard (`outline_v2` view at
`/<prefix>/responsibilities`) and the `ResponsibilityRollup` response
returned by `GET /api/companies/:companyId/responsibilities`.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
The Responsibilities dashboard header shows only a search box, total
counts, and the New area button. Each responsibility row shows only its
bar sentence or title, with no visual indicator of which agents are
assigned to its routines and no filter to narrow by routine presence.

**Proposed behavior**
The header adds the shared toolbar Filter icon button beside the search
box, opening a popover with "Has routines" and "No routines" options
(both unchecked by default so either is shown) and a Clear action. Each
responsibility row with one or more non-archived routines assigned to
agents displays those agents' avatars slightly overlapping on the right
side of the row (up to 4 avatars with a `+N` overflow indicator and a
tooltip listing agent names).

**Reason and benefit**
Operators scanning their responsibilities need to see at a glance which
responsibilities already have agents running routines and quickly filter
to responsibilities that still need routines set up (or only those with
routines).

**Breaking changes**
Additive field `routineAgentIds: string[]` added to
`ResponsibilityRollup`. Existing callers ignore unknown fields.

## What Changed

- Added `routineAgentIds: string[]` to `ResponsibilityRollup` in
`packages/shared/src/types/responsibility.ts` and refreshed the pinned
hash in `tests/runner-e2e/source-sdk-public-inputs.json`.
- Updated `responsibilityService.computeRollups` and
`buildResponsibilityRollup` in `server/src/services/responsibilities.ts`
to select `routines.assigneeAgentId` (ordered deterministically by title
and id) and deduplicate non-null assignees across non-archived member
routines (direct and project-linked) with no extra queries.
- Added `OutlineV2RoutineFilter` and `filterOutlineV2Groups` in
`ui/src/lib/responsibility-outline-v2.ts`.
- Added the shared toolbar `Filter` icon popover ("Has routines" / "No
routines", default either) and live filtered counts to
`ui/src/pages/Responsibilities.tsx`.
- Updated `ui/src/components/responsibilities/DashboardOutlineV2.tsx` to
filter groups, unfold matching areas while filtered, show an empty-match
state with a Clear filter button, and render slightly overlapping
routine-agent avatars (`size={20}`, `-space-x-1.5`, capped at 4 with
`+N`) on the right side of each row that has routines with assigned
agents.
- Added unit, embedded-Postgres integration, jsdom UI, and Storybook
coverage (`server/src/__tests__/responsibilities-rollup.test.ts`,
`server/src/__tests__/responsibilities.test.ts`,
`ui/src/lib/responsibility-outline-v2.test.ts`,
`ui/src/components/responsibilities/DashboardOutlineV2.test.tsx`,
`ui/src/pages/Responsibilities.outline-v2.test.tsx`, and
`ui/storybook/stories/activity/responsibilities.stories.tsx`).

## Verification

- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed (all 7 layers).
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm check:token-gates` — passed (all 4 gates clean).
- Focused Vitest suites (194 tests across 10 files) — passed:
  - `server/src/__tests__/responsibilities-rollup.test.ts` (18/18)
- `server/src/__tests__/responsibilities.test.ts` (37/37, embedded
PostgreSQL)
- `server/src/__tests__/responsibility-summaries.test.ts`,
`responsibility-summary-generator.test.ts`,
`responsibility-tools.test.ts`
- `ui/src/lib/responsibilities.test.ts` (41/41),
`responsibility-views.test.ts` (35/35),
`responsibility-outline-v2.test.ts` (15/15)
- `ui/src/components/responsibilities/DashboardOutlineV2.test.tsx` (2/2)
  - `ui/src/pages/Responsibilities.outline-v2.test.tsx` (1/1)
- Manually verified live Storybook preview (`Dashboard view: Outline v2,
routine avatars & filter`) in dark mode across default, "Has routines",
"No routines", and "Clear" states, confirming avatar overlap for 1, 2,
and 3 agents and empty states for rows without routines.
- Note: `pnpm verify` exited with code `2` because
`tests/runner-e2e/source-sdk-public-inputs.json` changed; CI supplies
the full broad suite.

## Risks

- Low risk. `routineAgentIds` is computed from the existing
`memberRoutines` query in `computeRollups` (adding one column selection
and deterministic ordering, no new queries or schema migrations).

## Model Used

- Google Gemini 4 Neon (High) via Antigravity with tool use and code
execution.

## 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
- [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: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-28 12:53:18 +00:00
1 parent c1bb0e80b3
commit c57471459f
17 files changed
+864 -40

No files matched your search

@@ -184,6 +184,8 @@ export interface ResponsibilityRollup {
projects: number;
/** Member routines that are not archived. */
routines: number;
/** Distinct agent ids assigned to non-archived member routines. */
routineAgentIds: string[];
openTasks: number;
blockedTasks: number;
/** Open tasks assigned to an agent. */
@@ -105,6 +105,22 @@ describe("responsibility attainment and status", () => {
expect(rollup.overdueProjects).toEqual([{ id: "p1", name: "Deck", targetDate: "2026-11-01", daysOverdue: 12 }]);
});
it("collects distinct routineAgentIds from non-archived routines only", () => {
const work = noWork();
work.routines.push(
{ id: "r1", title: "A", status: "active", assigneeAgentId: "agent-1", lastRunStatus: null, lastRunAt: null, nextRunAt: null },
{ id: "r2", title: "B", status: "paused", assigneeAgentId: "agent-2", lastRunStatus: null, lastRunAt: null, nextRunAt: null },
{ id: "r3", title: "C", status: "active", assigneeAgentId: "agent-1", lastRunStatus: null, lastRunAt: null, nextRunAt: null },
{ id: "r4", title: "D", status: "active", assigneeAgentId: null, lastRunStatus: null, lastRunAt: null, nextRunAt: null },
{ id: "r5", title: "E", status: "archived", assigneeAgentId: "agent-3", lastRunStatus: null, lastRunAt: null, nextRunAt: null },
);
const rollup = buildResponsibilityRollup({
responsibilityId: "r1", metric: metric(), healthOverride: null, counts: noCounts, work, now: NOW,
});
expect(rollup.routines).toBe(4);
expect(rollup.routineAgentIds).toEqual(["agent-1", "agent-2"]);
});
it("lists what an active responsibility is missing", () => {
expect(missingForActive({ standard: " ", metricName: null, metricTarget: null })).toEqual(["standard", "metricName", "metricTarget"]);
expect(missingForActive({ standard: "Bar", metricName: "Reply time", metricTarget: 0 })).toEqual([]);
@@ -1338,5 +1338,50 @@ describeEmbeddedPostgres("responsibility routes", () => {
const [row] = await db.select().from(responsibilities).where(eq(responsibilities.id, item.id));
expect(row?.areaId).toBe(to.body.id);
});
it("returns distinct routineAgentIds on overview rollups for direct and project-linked non-archived routines", async () => {
await enable();
const company = await seedCompany();
const agentA = await seedAgent(company.id, "Alpha");
const agentB = await seedAgent(company.id, "Beta");
const agentArchived = await seedAgent(company.id, "ArchivedAgent");
const board = createApp(db, localBoardActor());
const withRoutines = await createResponsibility(board, company.id, { title: "Has routines" });
const withoutRoutines = await createResponsibility(board, company.id, { title: "No routines" });
const [project] = await db.insert(projects).values({ companyId: company.id, name: "Ops", status: "in_progress" }).returning();
const [directRoutineA] = await db.insert(routines).values({
companyId: company.id, title: "A direct", status: "active", assigneeAgentId: agentA.id,
}).returning();
const [directRoutineDup] = await db.insert(routines).values({
companyId: company.id, title: "B duplicate agent", status: "paused", assigneeAgentId: agentA.id,
}).returning();
const [archivedRoutine] = await db.insert(routines).values({
companyId: company.id, title: "C archived", status: "archived", assigneeAgentId: agentArchived.id,
}).returning();
await db.insert(routines).values({
companyId: company.id, title: "D via project", status: "active", assigneeAgentId: agentB.id, projectId: project!.id,
});
await db.insert(responsibilityLinks).values([
{ companyId: company.id, responsibilityId: withRoutines.id, routineId: directRoutineA!.id },
{ companyId: company.id, responsibilityId: withRoutines.id, routineId: directRoutineDup!.id },
{ companyId: company.id, responsibilityId: withRoutines.id, routineId: archivedRoutine!.id },
{ companyId: company.id, responsibilityId: withRoutines.id, projectId: project!.id },
]);
const overview = await request(board).get(`/api/companies/${company.id}/responsibilities`);
expect(overview.status).toBe(200);
const byId = new Map(
(overview.body.responsibilities as Array<{ id: string; rollup: { routines: number; routineAgentIds: string[] } }>)
.map((item) => [item.id, item.rollup]),
);
expect(byId.get(withRoutines.id)).toMatchObject({
routines: 3,
routineAgentIds: [agentA.id, agentB.id],
});
expect(byId.get(withoutRoutines.id)).toMatchObject({
routines: 0,
routineAgentIds: [],
});
});
});
});
@@ -102,6 +102,7 @@ function row(input: RowInput): ResponsibilityWithRollup {
workSummary: input.signals ?? [],
projects: input.projects ?? 0,
routines: input.routines ?? 0,
routineAgentIds: [],
openTasks: input.open ?? 0,
blockedTasks: input.blocked ?? 0,
agentTasks: 0,
@@ -207,6 +208,7 @@ function detail(input: DetailInput = {}): ResponsibilityDetail {
workSummary: input.signals ?? [],
projects: input.counts?.projects ?? input.projects?.length ?? 0,
routines: input.counts?.routines ?? input.routines?.length ?? 0,
routineAgentIds: [],
openTasks: input.counts?.openTasks ?? 0,
blockedTasks: input.counts?.blockedTasks ?? 0,
agentTasks: 0,
@@ -110,7 +110,7 @@ function overview(): ResponsibilityOverview {
metric: { kind: "volume", name: "Investors contacted", unit: null, target: 20, low: null, high: null, current: 4,
direction: "at_least", attainment: 0.2, statusRule: null, updatedAt: new Date(), stale: false },
statusSentence: "4 of 20 investors contacted, 20% of target", workSummary: [],
projects: 0, routines: 0, openTasks: 2, blockedTasks: 0, agentTasks: 0, userTasks: 2, doneTasks: 0, nextDueAt: null, overdueProjects: [],
projects: 0, routines: 0, routineAgentIds: [], openTasks: 2, blockedTasks: 0, agentTasks: 0, userTasks: 2, doneTasks: 0, nextDueAt: null, overdueProjects: [],
},
}] as unknown as ResponsibilityOverview["responsibilities"],
proposed: [],
@@ -11,7 +11,7 @@ function rollup(overrides: Record<string, unknown> = {}) {
return {
health: "on_track", computedHealth: "on_track", healthOverridden: false, metric: null,
statusSentence: "12 of 20 investors contacted, 60% of target", workSummary: [{ text: "2 tasks blocked" }],
projects: 1, routines: 2, openTasks: 3, blockedTasks: 2, agentTasks: 1, userTasks: 2, doneTasks: 4,
projects: 1, routines: 2, routineAgentIds: [], openTasks: 3, blockedTasks: 2, agentTasks: 1, userTasks: 2, doneTasks: 4,
nextDueAt: null, overdueProjects: [], ...overrides,
};
}
+16 -2
View File
@@ -281,6 +281,7 @@ export interface ResponsibilityWorkRoutine {
id: string;
title: string;
status: string;
assigneeAgentId?: string | null;
lastRunStatus: string | null;
lastRunAt: Date | null;
nextRunAt: Date | null;
@@ -471,6 +472,15 @@ export function buildResponsibilityRollup(input: {
: null;
const unfinished = input.work.projects.filter(isUnfinishedProject).map((project) => project.targetDate)
.filter((date): date is string => date !== null).sort();
const nonArchivedRoutines = input.work.routines.filter((routine) => routine.status !== "archived");
const routineAgentIds: string[] = [];
const seenRoutineAgents = new Set<string>();
for (const routine of nonArchivedRoutines) {
if (routine.assigneeAgentId && !seenRoutineAgents.has(routine.assigneeAgentId)) {
seenRoutineAgents.add(routine.assigneeAgentId);
routineAgentIds.push(routine.assigneeAgentId);
}
}
return {
health: override ?? computedHealth,
computedHealth,
@@ -479,7 +489,8 @@ export function buildResponsibilityRollup(input: {
statusSentence: buildStatusSentence(metric),
workSummary: buildWorkSummary({ responsibilityId: input.responsibilityId, metric, work: input.work, now }),
projects: input.work.projects.length,
routines: input.work.routines.filter((routine) => routine.status !== "archived").length,
routines: nonArchivedRoutines.length,
routineAgentIds,
openTasks: input.counts.openTasks,
blockedTasks: input.counts.blockedTasks,
agentTasks: input.counts.agentTasks,
@@ -767,12 +778,14 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
id: routines.id,
title: routines.title,
status: routines.status,
assigneeAgentId: routines.assigneeAgentId,
lastRunStatus,
lastRunAt,
nextRunAt,
}).from(memberRoutineRows)
.innerJoin(routines, eq(routines.id, memberRoutineRows.routineId))
.where(sql`${routines.status} <> 'archived'`),
.where(sql`${routines.status} <> 'archived'`)
.orderBy(asc(routines.title), asc(routines.id)),
]);
const counts = new Map<string, RollupCounts>();
@@ -819,6 +832,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
id: row.id,
title: row.title,
status: row.status,
assigneeAgentId: row.assigneeAgentId,
lastRunStatus: row.lastRunStatus,
lastRunAt: row.lastRunAt ? new Date(row.lastRunAt) : null,
nextRunAt: row.nextRunAt ? new Date(row.nextRunAt) : null,
@@ -449,7 +449,7 @@
"packages/shared/src/types/project.ts": "50b9d9c51cb38d5862e287c1a47726716603f21c",
"packages/shared/src/types/quota.ts": "a0686a9afb3111a4de093f66200dc0c9152e883e",
"packages/shared/src/types/resource-memberships.ts": "9eab6fad50facf3e489f8c40e5bedd92e1d1faf8",
"packages/shared/src/types/responsibility.ts": "ca7eb329f98b9fc20fef3d8d25017edcfb230a0e",
"packages/shared/src/types/responsibility.ts": "a2b1dc01cefaf3e1a495f9035b7bd0293469bc57",
"packages/shared/src/types/routine.ts": "6b2f2fd27187c19f98afe99f926460ded2752f20",
"packages/shared/src/types/runtime-exposure.ts": "785f053a7ad5448cde94f36738cdb90585bbc92e",
"packages/shared/src/types/search.ts": "4e208a9b1942991bfe5f29ef58ec71625e2693e9",
+66 -1
View File
@@ -1,9 +1,74 @@
import { useId, type ReactNode } from "react";
import { Search } from "lucide-react";
import { Filter, Search } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "./ui/button";
import { Checkbox } from "./ui/checkbox";
import { FlyoutAppearanceProvider, FlyoutHeader } from "./ui/flyout";
import { Input } from "./ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import { TruncatedText } from "./TruncatedText";
export function ToolbarFilterPopover({
activeCount,
onClear,
label = "Filter",
contentLabel = "Filters",
align = "end",
contentClassName,
triggerDataAttr,
children,
}: {
activeCount: number;
onClear?: () => void;
label?: string;
contentLabel?: string;
align?: "start" | "center" | "end";
contentClassName?: string;
triggerDataAttr?: string;
children: ReactNode;
}) {
const active = activeCount > 0;
return (
<FlyoutAppearanceProvider appearance="refreshed">
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="design-toolbar-button design-toolbar-icon relative"
title={active ? `Filters: ${activeCount}` : "Filter"}
aria-label={active ? `${label} (${activeCount})` : label}
data-active={active}
{...(triggerDataAttr ? { [triggerDataAttr]: "" } : {})}
>
<Filter aria-hidden="true" />
{active ? (
<span
aria-hidden="true"
className="absolute -right-1 -top-1 flex size-3.5 items-center justify-center rounded-full bg-primary text-(length:--text-nano) font-semibold text-primary-foreground"
>
{activeCount}
</span>
) : null}
</Button>
</PopoverTrigger>
<PopoverContent align={align} className={cn("p-0", contentClassName)} aria-label={contentLabel}>
<FlyoutHeader className="flex items-center justify-between">
<span>Filters</span>
{active && onClear ? (
<Button type="button" variant="ghost" size="xs" onClick={onClear}>
Clear
</Button>
) : null}
</FlyoutHeader>
{children}
</PopoverContent>
</Popover>
</FlyoutAppearanceProvider>
);
}
export function FilterGroup({ title, searchLabel, query, onQueryChange, children, optionsKey }: { title: string; searchLabel?: string; query?: string; onQueryChange?: (value: string) => void; children: ReactNode; optionsKey: string }) {
const headingId = useId();
return (
@@ -0,0 +1,233 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { MemoryRouter } from "react-router-dom";
import type { Agent } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
areaFixture,
areaFundraising,
areaLegal,
areaPortfolio,
fundraisingBehind,
lpUpdatesStale,
portfolioOnTrack,
responsibilityFixture,
responsibilityOverviewFixture,
} from "../../../storybook/fixtures/responsibilities";
import { DashboardOutlineV2 } from "./DashboardOutlineV2";
vi.mock("@/context/CompanyContext", () => ({
useCompany: () => ({ selectedCompanyId: "company-1", selectedCompany: { id: "company-1", issuePrefix: "PAP" } }),
}));
vi.mock("./DashboardEditModule", () => ({
DashboardEditModule: () => null,
}));
function makeAgent(id: string, name: string): Agent {
return { id, name } as Agent;
}
describe("DashboardOutlineV2", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
localStorage.clear();
});
function renderOutline(props: Partial<Parameters<typeof DashboardOutlineV2>[0]> = {}) {
const multiRoutine = responsibilityFixture({
id: "resp-multi",
areaId: areaPortfolio.id,
title: "Ops coverage",
standard: "Five agents keep ops routines running.",
rollup: {
routines: 5,
routineAgentIds: ["agent-1", "agent-2", "agent-3", "agent-4", "agent-5"],
},
});
const unassignedRoutine = responsibilityFixture({
id: "resp-unassigned-routine",
areaId: areaPortfolio.id,
title: "Unassigned routine",
standard: "A routine with no agent assigned.",
rollup: {
routines: 1,
routineAgentIds: [],
},
});
const overview = props.overview ?? responsibilityOverviewFixture(
[fundraisingBehind, lpUpdatesStale, portfolioOnTrack, multiRoutine, unassignedRoutine],
[],
{ areas: [areaFundraising, areaPortfolio, areaLegal] },
);
const agents = [
makeAgent("agent-codex", "CodexCoder"),
makeAgent("agent-cto", "CTO"),
makeAgent("agent-1", "Alpha"),
makeAgent("agent-2", "Beta"),
makeAgent("agent-3", "Gamma"),
makeAgent("agent-4", "Delta"),
makeAgent("agent-5", "Epsilon"),
];
const agentsById = new Map(agents.map((agent) => [agent.id, agent]));
act(() => {
root.render(
<MemoryRouter>
<DashboardOutlineV2
companyId="company-1"
overview={overview}
agents={agents}
agentsById={agentsById}
now={new Date("2026-11-13T12:00:00Z")}
includeLetGo={false}
onToggleLetGo={vi.fn()}
keepEmptyAreas={new Set()}
onAddResponsibility={vi.fn()}
onNewTask={vi.fn()}
onAddArea={vi.fn()}
onReviewProposals={vi.fn()}
areaActions={{
onAddHere: vi.fn(),
onRename: vi.fn(),
onArchive: vi.fn(),
onRestore: vi.fn(),
}}
{...props}
/>
</MemoryRouter>,
);
});
}
it("renders overlapping routine agent avatars on rows with assigned routines and omits them otherwise", () => {
renderOutline();
const fundraisingRow = container.querySelector('[data-responsibility-id="resp-fundraising"]');
const fundraisingAvatars = fundraisingRow?.querySelector("[data-routine-agents]");
expect(fundraisingAvatars?.getAttribute("data-routine-agents")).toBe("agent-codex");
expect(fundraisingAvatars?.getAttribute("role")).toBe("img");
expect(fundraisingAvatars?.getAttribute("aria-label")).toBe("Routine agents: CodexCoder");
expect(fundraisingAvatars?.getAttribute("aria-hidden")).toBeNull();
expect(fundraisingAvatars?.querySelectorAll('[data-slot="agent-avatar"]')).toHaveLength(1);
expect(fundraisingRow?.querySelector("a")?.textContent).toBe(fundraisingBehind.standard);
const lpRow = container.querySelector('[data-responsibility-id="resp-lp-updates"]');
expect(lpRow?.querySelector("[data-routine-agents]")).toBeNull();
const unassignedRow = container.querySelector('[data-responsibility-id="resp-unassigned-routine"]');
expect(unassignedRow?.querySelector("[data-routine-agents]")).toBeNull();
const multiRow = container.querySelector('[data-responsibility-id="resp-multi"]');
const multiAvatars = multiRow?.querySelector("[data-routine-agents]");
expect(multiAvatars?.getAttribute("aria-label")).toBe("Routine agents: Alpha, Beta, Gamma, Delta, Epsilon");
expect(multiAvatars?.getAttribute("title")).toBe("Alpha, Beta, Gamma, Delta, Epsilon");
expect(multiAvatars?.querySelectorAll('[data-slot="agent-avatar"]')).toHaveLength(4);
expect(multiAvatars?.textContent).toContain("+1");
});
it("bounds render and agent-lookup work linearly on a 500+ responsibility dashboard across both filters", () => {
const areaCount = 50;
const perArea = 11;
const total = areaCount * perArea;
const agentCount = 520;
const areas = Array.from({ length: areaCount }, (_, index) =>
areaFixture({ id: `large-area-${index}`, title: `Large area ${index}`, sortOrder: index }),
);
const agents = Array.from({ length: agentCount }, (_, index) =>
makeAgent(`large-agent-${index}`, `Agent ${index}`),
);
const backingAgentsById = new Map(agents.map((agent) => [agent.id, agent]));
let agentLookups = 0;
const countedAgentsById = new Proxy(backingAgentsById, {
get(target, property, receiver) {
if (property === "get") {
return (key: string) => {
if (++agentLookups > total * 12) {
throw new Error("Routine avatar rendering exceeded linear agent lookup bound");
}
return target.get(key);
};
}
const value = Reflect.get(target, property, receiver);
return typeof value === "function" ? value.bind(target) : value;
},
});
let rowReads = 0;
const responsibilities = Array.from({ length: total }, (_, index) => {
const hasRoutine = index % 2 === 0;
const item = responsibilityFixture({
id: `large-resp-${index}`,
areaId: `large-area-${Math.floor(index / perArea)}`,
title: `Large responsibility ${index}`,
standard: `Standard ${index}`,
rollup: {
routines: hasRoutine ? 2 : 0,
routineAgentIds: hasRoutine ? [`large-agent-${index % agentCount}`, `large-agent-${(index + 1) % agentCount}`] : [],
},
});
return new Proxy(item, {
get(target, property, receiver) {
if (++rowReads > total * 40) {
throw new Error("DashboardOutlineV2 exceeded linear responsibility read bound");
}
return Reflect.get(target, property, receiver);
},
});
});
const overview = responsibilityOverviewFixture(responsibilities, [], { areas });
const expectedWithRoutines = Math.ceil(total / 2);
const expectedWithoutRoutines = Math.floor(total / 2);
renderOutline({ overview, agents, agentsById: countedAgentsById, routineFilter: "has_routines" });
expect(container.querySelectorAll("li[data-responsibility-id]")).toHaveLength(expectedWithRoutines);
expect(container.querySelectorAll("[data-routine-agents]")).toHaveLength(expectedWithRoutines);
renderOutline({ overview, agents, agentsById: countedAgentsById, routineFilter: "no_routines" });
expect(container.querySelectorAll("li[data-responsibility-id]")).toHaveLength(expectedWithoutRoutines);
expect(container.querySelectorAll("[data-routine-agents]")).toHaveLength(0);
expect(agentLookups).toBeGreaterThanOrEqual(expectedWithRoutines * 2);
expect(agentLookups).toBeLessThanOrEqual(total * 12);
expect(rowReads).toBeGreaterThanOrEqual(total);
expect(rowReads).toBeLessThanOrEqual(total * 40);
});
it("filters rows by has_routines and no_routines and offers clearing empty results", () => {
renderOutline({ routineFilter: "has_routines" });
expect(container.querySelector('[data-responsibility-id="resp-fundraising"]')).not.toBeNull();
expect(container.querySelector('[data-responsibility-id="resp-portfolio"]')).not.toBeNull();
expect(container.querySelector('[data-responsibility-id="resp-lp-updates"]')).toBeNull();
expect(container.querySelector('[data-outline-v2-area="area-legal"]')).toBeNull();
renderOutline({ routineFilter: "no_routines" });
expect(container.querySelector('[data-responsibility-id="resp-lp-updates"]')).not.toBeNull();
expect(container.querySelector('[data-responsibility-id="resp-fundraising"]')).toBeNull();
expect(container.querySelector('[data-responsibility-id="resp-portfolio"]')).toBeNull();
const onClearFilter = vi.fn();
renderOutline({
overview: responsibilityOverviewFixture([lpUpdatesStale], [], { areas: [areaFundraising] }),
routineFilter: "has_routines",
onClearFilter,
});
const empty = container.querySelector("[data-outline-v2-no-match]");
expect(empty?.textContent).toContain("None of your responsibilities have routines yet.");
const clearButton = empty?.querySelector("button");
expect(clearButton?.textContent).toBe("Clear filter");
act(() => clearButton?.click());
expect(onClearFilter).toHaveBeenCalledTimes(1);
});
});
@@ -1,16 +1,18 @@
import { useCallback, useMemo, useState } from "react";
import type { ResponsibilityWithRollup } from "@paperclipai/shared";
import type { Agent, ResponsibilityWithRollup } from "@paperclipai/shared";
import { ChevronRight, Plus } from "lucide-react";
import { AgentAvatar } from "@/components/AgentAvatar";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import {
outlineV2Groups,
outlineV2Href,
outlineV2Line,
outlineV2VisibleGroups,
readCollapsedAreas,
searchOutlineV2Groups,
writeCollapsedAreas,
type OutlineV2Group,
type OutlineV2RoutineFilter,
} from "@/lib/responsibility-outline-v2";
import { activeResponsibilities } from "@/lib/responsibility-views";
import { Link } from "@/lib/router";
@@ -34,16 +36,63 @@ function useCollapsedAreas(scope: string): [ReadonlySet<string>, (key: string) =
return [collapsed, toggle];
}
/** One responsibility: its bar sentence (or its title), opening its page. */
function OutlineV2Row({ responsibility }: { responsibility: ResponsibilityWithRollup }) {
const MAX_ROUTINE_AVATARS = 4;
/** Slightly overlapping avatars of the agents assigned to a responsibility's routines. */
function RoutineAgentAvatars({
agentIds,
agentsById,
names,
}: {
agentIds: readonly string[];
agentsById: ReadonlyMap<string, Agent>;
names: readonly string[];
}) {
if (agentIds.length === 0) return null;
const shown = agentIds.slice(0, MAX_ROUTINE_AVATARS);
const extra = agentIds.length - shown.length;
return (
<li data-responsibility-id={responsibility.id}>
<span
className="pointer-events-none flex shrink-0 items-center gap-1"
role="img"
aria-label={`Routine agents: ${names.join(", ")}`}
title={names.join(", ")}
data-routine-agents={agentIds.join(",")}
>
<span className="flex items-center -space-x-1.5" aria-hidden="true">
{shown.map((id) => {
const agent = agentsById.get(id);
return <AgentAvatar key={id} agent={agent ?? { id }} name={agent?.name} size={20} />;
})}
</span>
{extra > 0 ? <span className="text-xs tabular-nums text-muted-foreground" aria-hidden="true">+{extra}</span> : null}
</span>
);
}
/** One responsibility: its bar sentence (or its title), opening its page, with routine agent avatars on the right. */
function OutlineV2Row({
responsibility,
agentsById,
}: {
responsibility: ResponsibilityWithRollup;
agentsById: ReadonlyMap<string, Agent>;
}) {
const routineAgentIds = responsibility.rollup.routines > 0 ? responsibility.rollup.routineAgentIds : [];
const routineAgentNames = routineAgentIds.map((id) => agentsById.get(id)?.name ?? "An agent");
return (
<li
data-responsibility-id={responsibility.id}
className="relative flex items-center justify-between gap-4 py-3 pl-11 pr-5 text-sm text-foreground transition-colors hover:bg-accent/50"
>
<Link
to={outlineV2Href(responsibility.id)}
className="block break-words py-3 pl-11 pr-5 text-sm text-foreground transition-colors hover:bg-accent/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
title={routineAgentNames.length > 0 ? `Routine agents: ${routineAgentNames.join(", ")}` : undefined}
className="min-w-0 flex-1 break-words after:absolute after:inset-0 focus-visible:outline-none focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring"
>
{outlineV2Line(responsibility)}
</Link>
<RoutineAgentAvatars agentIds={routineAgentIds} agentsById={agentsById} names={routineAgentNames} />
</li>
);
}
@@ -55,11 +104,13 @@ function OutlineV2Row({ responsibility }: { responsibility: ResponsibilityWithRo
*/
function OutlineV2Area({
group,
agentsById,
expanded,
onToggle,
onAdd,
}: {
group: OutlineV2Group;
agentsById: ReadonlyMap<string, Agent>;
expanded: boolean;
onToggle: () => void;
onAdd: () => void;
@@ -103,7 +154,7 @@ function OutlineV2Area({
{group.items.length > 0 ? (
<ul className="flex flex-col divide-y divide-border border-t border-border">
{group.items.map((item) => (
<OutlineV2Row key={item.id} responsibility={item} />
<OutlineV2Row key={item.id} responsibility={item} agentsById={agentsById} />
))}
</ul>
) : canAdd ? (
@@ -128,11 +179,14 @@ function OutlineV2Area({
* "Edit your dashboard" with an agent, and its saved versions. An empty
* dashboard shows only the module, offering to create it with an agent.
*
* `search` narrows the areas to what matches and opens every match, whatever
* was folded; the page owns the field, which sits where its headline was.
* `search` and `routineFilter` narrow the areas to what matches and open every
* match, whatever was folded; the page owns both controls.
*/
export function DashboardOutlineV2({
search = "",
routineFilter = "all",
visibleGroups,
onClearFilter,
companyId,
overview,
agentsById,
@@ -140,28 +194,42 @@ export function DashboardOutlineV2({
onAddResponsibility,
onAddArea,
onReviewProposals,
}: DashboardViewProps & { search?: string }) {
}: DashboardViewProps & {
search?: string;
routineFilter?: OutlineV2RoutineFilter;
/** Pre-filtered visible groups from the page, avoiding a duplicate filter+search pass. */
visibleGroups?: readonly OutlineV2Group[];
onClearFilter?: () => void;
}) {
const active = useMemo(() => activeResponsibilities(overview.responsibilities), [overview.responsibilities]);
const groups = useMemo(
() => outlineV2Groups(overview.areas, overview.responsibilities, keepEmptyAreas),
[overview.areas, overview.responsibilities, keepEmptyAreas],
() => (visibleGroups ? null : outlineV2Groups(overview.areas, overview.responsibilities, keepEmptyAreas)),
[visibleGroups, overview.areas, overview.responsibilities, keepEmptyAreas],
);
const [collapsed, toggle] = useCollapsedAreas(JSON.stringify([companyId, overview.ownerUserId]));
const query = search.trim();
const shown = useMemo(() => searchOutlineV2Groups(groups, query), [groups, query]);
const shown = useMemo(
() => visibleGroups ?? outlineV2VisibleGroups(groups ?? [], { search: query, routineFilter }),
[visibleGroups, groups, query, routineFilter],
);
const isNarrowed = query !== "" || routineFilter !== "all";
const hasAnyGroups = visibleGroups
? overview.areas.some((area) => area.status === "active" || keepEmptyAreas.has(area.id)) || active.length > 0
: (groups?.length ?? 0) > 0;
const renderArea = (group: OutlineV2Group) => (
<OutlineV2Area
key={group.key}
group={group}
expanded={query !== "" || !collapsed.has(group.key)}
agentsById={agentsById}
expanded={isNarrowed || !collapsed.has(group.key)}
onToggle={() => toggle(group.key)}
onAdd={() => onAddResponsibility(group.area?.id ?? null)}
/>
);
// Nothing owned and nothing proposed: only the module, and any area just added by hand.
if (groups.length === 0 && active.length === 0 && overview.proposed.length === 0) {
if (!hasAnyGroups && active.length === 0 && overview.proposed.length === 0) {
return (
<div className="flex flex-col gap-4" data-dashboard-view="outline_v2" data-dashboard-empty="">
<DashboardEditModule
@@ -181,9 +249,27 @@ export function DashboardOutlineV2({
{shown.length > 0 ? (
shown.map(renderArea)
) : query ? (
<p className="text-sm text-muted-foreground" role="status" data-outline-v2-no-match="">
Nothing matches “{query}”.
</p>
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground" role="status" data-outline-v2-no-match="">
<span>
{routineFilter === "all"
? `Nothing matches “${query}”.`
: `Nothing matches “${query}” with this filter.`}
</span>
{routineFilter !== "all" && onClearFilter ? (
<Button type="button" size="xs" variant="ghost" onClick={onClearFilter}>Clear filter</Button>
) : null}
</div>
) : routineFilter !== "all" ? (
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground" role="status" data-outline-v2-no-match="">
<span>
{routineFilter === "has_routines"
? "None of your responsibilities have routines yet."
: "Every responsibility has at least one routine."}
</span>
{onClearFilter ? (
<Button type="button" size="xs" variant="ghost" onClick={onClearFilter}>Clear filter</Button>
) : null}
</div>
) : (
<p className="text-sm text-muted-foreground">No areas yet.</p>
)}
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
areaDealFlow,
areaFixture,
areaFundraising,
areaLegal,
areaPortfolio,
@@ -13,11 +14,13 @@ import {
import {
OUTLINE_V2_COLLAPSED_STORAGE_KEY,
OUTLINE_V2_NO_AREA_KEY,
filterOutlineV2Groups,
outlineV2Counts,
outlineV2CountsLabel,
outlineV2Groups,
outlineV2Href,
outlineV2Line,
outlineV2VisibleGroups,
readCollapsedAreas,
searchOutlineV2Groups,
writeCollapsedAreas,
@@ -123,6 +126,78 @@ describe("searchOutlineV2Groups", () => {
});
});
describe("filterOutlineV2Groups", () => {
const groups = outlineV2Groups(
[areaFundraising, areaPortfolio, areaLegal],
[fundraisingBehind, lpUpdatesStale, portfolioOnTrack, boardReportingOverridden],
);
const shape = (found: ReturnType<typeof filterOutlineV2Groups>) =>
found.map((group) => [group.key, group.items.map((item) => item.id)]);
it("returns every group including empty areas when filter is all", () => {
expect(shape(filterOutlineV2Groups(groups, "all"))).toEqual([
[areaFundraising.id, ["resp-fundraising", "resp-lp-updates"]],
[areaPortfolio.id, ["resp-portfolio"]],
[areaLegal.id, []],
[OUTLINE_V2_NO_AREA_KEY, ["resp-board-reporting"]],
]);
});
it("keeps only responsibilities with routines and drops empty areas", () => {
expect(shape(filterOutlineV2Groups(groups, "has_routines"))).toEqual([
[areaFundraising.id, ["resp-fundraising"]],
[areaPortfolio.id, ["resp-portfolio"]],
]);
});
it("keeps only responsibilities with no routines and drops empty areas", () => {
expect(shape(filterOutlineV2Groups(groups, "no_routines"))).toEqual([
[areaFundraising.id, ["resp-lp-updates"]],
[OUTLINE_V2_NO_AREA_KEY, ["resp-board-reporting"]],
]);
});
it.each(["has_routines", "no_routines"] as const)(
"bounds large-collection filtering work linearly for %s across 600 responsibilities",
(routineFilter) => {
const areaCount = 60;
const perArea = 10;
const total = areaCount * perArea;
const areas = Array.from({ length: areaCount }, (_, index) =>
areaFixture({ id: `area-${index}`, title: `Area ${index}`, sortOrder: index }),
);
let rowReads = 0;
const responsibilities = Array.from({ length: total }, (_, index) => {
const hasRoutine = index % 2 === 0;
const item = responsibilityFixture({
id: `resp-${index}`,
areaId: `area-${Math.floor(index / perArea)}`,
title: `Responsibility ${index}`,
standard: hasRoutine ? `Automated standard ${index}` : `Manual standard ${index}`,
rollup: {
routines: hasRoutine ? 2 : 0,
routineAgentIds: hasRoutine ? [`agent-${index % 500}`, `agent-${(index + 1) % 500}`] : [],
},
});
return new Proxy(item, {
get(target, property, receiver) {
if (++rowReads > total * 16) {
throw new Error("Outline v2 filtering exceeded linear collection work bound");
}
return Reflect.get(target, property, receiver);
},
});
});
const grouped = outlineV2Groups(areas, responsibilities);
const visible = outlineV2VisibleGroups(grouped, { routineFilter, search: "standard" });
expect(outlineV2Counts(visible)).toEqual({ areas: areaCount, responsibilities: total / 2 });
expect(rowReads).toBeGreaterThanOrEqual(total);
expect(rowReads).toBeLessThanOrEqual(total * 16);
},
);
});
describe("collapsed areas in storage", () => {
it("round-trips, and ignores anything that is not a list of keys", () => {
writeCollapsedAreas(new Set(["area-a", OUTLINE_V2_NO_AREA_KEY]), "owner");
+34
View File
@@ -28,6 +28,8 @@ export interface OutlineV2Group {
items: ResponsibilityWithRollup[];
}
export type OutlineV2RoutineFilter = "all" | "has_routines" | "no_routines";
/**
* Every active area, holding what the person owns there or nothing yet, plus
* any other area (proposed, archived) that holds one of their active
@@ -73,6 +75,25 @@ export function outlineV2CountsLabel({ areas, responsibilities }: OutlineV2Count
return `${areaPart} and ${responsibilityPart}`;
}
/**
* Narrow groups by whether each responsibility has one or more non-archived
* routines. `"all"` returns the groups unchanged (including empty areas);
* active filters keep only matching responsibilities and drop empty areas.
*/
export function filterOutlineV2Groups(
groups: readonly OutlineV2Group[],
routineFilter: OutlineV2RoutineFilter,
): OutlineV2Group[] {
if (routineFilter === "all") return [...groups];
const wantRoutines = routineFilter === "has_routines";
const found: OutlineV2Group[] = [];
for (const group of groups) {
const items = group.items.filter((item) => (item.rollup.routines > 0) === wantRoutines);
if (items.length > 0) found.push({ ...group, items });
}
return found;
}
/**
* The groups narrowed to a search. Every entered word must appear, in any
* order and any case, across a responsibility's sentence, its title and its
@@ -99,6 +120,19 @@ export function searchOutlineV2Groups(groups: readonly OutlineV2Group[], query:
return found;
}
/**
* Single selector for the Outline v2 groups shown after applying both the
* routine filter and search query, shared by the header counts and the list.
*/
export function outlineV2VisibleGroups(
groups: readonly OutlineV2Group[],
options: { search?: string; routineFilter?: OutlineV2RoutineFilter },
): OutlineV2Group[] {
const routineFilter = options.routineFilter ?? "all";
const query = options.search?.trim() ?? "";
return searchOutlineV2Groups(filterOutlineV2Groups(groups, routineFilter), query);
}
/** A row's link: the responsibility page, opened in its simplified view. */
export function outlineV2Href(responsibilityId: string): string {
return `${responsibilityPath(responsibilityId)}?view=${OUTLINE_V2_RESPONSIBILITY_VIEW}`;
@@ -0,0 +1,149 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MemoryRouter } from "react-router-dom";
import type { Agent } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
areaFundraising,
areaLegal,
areaPortfolio,
fundraisingBehind,
lpUpdatesStale,
portfolioOnTrack,
responsibilityOverviewFixture,
} from "../../storybook/fixtures/responsibilities";
import { Responsibilities } from "./Responsibilities";
const OVERVIEW = responsibilityOverviewFixture(
[fundraisingBehind, lpUpdatesStale, portfolioOnTrack],
[],
{ areas: [areaFundraising, areaPortfolio, areaLegal] },
);
const AGENTS: Agent[] = [
{ id: "agent-codex", name: "CodexCoder" } as Agent,
{ id: "agent-cto", name: "CTO" } as Agent,
];
vi.mock("@/context/CompanyContext", () => ({
useCompany: () => ({ selectedCompanyId: "company-1", selectedCompany: { id: "company-1", issuePrefix: "PAP" } }),
}));
vi.mock("@/context/BreadcrumbContext", () => ({
useBreadcrumbs: () => ({ setBreadcrumbs: vi.fn() }),
}));
vi.mock("@/hooks/useResolvedViewerId", () => ({
useResolvedViewerId: () => ({ userId: "user-storybook", error: null, retry: vi.fn() }),
}));
vi.mock("@/hooks/useAgentlessOnboardingAutoOpen", () => ({
useAgentlessOnboardingAutoOpen: () => {},
}));
vi.mock("@/api/responsibilities", () => ({
responsibilitiesApi: {
overview: vi.fn(async () => OVERVIEW),
},
}));
vi.mock("@/api/agents", () => ({
agentsApi: {
list: vi.fn(async () => AGENTS),
},
}));
vi.mock("@/components/responsibilities/DashboardEditModule", () => ({
DashboardEditModule: () => null,
}));
vi.mock("@/components/responsibilities/DashboardChatComposer", () => ({
DashboardChatComposer: () => null,
}));
async function flush() {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
}
describe("Responsibilities routine filter", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
localStorage.clear();
});
it("defaults to either, filters by Has routines or No routines via the filter popover, and clears back to either", async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
act(() => {
root.render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={["/PAP/responsibilities"]}>
<Responsibilities />
</MemoryRouter>
</QueryClientProvider>,
);
});
await flush();
// Default: all 3 areas (including empty Legal) and all 3 responsibilities.
await vi.waitFor(() => {
expect(container.querySelector("[data-dashboard-counts]")?.textContent).toBe("3 areas and 3 responsibilities");
});
expect(container.querySelector('[data-responsibility-id="resp-fundraising"] [data-routine-agents="agent-codex"]')).not.toBeNull();
expect(container.querySelector('[data-responsibility-id="resp-lp-updates"] [data-routine-agents]')).toBeNull();
const filterBtn = container.querySelector<HTMLButtonElement>("[data-outline-v2-filter]");
expect(filterBtn).not.toBeNull();
expect(filterBtn?.getAttribute("data-active")).toBe("false");
// Open filter popover.
act(() => filterBtn!.click());
await flush();
const hasRoutines = document.body.querySelector<HTMLButtonElement>('button[role="checkbox"][aria-label="Has routines"]');
const noRoutines = document.body.querySelector<HTMLButtonElement>('button[role="checkbox"][aria-label="No routines"]');
expect(hasRoutines).not.toBeNull();
expect(noRoutines).not.toBeNull();
expect(hasRoutines?.getAttribute("aria-checked")).toBe("false");
expect(noRoutines?.getAttribute("aria-checked")).toBe("false");
// Select "Has routines".
act(() => hasRoutines!.click());
await flush();
expect(filterBtn?.getAttribute("data-active")).toBe("true");
expect(container.querySelector("[data-dashboard-counts]")?.textContent).toBe("2 areas and 2 responsibilities");
expect(container.querySelector('[data-responsibility-id="resp-fundraising"]')).not.toBeNull();
expect(container.querySelector('[data-responsibility-id="resp-portfolio"]')).not.toBeNull();
expect(container.querySelector('[data-responsibility-id="resp-lp-updates"]')).toBeNull();
// Switch to "No routines".
act(() => noRoutines!.click());
await flush();
expect(container.querySelector("[data-dashboard-counts]")?.textContent).toBe("1 area and 1 responsibility");
expect(container.querySelector('[data-responsibility-id="resp-lp-updates"]')).not.toBeNull();
expect(container.querySelector('[data-responsibility-id="resp-fundraising"]')).toBeNull();
// Click "No routines" again to toggle back to default (either).
act(() => noRoutines!.click());
await flush();
expect(filterBtn?.getAttribute("data-active")).toBe("false");
expect(container.querySelector("[data-dashboard-counts]")?.textContent).toBe("3 areas and 3 responsibilities");
expect(container.querySelector('[data-responsibility-id="resp-fundraising"]')).not.toBeNull();
expect(container.querySelector('[data-responsibility-id="resp-lp-updates"]')).not.toBeNull();
});
});
+69 -15
View File
@@ -5,6 +5,7 @@ import type { ResponsibilityArea, ResponsibilityWithRollup } from "@paperclipai/
import { Plus } from "lucide-react";
import { describeError } from "@/api/errors";
import { responsibilitiesApi } from "@/api/responsibilities";
import { FilterGroup, FilterRow, ToolbarFilterPopover } from "@/components/CollectionFilterOptions";
import { PageSkeleton } from "@/components/PageSkeleton";
import { QueryErrorState, QueryView, useQueryView } from "@/components/QueryView";
import { ToolbarSearch } from "@/components/ToolbarSearch";
@@ -44,7 +45,13 @@ import {
onboardingProvenance,
type AttentionItem,
} from "@/lib/responsibilities";
import { outlineV2Counts, outlineV2CountsLabel, outlineV2Groups } from "@/lib/responsibility-outline-v2";
import {
outlineV2Counts,
outlineV2CountsLabel,
outlineV2Groups,
outlineV2VisibleGroups,
type OutlineV2RoutineFilter,
} from "@/lib/responsibility-outline-v2";
import { DASHBOARD_DEFAULT_VIEW, DASHBOARD_VIEW_OPTIONS } from "@/lib/responsibility-views";
import { cn, formatShortDate } from "@/lib/utils";
@@ -102,6 +109,8 @@ function OwnerDashboard({ selectedCompanyId, ownerUserId }: { selectedCompanyId:
// One dashboard, no switch between views; reviewing proposals visits the full layout.
const { view, visiting, visit, leave } = usePageView(DASHBOARD_VIEW_OPTIONS, DASHBOARD_DEFAULT_VIEW);
const [search, setSearch] = useState("");
const [routineFilter, setRoutineFilter] = useState<OutlineV2RoutineFilter>("all");
const clearRoutineFilter = useCallback(() => setRoutineFilter("all"), []);
const { agents, byId: agentsById, query: agentsQuery } = useAgentDirectory(selectedCompanyId);
const agentsView = useQueryView(agentsQuery);
// One clock per visit: day-level judgements, and a stable value keeps rows memoized.
@@ -130,13 +139,22 @@ function OwnerDashboard({ selectedCompanyId, ownerUserId }: { selectedCompanyId:
return counts;
}, [overview?.responsibilities]);
// Outline v2's one line of numbers, beside its search. Null on an empty dashboard.
const outlineGroups = useMemo(
() => (overview ? outlineV2Groups(overview.areas, overview.responsibilities, keepEmptyAreas) : null),
[overview, keepEmptyAreas],
);
const visibleOutlineGroups = useMemo(
() => (outlineGroups ? outlineV2VisibleGroups(outlineGroups, { search, routineFilter }) : null),
[outlineGroups, search, routineFilter],
);
// Outline v2's one line of numbers, beside its search and filter. Null on an empty dashboard.
const outlineCounts = useMemo(() => {
if (!overview) return null;
const counts = outlineV2Counts(outlineV2Groups(overview.areas, overview.responsibilities, keepEmptyAreas));
if (!overview || !outlineGroups || !visibleOutlineGroups) return null;
const total = outlineV2Counts(outlineGroups);
// The same rule as the view's empty state, which shows only the create module.
return counts.areas > 0 || counts.responsibilities > 0 || overview.proposed.length > 0 ? counts : null;
}, [overview, keepEmptyAreas]);
if (total.areas === 0 && total.responsibilities === 0 && overview.proposed.length === 0) return null;
return outlineV2Counts(visibleOutlineGroups);
}, [overview, outlineGroups, visibleOutlineGroups]);
const openAdd = useCallback((areaId: string | null) => setAdding({ areaId }), []);
const agentName = useCallback((id: string) => agentsById.get(id)?.name, [agentsById]);
@@ -168,16 +186,42 @@ function OwnerDashboard({ selectedCompanyId, ownerUserId }: { selectedCompanyId:
)}
>
{view === "outline_v2" ? (
// The breadcrumb bar's heading already names the page: search and the counts take the headline's place.
// The breadcrumb bar's heading already names the page: search, filter and the counts take the headline's place.
outlineCounts ? (
<div className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2">
<ToolbarSearch
query={search}
onQueryChange={setSearch}
label="Search your dashboard"
placeholder="Search"
inputType="search"
/>
<div className="design-page-toolbar gap-2">
<ToolbarSearch
query={search}
onQueryChange={setSearch}
label="Search your dashboard"
placeholder="Search"
inputType="search"
/>
<ToolbarFilterPopover
activeCount={routineFilter === "all" ? 0 : 1}
onClear={clearRoutineFilter}
label="Filter responsibilities"
contentLabel="Filter responsibilities"
align="start"
contentClassName="w-56"
triggerDataAttr="data-outline-v2-filter"
>
<div className="task-filters-grid">
<FilterGroup title="Routines" optionsKey="routines">
<FilterRow
label="Has routines"
checked={routineFilter === "has_routines"}
onToggle={() => setRoutineFilter((current) => (current === "has_routines" ? "all" : "has_routines"))}
/>
<FilterRow
label="No routines"
checked={routineFilter === "no_routines"}
onToggle={() => setRoutineFilter((current) => (current === "no_routines" ? "all" : "no_routines"))}
/>
</FilterGroup>
</div>
</ToolbarFilterPopover>
</div>
<p className="text-sm text-muted-foreground" data-dashboard-counts="">{outlineV2CountsLabel(outlineCounts)}</p>
</div>
) : null
@@ -251,7 +295,17 @@ function OwnerDashboard({ selectedCompanyId, ownerUserId }: { selectedCompanyId:
if (view === "full") return <ResponsibilitiesHomeLayout {...layoutProps} />;
const viewProps = { ...layoutProps, onAddArea: () => setAddingArea(true), onReviewProposals: () => visit("full") };
if (view === "outline") return <DashboardOutline {...viewProps} />;
if (view === "outline_v2") return <DashboardOutlineV2 {...viewProps} search={search} />;
if (view === "outline_v2") {
return (
<DashboardOutlineV2
{...viewProps}
search={search}
routineFilter={routineFilter}
visibleGroups={visibleOutlineGroups ?? undefined}
onClearFilter={clearRoutineFilter}
/>
);
}
if (view === "board") return <DashboardBoard {...viewProps} />;
if (view === "automation") return <DashboardAutomation {...viewProps} />;
if (view === "agent_status") return <DashboardAgentStatus {...viewProps} />;
@@ -101,6 +101,7 @@ export function responsibilityRollup(overrides: Partial<ResponsibilityRollup> =
workSummary: [],
projects: 0,
routines: 0,
routineAgentIds: [],
openTasks: 0,
blockedTasks: 0,
agentTasks: 0,
@@ -176,6 +177,7 @@ export const fundraisingBehind = responsibilityFixture({
],
projects: 2,
routines: 1,
routineAgentIds: ["agent-codex"],
openTasks: 4,
blockedTasks: 1,
agentTasks: 2,
@@ -249,6 +251,7 @@ export const portfolioOnTrack = responsibilityFixture({
],
projects: 1,
routines: 1,
routineAgentIds: [RESPONSIBILITY_FIXTURE_GUIDE_AGENT_ID],
openTasks: 3,
agentTasks: 3,
doneTasks: 12,
@@ -24,6 +24,7 @@ import {
standingCheckAutomationFixture,
homeOverviewFixture,
looseWorkFixture,
lpUpdatesStale,
nothingMeasuredOverviewFixture,
OUTLINE_DENSE_AREA_IDS,
outlineDenseOverviewFixture,
@@ -41,7 +42,7 @@ import {
import { METRIC_SET_FIXTURES, statusReportFixture } from "../../fixtures/responsibility-metrics";
import { prepareFixtureApi, type FixtureState } from "../../support/capability-gaps/api";
type Variant = "home" | "proposals" | "empty" | "allOnTrack" | "nothingMeasured" | "dense" | "outlineDense" | "outlineNoAreas";
type Variant = "home" | "proposals" | "empty" | "allOnTrack" | "nothingMeasured" | "dense" | "outlineDense" | "outlineNoAreas" | "outlineRoutineAvatars";
const OVERVIEWS: Record<Variant, ResponsibilityOverview> = {
home: homeOverviewFixture,
@@ -56,6 +57,29 @@ const OVERVIEWS: Record<Variant, ResponsibilityOverview> = {
dense: denseBoardOverviewFixture,
outlineDense: outlineDenseOverviewFixture,
outlineNoAreas: outlineNoAreasOverviewFixture,
outlineRoutineAvatars: responsibilityOverviewFixture(
[
{ ...fundraisingBehind, rollup: { ...fundraisingBehind.rollup, routines: 3, routineAgentIds: ["agent-codex", "agent-qa", "agent-cto"] } },
lpUpdatesStale,
{ ...portfolioOnTrack, rollup: { ...portfolioOnTrack.rollup, routines: 2, routineAgentIds: ["agent-cto", "agent-qa"] } },
responsibilityFixture({
id: "resp-single-routine",
areaId: portfolioOnTrack.areaId,
title: "Security reviews",
standard: "Every dependency vulnerability is triaged within 24 hours.",
rollup: { routines: 1, routineAgentIds: ["agent-codex"] },
}),
responsibilityFixture({
id: "resp-no-routine-team",
areaId: "area-team",
title: "Hiring",
standard: "Two senior engineers have accepted offers by the end of the quarter.",
rollup: { routines: 0, routineAgentIds: [] },
}),
],
[],
{ loose: EMPTY_LOOSE_WORK },
),
};
/** Opens a page in one of its views, as if the person had chosen it; restores the previous choice after. */
@@ -729,12 +753,34 @@ export const DashboardOutlineV2: Story = {
const fundraising = await canvas.findByRole("button", { name: "Fundraising", expanded: true });
await expect(canvas.getByRole("link", { name: fundraisingBehind.standard! })).toBeInTheDocument();
await expect(canvas.queryByText(/Behind|At risk|On track|Not measured/)).not.toBeInTheDocument();
await expect(canvasElement.querySelector('[data-responsibility-id="resp-fundraising"] [data-routine-agents="agent-codex"]')).toBeInTheDocument();
await expect(canvasElement.querySelector('[data-responsibility-id="resp-lp-updates"] [data-routine-agents]')).toBeNull();
await userEvent.click(fundraising);
await expect(canvas.getByRole("button", { name: "Fundraising", expanded: false })).toBeInTheDocument();
await userEvent.click(canvas.getByRole("button", { name: "Fundraising", expanded: false }));
const filterButton = canvas.getByRole("button", { name: "Filter responsibilities" });
await userEvent.click(filterButton);
const body = within(canvasElement.ownerDocument.body);
await userEvent.click(await body.findByRole("checkbox", { name: "Has routines" }));
await expect(canvas.getByRole("link", { name: fundraisingBehind.standard! })).toBeInTheDocument();
await expect(canvas.queryByRole("link", { name: lpUpdatesStale.standard! })).not.toBeInTheDocument();
await userEvent.click(body.getByRole("checkbox", { name: "No routines" }));
await expect(canvas.getByRole("link", { name: lpUpdatesStale.standard! })).toBeInTheDocument();
await expect(canvas.queryByRole("link", { name: fundraisingBehind.standard! })).not.toBeInTheDocument();
await userEvent.click(body.getByRole("button", { name: "Clear" }));
await expect(canvas.getByRole("link", { name: fundraisingBehind.standard! })).toBeInTheDocument();
await expect(canvas.getByRole("link", { name: lpUpdatesStale.standard! })).toBeInTheDocument();
},
};
/** Dashboard, Outline v2: rows with 1, 2, and 3 slightly overlapping routine-agent avatars alongside rows with no routines. */
export const DashboardOutlineV2RoutineAvatars: Story = {
name: "Dashboard view: Outline v2, routine avatars & filter",
parameters: { variant: "outlineRoutineAvatars" satisfies Variant },
beforeEach: chooseOutlineV2(),
};
/** Dashboard, Outline v2, dense: 46 responsibilities in 22 areas, long sentences wrapping, titles where there is no sentence. */
export const DashboardOutlineV2Dense: Story = {
name: "Dashboard view: Outline v2, dense",