From 0774cb90cd6aec4d35a4baa580938287e1acf573 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:31:54 -0600 Subject: [PATCH] feat(ui): open Needs You on All assignees and keep its filters between visits (#22964) 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 Coordinator Inbox (Needs You, `/decisions`) shows the decisions and problems that wait for a person > - Its toolbar has agent, project, and assignee filters, plus a grouping control > - Today the page always opens on "Assigned to you", so a board member who reviews work for the whole company must select "All assignees" again on every visit > - The page also forgets the agent, project, and grouping choices after a reload or on a new visit > - This pull request opens the page on "All assignees" for a person who can see everyone's cards, and saves the toolbar choices in local storage per company and person > - The benefit is that Inbox opens on the company-wide queue by default for board members and keeps each person's filters across visits with no repeated clicks ## Linked Issues or Issue Description Supersedes #21255 (rebased onto current `master` after InboxFilter dropdown menus and Waiting/History Inbox folders landed). Related: Refs #20959, Refs #22675, Refs #22846. **What existing behavior does this improve?** The Coordinator Inbox / Needs You page (`/decisions`) and the filters in its toolbar. **Current behavior** - The page always opens on "Assigned to you". To see everyone's cards, a board member must select "All assignees" on every visit. - The agent, project, and grouping choices stay in memory only. A reload or return visit resets them. **Proposed behavior** - A person who can see everyone's cards (a board member) opens Needs You on "All assignees". A viewer still opens on "Assigned to you". - The page saves the assignee, agent, project, and grouping choices for each company and person in local storage, and restores them on reload or return visits. - A link that names a view (for example `?view=company`) still opens that view without overwriting the saved choice. - Switching to Waiting or visiting `?folder=waiting` directly loads the Waiting feed immediately without waiting for board access and keeps Waiting filters isolated from Needs You's saved filters. **Reason and benefit** Operators who review work across the whole company open Inbox many times each day. Opening on "All assignees" by default and keeping filter choices eliminates repeated clicks on every visit. **Breaking changes** None for the API or stored server data. The initial default view on Needs You changes from "Assigned to you" to "All assignees" for board members. See Risks. ## What Changed - `ui/src/lib/coordinator-attention.ts`: Add `openingCoordinatorAssignee`, `coordinatorAssigneeNeedsEveryone`, `needsYouToolbarStorageKey`, `loadNeedsYouToolbar`, `saveNeedsYouToolbar`, `DEFAULT_NEEDS_YOU_TOOLBAR`, and toolbar types. Unreadable local storage fields fall back to their defaults one field at a time. - `ui/src/hooks/useAttentionViews.ts`: Add `useAttentionEveryoneAccess` returning `{ everyone, settled }`, with `useAttentionEveryoneView` delegating to it. - `ui/src/components/InboxFilter.tsx`: Add optional `disabled` prop and forward it to the trigger button so the assignee filter stays disabled while board access is settling. - `ui/src/components/coordinator/CoordinatorNeedsYou.tsx`: - Open Needs You on the saved assignee when no `view` query parameter is present, defaulting to "All assignees" for board members and "Assigned to you" for viewers. - Always write the selected assignee's view to the URL (including `?view=mine`), and clear the `view` param on "Back to Needs You" from Archived so the saved assignee applies again. - Persist agent, project, assignee, and grouping changes by merging only the changed field onto stored preferences. A `?decisionId=` link clears filters only for that visit without erasing stored filters, and clears a kept agent even before the agent list loads. - Apply a kept agent filter only when the loaded agent list includes that agent, and keep a saved project visible in the project menu even when it has no open cards (preserving `inboxProjectOptions` for folded provider-limit obligations). - Delay the initial feed request until board access settles when the opening view requires Everyone access, avoiding a flash of "Assigned to you". Direct `?folder=waiting` visits bypass that wait and keep Waiting's agent/project filters isolated from Needs You's saved filters. - Read `viewCounts` from the active feed instead of calling `useAttentionBadge` a second time. - `ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx` and `ui/src/lib/coordinator-attention.test.ts`: Add unit and jsdom integration regression tests covering default opening views, sticky filters, viewer fallback, board-access loading gate, missing/failed agent list, empty saved project, decision links, Archived return, and Waiting folder isolation. - `tests/e2e/coordinator-inbox-views.spec.ts`: Update the local-board desktop Inbox check to assert "All assignees" on open, verify assignee and grouping persistence across navigation and reload, and confirm wrapped toolbar alignment at 1024x720. - `doc/PRODUCT.md`: Document the new default opening view and per-person/per-company saved toolbar choices. ## Verification - RED before fix (on base `2d065677959b585065ff3fec8718156a4cf6f41d`): `cd ui && npx vitest run src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx` failed (`11 failed | 1 passed (12)`), proving Needs You opened on `me` instead of `all` and did not persist filters. - GREEN after fix: `cd ui && npx vitest run src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx src/lib/coordinator-attention.test.ts src/hooks/useAttentionViews.test.tsx src/lib/attention-views.test.ts src/lib/attention-obligations.test.ts src/components/coordinator/InboxProviderLimit.test.tsx` -> **6 passed (6), 49 passed (49)**. - `pnpm --filter @paperclipai/ui typecheck` -> **PASS**. - `pnpm check:token-gates` -> **All 4 gates CLEAN**. - `node scripts/check-test-budget.mjs --files ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx ui/src/lib/coordinator-attention.test.ts` -> **PASS**. - `pnpm verify --base 2d065677959b585065ff3fec8718156a4cf6f41d` -> exit 2 (broad input `tests/e2e/coordinator-inbox-views.spec.ts`); PR CI supplies full coverage. - Playwright E2E (`PAPERCLIP_E2E_PORT=3255 npx playwright test --config tests/e2e/playwright.config.ts tests/e2e/coordinator-inbox-views.spec.ts`) against freshly built production UI in `local_trusted` mode -> **2 passed (desktop + mobile)**, proving Needs You opens on "All assignees", persists assignee and grouping across navigation and reload, and preserves 1024x720 wrapped toolbar alignment. ## Risks - Behavioral shift: a board member's Needs You page now opens on "All assignees" instead of "Assigned to you". The sidebar badge still counts personal ("For you") items. - Toolbar preferences are stored in browser local storage (`paperclip:needs-you-toolbar:v1::`), so a different browser or device starts from the default. - While board access is still loading on an Everyone-requiring opening view, the feed waits for board access before fetching and the assignee menu stays disabled; if board access fails to load, the page falls back safely to "Assigned to you". - The classic (non-Coordinator) Decisions page is unchanged. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Rebase, conflict resolution, InboxFilter/Waiting-folder integration, E2E expansion, and verification: Gemini 3.1 Pro by Google DeepMind (in Antigravity, with tool use, shell execution, Vitest, and Playwright). - Original implementation in #21255: Claude Opus 5.5 (`claude-opus-5-5`) by Anthropic. ## 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: lucktastic <13757243+lucktastic@users.noreply.github.com> Co-authored-by: Paperclip --- doc/PRODUCT.md | 5 +- tests/e2e/coordinator-inbox-views.spec.ts | 15 + ui/src/components/InboxFilter.tsx | 5 +- .../CoordinatorNeedsYou.toolbar.test.tsx | 369 ++++++++++++++++++ .../coordinator/CoordinatorNeedsYou.tsx | 103 +++-- ui/src/hooks/useAttentionViews.ts | 9 +- ui/src/lib/coordinator-attention.test.ts | 53 +++ ui/src/lib/coordinator-attention.ts | 66 ++++ 8 files changed, 585 insertions(+), 40 deletions(-) create mode 100644 ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx 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; + } +}