From c57471459f81dd5c6ccd45b7ff9eab3beed3553c Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:53:18 +0000 Subject: [PATCH] feat(responsibilities): add routine filter and routine agent avatars (#23159) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 `//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 --- packages/shared/src/types/responsibility.ts | 2 + .../__tests__/responsibilities-rollup.test.ts | 16 ++ server/src/__tests__/responsibilities.test.ts | 45 ++++ .../responsibility-summaries.test.ts | 2 + .../responsibility-summary-generator.test.ts | 2 +- .../__tests__/responsibility-tools.test.ts | 2 +- server/src/services/responsibilities.ts | 18 +- .../runner-e2e/source-sdk-public-inputs.json | 2 +- ui/src/components/CollectionFilterOptions.tsx | 67 ++++- .../DashboardOutlineV2.test.tsx | 233 ++++++++++++++++++ .../responsibilities/DashboardOutlineV2.tsx | 122 +++++++-- ui/src/lib/responsibility-outline-v2.test.ts | 75 ++++++ ui/src/lib/responsibility-outline-v2.ts | 34 +++ .../Responsibilities.outline-v2.test.tsx | 149 +++++++++++ ui/src/pages/Responsibilities.tsx | 84 +++++-- ui/storybook/fixtures/responsibilities.ts | 3 + .../activity/responsibilities.stories.tsx | 48 +++- 17 files changed, 864 insertions(+), 40 deletions(-) create mode 100644 ui/src/components/responsibilities/DashboardOutlineV2.test.tsx create mode 100644 ui/src/pages/Responsibilities.outline-v2.test.tsx diff --git a/packages/shared/src/types/responsibility.ts b/packages/shared/src/types/responsibility.ts index ca7eb329f98..a2b1dc01cef 100644 --- a/packages/shared/src/types/responsibility.ts +++ b/packages/shared/src/types/responsibility.ts @@ -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. */ diff --git a/server/src/__tests__/responsibilities-rollup.test.ts b/server/src/__tests__/responsibilities-rollup.test.ts index df98b6d8e28..258b6b72cae 100644 --- a/server/src/__tests__/responsibilities-rollup.test.ts +++ b/server/src/__tests__/responsibilities-rollup.test.ts @@ -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([]); diff --git a/server/src/__tests__/responsibilities.test.ts b/server/src/__tests__/responsibilities.test.ts index 65955c6e660..da99d7ed32c 100644 --- a/server/src/__tests__/responsibilities.test.ts +++ b/server/src/__tests__/responsibilities.test.ts @@ -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: [], + }); + }); }); }); diff --git a/server/src/__tests__/responsibility-summaries.test.ts b/server/src/__tests__/responsibility-summaries.test.ts index fbacae1941f..ddc41612fe2 100644 --- a/server/src/__tests__/responsibility-summaries.test.ts +++ b/server/src/__tests__/responsibility-summaries.test.ts @@ -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, diff --git a/server/src/__tests__/responsibility-summary-generator.test.ts b/server/src/__tests__/responsibility-summary-generator.test.ts index 452789998f2..6d7383e2e5b 100644 --- a/server/src/__tests__/responsibility-summary-generator.test.ts +++ b/server/src/__tests__/responsibility-summary-generator.test.ts @@ -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: [], diff --git a/server/src/__tests__/responsibility-tools.test.ts b/server/src/__tests__/responsibility-tools.test.ts index 5a5ac7515ab..6c3b5f51b31 100644 --- a/server/src/__tests__/responsibility-tools.test.ts +++ b/server/src/__tests__/responsibility-tools.test.ts @@ -11,7 +11,7 @@ function rollup(overrides: Record = {}) { 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, }; } diff --git a/server/src/services/responsibilities.ts b/server/src/services/responsibilities.ts index e5ee8964f00..7619e6b3b85 100644 --- a/server/src/services/responsibilities.ts +++ b/server/src/services/responsibilities.ts @@ -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(); + 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 'archived'`), + .where(sql`${routines.status} <> 'archived'`) + .orderBy(asc(routines.title), asc(routines.id)), ]); const counts = new Map(); @@ -819,6 +832,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType void; + label?: string; + contentLabel?: string; + align?: "start" | "center" | "end"; + contentClassName?: string; + triggerDataAttr?: string; + children: ReactNode; +}) { + const active = activeCount > 0; + return ( + + + + + + + + Filters + {active && onClear ? ( + + ) : null} + + {children} + + + + ); +} + 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 ( diff --git a/ui/src/components/responsibilities/DashboardOutlineV2.test.tsx b/ui/src/components/responsibilities/DashboardOutlineV2.test.tsx new file mode 100644 index 00000000000..163d7752e9f --- /dev/null +++ b/ui/src/components/responsibilities/DashboardOutlineV2.test.tsx @@ -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).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[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( + + + , + ); + }); + } + + 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); + }); +}); diff --git a/ui/src/components/responsibilities/DashboardOutlineV2.tsx b/ui/src/components/responsibilities/DashboardOutlineV2.tsx index 6237c34e247..e73b1af3508 100644 --- a/ui/src/components/responsibilities/DashboardOutlineV2.tsx +++ b/ui/src/components/responsibilities/DashboardOutlineV2.tsx @@ -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, (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; + names: readonly string[]; +}) { + if (agentIds.length === 0) return null; + const shown = agentIds.slice(0, MAX_ROUTINE_AVATARS); + const extra = agentIds.length - shown.length; return ( -
  • + + + {extra > 0 ? : null} + + ); +} + +/** 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; +}) { + const routineAgentIds = responsibility.rollup.routines > 0 ? responsibility.rollup.routineAgentIds : []; + const routineAgentNames = routineAgentIds.map((id) => agentsById.get(id)?.name ?? "An agent"); + return ( +
  • 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)} +
  • ); } @@ -55,11 +104,13 @@ function OutlineV2Row({ responsibility }: { responsibility: ResponsibilityWithRo */ function OutlineV2Area({ group, + agentsById, expanded, onToggle, onAdd, }: { group: OutlineV2Group; + agentsById: ReadonlyMap; expanded: boolean; onToggle: () => void; onAdd: () => void; @@ -103,7 +154,7 @@ function OutlineV2Area({ {group.items.length > 0 ? (
      {group.items.map((item) => ( - + ))}
    ) : 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) => ( 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 (
    0 ? ( shown.map(renderArea) ) : query ? ( -

    - Nothing matches “{query}”. -

    +
    + + {routineFilter === "all" + ? `Nothing matches “${query}”.` + : `Nothing matches “${query}” with this filter.`} + + {routineFilter !== "all" && onClearFilter ? ( + + ) : null} +
    + ) : routineFilter !== "all" ? ( +
    + + {routineFilter === "has_routines" + ? "None of your responsibilities have routines yet." + : "Every responsibility has at least one routine."} + + {onClearFilter ? ( + + ) : null} +
    ) : (

    No areas yet.

    )} diff --git a/ui/src/lib/responsibility-outline-v2.test.ts b/ui/src/lib/responsibility-outline-v2.test.ts index fd89b83699d..95d22372d63 100644 --- a/ui/src/lib/responsibility-outline-v2.test.ts +++ b/ui/src/lib/responsibility-outline-v2.test.ts @@ -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) => + 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"); diff --git a/ui/src/lib/responsibility-outline-v2.ts b/ui/src/lib/responsibility-outline-v2.ts index 8eea890dc95..f871449d133 100644 --- a/ui/src/lib/responsibility-outline-v2.ts +++ b/ui/src/lib/responsibility-outline-v2.ts @@ -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}`; diff --git a/ui/src/pages/Responsibilities.outline-v2.test.tsx b/ui/src/pages/Responsibilities.outline-v2.test.tsx new file mode 100644 index 00000000000..476b4dec310 --- /dev/null +++ b/ui/src/pages/Responsibilities.outline-v2.test.tsx @@ -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).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( + + + + + , + ); + }); + 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("[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('button[role="checkbox"][aria-label="Has routines"]'); + const noRoutines = document.body.querySelector('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(); + }); +}); diff --git a/ui/src/pages/Responsibilities.tsx b/ui/src/pages/Responsibilities.tsx index 87d861af722..2a1e47bf4e0 100644 --- a/ui/src/pages/Responsibilities.tsx +++ b/ui/src/pages/Responsibilities.tsx @@ -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("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 ? (
    - +
    + + +
    + + setRoutineFilter((current) => (current === "has_routines" ? "all" : "has_routines"))} + /> + setRoutineFilter((current) => (current === "no_routines" ? "all" : "no_routines"))} + /> + +
    +
    +

    {outlineV2CountsLabel(outlineCounts)}

    ) : null @@ -251,7 +295,17 @@ function OwnerDashboard({ selectedCompanyId, ownerUserId }: { selectedCompanyId: if (view === "full") return ; const viewProps = { ...layoutProps, onAddArea: () => setAddingArea(true), onReviewProposals: () => visit("full") }; if (view === "outline") return ; - if (view === "outline_v2") return ; + if (view === "outline_v2") { + return ( + + ); + } if (view === "board") return ; if (view === "automation") return ; if (view === "agent_status") return ; diff --git a/ui/storybook/fixtures/responsibilities.ts b/ui/storybook/fixtures/responsibilities.ts index 7196cee5061..5c986a4bf49 100644 --- a/ui/storybook/fixtures/responsibilities.ts +++ b/ui/storybook/fixtures/responsibilities.ts @@ -101,6 +101,7 @@ export function responsibilityRollup(overrides: Partial = 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, diff --git a/ui/storybook/stories/activity/responsibilities.stories.tsx b/ui/storybook/stories/activity/responsibilities.stories.tsx index 4744e821048..4769e73f603 100644 --- a/ui/storybook/stories/activity/responsibilities.stories.tsx +++ b/ui/storybook/stories/activity/responsibilities.stories.tsx @@ -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 = { home: homeOverviewFixture, @@ -56,6 +57,29 @@ const OVERVIEWS: Record = { 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",