fix(dashboard): scope areas and responsibilities to each user (#22513)

This commit is contained in:
scotttong authored and GitHub committed 2026-11-21 13:59:00 -08:00
1 parent 558dbb0132
commit 856f14e507
68 files changed
+2708 -559

No files matched your search

+1 -2
View File
@@ -100,8 +100,7 @@ export const responsibilitiesApi = {
};
/**
* Areas: broad things a company cares about, with no owner. Any board user
* manages them. Creating one whose title already exists returns that area.
* Areas on the acting person's dashboard. A repeated title returns their existing area.
*/
export const responsibilityAreasApi = {
list: (companyId: string, options?: { includeArchived?: boolean }) =>
@@ -21,17 +21,19 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { useResolvedViewerId } from "@/hooks/useResolvedViewerId";
import { Input } from "@/components/ui/input";
import { queryKeys } from "@/lib/queryKeys";
type AreaRef = Pick<ResponsibilityArea, "id" | "title" | "status">;
/** The company's areas that can take a responsibility (active and proposed). */
/** The viewer's areas that can take a responsibility (active and proposed). */
export function useResponsibilityAreas(companyId: string | null | undefined, enabled = true) {
const { userId } = useResolvedViewerId({ enabled });
return useQuery({
queryKey: queryKeys.responsibilities.areas(companyId ?? "__none__"),
queryKey: [...queryKeys.responsibilities.areas(companyId ?? "__none__"), userId],
queryFn: () => responsibilityAreasApi.list(companyId!),
enabled: enabled && !!companyId,
enabled: enabled && !!companyId && !!userId,
});
}
@@ -458,7 +458,7 @@ function AgentStatusBody({
mutationFn: (row: AgentStatusRow) => responsibilitiesApi.requestStatusUpdate(row.responsibility.id),
onSuccess: async (_state, row) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: queryKeys.responsibilities.statusReports(companyId) }),
queryClient.invalidateQueries({ queryKey: ["responsibilities", "status-reports", companyId] }),
queryClient.invalidateQueries({ queryKey: queryKeys.responsibilities.statusReport(row.responsibility.id) }),
]);
},
@@ -577,7 +577,7 @@ export function DashboardAgentStatus(props: DashboardViewProps) {
const active = useMemo(() => activeResponsibilities(overview.responsibilities), [overview.responsibilities]);
const { data: session } = useQuery({ queryKey: queryKeys.auth.session, queryFn: () => authApi.getSession() });
const query = useQuery({
queryKey: queryKeys.responsibilities.statusReports(companyId),
queryKey: queryKeys.responsibilities.statusReports(companyId, props.overview.ownerUserId),
queryFn: () => responsibilitiesApi.statusReports(companyId),
enabled: active.length > 0,
});
@@ -671,7 +671,7 @@ function AutomationSkeleton() {
export function DashboardAutomation({ companyId, overview, agents, agentsById, now, onAddResponsibility, onReviewProposals }: DashboardViewProps) {
const active = useMemo(() => activeResponsibilities(overview.responsibilities), [overview.responsibilities]);
const query = useQuery({
queryKey: queryKeys.responsibilities.automation(companyId),
queryKey: queryKeys.responsibilities.automation(companyId, overview.ownerUserId),
queryFn: () => responsibilitiesApi.automation(companyId),
enabled: active.length > 0,
});
@@ -20,17 +20,17 @@ import { ProposalsNotice } from "./ResponsibilityViewParts";
import type { DashboardViewProps } from "./view-props";
/** Which areas are folded, remembered in the browser; works without storage. */
function useCollapsedAreas(): [ReadonlySet<string>, (key: string) => void] {
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => readCollapsedAreas());
function useCollapsedAreas(scope: string): [ReadonlySet<string>, (key: string) => void] {
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => readCollapsedAreas(scope));
const toggle = useCallback((key: string) => {
setCollapsed((current) => {
const next = new Set(current);
if (next.has(key)) next.delete(key);
else next.add(key);
writeCollapsedAreas(next);
writeCollapsedAreas(next, scope);
return next;
});
}, []);
}, [scope]);
return [collapsed, toggle];
}
@@ -146,7 +146,7 @@ export function DashboardOutlineV2({
() => outlineV2Groups(overview.areas, overview.responsibilities, keepEmptyAreas),
[overview.areas, overview.responsibilities, keepEmptyAreas],
);
const [collapsed, toggle] = useCollapsedAreas();
const [collapsed, toggle] = useCollapsedAreas(JSON.stringify([companyId, overview.ownerUserId]));
const query = search.trim();
const shown = useMemo(() => searchOutlineV2Groups(groups, query), [groups, query]);
@@ -161,7 +161,7 @@ export function DashboardOutlineV2({
);
// Nothing owned and nothing proposed: only the module, and any area just added by hand.
if (active.length === 0 && overview.proposed.length === 0) {
if (groups.length === 0 && active.length === 0 && overview.proposed.length === 0) {
return (
<div className="flex flex-col gap-4" data-dashboard-view="outline_v2" data-dashboard-empty="">
<DashboardEditModule
@@ -171,7 +171,6 @@ export function DashboardOutlineV2({
agentsById={agentsById}
onAddArea={onAddArea}
/>
{groups.filter((group) => keepEmptyAreas.has(group.key)).map(renderArea)}
</div>
);
}
@@ -61,7 +61,7 @@ function useUpdateResponsibility(id: string) {
return useMutation({
mutationFn: (patch: UpdateResponsibility) => responsibilitiesApi.update(id, patch),
onSuccess: (updated) => {
queryClient.setQueryData<ResponsibilityDetail>(queryKeys.responsibilities.detail(id), (old) =>
queryClient.setQueriesData<ResponsibilityDetail>({ queryKey: queryKeys.responsibilities.detail(id) }, (old) =>
old ? { ...old, ...updated } : old);
void queryClient.invalidateQueries({ queryKey: queryKeys.responsibilities.all });
},
@@ -4,6 +4,7 @@ import type { ResponsibilitySummary as Narrative } from "@paperclipai/shared";
import { responsibilitiesApi } from "@/api/responsibilities";
import { queryKeys } from "@/lib/queryKeys";
import { summaryAttribution, summaryRefetchDelay } from "@/lib/responsibility-summary";
import { useResolvedViewerId } from "@/hooks/useResolvedViewerId";
import { cn } from "@/lib/utils";
/**
@@ -28,10 +29,11 @@ function useNarrative(queryKey: readonly unknown[], queryFn: () => Promise<Narra
/** The Dashboard's paragraph of where everything stands. */
export function useDashboardNarrative(companyId: string | null | undefined) {
const { userId } = useResolvedViewerId();
return useNarrative(
queryKeys.responsibilities.summary(companyId ?? "__none__"),
queryKeys.responsibilities.summary(companyId ?? "__none__", userId),
() => responsibilitiesApi.companySummary(companyId!),
!!companyId,
!!companyId && !!userId,
);
}
@@ -7,6 +7,7 @@ import { responsibilitiesApi } from "@/api/responsibilities";
import { secretsApi } from "@/api/secrets";
import type { MentionOption } from "@/components/MarkdownEditor";
import { useQueryView } from "@/components/QueryView";
import { useResolvedViewerId } from "@/hooks/useResolvedViewerId";
import { useResponsibilitiesEnabled } from "@/hooks/useResponsibilitiesEnabled";
import { companyProjectsQuery } from "@/lib/company-projects-query";
import { buildCompanyUserProfileMap, buildMarkdownMentionOptions } from "@/lib/company-members";
@@ -34,6 +35,7 @@ export function useRoutineFormOptions(
const enabled = Boolean(companyId) && active;
const { enabled: responsibilitiesOn } = useResponsibilitiesEnabled();
const { userId } = useResolvedViewerId({ enabled: enabled && responsibilitiesOn });
const agentsQuery = useQuery({
queryKey: queryKeys.agents.list(companyId ?? ""),
queryFn: () => agentsApi.list(companyId!),
@@ -51,9 +53,9 @@ export function useRoutineFormOptions(
enabled,
});
const responsibilitiesQuery = useQuery({
queryKey: queryKeys.responsibilities.overview(companyId ?? ""),
queryKey: queryKeys.responsibilities.overview(companyId ?? "", { ownerUserId: userId }),
queryFn: () => responsibilitiesApi.overview(companyId!),
enabled: enabled && responsibilitiesOn,
enabled: enabled && responsibilitiesOn && !!userId,
});
// Failed reads are reported, never shown as empty choices.
+1 -1
View File
@@ -591,7 +591,7 @@ export const queryKeys = {
/** The responsibilities one routine is under, directly or through its project. */
routineLinks: (companyId: string, routineId: string) =>
["responsibilities", "links", companyId, "routine", routineId] as const,
/** The company's areas (active and proposed). */
/** The viewer's active and proposed areas. */
areas: (companyId: string) => ["responsibilities", "areas", companyId] as const,
/** Recent activity on one responsibility, for who last reported its reading. */
activity: (id: string) => ["responsibilities", "activity", id] as const,
+8 -8
View File
@@ -126,12 +126,12 @@ describe("searchOutlineV2Groups", () => {
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]));
expect([...readCollapsedAreas()]).toEqual(["area-a", OUTLINE_V2_NO_AREA_KEY]);
localStorage.setItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY, "{not json");
expect(readCollapsedAreas().size).toBe(0);
localStorage.setItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY, JSON.stringify({ a: 1 }));
expect(readCollapsedAreas().size).toBe(0);
writeCollapsedAreas(new Set(["area-a", OUTLINE_V2_NO_AREA_KEY]), "owner");
expect([...readCollapsedAreas("owner")]).toEqual(["area-a", OUTLINE_V2_NO_AREA_KEY]);
localStorage.setItem(`${OUTLINE_V2_COLLAPSED_STORAGE_KEY}:owner`, "{not json");
expect(readCollapsedAreas("owner").size).toBe(0);
localStorage.setItem(`${OUTLINE_V2_COLLAPSED_STORAGE_KEY}:owner`, JSON.stringify({ a: 1 }));
expect(readCollapsedAreas("owner").size).toBe(0);
});
it("never throws when storage is blocked", () => {
@@ -141,7 +141,7 @@ describe("collapsed areas in storage", () => {
vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
throw new Error("blocked");
});
expect(readCollapsedAreas().size).toBe(0);
expect(() => writeCollapsedAreas(new Set(["area-a"]))).not.toThrow();
expect(readCollapsedAreas("owner").size).toBe(0);
expect(() => writeCollapsedAreas(new Set(["area-a"]), "owner")).not.toThrow();
});
});
+4 -4
View File
@@ -105,9 +105,9 @@ export function outlineV2Href(responsibilityId: string): string {
}
/** The collapsed groups' keys as stored; empty when nothing is stored or storage is unavailable. Never throws. */
export function readCollapsedAreas(): Set<string> {
export function readCollapsedAreas(scope: string): Set<string> {
try {
const stored = globalThis.localStorage?.getItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY);
const stored = globalThis.localStorage?.getItem(`${OUTLINE_V2_COLLAPSED_STORAGE_KEY}:${scope}`);
const parsed: unknown = stored ? JSON.parse(stored) : [];
return new Set(Array.isArray(parsed) ? parsed.filter((key): key is string => typeof key === "string") : []);
} catch {
@@ -116,9 +116,9 @@ export function readCollapsedAreas(): Set<string> {
}
/** Remembers the collapsed groups when storage is available; silently does nothing otherwise. */
export function writeCollapsedAreas(keys: ReadonlySet<string>): void {
export function writeCollapsedAreas(keys: ReadonlySet<string>, scope: string): void {
try {
globalThis.localStorage?.setItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY, JSON.stringify([...keys]));
globalThis.localStorage?.setItem(`${OUTLINE_V2_COLLAPSED_STORAGE_KEY}:${scope}`, JSON.stringify([...keys]));
} catch {
// Private windows and blocked storage: the choice lasts for this visit only.
}
+4 -1
View File
@@ -27,10 +27,12 @@ const routinesApi = vi.hoisted(() => ({ update: vi.fn() }));
const projectsApi = vi.hoisted(() => ({ update: vi.fn() }));
const areasApi = vi.hoisted(() => ({ list: vi.fn(), create: vi.fn(), update: vi.fn() }));
const agentsApi = vi.hoisted(() => ({ list: vi.fn() }));
const authApi = vi.hoisted(() => ({ getSession: vi.fn() }));
const autoOpen = vi.hoisted(() => vi.fn());
const breadcrumbs = vi.hoisted(() => vi.fn());
vi.mock("@/api/responsibilities", () => ({ responsibilitiesApi: api, responsibilityAreasApi: areasApi }));
vi.mock("@/api/agents", () => ({ agentsApi }));
vi.mock("@/api/auth", () => ({ authApi }));
vi.mock("@/api/issues", () => ({ issuesApi }));
vi.mock("@/api/routines", () => ({ routinesApi }));
vi.mock("@/api/projects", () => ({ projectsApi }));
@@ -87,6 +89,7 @@ beforeEach(() => {
// These tests cover the full layout, which the Dashboard shows only when the address names it.
location.search = "?view=full";
agentsApi.list.mockResolvedValue([guide, codex]);
authApi.getSession.mockResolvedValue({ user: { id: "user-storybook" } });
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
@@ -301,7 +304,7 @@ describe("Responsibilities home", () => {
expect(text()).not.toContain("Old fund");
await act(async () => buttonByText("Show let-go responsibilities")!.click());
await flush();
expect(api.overview).toHaveBeenLastCalledWith("company-storybook", { includeLetGo: true });
expect(api.overview).toHaveBeenLastCalledWith("company-storybook", { includeLetGo: true, ownerUserId: "user-storybook" });
expect(text()).toContain("Old fund");
});
});
+12 -5
View File
@@ -1,5 +1,6 @@
import { useResolvedViewerId } from "@/hooks/useResolvedViewerId";
import { useCallback, useEffect, useMemo, useState } from "react";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { useQuery } from "@tanstack/react-query";
import type { ResponsibilityArea, ResponsibilityWithRollup } from "@paperclipai/shared";
import { Plus } from "lucide-react";
import { describeError } from "@/api/errors";
@@ -82,6 +83,13 @@ function ProvenanceLine({
*/
export function Responsibilities() {
const { selectedCompanyId } = useCompany();
const viewer = useResolvedViewerId();
if (viewer.error) return <QueryErrorState error={viewer.error} action="load your dashboard" onRetry={() => { void viewer.retry(); }} />;
if (!selectedCompanyId || !viewer.userId) return <PageSkeleton variant="dashboard" />;
return <OwnerDashboard key={JSON.stringify([selectedCompanyId, viewer.userId])} selectedCompanyId={selectedCompanyId} ownerUserId={viewer.userId} />;
}
function OwnerDashboard({ selectedCompanyId, ownerUserId }: { selectedCompanyId: string; ownerUserId: string }) {
const { setBreadcrumbs } = useBreadcrumbs();
const [includeLetGo, setIncludeLetGo] = useState(false);
const [adding, setAdding] = useState<{ areaId: string | null } | null>(null);
@@ -107,10 +115,9 @@ export function Responsibilities() {
}, [setBreadcrumbs]);
const overviewQuery = useQuery({
queryKey: queryKeys.responsibilities.overview(selectedCompanyId ?? "__none__", { includeLetGo }),
queryFn: () => responsibilitiesApi.overview(selectedCompanyId!, { includeLetGo }),
queryKey: queryKeys.responsibilities.overview(selectedCompanyId ?? "__none__", { includeLetGo, ownerUserId }),
queryFn: () => responsibilitiesApi.overview(selectedCompanyId!, { includeLetGo, ownerUserId }),
enabled: !!selectedCompanyId,
placeholderData: keepPreviousData,
});
const overview = overviewQuery.data;
const areasForNew = useMemo(
@@ -128,7 +135,7 @@ export function Responsibilities() {
if (!overview) return null;
const counts = outlineV2Counts(outlineV2Groups(overview.areas, overview.responsibilities, keepEmptyAreas));
// The same rule as the view's empty state, which shows only the create module.
return counts.responsibilities > 0 || overview.proposed.length > 0 ? counts : null;
return counts.areas > 0 || counts.responsibilities > 0 || overview.proposed.length > 0 ? counts : null;
}, [overview, keepEmptyAreas]);
const openAdd = useCallback((areaId: string | null) => setAdding({ areaId }), []);
+6 -4
View File
@@ -757,7 +757,7 @@ describe("Dashboard views", () => {
expect(bar("area-fundraising").getAttribute("aria-expanded")).toBe("false");
// Nothing to search or count on an empty dashboard.
api.overview.mockResolvedValue(responsibilityOverviewFixture([], []));
api.overview.mockResolvedValue(responsibilityOverviewFixture([], [], { areas: [] }));
await remount();
await flush();
expect(host.querySelector("header [data-toolbar-search]")).toBeNull();
@@ -794,7 +794,7 @@ describe("Dashboard views", () => {
});
it("on an empty dashboard shows only the create module, naming the agent, with adding an area by hand kept quiet", async () => {
api.overview.mockResolvedValue(responsibilityOverviewFixture([], []));
api.overview.mockResolvedValue(responsibilityOverviewFixture([], [], { areas: [] }));
await openOutlineV2();
const root = outlineV2();
expect(root.querySelector("[data-outline-v2-area]")).toBeNull();
@@ -847,7 +847,9 @@ describe("Dashboard views", () => {
await act(async () => toggle.click());
expect(toggle.getAttribute("aria-expanded")).toBe("false");
expect(list.hidden).toBe(true);
expect(JSON.parse(localStorage.getItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY)!)).toEqual(["area-fundraising"]);
const scope = JSON.stringify(["company-storybook", homeOverviewFixture.ownerUserId]);
const storageKey = `${OUTLINE_V2_COLLAPSED_STORAGE_KEY}:${scope}`;
expect(JSON.parse(localStorage.getItem(storageKey)!)).toEqual(["area-fundraising"]);
// A native button: Enter and Space press it, and it takes focus in tab order.
toggle.focus();
@@ -860,7 +862,7 @@ describe("Dashboard views", () => {
expect(bar("area-portfolio").getAttribute("aria-expanded")).toBe("true");
await act(async () => bar("area-fundraising").click());
expect(bar("area-fundraising").getAttribute("aria-expanded")).toBe("true");
expect(JSON.parse(localStorage.getItem(OUTLINE_V2_COLLAPSED_STORAGE_KEY)!)).toEqual([]);
expect(JSON.parse(localStorage.getItem(storageKey)!)).toEqual([]);
});
it("folds without storage", async () => {
@@ -7,6 +7,7 @@ import { ApiError } from "@/api/client";
import { describeLinkError } from "@/components/responsibilities/AddExistingWorkPicker";
import { artifactsTruncationNote } from "@/components/responsibilities/ResponsibilitySkillsAndArtifacts";
import { TooltipProvider } from "@/components/ui/tooltip";
import { queryKeys } from "@/lib/queryKeys";
import {
areaFundraising,
areaPortfolio,
@@ -124,6 +125,7 @@ beforeEach(() => {
document.body.append(host);
root = createRoot(host);
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
client.setQueryData(queryKeys.auth.session, { user: { id: "user-storybook" } });
});
afterEach(async () => {
+5 -3
View File
@@ -34,6 +34,7 @@ import {
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { useResolvedViewerId } from "@/hooks/useResolvedViewerId";
import { useCompany } from "@/context/CompanyContext";
import { Link, useNavigate, useParams } from "@/lib/router";
import { queryKeys } from "@/lib/queryKeys";
@@ -58,7 +59,7 @@ function useResponsibilityPage(responsibility: ResponsibilityDetailData, company
const [removed, setRemoved] = useState<{ label: string; relink: LinkResponsibility } | null>(null);
const directory = useAgentDirectory(companyId);
const areasQuery = useResponsibilityAreas(companyId);
const detailKey = queryKeys.responsibilities.detail(responsibility.id);
const detailKey = [...queryKeys.responsibilities.detail(responsibility.id), companyId, responsibility.ownerUserId];
const refreshAll = () => queryClient.invalidateQueries({ queryKey: queryKeys.responsibilities.all });
const update = useMutation({
@@ -247,10 +248,11 @@ export function ResponsibilityDetail() {
const { responsibilityId } = useParams<{ responsibilityId: string }>();
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const { userId } = useResolvedViewerId();
const detailQuery = useQuery({
queryKey: queryKeys.responsibilities.detail(responsibilityId ?? "__none__"),
queryKey: [...queryKeys.responsibilities.detail(responsibilityId ?? "__none__"), selectedCompanyId, userId],
queryFn: () => responsibilitiesApi.get(responsibilityId!),
enabled: !!responsibilityId,
enabled: !!responsibilityId && !!selectedCompanyId && !!userId,
});
const title = detailQuery.data?.title;
+3
View File
@@ -48,6 +48,9 @@ vi.mock("../api/routines", () => ({
},
}));
vi.mock("../api/issues", () => ({ issuesApi: { list: vi.fn() } }));
vi.mock("../api/auth", () => ({
authApi: { getSession: vi.fn(async () => ({ user: { id: "user-1" } })) },
}));
vi.mock("../api/agents", () => ({
agentsApi: { list: vi.fn(async () => [{ id: "agent-1", name: "Digest Bot", status: "active", role: "engineer", title: null }]) },
}));
+6 -4
View File
@@ -46,6 +46,7 @@ import { useToastActions } from "@/context/ToastContext";
import { useStreamlinedUiEnabled } from "@/hooks/useStreamlinedUiEnabled";
import { configurationWarningMessages } from "@/lib/configuration-warnings";
import { createIssueDetailLocationState } from "@/lib/issueDetailBreadcrumb";
import { useResolvedViewerId } from "@/hooks/useResolvedViewerId";
import { queryKeys } from "@/lib/queryKeys";
import { Navigate, useLocation, useNavigate, useParams, useSearchParams } from "@/lib/router";
@@ -141,10 +142,11 @@ function RoutineDetailPage({ companyId, routineId, view }: { companyId: string;
[historyQuery.data],
);
const { userId } = useResolvedViewerId({ enabled: options.responsibilitiesOn });
const linksQuery = useQuery({
queryKey: queryKeys.responsibilities.routineLinks(companyId, routineId),
queryKey: [...queryKeys.responsibilities.routineLinks(companyId, routineId), userId],
queryFn: () => responsibilitiesApi.lookupRoutineLinks(companyId, routineId),
enabled: options.responsibilitiesOn,
enabled: options.responsibilitiesOn && !!userId,
});
const linkEntries = linksQuery.data?.responsibilities;
const linksView = useQueryView(linksQuery);
@@ -308,11 +310,11 @@ function RoutineDetailPage({ companyId, routineId, view }: { companyId: string;
const loadDirectResponsibility = useCallback(async () => {
if (!options.responsibilitiesOn) return "";
const links = await queryClient.fetchQuery({
queryKey: queryKeys.responsibilities.routineLinks(companyId, routineId),
queryKey: [...queryKeys.responsibilities.routineLinks(companyId, routineId), userId],
queryFn: () => responsibilitiesApi.lookupRoutineLinks(companyId, routineId),
});
return links.responsibilities.find((entry) => entry.via === "direct")?.id ?? "";
}, [companyId, options.responsibilitiesOn, queryClient, routineId]);
}, [companyId, options.responsibilitiesOn, queryClient, routineId, userId]);
const openEdit = useCallback(async () => {
const current = routineRef.current;