diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index b7d28e23681..4ca1b4758d7 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -534,7 +534,10 @@ Coordinator navigation uses **Chat**, **Tasks**, and **Inbox**. Inbox uses the inbox icon and keeps the existing decision feed, its count, and decision history at `/decisions`. The previous Inbox destination under More is removed. -Inbox opens to **Needs you** with **Assigned to you** selected. Its badge counts +Inbox opens to **Needs you** with **All assignees** selected for a board member +and **Assigned to you** for a viewer. The assignee, agent, project, and grouping +choices are saved per person and company, so the next visit opens the same way; +a link that names a view still opens that view. Its badge counts personal actions. **Waiting** shows scheduled provider retries and personal snoozes. A provider limit with a known account and reset appears once per recipient, with the affected tasks, agents and run logs inside. When the account or diff --git a/tests/e2e/coordinator-inbox-views.spec.ts b/tests/e2e/coordinator-inbox-views.spec.ts index 23b34093849..9710f51771e 100644 --- a/tests/e2e/coordinator-inbox-views.spec.ts +++ b/tests/e2e/coordinator-inbox-views.spec.ts @@ -94,7 +94,22 @@ for (const mobile of [false, true]) test(`Mine retains Inbox behavior inside Tas await page.getByRole("link", { name: "Inbox", exact: true }).click(); const inbox = page.getByRole("region", { name: "Inbox", exact: true }); await expect(inbox.getByRole("toolbar", { name: "Decisions controls" })).toBeVisible(); + await expect(inbox.getByRole("button", { name: "Filter decisions by assignee, All assignees", exact: true })).toBeVisible(); + await inbox.getByRole("button", { name: "Filter decisions by assignee, All assignees", exact: true }).click(); + await page.getByRole("menuitem", { name: "Assigned to you", exact: true }).click(); await expect(inbox.getByRole("button", { name: "Filter decisions by assignee, Assigned to you", exact: true })).toBeVisible(); + await inbox.getByRole("button", { name: "Group decisions, By type", exact: true }).click(); + await page.getByRole("menuitem", { name: "By project", exact: true }).click(); + await expect(inbox.getByRole("button", { name: "Group decisions, By project", exact: true })).toBeVisible(); + await page.goto(`/${company.issuePrefix}/decisions`); + await expect(inbox.getByRole("button", { name: "Filter decisions by assignee, Assigned to you", exact: true })).toBeVisible(); + await expect(inbox.getByRole("button", { name: "Group decisions, By project", exact: true })).toBeVisible(); + await page.reload(); + await expect(inbox.getByRole("button", { name: "Filter decisions by assignee, Assigned to you", exact: true })).toBeVisible(); + await expect(inbox.getByRole("button", { name: "Group decisions, By project", exact: true })).toBeVisible(); + await inbox.getByRole("button", { name: "Filter decisions by assignee, Assigned to you", exact: true }).click(); + await page.getByRole("menuitem", { name: "All assignees", exact: true }).click(); + await expect(inbox.getByRole("button", { name: "Filter decisions by assignee, All assignees", exact: true })).toBeVisible(); await page.setViewportSize({ width: 1024, height: 720 }); const search = await inbox.locator("[data-toolbar-search]").boundingBox(); const firstFilter = await inbox.getByRole("button", { name: /^Filter decisions by agent,/ }).boundingBox(); diff --git a/ui/src/components/InboxFilter.tsx b/ui/src/components/InboxFilter.tsx index 389021bf285..8e5e9918b0b 100644 --- a/ui/src/components/InboxFilter.tsx +++ b/ui/src/components/InboxFilter.tsx @@ -3,18 +3,19 @@ import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { cn } from "@/lib/utils"; -export function InboxFilter({ label, heading, value, options, onChange, defaultLabel }: { +export function InboxFilter({ label, heading, value, options, onChange, defaultLabel, disabled }: { label: string; heading: string; value: T; options: readonly { value: T; label: string }[]; onChange: (value: T) => void; defaultLabel?: string; + disabled?: boolean; }) { const selected = options.find(option => option.value === value); return - diff --git a/ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx b/ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx new file mode 100644 index 00000000000..beecb5ac178 --- /dev/null +++ b/ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx @@ -0,0 +1,369 @@ +// @vitest-environment jsdom +import { act, type ReactNode } from "react"; +import { MemoryRouter, useLocation } from "react-router-dom"; +import { createRoot, type Root } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Agent, AttentionItem } from "@paperclipai/shared"; +import { CoordinatorNeedsYou } from "./CoordinatorNeedsYou"; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; +const fixture = vi.hoisted(() => ({ + byView: {} as Record, + listCalls: [] as Array<{ view?: string }>, + agents: [] as Agent[] | null, + agentsGate: null as null | Promise, + boardAccess: null as null | Record, + boardAccessGate: null as null | Promise, + navigate: vi.fn(), breadcrumbs: vi.fn(), openPanel: vi.fn(), closePanel: vi.fn(), setPanelVisible: vi.fn(), +})); +vi.mock("@/api/inboxDismissals", () => ({ inboxDismissalsApi: { restore: vi.fn(async () => ({})), dismiss: vi.fn(async () => ({})) } })); +vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: "company" }) })); +vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: fixture.breadcrumbs }) })); +vi.mock("@/context/PanelContext", () => ({ usePanel: () => ({ openPanel: fixture.openPanel, closePanel: fixture.closePanel, setPanelVisible: fixture.setPanelVisible, panelVisible: true }) })); +vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false }) })); +vi.mock("@/hooks/useCoordinatorWorkspaceEnabled", () => ({ useCoordinatorWorkspaceEnabled: () => ({ userId: "reviewer" }) })); +vi.mock("@/lib/router", async importOriginal => ({ ...await importOriginal(), useNavigate: () => fixture.navigate })); +vi.mock("@/api/agents", () => ({ agentsApi: { list: async () => { + if (fixture.agentsGate) await fixture.agentsGate; + if (!fixture.agents) throw new Error("Agents unavailable"); + return fixture.agents; +} } })); +vi.mock("@/api/projects", () => ({ projectsApi: { list: async () => [] } })); +vi.mock("@/api/access", () => ({ accessApi: { + listUserDirectory: async () => ({ users: [{ principalId: "dotta", status: "active", user: { name: "Dotta" } }] }), + getCurrentBoardAccess: async () => { + if (fixture.boardAccessGate) await fixture.boardAccessGate; + if (!fixture.boardAccess) throw new Error("No board access"); + return fixture.boardAccess; + }, +} })); +vi.mock("@/api/attention", () => ({ attentionApi: { + claim: vi.fn(async () => ({})), + close: vi.fn(async () => ({ until: null })), + list: async (_companyId: string, options: { view?: string }) => { + fixture.listCalls.push(options); + return { items: [...(fixture.byView[options.view ?? ""] ?? [])], viewCounts: { mine: 0, unassigned: 0, company: 0, archived: 0, all: 0 }, receipts: [] }; + }, + history: async () => ({ items: [], nextCursor: null }), + runHistory: async () => ({ items: [], nextCursor: null }), +} })); +vi.mock("motion/react", () => ({ + LayoutGroup: ({ children }: { children: ReactNode }) => children, + useReducedMotion: () => true, + motion: { div: ({ children, id, tabIndex }: { children: ReactNode; id?: string; tabIndex?: number }) =>
{children}
}, +})); +vi.mock("@/components/PropertiesPanel", () => ({ PROPERTIES_PANE_HEADER_SLOT_ID: "test-sidebar" })); +vi.mock("@/components/DecisionResolver", () => ({ DecisionResolver: () => null })); +vi.mock("@/components/AttentionInteractionResolver", () => ({ AttentionInteractionResolver: ({ interactionId }: { interactionId: string }) => {interactionId} })); + +function Location() { return {useLocation().search}; } + +const member = (membershipRole: string) => ({ userId: "reviewer", source: "session", isInstanceAdmin: false, companyIds: ["company"], + memberships: [{ companyId: "company", membershipRole, status: "active" }] }); +const card = (id: string, minutesAgo: number, extra: { userId?: string; agentId?: string; project?: { id: string; name: string } } = {}) => ({ + id, sourceKind: "issue_thread_interaction", inlineResolvable: true, + subject: { id, kind: "interaction", title: `Card ${id}`, metadata: { issueId: `task-${id}`, ...(extra.agentId ? { createdByAgentId: extra.agentId } : {}) } }, + relatedIssue: { id: `task-${id}`, identifier: `PAP-${id}`, title: `Task ${id}`, href: `/PAP/issues/PAP-${id}` }, + project: extra.project ?? null, originAgentName: null, activityAt: new Date(Date.now() - minutesAgo * 60_000).toISOString(), + audience: { kind: "user", userId: extra.userId ?? "reviewer", reason: "addressee" }, +}) as unknown as AttentionItem; +const website = { id: "project-web", name: "Website" }; + +let root: Root; +let container: HTMLDivElement; +let client: QueryClient | null = null; +beforeEach(() => { + fixture.byView = {}; fixture.listCalls = []; fixture.boardAccess = null; fixture.boardAccessGate = null; fixture.agentsGate = null; + fixture.agents = [{ id: "agent-cos", name: "Chief of Staff" }] as Agent[]; + localStorage.clear(); + container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); +}); +afterEach(async () => { await act(async () => root.unmount()); client?.clear(); client = null; container.remove(); vi.restoreAllMocks(); }); +async function flush() { await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); } +async function visit(url: string) { + if (client) { + await act(async () => root.unmount()); + client.clear(); + root = createRoot(container); + } + fixture.listCalls = []; + client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + await act(async () => root.render()); + await flush(); await flush(); +} +const filterButton = (label: string) => container.querySelector(`button[aria-label^="${label}"]`)!; +const assignee = () => filterButton("Filter decisions by assignee"); +async function menuItems(trigger: HTMLButtonElement) { + if (trigger.getAttribute("aria-expanded") !== "true") { + await act(async () => { trigger.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 })); }); + await flush(); + } + return [...document.querySelectorAll('[role="menu"] [role="menuitem"]')]; +} +async function choose(label: string, optionLabel: string) { + const trigger = filterButton(label); + const item = (await menuItems(trigger)).find((option) => option.textContent === optionLabel); + expect(item, `${label} -> ${optionLabel}`).toBeDefined(); + await act(async () => item!.click()); + await flush(); +} +const cards = () => [...container.querySelectorAll("[data-attention-card]")].map((node) => node.getAttribute("data-attention-card")); +const location = () => container.querySelector("[data-location]")?.textContent; +const listedViews = () => fixture.listCalls.map((call) => call.view); + +describe("Needs You keeps its toolbar between visits", () => { + it("opens All assignees for a board member, and keeps the chosen assignee, agent, project and grouping on the next visit", async () => { + fixture.boardAccess = member("admin"); + const ours = card("ours", 1, { agentId: "agent-cos", project: website }); + fixture.byView = { all: [ours, card("dottas", 2, { userId: "dotta" })], mine: [ours] }; + await visit("/decisions"); + await vi.waitFor(() => expect(assignee().value).toBe("all")); + expect(assignee().textContent).toBe("All assignees"); + expect(assignee().getAttribute("aria-label")).toBe("Filter decisions by assignee, All assignees"); + expect(location()).toBe(""); + expect(listedViews()).toEqual(["all"]); + expect(cards()).toEqual(["ours", "dottas"]); + + await choose("Filter decisions by agent", "Chief of Staff"); + await choose("Filter decisions by project", "Website"); + await choose("Group decisions", "By project"); + await choose("Filter decisions by assignee", "Assigned to you"); + expect(location()).toBe("?view=mine"); + expect(cards()).toEqual(["ours"]); + + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours"])); + expect(assignee().value).toBe("me"); + expect(filterButton("Filter decisions by agent").value).toBe("agent-cos"); + expect(filterButton("Filter decisions by project").value).toBe("project-web"); + expect(filterButton("Group decisions").value).toBe("project"); + expect([...container.querySelectorAll("h2")].map((heading) => heading.textContent)).toContain("Website"); + expect(location()).toBe(""); + expect(listedViews()).toEqual(["mine"]); + }); + + it("reopens one person's cards, and a link's own view wins without replacing the kept choice", async () => { + fixture.boardAccess = member("admin"); + fixture.byView = { all: [card("ours", 1), card("dottas", 2, { userId: "dotta" })], company: [card("alert", 3, { userId: "dotta" })] }; + await visit("/decisions"); + await vi.waitFor(() => expect(assignee().value).toBe("all")); + await choose("Filter decisions by assignee", "Dotta"); + expect(location()).toBe("?view=all&for=dotta"); + expect(cards()).toEqual(["dottas"]); + + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["dottas"])); + expect(assignee().value).toBe("user:dotta"); + expect(assignee().textContent).toBe("Dotta"); + + await visit("/decisions?view=company"); + await vi.waitFor(() => expect(cards()).toEqual(["alert"])); + expect(assignee().value).toBe("company"); + + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["dottas"])); + expect(assignee().value).toBe("user:dotta"); + }); + + it("opens Assigned to you for a viewer, even when another person's cards were kept on this browser", async () => { + fixture.boardAccess = member("admin"); + fixture.byView = { all: [card("ours", 1), card("dottas", 2, { userId: "dotta" })], mine: [card("ours", 1)] }; + await visit("/decisions"); + await vi.waitFor(() => expect(assignee().value).toBe("all")); + await choose("Filter decisions by assignee", "Dotta"); + + fixture.boardAccess = member("viewer"); + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours"])); + expect(assignee().value).toBe("me"); + expect((await menuItems(assignee())).map((option) => option.textContent)).toEqual(["Assigned to you", "No owner yet", "Company alerts"]); + expect(listedViews()).toEqual(["mine"]); + }); + + it("opens Assigned to you when board access cannot be read", async () => { + fixture.byView = { all: [card("ours", 1), card("dottas", 2, { userId: "dotta" })], mine: [card("ours", 1)] }; + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours"])); + expect(assignee().value).toBe("me"); + expect(assignee().disabled).toBe(false); + expect(listedViews()).toEqual(["mine"]); + }); + + it("reads no feed until board access is known, so Assigned to you never shows first", async () => { + let release!: () => void; + fixture.boardAccessGate = new Promise((resolve) => { release = resolve; }); + fixture.boardAccess = member("admin"); + fixture.byView = { all: [card("ours", 1), card("dottas", 2, { userId: "dotta" })], mine: [card("ours", 1)] }; + await visit("/decisions"); + expect(listedViews()).toEqual([]); + expect(container.querySelector('[role="status"]')?.textContent).toContain("Loading decisions"); + expect(cards()).toEqual([]); + expect(container.querySelector("[data-needs-you-summary]")).toBeNull(); + expect(assignee().value).toBe("all"); + expect(assignee().disabled).toBe(true); + + await act(async () => release()); await flush(); await flush(); + await vi.waitFor(() => expect(cards()).toEqual(["ours", "dottas"])); + expect(assignee().value).toBe("all"); + expect(assignee().disabled).toBe(false); + expect(listedViews()).toEqual(["all"]); + }); + + it("still names a kept project with no open cards, so the filter never reads as All projects", async () => { + fixture.boardAccess = member("admin"); + fixture.byView = { all: [card("ours", 1, { project: website }), card("other", 2)] }; + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours", "other"])); + await choose("Filter decisions by project", "Website"); + expect(cards()).toEqual(["ours"]); + + fixture.byView = { all: [card("other", 2)] }; + await visit("/decisions"); + await vi.waitFor(() => expect(container.textContent).toContain("No open decisions match these filters.")); + expect(filterButton("Filter decisions by project").value).toBe("project-web"); + expect(filterButton("Filter decisions by project").textContent).toBe("Website"); + await choose("Filter decisions by project", "All projects"); + expect(cards()).toEqual(["other"]); + }); + + it("stops filtering by a kept agent the company no longer has", async () => { + fixture.agents = [{ id: "agent-cos", name: "Chief of Staff" }, { id: "agent-old", name: "Old agent" }] as Agent[]; + fixture.boardAccess = member("admin"); + fixture.byView = { all: [card("ours", 1, { agentId: "agent-old" }), card("other", 2)] }; + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours", "other"])); + await choose("Filter decisions by agent", "Old agent"); + expect(cards()).toEqual(["ours"]); + + fixture.agents = [{ id: "agent-cos", name: "Chief of Staff" }] as Agent[]; + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours", "other"])); + expect(filterButton("Filter decisions by agent").value).toBe(""); + }); + + it("shows every agent's cards while the agent list cannot be read, then filters by the kept agent again", async () => { + fixture.boardAccess = member("admin"); + fixture.byView = { all: [card("ours", 1, { agentId: "agent-cos" }), card("other", 2)] }; + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours", "other"])); + await choose("Filter decisions by agent", "Chief of Staff"); + expect(cards()).toEqual(["ours"]); + + fixture.agents = null; + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours", "other"])); + expect(filterButton("Filter decisions by agent").value).toBe(""); + expect(filterButton("Filter decisions by agent").getAttribute("aria-label")).toBe("Filter decisions by agent, All agents"); + + fixture.agents = [{ id: "agent-cos", name: "Chief of Staff" }] as Agent[]; + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours"])); + expect(filterButton("Filter decisions by agent").value).toBe("agent-cos"); + }); + + it("lets a decision link clear kept filters for that visit only", async () => { + Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { configurable: true, writable: true, value: vi.fn() }); + fixture.boardAccess = member("admin"); + const linked = { ...card("linked", 3), sourceKind: "decision", subject: { id: "target", kind: "decision", title: "Linked decision" } } as unknown as AttentionItem; + fixture.byView = { all: [card("ours", 1, { agentId: "agent-cos", project: website }), linked] }; + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours", "linked"])); + await choose("Filter decisions by agent", "Chief of Staff"); + await choose("Filter decisions by project", "Website"); + expect(cards()).toEqual(["ours"]); + + await visit("/decisions?decisionId=target"); + for (let tick = 0; tick < 5; tick++) await flush(); + expect(container.querySelector("#coordinator-decision-target")).not.toBeNull(); + expect(filterButton("Filter decisions by agent").value).toBe(""); + expect(filterButton("Filter decisions by project").value).toBe(""); + expect(location()).not.toContain("decisionId"); + await choose("Group decisions", "By task"); + + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours"])); + expect(filterButton("Filter decisions by agent").value).toBe("agent-cos"); + expect(filterButton("Filter decisions by project").value).toBe("project-web"); + expect(filterButton("Group decisions").value).toBe("task"); + }); + + it("keeps a decision link's card in view when the agent list loads after it", async () => { + Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { configurable: true, writable: true, value: vi.fn() }); + fixture.boardAccess = member("admin"); + const linked = { ...card("linked", 3), sourceKind: "decision", subject: { id: "target", kind: "decision", title: "Linked decision" } } as unknown as AttentionItem; + fixture.byView = { all: [card("ours", 1, { agentId: "agent-cos" }), linked] }; + await visit("/decisions"); + await vi.waitFor(() => expect(cards()).toEqual(["ours", "linked"])); + await choose("Filter decisions by agent", "Chief of Staff"); + expect(cards()).toEqual(["ours"]); + + let release!: () => void; + fixture.agentsGate = new Promise((resolve) => { release = resolve; }); + await visit("/decisions?decisionId=target"); + for (let tick = 0; tick < 5; tick++) await flush(); + expect(location()).not.toContain("decisionId"); + await act(async () => release()); await flush(); await flush(); + expect(cards()).toEqual(["ours", "linked"]); + expect(filterButton("Filter decisions by agent").value).toBe(""); + }); + + it("returns from Archived to the kept assignee", async () => { + fixture.boardAccess = member("admin"); + fixture.byView = { all: [card("ours", 1), card("dottas", 2, { userId: "dotta" })], unassigned: [card("pool", 4)], archived: [] }; + await visit("/decisions"); + await vi.waitFor(() => expect(assignee().value).toBe("all")); + await choose("Filter decisions by assignee", "No owner yet"); + await vi.waitFor(() => expect(cards()).toEqual(["pool"])); + + await visit("/decisions?view=archived"); + await vi.waitFor(() => expect(container.querySelector("h1")?.textContent).toBe("Archived")); + await act(async () => container.querySelector('[aria-label="Back to Needs You"]')!.click()); await flush(); + expect(location()).toBe(""); + await vi.waitFor(() => expect(cards()).toEqual(["pool"])); + expect(assignee().value).toBe("unassigned"); + }); + + it("keeps saved filters when switching to Waiting and back to Needs you, and loads Waiting without waiting for board access", async () => { + fixture.boardAccess = member("admin"); + const dottas = card("dottas", 1, { userId: "dotta", agentId: "agent-cos", project: website }); + const other = card("other", 2); + const waiting = card("waiting-1", 3); + fixture.byView = { all: [dottas, other], waiting: [waiting] }; + await visit("/decisions"); + await vi.waitFor(() => expect(assignee().value).toBe("all")); + await choose("Filter decisions by agent", "Chief of Staff"); + await choose("Filter decisions by project", "Website"); + await choose("Filter decisions by assignee", "Dotta"); + await vi.waitFor(() => expect(cards()).toEqual(["dottas"])); + + const waitingTab = [...container.querySelectorAll('[aria-label="Inbox views"] button')].find((button) => button.textContent?.startsWith("Waiting"))!; + await act(async () => waitingTab.click()); await flush(); + await vi.waitFor(() => expect(cards()).toEqual(["waiting-1"])); + + const needsTab = [...container.querySelectorAll('[aria-label="Inbox views"] button')].find((button) => button.textContent === "Needs you")!; + await act(async () => needsTab.click()); await flush(); + await vi.waitFor(() => expect(cards()).toEqual(["dottas"])); + expect(assignee().value).toBe("user:dotta"); + expect(filterButton("Filter decisions by agent").value).toBe("agent-cos"); + expect(filterButton("Filter decisions by project").value).toBe("project-web"); + + // Visiting ?folder=waiting directly loads waiting feed immediately even while boardAccess is pending, + // without applying Needs You's saved person/agent/project filters, and keeps a Waiting filter chosen + // before boardAccess settles. + let releaseBoardAccess!: () => void; + fixture.boardAccessGate = new Promise((resolve) => { releaseBoardAccess = resolve; }); + const waitingAgent = card("waiting-agent", 2, { agentId: "agent-cos" }); + fixture.byView = { ...fixture.byView, waiting: [waitingAgent, waiting] }; + await visit("/decisions?folder=waiting"); + await vi.waitFor(() => expect(cards()).toEqual(["waiting-agent", "waiting-1"])); + expect(listedViews()).toEqual(["waiting"]); + + await choose("Filter decisions by agent", "Chief of Staff"); + expect(cards()).toEqual(["waiting-agent"]); + + await act(async () => releaseBoardAccess()); await flush(); await flush(); + expect(filterButton("Filter decisions by agent").value).toBe("agent-cos"); + expect(cards()).toEqual(["waiting-agent"]); + }); +}); diff --git a/ui/src/components/coordinator/CoordinatorNeedsYou.tsx b/ui/src/components/coordinator/CoordinatorNeedsYou.tsx index 6dd21067b0d..1590c6b9033 100644 --- a/ui/src/components/coordinator/CoordinatorNeedsYou.tsx +++ b/ui/src/components/coordinator/CoordinatorNeedsYou.tsx @@ -14,12 +14,12 @@ import { useBreadcrumbs } from "@/context/BreadcrumbContext"; import { usePanel } from "@/context/PanelContext"; import { useSidebar } from "@/context/SidebarContext"; import { useCoordinatorWorkspaceEnabled } from "@/hooks/useCoordinatorWorkspaceEnabled"; -import { useAttentionBadge, useAttentionCloseActions, useAttentionEveryoneView, useAttentionViewFeed, useClaimAttentionItem, useDismissAttentionReceipt } from "@/hooks/useAttentionViews"; +import { useAttentionCloseActions, useAttentionEveryoneAccess, useAttentionViewFeed, useClaimAttentionItem, useDismissAttentionReceipt } from "@/hooks/useAttentionViews"; import { useNavigate, useSearchParams } from "@/lib/router"; import { queryKeys } from "@/lib/queryKeys"; -import { COORDINATOR_ASSIGNEE_PARAM, COORDINATOR_RECENT_DECISION_MS, DEFAULT_DECISION_HISTORY_SCOPE, coordinatorAssignee, coordinatorAssigneeTarget, coordinatorAudienceKey, coordinatorCardDetail, coordinatorCardTitle, recentDecisionReceipts, type CoordinatorAssignee } from "@/lib/coordinator-attention"; +import { COORDINATOR_ASSIGNEE_PARAM, COORDINATOR_RECENT_DECISION_MS, DEFAULT_DECISION_HISTORY_SCOPE, coordinatorAssignee, coordinatorAssigneeNeedsEveryone, coordinatorAssigneeTarget, coordinatorAudienceKey, coordinatorCardDetail, coordinatorCardTitle, loadNeedsYouToolbar, needsYouToolbarStorageKey, openingCoordinatorAssignee, recentDecisionReceipts, saveNeedsYouToolbar, type CoordinatorAssignee, type NeedsYouGroup, type NeedsYouToolbar } from "@/lib/coordinator-attention"; import { attentionDetailLine, isInlineResolvable } from "@/lib/attention"; -import { ATTENTION_VIEW_PARAM, attentionAudienceLineNamesResponders, parseAttentionView } from "@/lib/attention-views"; +import { ATTENTION_VIEW_PARAM, EMPTY_ATTENTION_VIEW_COUNTS, attentionAudienceLineNamesResponders, parseAttentionView } from "@/lib/attention-views"; import { splitArchivedAttentionItems, splitStaleAttentionItems } from "@/lib/attention-close"; import { attentionObligationEvidence, foldAttentionObligations, inboxCardMatchesFilters, inboxProjectOptions } from "@/lib/attention-obligations"; import { buildCompanyUserLabelMap } from "@/lib/company-members"; @@ -49,8 +49,6 @@ import { CoordinatorNeedsYouSidePanel, needsYouReviewTab, needsYouReviewTabId, n import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; import { cn } from "@/lib/utils"; -type Group = "type" | "none" | "task" | "agent" | "project"; - const inboxFolders = [ { value: "needs", label: "Needs you", description: "Review open requests and decide what happens next." }, { value: "waiting", label: "Waiting", description: "See what you’ve snoozed and which tasks are waiting for an automatic retry." }, @@ -93,30 +91,44 @@ export function CoordinatorNeedsYou() { const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); const deepLinkDecisionId = searchParams.get("decisionId"); - // For you is the default; the other views live in the URL (PAP-749 Rule 3). - // Everyone opens for a board member only (PAP-768). - const everyone = useAttentionEveryoneView(selectedCompanyId); - const view = parseAttentionView(searchParams.get(ATTENTION_VIEW_PARAM), { everyone }); + const toolbarKey = needsYouToolbarStorageKey(selectedCompanyId, userId); + const [toolbarState, setToolbarState] = useState(() => ({ key: toolbarKey, toolbar: loadNeedsYouToolbar(toolbarKey) })); + const toolbar = toolbarState.key === toolbarKey ? toolbarState.toolbar : loadNeedsYouToolbar(toolbarKey); + useEffect(() => { + setToolbarState(current => current.key === toolbarKey ? current : { key: toolbarKey, toolbar: loadNeedsYouToolbar(toolbarKey) }); + }, [toolbarKey]); + const keepToolbar = (patch: Partial) => { + setToolbarState({ key: toolbarKey, toolbar: { ...toolbar, ...patch } }); + saveNeedsYouToolbar(toolbarKey, { ...loadNeedsYouToolbar(toolbarKey), ...patch }); + }; + const clearToolbarFilters = useCallback(() => setToolbarState(current => ({ key: toolbarKey, + toolbar: { ...(current.key === toolbarKey ? current.toolbar : loadNeedsYouToolbar(toolbarKey)), agentId: "", project: null } })), [toolbarKey]); + const folder = searchParams.get("folder"); + const historyOpen = folder === "history"; + const waitingOpen = folder === "waiting"; + const { everyone, settled: everyoneSettled } = useAttentionEveryoneAccess(selectedCompanyId); + const requestedView = searchParams.get(ATTENTION_VIEW_PARAM) || null; + const awaitingEveryone = !waitingOpen && !everyoneSettled + && (requestedView ? requestedView === "all" : coordinatorAssigneeNeedsEveryone(openingCoordinatorAssignee(toolbar.assignee, true))); + const mayOpenEveryone = everyone || awaitingEveryone; + const opening = coordinatorAssigneeTarget(openingCoordinatorAssignee(toolbar.assignee, mayOpenEveryone), userId); + const view = requestedView ? parseAttentionView(requestedView, { everyone: mayOpenEveryone }) : opening.view; // Everyone can be narrowed to one person (PAP-775); the person lives in the URL too. - const forUserId = view === "all" ? searchParams.get(COORDINATOR_ASSIGNEE_PARAM) : null; - const setView = useCallback((next: typeof view, person: string | null = null) => setSearchParams(current => { + const forUserId = waitingOpen || view !== "all" ? null : requestedView ? searchParams.get(COORDINATOR_ASSIGNEE_PARAM) : opening.forUserId; + const setView = useCallback((next: typeof view | null, person: string | null = null) => setSearchParams(current => { const params = new URLSearchParams(current); params.delete("folder"); - if (next === "mine") params.delete(ATTENTION_VIEW_PARAM); else params.set(ATTENTION_VIEW_PARAM, next); + if (next) params.set(ATTENTION_VIEW_PARAM, next); else params.delete(ATTENTION_VIEW_PARAM); if (person) params.set(COORDINATOR_ASSIGNEE_PARAM, person); else params.delete(COORDINATOR_ASSIGNEE_PARAM); return params; }, { replace: true }), [setSearchParams]); const assignee = coordinatorAssignee(view, forUserId); const reducedMotion = useReducedMotion(); const [query, setQuery] = useState(""); - const [agentFilter, setAgentFilter] = useState(""); - const [projectFilter, setProjectFilter] = useState(""); - const [groupBy, setGroupBy] = useState("type"); - const folder = searchParams.get("folder"); - const historyOpen = folder === "history"; - const waitingOpen = folder === "waiting"; + const [waitingFilters, setWaitingFilters] = useState({ agentId: "", projectId: "" }); const changeFolder = (next: "needs" | "waiting" | "history") => { - setQuery(""); setAgentFilter(""); setProjectFilter(""); + setQuery(""); + setWaitingFilters({ agentId: "", projectId: "" }); setSearchParams(current => { const params = new URLSearchParams(current); params.delete(ATTENTION_VIEW_PARAM); params.delete(COORDINATOR_ASSIGNEE_PARAM); @@ -136,10 +148,11 @@ export function CoordinatorNeedsYou() { const [staleOpen, setStaleOpen] = useState(false); const [snoozedOpen, setSnoozedOpen] = useState(true); useEffect(() => { setSettling([]); setSavedIds(new Map()); setStaleOpen(false); setSnoozedOpen(true); }, [selectedCompanyId, userId, view, folder]); + useEffect(() => { setWaitingFilters({ agentId: "", projectId: "" }); }, [selectedCompanyId, userId, folder]); const archivedView = view === "archived"; const [renderLimit, setRenderLimit] = useState(40); // Keyed by person and view; the For you key is the one the badge reads. - const feed = useAttentionViewFeed(selectedCompanyId, waitingOpen ? "waiting" : view); + const feed = useAttentionViewFeed(selectedCompanyId, waitingOpen ? "waiting" : view, { enabled: waitingOpen || !awaitingEveryone }); useEffect(() => { setSavedIds(current => { const pending = new Map([...current].filter(([, hidden]) => hidden.closed || hidden.version === feed.dataUpdatedAt)); @@ -148,7 +161,7 @@ export function CoordinatorNeedsYou() { }, [feed.dataUpdatedAt]); const feedView = useQueryView(feed); const feedWaiting = feedView.kind === "loading" || feedView.kind === "reconnecting"; - const { viewCounts } = useAttentionBadge(selectedCompanyId); + const viewCounts = feed.data?.viewCounts ?? EMPTY_ATTENTION_VIEW_COUNTS; const claim = useClaimAttentionItem(selectedCompanyId); const receiptActions = useDismissAttentionReceipt(selectedCompanyId); const directory = useQuery({ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!), queryFn: () => accessApi.listUserDirectory(selectedCompanyId!), enabled: !!selectedCompanyId }); @@ -177,6 +190,10 @@ export function CoordinatorNeedsYou() { const recent = useQuery({ queryKey: [...queryKeys.attention(selectedCompanyId!), "history", "recent", DEFAULT_DECISION_HISTORY_SCOPE], queryFn: () => attentionApi.history(selectedCompanyId!, { limit: 100, scope: DEFAULT_DECISION_HISTORY_SCOPE, since: new Date(Date.now() - COORDINATOR_RECENT_DECISION_MS).toISOString() }), enabled: !!selectedCompanyId, refetchOnWindowFocus: true }); const agentMap = useMemo(() => new Map((agentQuery.data ?? []).map((agent) => [agent.id, agent])), [agentQuery.data]); + const activeAgentId = waitingOpen ? waitingFilters.agentId : toolbar.agentId; + const agentFilter = agentMap.has(activeAgentId) ? activeAgentId : ""; + const projectFilter = waitingOpen ? waitingFilters.projectId : toolbar.project?.id ?? ""; + const groupBy = toolbar.groupBy; const recentItems = useMemo(() => recentDecisionReceipts(recent.data?.items ?? [], now), [recent.data, now]); const settlingIds = useMemo(() => new Set(settling.map(item => `${item.sourceKind}:${item.subject.id}`)), [settling]); // One card for each obligation (PAP-749 Rule 11): evidence folds into its @@ -224,7 +241,7 @@ export function CoordinatorNeedsYou() { } // A saved decision link takes precedence over local toolbar filters and the // rendering window. Consume it only after its actual card has mounted. - if (query || agentFilter || projectFilter) { setQuery(""); setAgentFilter(""); setProjectFilter(""); return; } + if (query || toolbar.agentId || projectFilter) { setQuery(""); clearToolbarFilters(); return; } if (forUserId) { setView("all"); return; } if (staleItems.some(item => item.sourceKind === "decision" && item.subject.id === deepLinkDecisionId)) setStaleOpen(true); const index = currentItems.findIndex(item => item.sourceKind === "decision" && item.subject.id === deepLinkDecisionId); @@ -234,20 +251,37 @@ export function CoordinatorNeedsYou() { card.focus({ preventScroll: true }); card.scrollIntoView({ block: "center", behavior: reducedMotion ? "auto" : "smooth" }); setSearchParams(current => { const next = new URLSearchParams(current); next.delete("decisionId"); return next; }, { replace: true }); - }, [deepLinkDecisionId, selectedCompanyId, pendingItems, currentItems, staleItems, feedWaiting, everyone, view, query, agentFilter, projectFilter, forUserId, setView, renderLimit, reducedMotion, setSearchParams]); - const projects = useMemo(() => inboxProjectOptions(obligations, pendingItems, recentItems), - [obligations, pendingItems, recentItems]); + }, [deepLinkDecisionId, selectedCompanyId, pendingItems, currentItems, staleItems, feedWaiting, everyone, view, query, toolbar.agentId, projectFilter, forUserId, setView, clearToolbarFilters, renderLimit, reducedMotion, setSearchParams]); + const keptProjectId = waitingOpen ? undefined : toolbar.project?.id; + const keptProjectName = waitingOpen ? undefined : toolbar.project?.name; + const projects = useMemo(() => { + const entries = inboxProjectOptions(obligations, pendingItems, recentItems); + if (keptProjectId && !entries.some(([id]) => id === keptProjectId)) { + return [...entries, [keptProjectId, keptProjectName || "Unnamed project"] as const]; + } + return entries; + }, [obligations, pendingItems, recentItems, keptProjectId, keptProjectName]); + const chooseAgent = (agentId: string) => waitingOpen + ? setWaitingFilters(current => ({ ...current, agentId })) + : keepToolbar({ agentId }); + const chooseProject = (id: string) => waitingOpen + ? setWaitingFilters(current => ({ ...current, projectId: id })) + : keepToolbar({ project: id ? { id, name: projects.find(([projectId]) => projectId === id)?.[1] ?? "Unnamed project" } : null }); // Assigned to you, everyone the viewer may see, one person, no owner yet, or company alerts. const assigneeOptions = useMemo(() => { const people = [...userLabelMap].filter(([id]) => id !== userId).sort(([, a], [, b]) => a.localeCompare(b)); return [ { value: "me" as CoordinatorAssignee, label: "Assigned to you" }, - ...(everyone ? [{ value: "all" as CoordinatorAssignee, label: "All assignees" }, ...people.map(([id, name]) => ({ value: `user:${id}` as CoordinatorAssignee, label: name }))] : []), + ...(mayOpenEveryone ? [{ value: "all" as CoordinatorAssignee, label: "All assignees" }, ...people.map(([id, name]) => ({ value: `user:${id}` as CoordinatorAssignee, label: name }))] : []), { value: "unassigned" as CoordinatorAssignee, label: "No owner yet" }, { value: "company" as CoordinatorAssignee, label: "Company alerts" }, ]; - }, [userLabelMap, userId, everyone]); - const chooseAssignee = (value: CoordinatorAssignee) => { const target = coordinatorAssigneeTarget(value, userId); setView(target.view, target.forUserId); }; + }, [userLabelMap, userId, mayOpenEveryone]); + const chooseAssignee = (value: CoordinatorAssignee) => { + const target = coordinatorAssigneeTarget(value, userId); + keepToolbar({ assignee: value }); + setView(target.view, target.forUserId); + }; const showHistory = () => changeFolder("history"); // Cards whose artifact can open beside them: the + launcher lists these. const reviewable = useMemo(() => pendingItems.filter(item => !!needsYouArtifact(item)), [pendingItems]); @@ -419,24 +453,21 @@ export function CoordinatorNeedsYou() { {NEEDS_YOU_SECTIONS[section].title} ; return
- {archivedView ?

Archived

: null} - {/* Assigned to you by default (PAP-775); the assignee filter widens to all - assignees, one person, no owner yet or company alerts. Archived and - Decision history sit in View. */} + {archivedView ?

Archived

: null}
- ({ value: agent.id, label: agent.name }))]} /> - ({ value, label }))]} /> {!waitingOpen && assignee && option.value === assignee) ? [...assigneeOptions, { value: assignee, label: "Someone else" }] : assigneeOptions} />} - label="Group decisions" heading="Group by" value={groupBy} onChange={setGroupBy} + label="Group decisions" heading="Group by" value={groupBy} onChange={next => keepToolbar({ groupBy: next })} options={[{ value: "type", label: "By type" }, { value: "task", label: "By task" }, { value: "agent", label: "By agent" }, { value: "project", label: "By project" }, { value: "none", label: "No grouping" }]} /> diff --git a/ui/src/hooks/useAttentionViews.ts b/ui/src/hooks/useAttentionViews.ts index 5086e1296bc..a4a378f07d9 100644 --- a/ui/src/hooks/useAttentionViews.ts +++ b/ui/src/hooks/useAttentionViews.ts @@ -55,6 +55,10 @@ export function useAttentionBadge(companyId: string | null | undefined, options: * only. Reads the shared board access snapshot; false until it loads. */ export function useAttentionEveryoneView(companyId: string | null | undefined) { + return useAttentionEveryoneAccess(companyId).everyone; +} + +export function useAttentionEveryoneAccess(companyId: string | null | undefined) { const { userId } = useCoordinatorWorkspaceEnabled(); const boardAccess = useQuery({ queryKey: queryKeys.access.currentBoardAccess, @@ -62,7 +66,10 @@ export function useAttentionEveryoneView(companyId: string | null | undefined) { enabled: !!companyId && !!userId, staleTime: 30_000, }); - return boardAccess.data?.userId === userId && attentionEveryoneViewAllowed(companyId, boardAccess.data); + return { + everyone: boardAccess.data?.userId === userId && attentionEveryoneViewAllowed(companyId, boardAccess.data), + settled: boardAccess.isSuccess || boardAccess.isError || boardAccess.failureCount > 0, + }; } /** diff --git a/ui/src/lib/coordinator-attention.test.ts b/ui/src/lib/coordinator-attention.test.ts index 3d0db2d0a2d..2107cbc2151 100644 --- a/ui/src/lib/coordinator-attention.test.ts +++ b/ui/src/lib/coordinator-attention.test.ts @@ -3,15 +3,21 @@ import { attentionReceiptText, type AttentionItem, type DecisionHistoryItem } fr import { COORDINATOR_RECENT_DECISION_MS, DECISION_HISTORY_OUTCOME_OPTIONS, + DEFAULT_NEEDS_YOU_TOOLBAR, coordinatorAudienceKey, coordinatorAssignee, + coordinatorAssigneeNeedsEveryone, coordinatorAssigneeTarget, coordinatorCardDetail, coordinatorCardTitle, decisionHistoryContext, decisionHistoryHeadline, + loadNeedsYouToolbar, + needsYouToolbarStorageKey, + openingCoordinatorAssignee, pendingDecisionTaskIds, recentDecisionReceipts, + saveNeedsYouToolbar, } from "./coordinator-attention"; describe("Coordinator attention projections", () => { @@ -123,4 +129,51 @@ describe("who a card is for (PAP-775)", () => { expect(coordinatorAssigneeTarget("user:scott", "scott")).toEqual({ view: "mine", forUserId: null }); expect(coordinatorAssigneeTarget("unassigned", "scott")).toEqual({ view: "unassigned", forUserId: null }); }); + + it("opens on All assignees for board members, Assigned to you for viewers, and honors kept choices they can open", () => { + expect(coordinatorAssigneeNeedsEveryone("all")).toBe(true); + expect(coordinatorAssigneeNeedsEveryone("user:dotta")).toBe(true); + expect(coordinatorAssigneeNeedsEveryone("me")).toBe(false); + expect(coordinatorAssigneeNeedsEveryone("unassigned")).toBe(false); + expect(coordinatorAssigneeNeedsEveryone("company")).toBe(false); + + expect(openingCoordinatorAssignee(null, true)).toBe("all"); + expect(openingCoordinatorAssignee(null, false)).toBe("me"); + expect(openingCoordinatorAssignee("me", true)).toBe("me"); + expect(openingCoordinatorAssignee("user:dotta", true)).toBe("user:dotta"); + expect(openingCoordinatorAssignee("user:dotta", false)).toBe("me"); + expect(openingCoordinatorAssignee("all", false)).toBe("me"); + expect(openingCoordinatorAssignee("company", false)).toBe("company"); + }); + + const memoryStorage = () => { + const values = new Map(); + return { values, getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } }; + }; + + it("saves and restores Needs You toolbar state per company and user", () => { + const storage = memoryStorage(); + const mine = needsYouToolbarStorageKey("company", "scott"); + const kept = { assignee: "user:dotta" as const, agentId: "agent-cos", project: { id: "project-web", name: "Website" }, groupBy: "project" as const }; + saveNeedsYouToolbar(mine, kept, storage); + expect(loadNeedsYouToolbar(mine, storage)).toEqual(kept); + expect(loadNeedsYouToolbar(needsYouToolbarStorageKey("company", "dotta"), storage)).toEqual(DEFAULT_NEEDS_YOU_TOOLBAR); + expect(loadNeedsYouToolbar(needsYouToolbarStorageKey("other-company", "scott"), storage)).toEqual(DEFAULT_NEEDS_YOU_TOOLBAR); + saveNeedsYouToolbar(null, kept, storage); + expect(storage.values.size).toBe(1); + }); + + it("reads anything unreadable as its default, field by field", () => { + const storage = memoryStorage(); + const key = needsYouToolbarStorageKey("company", "scott"); + storage.setItem(key!, JSON.stringify({ assignee: "user:", agentId: 7, project: { id: "", name: "Gone" }, groupBy: "severity" })); + expect(loadNeedsYouToolbar(key, storage)).toEqual(DEFAULT_NEEDS_YOU_TOOLBAR); + storage.setItem(key!, JSON.stringify({ assignee: "company", project: { id: "project-web" }, groupBy: "agent" })); + expect(loadNeedsYouToolbar(key, storage)).toEqual({ ...DEFAULT_NEEDS_YOU_TOOLBAR, assignee: "company", groupBy: "agent" }); + storage.setItem(key!, "{not json"); + expect(loadNeedsYouToolbar(key, storage)).toEqual(DEFAULT_NEEDS_YOU_TOOLBAR); + const denied = { getItem: () => { throw new Error("denied"); }, setItem: () => { throw new Error("denied"); } }; + expect(loadNeedsYouToolbar(key, denied)).toEqual(DEFAULT_NEEDS_YOU_TOOLBAR); + expect(() => saveNeedsYouToolbar(key, DEFAULT_NEEDS_YOU_TOOLBAR, denied)).not.toThrow(); + }); }); diff --git a/ui/src/lib/coordinator-attention.ts b/ui/src/lib/coordinator-attention.ts index 02a0622d639..86247060b94 100644 --- a/ui/src/lib/coordinator-attention.ts +++ b/ui/src/lib/coordinator-attention.ts @@ -152,3 +152,69 @@ export function coordinatorAssigneeTarget(assignee: CoordinatorAssignee, current if (assignee.startsWith("user:")) return { view: "all", forUserId: assignee.slice(5) }; return { view: assignee as "all" | "unassigned" | "company", forUserId: null }; } + +export function coordinatorAssigneeNeedsEveryone(assignee: CoordinatorAssignee) { + return assignee === "all" || assignee.startsWith("user:"); +} + +export function openingCoordinatorAssignee(kept: CoordinatorAssignee | null, everyone: boolean): CoordinatorAssignee { + if (kept && (everyone || !coordinatorAssigneeNeedsEveryone(kept))) return kept; + return everyone ? "all" : "me"; +} + +export type NeedsYouGroup = "type" | "none" | "task" | "agent" | "project"; +const NEEDS_YOU_GROUPS: readonly NeedsYouGroup[] = ["type", "task", "agent", "project", "none"]; + +export interface NeedsYouToolbar { + assignee: CoordinatorAssignee | null; + agentId: string; + project: { id: string; name: string } | null; + groupBy: NeedsYouGroup; +} + +export const DEFAULT_NEEDS_YOU_TOOLBAR: NeedsYouToolbar = { assignee: null, agentId: "", project: null, groupBy: "type" }; + +export function needsYouToolbarStorageKey(companyId: string | null | undefined, userId: string | null | undefined): string | null { + return companyId && userId ? `paperclip:needs-you-toolbar:v1:${encodeURIComponent(companyId)}:${encodeURIComponent(userId)}` : null; +} + +type ToolbarStorage = Pick; +function browserStorage(): ToolbarStorage | null { + try { + return typeof localStorage === "undefined" ? null : localStorage; + } catch { + return null; + } +} + +function isCoordinatorAssignee(value: unknown): value is CoordinatorAssignee { + return value === "me" || value === "all" || value === "unassigned" || value === "company" + || (typeof value === "string" && value.startsWith("user:") && value.length > "user:".length); +} + +export function loadNeedsYouToolbar(key: string | null, storage: ToolbarStorage | null = browserStorage()): NeedsYouToolbar { + if (!key) return DEFAULT_NEEDS_YOU_TOOLBAR; + try { + const saved: unknown = JSON.parse(storage?.getItem(key) ?? "null"); + if (!saved || typeof saved !== "object") return DEFAULT_NEEDS_YOU_TOOLBAR; + const { assignee, agentId, project, groupBy } = saved as Record; + const { id, name } = (project && typeof project === "object" ? project : {}) as Record; + return { + assignee: isCoordinatorAssignee(assignee) ? assignee : null, + agentId: typeof agentId === "string" ? agentId : "", + project: typeof id === "string" && id && typeof name === "string" ? { id, name } : null, + groupBy: NEEDS_YOU_GROUPS.find((group) => group === groupBy) ?? "type", + }; + } catch { + return DEFAULT_NEEDS_YOU_TOOLBAR; + } +} + +export function saveNeedsYouToolbar(key: string | null, toolbar: NeedsYouToolbar, storage: ToolbarStorage | null = browserStorage()): void { + if (!key) return; + try { + storage?.setItem(key, JSON.stringify(toolbar)); + } catch { + return; + } +}