mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
feat(inbox): rebuild compact cards and share task review controls (#20961)
## Thinking Path > - Paperclip helps people manage AI agents and their work. > - The inbox collects decisions, requests, and updates for the people in a company. > - People need a clear personal queue and a consistent way to answer each request. > - Repeated headings, inconsistent card actions, and separate review flows make that work harder. > - This pull request connects the inbox UI to the routing foundation in #20959. > - Compact cards use shared task controls and open supporting work in a side panel. > - People can answer, claim, transfer, archive, and inspect outcomes from one place. ## Linked Issues or Issue Description **What existing behavior does this improve?** The inbox cards, personal views, shared task controls, and decision history. **Subsystem affected** UI. This PR targets master and uses the routing foundation merged in #20959. **Current behavior** The inbox repeats headings and counts. Cards have different layouts and action placement. The requester can repeat the signed-in person's name. Review and question controls differ between the inbox and task thread. **Proposed behavior** Open Assigned to you by default. Show one count line above the cards. Use a compact card layout with consistent actions and supporting details. Show the requester's avatar and name only when they differ from the signed-in person. Share question controls, including a radio option for Other that reveals a text field when selected. **Reason and benefit** People can scan their queue and complete requests without losing the surrounding task or creating separate drafts for the same review. **Breaking changes** The default inbox view becomes personal. The all-assignee and shared views remain available. Card close menus distinguish personal archive and snooze from shared withdrawal. **Additional context** Refs #20959, #19363, and #19520. Refs #20268 for related actionable-request work. This stack adds personal routing and shared controls. ROADMAP.md includes Multiple Human Users and Agent Reviews and Approvals. ## What Changed - Add personal, unassigned, company, all-assignee, and archived inbox views. Add claim, transfer, personal close actions, receipts, and history controls. - Use compact decision cards with a single count line, one-pixel borders, and equal space above, below, and to the right of each primary action. - Open artifacts and synchronized confirmation/approval controls in a shared side panel. Share their revision drafts and action state with the task thread. Other requests keep one editable form on the inbox card while reviewing an artifact. - Make Other match the question options and reveal its field only when selected. Apply this to inbox and task question cards. - Hide self-requester labels, space agent avatars, and use the standard canceled status icon for withdrawn requests. - Use connector logos in connector cards. Keep the connector promotion background and sidebar border continuous. - Add company and project decision-owner controls and document the updated inbox behavior. ## Verification - The complete [GitHub Actions CI matrix](https://github.com/paperclipai/paperclip/actions/runs/43141559641) passes on `8d81a75e49b518fff6b6ff4c23dd67979b0b97ee` (Linux/Node 24: typecheck, build, general and serialized tests, Runner support, browser shards, and aggregate gates). Greptile is 5/5 on that exact head with zero open findings, and the security scan passes. - Local UI typechecking passes. Eight focused suites pass 382 tests: 236 inbox/review/question/connector tests plus all 146 composer tests. Regressions passed red to green for attachment links, prompt rendering, single-form artifact review, connector scope copy, accessible headings, and the composer test harness's missing theme provider. The final commit changes only that test harness; production code is unchanged from `59d015833f`. - Browser acceptance on the production implementation confirms preserved selected answers with one editable question form, accessible Markdown prompts, inert image references, accurate connector scope copy, native PDF downloads, image sidebar previews, and Open file requesting the attachment endpoint while preserving the inbox URL. Request reads and file responses were intercepted; no question answers were written. The preview is healthy on the final head. - Visual and interaction checks cover Other radio behavior in both themes and on mobile, the loaded Google Calendar logo, and 20px above, below, and to the right of the primary action across all 23 visible cards. The affected desktop/mobile navigation and sidebar specs pass locally and in the final CI browser matrix. - Real-editor browser checks confirm Ctrl/Cmd+Enter cannot bypass another person's confirmation. Cancel preserves the draft and unlocks silently; Continue submits once. Approval write failures remain visible. - `pnpm verify` returns exit 2 because DESIGN.md requires broader coverage; the final full CI matrix supplies every requested gate. Maps and Storybook catalog structural checks pass. The routing foundation #20959 merged after passing 249 database tests, server typechecking, full CI, Greptile 5/5, and security scanning. Its backend and SDK registry are preserved. - Demo data is retained for testing; database suites and browser specs use separate disposable databases. ## Risks - The inbox uses the routing contracts merged in #20959. Personal filters and history affect shared task entry points; the affected controls are included in local regression coverage and full CI. - Personal defaults and close-menu wording change inbox behavior. Existing resolver permissions still control shared actions. - Shared revision state and live invalidation affect two surfaces. Focused tests cover draft synchronization, action locks, and incoming updates. - Visual changes use the existing design tokens and component primitives. ## Model Used OpenAI GPT-6 through Codex. Used repository tools, code execution, and browser checks. This session does not expose a more specific runtime model ID or its context-window size. ## 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 described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal Paperclip ticket id - [x] I have run focused 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: Scott Tong <scott@scottsmbpm5max.lan> Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
85 files changed
+9492
-1043
No files matched your search
@@ -1,7 +1,8 @@
|
||||
import { ChangeEvent, useEffect, useState } from "react";
|
||||
import { QueryErrorState, useQueryView } from "@/components/QueryView";
|
||||
import { ChangeEvent, type ReactNode, useEffect, useId, useState } from "react";
|
||||
import { AgentObservabilitySettingsSection } from "../components/observability/AgentObservabilitySettings";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
type InteractionResolverGovernance,
|
||||
type IssueThreadInteractionKind,
|
||||
@@ -14,10 +15,12 @@ import { resolveCompanyArchiveDeparture } from "../lib/company-selection";
|
||||
import { cloudPortfolioManageUrl } from "../lib/cloudLinks";
|
||||
import { navigateTopLevel } from "@/lib/browserNavigation";
|
||||
import { companiesApi } from "../api/companies";
|
||||
import { accessApi } from "../api/access";
|
||||
import { assetsApi } from "../api/assets";
|
||||
import { describeError } from "@/api/errors";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { NativeSelect } from "@/components/ui/select";
|
||||
import { SlidersHorizontal } from "lucide-react";
|
||||
import {
|
||||
InteractionGovernancePanel,
|
||||
@@ -28,6 +31,7 @@ import {
|
||||
import { CompanyPatternIcon } from "../components/CompanyPatternIcon";
|
||||
import {
|
||||
Field,
|
||||
HintIcon,
|
||||
ToggleField,
|
||||
} from "../components/agent-config-primitives";
|
||||
import { InstanceGeneralSettings } from "./InstanceGeneralSettings";
|
||||
@@ -54,14 +58,24 @@ export function CompanySettings() {
|
||||
const [logoUploadError, setLogoUploadError] = useState<string | null>(null);
|
||||
const [governance, setGovernance] = useState<InteractionResolverGovernance>({});
|
||||
|
||||
// Sync local state from selected company
|
||||
// Sync local state from the selected company. Keyed on the saved values, not
|
||||
// the company object: the sections that save on change (Hiring, Decisions,
|
||||
// governance, logo) refetch the company list, and that fresh object must not
|
||||
// wipe an unsaved name or description draft.
|
||||
const savedName = selectedCompany?.name ?? null;
|
||||
const savedDescription = selectedCompany?.description ?? "";
|
||||
const savedLogoUrl = selectedCompany?.logoUrl ?? "";
|
||||
const savedGovernance = selectedCompany?.interactionResolverGovernance;
|
||||
useEffect(() => {
|
||||
if (!selectedCompany) return;
|
||||
setCompanyName(selectedCompany.name);
|
||||
setDescription(selectedCompany.description ?? "");
|
||||
setLogoUrl(selectedCompany.logoUrl ?? "");
|
||||
setGovernance(selectedCompany.interactionResolverGovernance ?? {});
|
||||
}, [selectedCompany]);
|
||||
if (savedName === null) return;
|
||||
setCompanyName(savedName);
|
||||
setDescription(savedDescription);
|
||||
}, [selectedCompanyId, savedName, savedDescription]);
|
||||
useEffect(() => {
|
||||
if (savedName === null) return;
|
||||
setLogoUrl(savedLogoUrl);
|
||||
setGovernance(savedGovernance ?? {});
|
||||
}, [selectedCompanyId, savedName, savedLogoUrl, savedGovernance]);
|
||||
|
||||
const generalDirty =
|
||||
!!selectedCompany &&
|
||||
@@ -88,6 +102,41 @@ export function CompanySettings() {
|
||||
}
|
||||
});
|
||||
|
||||
// Members populate the default decision owner and budget owner pickers.
|
||||
// Ownerless "Needs You" cards route to the default decision owner's "For
|
||||
// you" list; clearing it sends them to the claimable Unassigned pool
|
||||
// (PAP-749 task 1d-lite). A budget hard stop also goes to the budget owner,
|
||||
// and Company keeps showing it (task 1d).
|
||||
const membersQuery = useQuery({
|
||||
queryKey: queryKeys.access.companyMembers(selectedCompanyId ?? ""),
|
||||
queryFn: () => accessApi.listMembers(selectedCompanyId!),
|
||||
enabled: !!selectedCompanyId,
|
||||
});
|
||||
|
||||
// Each owner saves on change with only its own field, so neither belongs to
|
||||
// the General draft or its "Save changes" button. Waiting for the refetch
|
||||
// keeps the picker on the new owner instead of flashing back to the old one.
|
||||
async function saveDefaultDecisionOwner(defaultDecisionOwnerUserId: string | null) {
|
||||
const company = await companiesApi.update(selectedCompanyId!, { defaultDecisionOwnerUserId });
|
||||
await queryClient.invalidateQueries({ queryKey: queryKeys.companies.all });
|
||||
return company;
|
||||
}
|
||||
|
||||
async function saveBudgetOwner(budgetOwnerUserId: string | null) {
|
||||
const company = await companiesApi.update(selectedCompanyId!, { budgetOwnerUserId });
|
||||
await queryClient.invalidateQueries({ queryKey: queryKeys.companies.all });
|
||||
return company;
|
||||
}
|
||||
|
||||
const membersView = useQueryView(membersQuery);
|
||||
const memberOptions = (membersQuery.data?.members ?? [])
|
||||
.filter((member) => member.user?.id)
|
||||
.map((member) => (
|
||||
<option key={member.user!.id} value={member.user!.id}>
|
||||
{member.user!.name || member.user!.email || member.user!.id}
|
||||
</option>
|
||||
));
|
||||
|
||||
const governanceMutation = useMutation({
|
||||
mutationFn: (next: InteractionResolverGovernance) =>
|
||||
companiesApi.update(selectedCompanyId!, { interactionResolverGovernance: next }),
|
||||
@@ -351,14 +400,57 @@ export function CompanySettings() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Interaction governance */}
|
||||
<InteractionGovernancePanel
|
||||
governance={governance}
|
||||
onChange={handleGovernanceChange}
|
||||
isPending={governanceMutation.isPending}
|
||||
errorMessage={governanceMutation.error ? describeError(governanceMutation.error).body : null}
|
||||
/>
|
||||
{/* Decisions */}
|
||||
<div className="max-w-2xl space-y-4" data-testid="company-settings-decisions-section">
|
||||
<div className="space-y-1">
|
||||
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||
Decisions
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Each owner saves as soon as you choose it.
|
||||
</p>
|
||||
</div>
|
||||
{membersView.kind === "error" ? <QueryErrorState error={membersView.error} onRetry={membersView.retry} /> : null}
|
||||
<DecisionOwnerField
|
||||
label="Default decision owner"
|
||||
hint="When a card needs a person but has no explicit owner, it goes to this user's For you list. Leave as Unassigned to keep ownerless cards in the claimable pool."
|
||||
testId="company-settings-default-decision-owner"
|
||||
unsetLabel="Unassigned (no default owner)"
|
||||
savedUserId={selectedCompany.defaultDecisionOwnerUserId ?? null}
|
||||
memberOptions={memberOptions}
|
||||
membersLoading={membersQuery.isLoading}
|
||||
fallbackError="Couldn't save the default decision owner."
|
||||
save={saveDefaultDecisionOwner}
|
||||
/>
|
||||
<DecisionOwnerField
|
||||
label="Budget owner"
|
||||
hint="A budget hard stop also goes to this user's For you list, with Raise limit and Keep paused. The Company view still shows it to every operator."
|
||||
testId="company-settings-budget-owner"
|
||||
unsetLabel="No budget owner (Company view only)"
|
||||
savedUserId={selectedCompany.budgetOwnerUserId ?? null}
|
||||
memberOptions={memberOptions}
|
||||
membersLoading={membersQuery.isLoading}
|
||||
fallbackError="Couldn't save the budget owner."
|
||||
save={saveBudgetOwner}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Interaction governance. Held to the form column like the sections
|
||||
above; the wrapper scrolls rather than letting the policy grid push
|
||||
past the column when the content area is narrow. The padding keeps
|
||||
the selects' focus rings inside the scroll box, and the negative
|
||||
inline margin keeps the panel aligned with the other sections. */}
|
||||
<div
|
||||
className="-mx-1 min-w-0 max-w-2xl overflow-x-auto p-1"
|
||||
data-testid="company-settings-interaction-governance-frame"
|
||||
>
|
||||
<InteractionGovernancePanel
|
||||
governance={governance}
|
||||
onChange={handleGovernanceChange}
|
||||
isPending={governanceMutation.isPending}
|
||||
errorMessage={governanceMutation.error ? describeError(governanceMutation.error).body : null}
|
||||
/>
|
||||
</div>
|
||||
<AgentObservabilitySettingsSection companyId={selectedCompanyId!} />
|
||||
|
||||
<InstanceGeneralSettings embedded />
|
||||
@@ -407,3 +499,77 @@ export function CompanySettings() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One Decisions owner picker. It saves on change, on its own, so the page's
|
||||
* General "Save changes" never carries it. A real `<label htmlFor>` names the
|
||||
* select, and the line under it reports saving, saved, or the server's error
|
||||
* (for example the 422 for an owner who is not an active member).
|
||||
*/
|
||||
function DecisionOwnerField({
|
||||
label,
|
||||
hint,
|
||||
testId,
|
||||
unsetLabel,
|
||||
savedUserId,
|
||||
memberOptions,
|
||||
membersLoading,
|
||||
fallbackError,
|
||||
save,
|
||||
}: {
|
||||
label: string;
|
||||
hint: string;
|
||||
testId: string;
|
||||
unsetLabel: string;
|
||||
savedUserId: string | null;
|
||||
memberOptions: ReactNode;
|
||||
membersLoading: boolean;
|
||||
fallbackError: string;
|
||||
save: (userId: string | null) => Promise<unknown>;
|
||||
}) {
|
||||
const controlId = useId();
|
||||
const errorId = `${controlId}-error`;
|
||||
const mutation = useMutation({
|
||||
mutationFn: save,
|
||||
// Quick successive picks save in order, so the last choice is what sticks.
|
||||
scope: { id: `company-settings:${testId}` },
|
||||
});
|
||||
// Show the choice while it saves. Otherwise show what the server holds, so
|
||||
// a rejected owner snaps back beside its error.
|
||||
const value = mutation.isPending ? (mutation.variables ?? "") : (savedUserId ?? "");
|
||||
const errorMessage = mutation.error ? describeError(mutation.error).body ?? fallbackError : null;
|
||||
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<label htmlFor={controlId} className="text-xs text-muted-foreground">
|
||||
{label}
|
||||
</label>
|
||||
<HintIcon text={hint} />
|
||||
</div>
|
||||
<NativeSelect
|
||||
id={controlId}
|
||||
data-testid={testId}
|
||||
value={value}
|
||||
// Not disabled while saving: disabling would drop keyboard focus.
|
||||
disabled={membersLoading}
|
||||
aria-busy={mutation.isPending || undefined}
|
||||
aria-invalid={errorMessage ? true : undefined}
|
||||
aria-describedby={errorMessage ? errorId : undefined}
|
||||
onChange={(event) => mutation.mutate(event.target.value === "" ? null : event.target.value)}
|
||||
>
|
||||
<option value="">{unsetLabel}</option>
|
||||
{memberOptions}
|
||||
</NativeSelect>
|
||||
{errorMessage ? (
|
||||
<p id={errorId} role="alert" className="text-xs text-destructive">
|
||||
{errorMessage}
|
||||
</p>
|
||||
) : (
|
||||
<p role="status" className="min-h-4 text-xs text-muted-foreground">
|
||||
{mutation.isPending ? "Saving…" : mutation.isSuccess ? "Saved" : null}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { CompanySettings } from "./CompanySettings";
|
||||
|
||||
const mockCompaniesApi = vi.hoisted(() => ({
|
||||
update: vi.fn(),
|
||||
archive: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockAccessApi = vi.hoisted(() => ({
|
||||
listMembers: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockAssetsApi = vi.hoisted(() => ({
|
||||
uploadCompanyLogo: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockSetBreadcrumbs = vi.hoisted(() => vi.fn());
|
||||
const mockSetSelectedCompanyId = vi.hoisted(() => vi.fn());
|
||||
|
||||
// A tiny external store stands in for the company list query, so a save can
|
||||
// hand the page a fresh company object the way a real refetch does.
|
||||
const companyStore = vi.hoisted(() => {
|
||||
type Company = Record<string, unknown>;
|
||||
const initial: Company = {
|
||||
id: "company-1",
|
||||
name: "Acme Robotics",
|
||||
description: null,
|
||||
status: "active",
|
||||
issuePrefix: "ACM",
|
||||
brandColor: null,
|
||||
logoUrl: null,
|
||||
attachmentMaxBytes: null,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
interactionResolverGovernance: {},
|
||||
defaultDecisionOwnerUserId: null,
|
||||
budgetOwnerUserId: "user-1",
|
||||
};
|
||||
let company: Company = initial;
|
||||
const listeners = new Set<() => void>();
|
||||
return {
|
||||
initial,
|
||||
get: () => company,
|
||||
set(next: Company) {
|
||||
company = next;
|
||||
for (const listener of listeners) listener();
|
||||
},
|
||||
subscribe(listener: () => void) {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../api/companies", () => ({ companiesApi: mockCompaniesApi }));
|
||||
vi.mock("../api/access", () => ({ accessApi: mockAccessApi }));
|
||||
vi.mock("../api/assets", () => ({ assetsApi: mockAssetsApi }));
|
||||
|
||||
vi.mock("../context/BreadcrumbContext", () => ({
|
||||
useBreadcrumbs: () => ({ setBreadcrumbs: mockSetBreadcrumbs }),
|
||||
}));
|
||||
|
||||
vi.mock("../context/CompanyContext", async () => {
|
||||
const { useSyncExternalStore } = await import("react");
|
||||
return {
|
||||
useCompany: () => {
|
||||
const company = useSyncExternalStore(companyStore.subscribe, companyStore.get);
|
||||
return {
|
||||
companies: [company],
|
||||
selectedCompany: company,
|
||||
selectedCompanyId: company.id,
|
||||
setSelectedCompanyId: mockSetSelectedCompanyId,
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// The governance panel has its own tests; here only its frame matters.
|
||||
vi.mock("../components/InteractionGovernancePanel", () => ({
|
||||
InteractionGovernancePanel: () => <div data-testid="interaction-governance-panel" />,
|
||||
applyGovernanceChange: (governance: unknown) => governance,
|
||||
}));
|
||||
|
||||
// These sections own their own queries (and their own "Save changes").
|
||||
vi.mock("../components/observability/AgentObservabilitySettings", () => ({
|
||||
AgentObservabilitySettingsSection: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("./InstanceGeneralSettings", () => ({
|
||||
InstanceGeneralSettings: () => null,
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const MEMBERS = {
|
||||
members: [
|
||||
{ id: "membership-1", user: { id: "user-1", name: "Ada Lovelace", email: "ada@example.test" } },
|
||||
{ id: "membership-2", user: { id: "user-2", name: "Grace Hopper", email: "grace@example.test" } },
|
||||
],
|
||||
};
|
||||
|
||||
async function flushReact() {
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 0));
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForAssertion(assertion: () => void) {
|
||||
let lastError: unknown;
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
await flushReact();
|
||||
try {
|
||||
assertion();
|
||||
return;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
describe("CompanySettings Decisions section", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root | null = null;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
companyStore.set({ ...companyStore.initial });
|
||||
mockAccessApi.listMembers.mockResolvedValue(MEMBERS);
|
||||
// Mirrors the server: the PATCH answers with the updated company, and the
|
||||
// refetch then carries it to the page.
|
||||
mockCompaniesApi.update.mockImplementation(
|
||||
async (_companyId: string, patch: Record<string, unknown>) => {
|
||||
await Promise.resolve();
|
||||
const next = { ...companyStore.get(), ...patch };
|
||||
companyStore.set(next);
|
||||
return next;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (root) flushSync(() => root!.unmount());
|
||||
root = null;
|
||||
container.remove();
|
||||
document.body.innerHTML = "";
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
async function render() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
// CloudAccessGate owns the health fetch in the app.
|
||||
queryClient.setQueryData(queryKeys.health, { status: "ok", cloud: null });
|
||||
root = createRoot(container);
|
||||
flushSync(() => {
|
||||
root!.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TooltipProvider>
|
||||
<MemoryRouter>
|
||||
<CompanySettings />
|
||||
</MemoryRouter>
|
||||
</TooltipProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
// Members fill the pickers before anyone can choose.
|
||||
await waitForAssertion(() => {
|
||||
expect(getByLabelText("Budget owner").querySelectorAll("option")).toHaveLength(3);
|
||||
});
|
||||
}
|
||||
|
||||
/** The control a `<label>` with exactly this text names via `htmlFor`. */
|
||||
function getByLabelText(text: string): HTMLSelectElement {
|
||||
const label = Array.from(container.querySelectorAll("label")).find(
|
||||
(element) => element.textContent?.trim() === text,
|
||||
);
|
||||
expect(label, `label "${text}"`).toBeDefined();
|
||||
expect(label!.htmlFor).not.toBe("");
|
||||
const control = document.getElementById(label!.htmlFor);
|
||||
expect(control).toBeInstanceOf(HTMLSelectElement);
|
||||
return control as HTMLSelectElement;
|
||||
}
|
||||
|
||||
function changeSelect(select: HTMLSelectElement, value: string) {
|
||||
// Go through the native setter so React sees a real change.
|
||||
Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, "value")!.set!.call(select, value);
|
||||
act(() => {
|
||||
select.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
}
|
||||
|
||||
function typeInto(input: HTMLInputElement, value: string) {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
|
||||
act(() => {
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
}
|
||||
|
||||
function statusFor(select: HTMLSelectElement) {
|
||||
return select.parentElement!.querySelector("[role=status]")?.textContent?.trim() ?? "";
|
||||
}
|
||||
|
||||
function alertFor(select: HTMLSelectElement) {
|
||||
return select.parentElement!.querySelector("[role=alert]")?.textContent?.trim() ?? null;
|
||||
}
|
||||
|
||||
function saveChangesButtons() {
|
||||
return Array.from(container.querySelectorAll("button")).filter(
|
||||
(button) => button.textContent?.trim() === "Save changes",
|
||||
);
|
||||
}
|
||||
|
||||
it("names both owner selects with an associated label", async () => {
|
||||
await render();
|
||||
const decisionOwner = getByLabelText("Default decision owner");
|
||||
const budgetOwner = getByLabelText("Budget owner");
|
||||
|
||||
expect(decisionOwner.dataset.testid).toBe("company-settings-default-decision-owner");
|
||||
expect(budgetOwner.dataset.testid).toBe("company-settings-budget-owner");
|
||||
expect(Array.from(decisionOwner.labels ?? []).map((label) => label.textContent)).toEqual([
|
||||
"Default decision owner",
|
||||
]);
|
||||
expect(budgetOwner.value).toBe("user-1");
|
||||
});
|
||||
|
||||
it("saves the default decision owner on change with only that field", async () => {
|
||||
await render();
|
||||
const decisionOwner = getByLabelText("Default decision owner");
|
||||
// Nothing is waiting on the page-level save before or after the change.
|
||||
expect(saveChangesButtons()).toHaveLength(0);
|
||||
|
||||
changeSelect(decisionOwner, "user-2");
|
||||
|
||||
await waitForAssertion(() => {
|
||||
expect(statusFor(getByLabelText("Default decision owner"))).toBe("Saved");
|
||||
});
|
||||
expect(mockCompaniesApi.update).toHaveBeenCalledTimes(1);
|
||||
expect(mockCompaniesApi.update).toHaveBeenCalledWith("company-1", {
|
||||
defaultDecisionOwnerUserId: "user-2",
|
||||
});
|
||||
expect(getByLabelText("Default decision owner").value).toBe("user-2");
|
||||
expect(saveChangesButtons()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("clears the budget owner with an explicit null", async () => {
|
||||
await render();
|
||||
|
||||
changeSelect(getByLabelText("Budget owner"), "");
|
||||
|
||||
await waitForAssertion(() => {
|
||||
expect(statusFor(getByLabelText("Budget owner"))).toBe("Saved");
|
||||
});
|
||||
expect(mockCompaniesApi.update).toHaveBeenCalledWith("company-1", { budgetOwnerUserId: null });
|
||||
expect(getByLabelText("Budget owner").value).toBe("");
|
||||
});
|
||||
|
||||
it("shows the server's rejection and keeps the saved owner", async () => {
|
||||
const message = "Budget owner must be an active member of this company";
|
||||
mockCompaniesApi.update.mockRejectedValueOnce(
|
||||
new ApiError(message, 422, { error: message }),
|
||||
);
|
||||
await render();
|
||||
|
||||
changeSelect(getByLabelText("Budget owner"), "user-2");
|
||||
|
||||
await waitForAssertion(() => {
|
||||
expect(alertFor(getByLabelText("Budget owner"))).toBe(message);
|
||||
});
|
||||
const budgetOwner = getByLabelText("Budget owner");
|
||||
expect(budgetOwner.value).toBe("user-1");
|
||||
expect(budgetOwner.getAttribute("aria-invalid")).toBe("true");
|
||||
expect(document.getElementById(budgetOwner.getAttribute("aria-describedby")!)?.textContent).toBe(
|
||||
message,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps an unsaved organization name draft when an owner saves", async () => {
|
||||
await render();
|
||||
const nameInput = container.querySelector<HTMLInputElement>("input[type=text]")!;
|
||||
typeInto(nameInput, "Acme Labs");
|
||||
expect(saveChangesButtons()).toHaveLength(1);
|
||||
|
||||
changeSelect(getByLabelText("Default decision owner"), "user-2");
|
||||
|
||||
await waitForAssertion(() => {
|
||||
expect(statusFor(getByLabelText("Default decision owner"))).toBe("Saved");
|
||||
});
|
||||
// The owner PATCH did not carry the draft, and the refetch did not wipe it.
|
||||
expect(mockCompaniesApi.update).toHaveBeenCalledWith("company-1", {
|
||||
defaultDecisionOwnerUserId: "user-2",
|
||||
});
|
||||
expect(container.querySelector<HTMLInputElement>("input[type=text]")!.value).toBe("Acme Labs");
|
||||
expect(saveChangesButtons()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("frames the interaction governance table to the form column", async () => {
|
||||
await render();
|
||||
const frame = container.querySelector("[data-testid=interaction-governance-panel]")!.parentElement!;
|
||||
expect(frame.dataset.testid).toBe("company-settings-interaction-governance-frame");
|
||||
expect(frame.className.split(" ")).toEqual(
|
||||
expect.arrayContaining(["min-w-0", "max-w-2xl", "overflow-x-auto"]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import { useBreadcrumbs } from "../context/BreadcrumbContext";
|
||||
import { useToastActions } from "../context/ToastContext";
|
||||
import { useInboxDismissals } from "../hooks/useInboxBadge";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { attentionObligationEvidence, foldAttentionObligations } from "../lib/attention-obligations";
|
||||
import {
|
||||
ATTENTION_AGING_DAYS,
|
||||
attentionIsAging,
|
||||
@@ -144,9 +145,11 @@ export function DecisionQueuePage() {
|
||||
[feed?.generatedAt],
|
||||
);
|
||||
|
||||
// One card for each obligation (PAP-749 Rule 11): evidence folds into its lead.
|
||||
const obligations = useMemo(() => foldAttentionObligations(feed?.items ?? []), [feed]);
|
||||
const activeItems = useMemo(
|
||||
() => (feed?.items ?? []).filter((item) => !(item.dismissal?.isActive ?? false)),
|
||||
[feed],
|
||||
() => obligations.cards.filter((item) => !(item.dismissal?.isActive ?? false)),
|
||||
[obligations],
|
||||
);
|
||||
|
||||
// Aging shelf (§4.4): items the server flags as idle past retention leave the
|
||||
@@ -321,9 +324,10 @@ export function DecisionQueuePage() {
|
||||
currentUserId={currentUserId}
|
||||
expanded={expandedId === item.id}
|
||||
onToggleExpand={handleToggleExpand}
|
||||
onDismiss={(next) => dismiss(next.dismissalKey)}
|
||||
onSnooze={(next, until) => snooze(next.dismissalKey, until)}
|
||||
onDismiss={(next) => dismiss(next.dismissalKey, next.changeFingerprint)}
|
||||
onSnooze={(next, until) => snooze(next.dismissalKey, until, next.changeFingerprint)}
|
||||
onExcluded={invalidate}
|
||||
evidence={attentionObligationEvidence(obligations, item)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -354,8 +358,9 @@ export function DecisionQueuePage() {
|
||||
currentUserId={currentUserId}
|
||||
expanded={expandedId === item.id}
|
||||
onToggleExpand={handleToggleExpand}
|
||||
onDismiss={(next) => dismiss(next.dismissalKey)}
|
||||
onSnooze={(next, until) => snooze(next.dismissalKey, until)}
|
||||
onDismiss={(next) => dismiss(next.dismissalKey, next.changeFingerprint)}
|
||||
onSnooze={(next, until) => snooze(next.dismissalKey, until, next.changeFingerprint)}
|
||||
evidence={attentionObligationEvidence(obligations, item)}
|
||||
/>
|
||||
))}
|
||||
</Curtain>
|
||||
@@ -431,6 +436,7 @@ function QueueItemRow({
|
||||
onDismiss,
|
||||
onSnooze,
|
||||
onExcluded,
|
||||
evidence,
|
||||
}: {
|
||||
item: AttentionItem;
|
||||
companyId: string;
|
||||
@@ -443,6 +449,7 @@ function QueueItemRow({
|
||||
onDismiss: (item: AttentionItem) => void;
|
||||
onSnooze: (item: AttentionItem, snoozedUntil: string) => void;
|
||||
onExcluded: () => void;
|
||||
evidence: readonly AttentionItem[];
|
||||
}) {
|
||||
const { pushToast } = useToastActions();
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -518,6 +525,7 @@ function QueueItemRow({
|
||||
agents={agents}
|
||||
showTriage
|
||||
currentUserId={currentUserId}
|
||||
evidence={evidence}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
+266
-140
@@ -2,17 +2,25 @@ import { Fragment, useCallback, useEffect, useMemo, useRef, useState, type React
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useCoordinatorWorkspaceEnabled } from "../hooks/useCoordinatorWorkspaceEnabled";
|
||||
import { CoordinatorNeedsYou } from "../components/coordinator/CoordinatorNeedsYou";
|
||||
import { CheckCircle2, Inbox } from "lucide-react";
|
||||
import type { Agent, AttentionItem, AttentionSubject } from "@paperclipai/shared";
|
||||
import { CheckCircle2, History, Inbox } from "lucide-react";
|
||||
import type { Agent, AttentionItem, AttentionPersonalView, AttentionSubject } from "@paperclipai/shared";
|
||||
import { useNavigate, useSearchParams } from "@/lib/router";
|
||||
import { accessApi } from "../api/access";
|
||||
import { attentionApi } from "../api/attention";
|
||||
import { agentsApi } from "../api/agents";
|
||||
import { authApi } from "../api/auth";
|
||||
import { decisionsApi } from "../api/decisions";
|
||||
import { useCompany } from "../context/CompanyContext";
|
||||
import { useBreadcrumbs } from "../context/BreadcrumbContext";
|
||||
import { useToastActions } from "../context/ToastContext";
|
||||
import { useInboxDismissals } from "../hooks/useInboxBadge";
|
||||
import { useAttentionBadge, useAttentionCloseActions, useAttentionEveryoneView, useClaimAttentionItem, useDismissAttentionReceipt } from "../hooks/useAttentionViews";
|
||||
import { ATTENTION_VIEW_PARAM, parseAttentionView } from "../lib/attention-views";
|
||||
import { buildCompanyUserLabelMap } from "../lib/company-members";
|
||||
import { AttentionReceiptList, AttentionUnassignedBanner, AttentionViewSwitch } from "../components/AttentionViews";
|
||||
import { AttentionSnoozedGroup, AttentionStaleGroup } from "../components/AttentionCloseMenu";
|
||||
import { DecisionHistoryPanel } from "../components/DecisionHistoryPanel";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "../components/ui/sheet";
|
||||
import { splitArchivedAttentionItems } from "../lib/attention-close";
|
||||
import { attentionObligationEvidence, foldAttentionObligations } from "../lib/attention-obligations";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import {
|
||||
ATTENTION_AGING_DAYS,
|
||||
@@ -51,9 +59,6 @@ import { DecisionDateChips, type AttentionCustomRange } from "../components/Deci
|
||||
import { DecisionResolver } from "../components/DecisionResolver";
|
||||
import { IssueGroupHeader } from "../components/IssueGroupHeader";
|
||||
|
||||
/** Curtain rows never expand; module-level so memoized rows see one identity. */
|
||||
const noopToggleExpand = () => {};
|
||||
|
||||
// Incremental rendering (PAP-13784, same pattern as IssuesList): the feed is
|
||||
// uncapped, so mounting every row up front makes the page slow to paint and
|
||||
// scroll. Render a bounded window and grow it as the scroll position nears the
|
||||
@@ -94,6 +99,9 @@ export function WhatNeedsMe() {
|
||||
|
||||
function ClassicWhatNeedsMe() {
|
||||
const { selectedCompanyId } = useCompany();
|
||||
// The signed-in person; it keys every list so an account switch never shows
|
||||
// the previous person's cards (PAP-749 plan §1).
|
||||
const { userId: currentUserId } = useCoordinatorWorkspaceEnabled();
|
||||
const { setBreadcrumbs } = useBreadcrumbs();
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
const [selectedAttentionId, setSelectedAttentionId] = useState<string | null>(null);
|
||||
@@ -113,9 +121,12 @@ function ClassicWhatNeedsMe() {
|
||||
const [sortOrder, setSortOrder] = useState<AttentionSortOrder>(() => loadAttentionSortOrder());
|
||||
const [filters, setFilters] = useState<AttentionFilterState>(() => defaultAttentionFilterState);
|
||||
const [collapsedGroupKeys, setCollapsedGroupKeys] = useState<Set<string>>(() => new Set());
|
||||
const [snoozedOpen, setSnoozedOpen] = useState(false);
|
||||
const [dismissedOpen, setDismissedOpen] = useState(false);
|
||||
// The Archived view's Snoozed group starts open (PAP-749 plan §3).
|
||||
const [snoozedOpen, setSnoozedOpen] = useState(true);
|
||||
const [agingOpen, setAgingOpen] = useState(false);
|
||||
const [historyOpen, setHistoryOpen] = useState(false);
|
||||
// The Stale (N) group starts collapsed (PAP-749 plan §3).
|
||||
const [staleOpen, setStaleOpen] = useState(false);
|
||||
const [decidedOpen, setDecidedOpen] = useState(false);
|
||||
const [expiredOpen, setExpiredOpen] = useState(false);
|
||||
|
||||
@@ -127,13 +138,28 @@ function ClassicWhatNeedsMe() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const deepLinkDecisionId = searchParams.get("decisionId");
|
||||
const [deepLinkConsumed, setDeepLinkConsumed] = useState(false);
|
||||
// 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 setView = useCallback((next: AttentionPersonalView) => {
|
||||
setSearchParams((prev) => {
|
||||
const params = new URLSearchParams(prev);
|
||||
if (next === "mine") params.delete(ATTENTION_VIEW_PARAM);
|
||||
else params.set(ATTENTION_VIEW_PARAM, next);
|
||||
return params;
|
||||
}, { replace: true });
|
||||
}, [setSearchParams]);
|
||||
// Archived: the cards you archived or snoozed for yourself (PAP-749 plan §3).
|
||||
const archivedView = view === "archived";
|
||||
const { viewCounts } = useAttentionBadge(selectedCompanyId);
|
||||
const claim = useClaimAttentionItem(selectedCompanyId);
|
||||
const claimingId = claim.isPending ? claim.variables?.id ?? null : null;
|
||||
const handleClaim = useCallback((item: AttentionItem) => claim.mutate(item), [claim.mutate]);
|
||||
|
||||
// Optimistic hide/restore. Reset whenever a fresh feed lands (server truth).
|
||||
// Optimistic hide. Reset whenever a fresh feed lands (server truth).
|
||||
const [pendingHide, setPendingHide] = useState<Set<string>>(() => new Set());
|
||||
const [pendingRestore, setPendingRestore] = useState<Set<string>>(() => new Set());
|
||||
|
||||
const { dismiss, snooze, restore } = useInboxDismissals(selectedCompanyId);
|
||||
const { pushToast } = useToastActions();
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Date chips resolve to server-side activity bounds. Anchored to start-of-day,
|
||||
@@ -160,16 +186,18 @@ function ClassicWhatNeedsMe() {
|
||||
// `["attention", companyId]` prefix still cascades to this query.
|
||||
queryKey: [
|
||||
...queryKeys.attention(selectedCompanyId!),
|
||||
"with-dismissed",
|
||||
currentUserId,
|
||||
view,
|
||||
"classic",
|
||||
activityBounds.activitySince ?? null,
|
||||
activityBounds.activityUntil ?? null,
|
||||
],
|
||||
queryFn: () => attentionApi.list(selectedCompanyId!, {
|
||||
includeDismissed: true,
|
||||
all: true,
|
||||
view,
|
||||
...activityBounds,
|
||||
}),
|
||||
enabled: !!selectedCompanyId,
|
||||
enabled: !!selectedCompanyId && !!currentUserId,
|
||||
refetchOnWindowFocus: true,
|
||||
});
|
||||
const { data: feed, isLoading } = feedQuery;
|
||||
@@ -194,11 +222,27 @@ function ClassicWhatNeedsMe() {
|
||||
enabled: decisionHistoryQueryEnabled(selectedCompanyId, expiredOpen),
|
||||
});
|
||||
|
||||
const { data: session } = useQuery({
|
||||
queryKey: queryKeys.auth.session,
|
||||
queryFn: () => authApi.getSession(),
|
||||
const { data: userDirectory } = useQuery({
|
||||
queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
|
||||
queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
|
||||
enabled: !!selectedCompanyId,
|
||||
});
|
||||
const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;
|
||||
const userLabelMap = useMemo(() => buildCompanyUserLabelMap(userDirectory?.users), [userDirectory?.users]);
|
||||
|
||||
// Every Close… verb goes through the one close API (PAP-749 plan §2). The row
|
||||
// hides at once; it comes back if the server refuses.
|
||||
const unhide = useCallback((item: AttentionItem) => {
|
||||
setPendingHide((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(item.id);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
const closeActions = useAttentionCloseActions(selectedCompanyId, { userLabelMap, onCloseFailed: unhide });
|
||||
const receiptActions = useDismissAttentionReceipt(selectedCompanyId);
|
||||
const closeCard = closeActions.close;
|
||||
const transferCard = closeActions.transfer;
|
||||
const closingId = closeActions.closingItemId ?? closeActions.transferringItemId;
|
||||
|
||||
const agentMap = useMemo(() => {
|
||||
const map = new Map<string, Agent>();
|
||||
@@ -209,19 +253,16 @@ function ClassicWhatNeedsMe() {
|
||||
// Reset optimistic state once the server sends a fresh snapshot.
|
||||
useEffect(() => {
|
||||
setPendingHide(new Set());
|
||||
setPendingRestore(new Set());
|
||||
}, [feed?.generatedAt]);
|
||||
|
||||
const allItems = useMemo(() => feed?.items ?? [], [feed]);
|
||||
|
||||
const isServerHidden = (item: AttentionItem) => item.dismissal != null && item.dismissal.isActive;
|
||||
// One card for each obligation (PAP-749 Rule 11): evidence folds into its
|
||||
// lead before any split, so a lead and its evidence always move together.
|
||||
const obligations = useMemo(() => foldAttentionObligations(feed?.items ?? []), [feed]);
|
||||
const allItems = obligations.cards;
|
||||
|
||||
const activeItems = useMemo(
|
||||
() =>
|
||||
allItems.filter(
|
||||
(item) => (!isServerHidden(item) || pendingRestore.has(item.id)) && !pendingHide.has(item.id),
|
||||
),
|
||||
[allItems, pendingHide, pendingRestore],
|
||||
() => allItems.filter((item) => !pendingHide.has(item.id)),
|
||||
[allItems, pendingHide],
|
||||
);
|
||||
|
||||
// The server's clock at feed time — used for the arrival/decide-by shelves and
|
||||
@@ -232,26 +273,23 @@ function ClassicWhatNeedsMe() {
|
||||
[feed?.generatedAt],
|
||||
);
|
||||
|
||||
// Aging shelf (§4.4): items the server flags as idle past retention leave the
|
||||
// live desk for their own curtain, so today's desk shows only fresh decisions.
|
||||
const agingItems = useMemo(() => activeItems.filter(attentionIsAging), [activeItems]);
|
||||
const deskItems = useMemo(() => activeItems.filter((item) => !attentionIsAging(item)), [activeItems]);
|
||||
const snoozedItems = useMemo(
|
||||
() =>
|
||||
allItems.filter(
|
||||
(item) =>
|
||||
item.dismissal?.kind === "snooze" && item.dismissal.isActive && !pendingRestore.has(item.id),
|
||||
),
|
||||
[allItems, pendingRestore],
|
||||
);
|
||||
const dismissedItems = useMemo(
|
||||
() =>
|
||||
allItems.filter(
|
||||
(item) =>
|
||||
item.dismissal?.kind === "dismiss" && item.dismissal.isActive && !pendingRestore.has(item.id),
|
||||
),
|
||||
[allItems, pendingRestore],
|
||||
);
|
||||
// Stale cards (PAP-749 Rule 10) go to the collapsed Stale group at the bottom.
|
||||
// Aging shelf (§4.4): other items the server flags as idle past retention
|
||||
// leave the live desk for their own curtain, so the desk shows fresh decisions.
|
||||
// The Archived view (plan §3) keeps stale cards in place with their chip and
|
||||
// puts snoozed cards in their own group.
|
||||
const { staleItems, agingItems, deskItems, snoozedItems } = useMemo(() => {
|
||||
if (archivedView) {
|
||||
const { archived, snoozed } = splitArchivedAttentionItems(activeItems);
|
||||
return { staleItems: [], agingItems: [], deskItems: archived, snoozedItems: snoozed };
|
||||
}
|
||||
return {
|
||||
staleItems: activeItems.filter((item) => item.stale),
|
||||
agingItems: activeItems.filter((item) => !item.stale && attentionIsAging(item)),
|
||||
deskItems: activeItems.filter((item) => !item.stale && !attentionIsAging(item)),
|
||||
snoozedItems: [] as AttentionItem[],
|
||||
};
|
||||
}, [activeItems, archivedView]);
|
||||
|
||||
const filterOptions = useMemo(() => buildAttentionFilterOptions(deskItems), [deskItems]);
|
||||
|
||||
@@ -269,6 +307,11 @@ function ClassicWhatNeedsMe() {
|
||||
return groupAttentionItems(sorted, groupBy);
|
||||
}, [deskItems, filters, searchQuery, sortOrder, groupBy, now]);
|
||||
|
||||
const visibleStaleItems = useMemo(
|
||||
() => sortAttentionItems(filterAttentionItems(staleItems, filters, searchQuery), sortOrder),
|
||||
[staleItems, filters, searchQuery, sortOrder],
|
||||
);
|
||||
|
||||
const visibleCount = useMemo(() => groups.reduce((sum, group) => sum + group.items.length, 0), [groups]);
|
||||
const keyboardItems = useMemo(
|
||||
() => groups.filter((group) => group.label === null || !collapsedGroupKeys.has(group.key)).flatMap((group) => group.items),
|
||||
@@ -295,14 +338,12 @@ function ClassicWhatNeedsMe() {
|
||||
collapsedGroupKeys,
|
||||
snoozedItems,
|
||||
snoozedOpen,
|
||||
dismissedItems,
|
||||
dismissedOpen,
|
||||
dismissedItems: [],
|
||||
dismissedOpen: false,
|
||||
limit: Math.max(renderedRowLimit, selectedIndex + 1),
|
||||
});
|
||||
}, [
|
||||
collapsedGroupKeys,
|
||||
dismissedItems,
|
||||
dismissedOpen,
|
||||
groups,
|
||||
keyboardItems,
|
||||
renderedRowLimit,
|
||||
@@ -365,10 +406,14 @@ function ClassicWhatNeedsMe() {
|
||||
// card once the feed lands, then drop the param so a later manual collapse is
|
||||
// not re-forced on the next refetch. Wins over the generic auto-expand below.
|
||||
useEffect(() => {
|
||||
if (deepLinkConsumed || !deepLinkDecisionId || allItems.length === 0) return;
|
||||
if (deepLinkConsumed || !deepLinkDecisionId || isLoading) return;
|
||||
const target = allItems.find(
|
||||
(item) => item.sourceKind === "decision" && item.subject.id === deepLinkDecisionId,
|
||||
);
|
||||
if (!target) {
|
||||
if (everyone && view !== "all") setView("all");
|
||||
return;
|
||||
}
|
||||
setDeepLinkConsumed(true);
|
||||
setAutoExpandDone(true);
|
||||
if (target) {
|
||||
@@ -384,7 +429,7 @@ function ClassicWhatNeedsMe() {
|
||||
{ replace: true },
|
||||
);
|
||||
}
|
||||
}, [allItems, deepLinkConsumed, deepLinkDecisionId, setSearchParams]);
|
||||
}, [allItems, deepLinkConsumed, deepLinkDecisionId, setSearchParams, isLoading, everyone, view, setView]);
|
||||
|
||||
// Auto-expand the topmost inline-capable decision, once.
|
||||
useEffect(() => {
|
||||
@@ -418,51 +463,66 @@ function ClassicWhatNeedsMe() {
|
||||
};
|
||||
|
||||
// All row callbacks are stable (deps are setState functions, stable hook
|
||||
// callbacks, and the stable `pushToast`) so the memoized rows only re-render
|
||||
// callbacks, and the stable mutation `mutate`s) so the memoized rows only re-render
|
||||
// when their own item/expanded/selected props change (PAP-13784).
|
||||
const handleUndoDismiss = useCallback(
|
||||
(item: AttentionItem) => {
|
||||
setPendingHide((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(item.id);
|
||||
return next;
|
||||
});
|
||||
restore(item.dismissalKey);
|
||||
},
|
||||
[restore],
|
||||
);
|
||||
const handleDismiss = useCallback(
|
||||
(item: AttentionItem) => {
|
||||
setPendingHide((prev) => new Set(prev).add(item.id));
|
||||
dismiss(item.dismissalKey);
|
||||
// "Archive for me": personal, with an Undo toast from the close hook.
|
||||
closeCard({ item, mode: "archive" });
|
||||
setExpandedId((previous) => (previous === item.id ? null : previous));
|
||||
// ~8s undo window; restores the row in place via T1's DELETE endpoint.
|
||||
pushToast({
|
||||
id: `attention-dismiss-${item.id}`,
|
||||
dedupeKey: `attention-dismiss-${item.dismissalKey}`,
|
||||
title: "Dismissed",
|
||||
body: item.subject.title ?? undefined,
|
||||
tone: "info",
|
||||
ttlMs: 8000,
|
||||
action: { label: "Undo", onClick: () => handleUndoDismiss(item) },
|
||||
});
|
||||
},
|
||||
[dismiss, handleUndoDismiss, pushToast],
|
||||
[closeCard],
|
||||
);
|
||||
const handleSnooze = useCallback(
|
||||
(item: AttentionItem, snoozedUntil: string) => {
|
||||
// In the Archived view a new snooze time keeps the card; it only moves
|
||||
// to (or within) the Snoozed group after the refetch.
|
||||
if (!archivedView) {
|
||||
setPendingHide((prev) => new Set(prev).add(item.id));
|
||||
setExpandedId((previous) => (previous === item.id ? null : previous));
|
||||
}
|
||||
closeCard({ item, mode: "snooze", until: snoozedUntil });
|
||||
},
|
||||
[archivedView, closeCard],
|
||||
);
|
||||
const handleWithdraw = useCallback(
|
||||
(item: AttentionItem, reason: string) => {
|
||||
setPendingHide((prev) => new Set(prev).add(item.id));
|
||||
snooze(item.dismissalKey, snoozedUntil);
|
||||
closeCard({ item, mode: "withdraw", reason });
|
||||
setExpandedId((previous) => (previous === item.id ? null : previous));
|
||||
},
|
||||
[snooze],
|
||||
[closeCard],
|
||||
);
|
||||
const handleTransfer = useCallback(
|
||||
(item: AttentionItem, userId: string) => transferCard({ item, userId }),
|
||||
[transferCard],
|
||||
);
|
||||
const handleWithdrawAll = useCallback(
|
||||
(items: AttentionItem[], reason: string) => {
|
||||
setPendingHide((prev) => {
|
||||
const next = new Set(prev);
|
||||
for (const item of items) next.add(item.id);
|
||||
return next;
|
||||
});
|
||||
return closeActions.withdrawAll(items, reason).then((result) => {
|
||||
for (const item of result.failed) unhide(item);
|
||||
return result;
|
||||
});
|
||||
},
|
||||
[closeActions.withdrawAll, unhide],
|
||||
);
|
||||
// Restore deletes your dismissal: the card leaves Archived at once and is
|
||||
// back in its view after the refetch. It comes back here if the server refuses.
|
||||
const restoreCard = closeActions.restore;
|
||||
const handleRestore = useCallback(
|
||||
(item: AttentionItem) => {
|
||||
setPendingRestore((prev) => new Set(prev).add(item.id));
|
||||
restore(item.dismissalKey);
|
||||
setPendingHide((prev) => new Set(prev).add(item.id));
|
||||
void restoreCard(item).then((restored) => {
|
||||
if (!restored) unhide(item);
|
||||
});
|
||||
},
|
||||
[restore],
|
||||
[restoreCard, unhide],
|
||||
);
|
||||
const handleToggleExpand = useCallback((item: AttentionItem) => {
|
||||
setSelectedAttentionId(item.id);
|
||||
@@ -535,12 +595,33 @@ function ClassicWhatNeedsMe() {
|
||||
);
|
||||
}
|
||||
|
||||
const hasAnything = activeItems.length > 0 || snoozedItems.length > 0 || dismissedItems.length > 0;
|
||||
const receipts = view === "mine" ? feed?.receipts ?? [] : [];
|
||||
const hasAnything = activeItems.length > 0 || receipts.length > 0;
|
||||
|
||||
return (
|
||||
<div ref={rootRef} className="max-w-3xl space-y-4">
|
||||
{/* Closed cards — answered, withdrawn, expired, closed with their task,
|
||||
approvals too — with outcome filters (PAP-749 plan §3). */}
|
||||
<Sheet open={historyOpen} onOpenChange={setHistoryOpen}>
|
||||
<SheetContent side="right" className="w-full gap-0 overflow-y-auto sm:max-w-md" data-classic-decision-history>
|
||||
<SheetHeader>
|
||||
<SheetTitle>Decision history</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="p-4">
|
||||
{historyOpen && <DecisionHistoryPanel companyId={selectedCompanyId} agents={agents ?? []} userLabelMap={userLabelMap} />}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-xl font-bold">Decisions</h1>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h1 className="text-xl font-bold">Decisions</h1>
|
||||
<Button variant="ghost" size="sm" onClick={() => setHistoryOpen(true)}>
|
||||
<History className="h-4 w-4" />
|
||||
Decision history
|
||||
</Button>
|
||||
</div>
|
||||
<AttentionViewSwitch value={view} counts={viewCounts} onChange={setView} everyone={everyone} />
|
||||
{view === "mine" ? <AttentionUnassignedBanner count={viewCounts.unassigned} onOpen={() => setView("unassigned")} /> : null}
|
||||
<DecisionsToolbar
|
||||
query={searchQuery}
|
||||
onQueryChange={setSearchQuery}
|
||||
@@ -555,6 +636,9 @@ function ClassicWhatNeedsMe() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AttentionReceiptList receipts={receipts} userLabelMap={userLabelMap}
|
||||
onDismiss={receiptActions.dismiss} dismissingId={receiptActions.dismissingId} onOpen={navigate} />
|
||||
|
||||
{/* Queue quicklinks + date-range chips (§4.1–§4.2). The rail self-hides
|
||||
when the company has no queues; the chips filter the desk server-side. */}
|
||||
<div className="space-y-2">
|
||||
@@ -570,11 +654,11 @@ function ClassicWhatNeedsMe() {
|
||||
</div>
|
||||
|
||||
{!hasAnything ? (
|
||||
<ZeroState />
|
||||
<ZeroState view={view} />
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{visibleCount === 0 ? (
|
||||
<CaughtUpNote filtered={deskItems.length > 0} />
|
||||
<CaughtUpNote filtered={deskItems.length > 0} view={view} snoozedBelow={snoozedItems.length > 0} />
|
||||
) : (
|
||||
<>
|
||||
{groups.map((group) => {
|
||||
@@ -632,11 +716,19 @@ function ClassicWhatNeedsMe() {
|
||||
onToggleExpand={handleToggleExpand}
|
||||
onDismiss={handleDismiss}
|
||||
onSnooze={handleSnooze}
|
||||
onWithdraw={handleWithdraw}
|
||||
onTransfer={handleTransfer}
|
||||
onRestore={archivedView ? handleRestore : undefined}
|
||||
closing={closingId === item.id}
|
||||
agentMap={agentMap}
|
||||
agents={agents}
|
||||
showTriage
|
||||
currentUserId={currentUserId}
|
||||
userLabelMap={userLabelMap}
|
||||
onClaim={handleClaim}
|
||||
claiming={claimingId === item.id}
|
||||
selected={selectionFromKeyboard && selectedAttentionId === item.id}
|
||||
evidence={attentionObligationEvidence(obligations, item)}
|
||||
/>
|
||||
</div>
|
||||
</Fragment>
|
||||
@@ -651,53 +743,68 @@ function ClassicWhatNeedsMe() {
|
||||
</>
|
||||
)}
|
||||
|
||||
{snoozedItems.length > 0 && (
|
||||
<Curtain
|
||||
label="Snoozed"
|
||||
count={snoozedItems.length}
|
||||
open={snoozedOpen}
|
||||
onToggle={() => setSnoozedOpen((prev) => !prev)}
|
||||
>
|
||||
{renderPlan.snoozedRows.map((item) => (
|
||||
<AttentionQueueRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
companyId={selectedCompanyId}
|
||||
variant="hidden"
|
||||
expanded={false}
|
||||
onToggleExpand={noopToggleExpand}
|
||||
onDismiss={handleDismiss}
|
||||
onRestore={handleRestore}
|
||||
agentMap={agentMap}
|
||||
currentUserId={currentUserId}
|
||||
/>
|
||||
))}
|
||||
</Curtain>
|
||||
)}
|
||||
<AttentionStaleGroup
|
||||
items={visibleStaleItems}
|
||||
open={staleOpen}
|
||||
onToggle={() => setStaleOpen((prev) => !prev)}
|
||||
onWithdrawAll={handleWithdrawAll}
|
||||
busy={closeActions.bulkPending}
|
||||
currentUserId={currentUserId}
|
||||
userLabelMap={userLabelMap}
|
||||
>
|
||||
{visibleStaleItems.map((item) => (
|
||||
<AttentionQueueRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
companyId={selectedCompanyId}
|
||||
expanded={expandedId === item.id}
|
||||
onToggleExpand={handleToggleExpand}
|
||||
onDismiss={handleDismiss}
|
||||
onSnooze={handleSnooze}
|
||||
onWithdraw={handleWithdraw}
|
||||
onTransfer={handleTransfer}
|
||||
closing={closingId === item.id}
|
||||
agentMap={agentMap}
|
||||
agents={agents}
|
||||
currentUserId={currentUserId}
|
||||
userLabelMap={userLabelMap}
|
||||
onClaim={handleClaim}
|
||||
claiming={claimingId === item.id}
|
||||
evidence={attentionObligationEvidence(obligations, item)}
|
||||
/>
|
||||
))}
|
||||
</AttentionStaleGroup>
|
||||
|
||||
{dismissedItems.length > 0 && (
|
||||
<Curtain
|
||||
label="Dismissed"
|
||||
count={dismissedItems.length}
|
||||
open={dismissedOpen}
|
||||
onToggle={() => setDismissedOpen((prev) => !prev)}
|
||||
>
|
||||
{renderPlan.dismissedRows.map((item) => (
|
||||
<AttentionQueueRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
companyId={selectedCompanyId}
|
||||
variant="hidden"
|
||||
expanded={false}
|
||||
onToggleExpand={noopToggleExpand}
|
||||
onDismiss={handleDismiss}
|
||||
onRestore={handleRestore}
|
||||
agentMap={agentMap}
|
||||
currentUserId={currentUserId}
|
||||
/>
|
||||
))}
|
||||
</Curtain>
|
||||
)}
|
||||
{/* Snoozed by you, in the Archived view: each card says when it
|
||||
comes back; Restore now or change the time (PAP-749 plan §3). */}
|
||||
<AttentionSnoozedGroup
|
||||
count={snoozedItems.length}
|
||||
open={snoozedOpen}
|
||||
onToggle={() => setSnoozedOpen((prev) => !prev)}
|
||||
>
|
||||
{renderPlan.snoozedRows.map((item) => (
|
||||
<AttentionQueueRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
companyId={selectedCompanyId}
|
||||
expanded={expandedId === item.id}
|
||||
onToggleExpand={handleToggleExpand}
|
||||
onDismiss={handleDismiss}
|
||||
onSnooze={handleSnooze}
|
||||
onWithdraw={handleWithdraw}
|
||||
onTransfer={handleTransfer}
|
||||
onRestore={handleRestore}
|
||||
closing={closingId === item.id}
|
||||
agentMap={agentMap}
|
||||
agents={agents}
|
||||
currentUserId={currentUserId}
|
||||
userLabelMap={userLabelMap}
|
||||
onClaim={handleClaim}
|
||||
claiming={claimingId === item.id}
|
||||
evidence={attentionObligationEvidence(obligations, item)}
|
||||
/>
|
||||
))}
|
||||
</AttentionSnoozedGroup>
|
||||
|
||||
{agingItems.length > 0 && (
|
||||
<Curtain
|
||||
@@ -722,6 +829,7 @@ function ClassicWhatNeedsMe() {
|
||||
onToggleExpand={handleToggleExpand}
|
||||
onDismiss={handleDismiss}
|
||||
onSnooze={handleSnooze}
|
||||
evidence={attentionObligationEvidence(obligations, item)}
|
||||
/>
|
||||
))}
|
||||
</Curtain>
|
||||
@@ -821,11 +929,21 @@ export function DecisionBundleHeader({
|
||||
);
|
||||
}
|
||||
|
||||
function CaughtUpNote({ filtered }: { filtered: boolean }) {
|
||||
const CAUGHT_UP_TEXT: Record<AttentionPersonalView, string> = {
|
||||
mine: "You're all caught up.",
|
||||
unassigned: "No cards need an owner.",
|
||||
company: "No company alerts right now.",
|
||||
archived: "Nothing archived.",
|
||||
all: "No open cards for anyone.",
|
||||
};
|
||||
|
||||
function CaughtUpNote({ filtered, view, snoozedBelow = false }: { filtered: boolean; view: AttentionPersonalView; snoozedBelow?: boolean }) {
|
||||
return (
|
||||
<div className="rounded-xl border border-dashed border-border py-10 text-center">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{filtered ? "No decisions match your search or filters." : "You're all caught up."}
|
||||
{filtered
|
||||
? "No decisions match your search or filters."
|
||||
: snoozedBelow ? "No archived cards. Snoozed cards are below." : CAUGHT_UP_TEXT[view]}
|
||||
</p>
|
||||
{filtered && (
|
||||
<p className="mt-1 text-xs text-muted-foreground">Adjust or clear your search and filters to see the rest.</p>
|
||||
@@ -834,16 +952,24 @@ function CaughtUpNote({ filtered }: { filtered: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
function ZeroState() {
|
||||
const ZERO_STATE_DETAIL: Record<AttentionPersonalView, string> = {
|
||||
mine: "Nothing needs a decision from you right now.",
|
||||
unassigned: "Every open card has an owner.",
|
||||
company: "No failed runs, agent errors, budget stops or join requests.",
|
||||
archived: "Cards you archive or snooze for yourself show here. Restore one to see it again.",
|
||||
all: "Nobody has a card waiting right now.",
|
||||
};
|
||||
|
||||
function ZeroState({ view }: { view: AttentionPersonalView }) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-20 text-center">
|
||||
<div className="mb-4 rounded-full bg-green-500/10 p-4">
|
||||
<CheckCircle2 className="h-10 w-10 text-green-500" />
|
||||
</div>
|
||||
<p className="text-lg font-semibold text-foreground">You're all caught up</p>
|
||||
<p className="text-lg font-semibold text-foreground">{view === "mine" ? "You're all caught up" : CAUGHT_UP_TEXT[view]}</p>
|
||||
<p className="mt-1 flex items-center gap-1.5 text-sm text-muted-foreground">
|
||||
<Inbox className="h-4 w-4" />
|
||||
Nothing needs a decision from you right now.
|
||||
{ZERO_STATE_DETAIL[view]}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } 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 { AttentionItem, AttentionReceipt } from "@paperclipai/shared";
|
||||
import { WhatNeedsMe } from "./WhatNeedsMe";
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
// PAP-749 tasks 1b and 2e on the classic Decisions page: the view switch, per
|
||||
// person and view query keys, the Unassigned banner, Claim, and the Archived
|
||||
// view with Restore and its Snoozed group.
|
||||
const fixture = vi.hoisted(() => ({
|
||||
userId: "scott",
|
||||
byView: {} as Record<string, AttentionItem[]>,
|
||||
calls: [] as Array<Record<string, unknown>>,
|
||||
claim: vi.fn(async () => ({})),
|
||||
close: vi.fn(async (..._args: unknown[]) => ({ until: null })),
|
||||
restore: vi.fn(async (..._args: unknown[]) => ({})),
|
||||
boardAccess: null as null | Record<string, unknown>,
|
||||
receipts: [] as AttentionReceipt[],
|
||||
}));
|
||||
vi.mock("../hooks/useCoordinatorWorkspaceEnabled", () => ({ useCoordinatorWorkspaceEnabled: () => ({ enabled: false, userId: fixture.userId }) }));
|
||||
vi.mock("../context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: "company" }) }));
|
||||
vi.mock("../context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: vi.fn() }) }));
|
||||
vi.mock("../context/ToastContext", () => ({ useToastActions: () => ({ pushToast: vi.fn() }), useOptionalToastActions: () => ({ pushToast: vi.fn() }) }));
|
||||
vi.mock("../hooks/useInboxBadge", () => ({ useInboxDismissals: () => ({ dismiss: vi.fn(), snooze: vi.fn(), restore: vi.fn() }) }));
|
||||
vi.mock("../api/agents", () => ({ agentsApi: { list: async () => [] } }));
|
||||
vi.mock("../api/decisions", () => ({ decisionsApi: { list: async () => [] } }));
|
||||
vi.mock("../api/access", () => ({ accessApi: {
|
||||
listUserDirectory: async () => ({ users: [] }),
|
||||
getCurrentBoardAccess: async () => { if (!fixture.boardAccess) throw new Error("No board access"); return fixture.boardAccess; },
|
||||
} }));
|
||||
vi.mock("../api/inboxDismissals", () => ({ inboxDismissalsApi: { restore: fixture.restore, dismiss: vi.fn() } }));
|
||||
vi.mock("../components/DecisionHistoryPanel", () => ({ DecisionHistoryPanel: () => <div data-history-panel>History</div> }));
|
||||
vi.mock("../api/attention", () => ({ attentionApi: {
|
||||
claim: fixture.claim,
|
||||
close: fixture.close,
|
||||
list: async (_companyId: string, options: Record<string, unknown>) => {
|
||||
fixture.calls.push(options);
|
||||
const items = fixture.byView[String(options.view)] ?? [];
|
||||
return { companyId: "company", generatedAt: "2026-10-30T12:00:00Z", totalCount: items.length, deskBadgeCount: 2,
|
||||
viewCounts: { mine: 2, unassigned: 1, company: 0, archived: 3, all: 3 }, nextCursor: null, countsBySourceKind: {}, items,
|
||||
receipts: options.view === "mine" ? fixture.receipts : [] };
|
||||
},
|
||||
} }));
|
||||
vi.mock("../components/DecisionsToolbar", () => ({ DecisionsToolbar: () => null }));
|
||||
vi.mock("../components/DecisionQueueRail", () => ({ DecisionQueueRail: () => null }));
|
||||
vi.mock("../components/DecisionDateChips", () => ({ DecisionDateChips: () => null }));
|
||||
vi.mock("../components/DecisionResolver", () => ({ DecisionResolver: () => null }));
|
||||
vi.mock("../components/AttentionQueueRow", () => ({
|
||||
AttentionQueueRow: ({ item, onClaim, onDismiss, onRestore, onSnooze, currentUserId }: { item: AttentionItem; onClaim?: (item: AttentionItem) => void; onDismiss?: (item: AttentionItem) => void; onRestore?: (item: AttentionItem) => void; onSnooze?: (item: AttentionItem, until: string) => void; currentUserId?: string | null }) => (
|
||||
<div data-row={item.id} data-viewer={currentUserId ?? ""}>
|
||||
{item.subject.title}
|
||||
{onClaim ? <button type="button" onClick={() => onClaim(item)}>Claim {item.id}</button> : null}
|
||||
{onDismiss && !onRestore ? <button type="button" onClick={() => onDismiss(item)}>Archive {item.id}</button> : null}
|
||||
{onRestore ? <button type="button" onClick={() => onRestore(item)}>Restore {item.id}</button> : null}
|
||||
{onRestore && onSnooze ? <button type="button" onClick={() => onSnooze(item, "2026-11-02T09:00:00.000Z")}>Change time {item.id}</button> : null}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
function card(id: string, audience: AttentionItem["audience"]) {
|
||||
const at = new Date().toISOString();
|
||||
return { id, sourceKind: "issue_thread_interaction", subject: { id: `${id}-interaction`, kind: "interaction", title: `Card ${id}`, metadata: {} },
|
||||
audience, dismissal: null, dismissalKey: `attention:${id}`, changeFingerprint: `${id}.me`, closeModes: ["archive", "snooze"], obligationKey: null, obligationLeadId: null, activityAt: at, createdAt: at, updatedAt: at, inlineResolvable: false, decisionVerbs: [], queues: [], shelf: false,
|
||||
severity: "medium", relatedIssue: null, project: null } as unknown as AttentionItem;
|
||||
}
|
||||
|
||||
function Location() { return <output data-location>{useLocation().search}</output>; }
|
||||
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
let client: QueryClient;
|
||||
beforeEach(() => {
|
||||
fixture.userId = "scott";
|
||||
fixture.calls = [];
|
||||
fixture.boardAccess = null;
|
||||
fixture.receipts = [];
|
||||
fixture.claim.mockClear();
|
||||
fixture.close.mockClear();
|
||||
fixture.restore.mockClear();
|
||||
fixture.byView = {
|
||||
mine: [card("mine-1", { kind: "user", userId: "scott", reason: "addressee" })],
|
||||
unassigned: [card("pool-1", { kind: "pool", userId: null, reason: "none" })],
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
});
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
async function flush() { await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); }
|
||||
async function render(url = "/decisions") {
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><MemoryRouter initialEntries={[url]}><WhatNeedsMe /><Location /></MemoryRouter></QueryClientProvider>));
|
||||
await flush(); await flush();
|
||||
}
|
||||
|
||||
describe("classic Decisions views", () => {
|
||||
it("finds a linked decision outside Mine before consuming its URL", async () => {
|
||||
fixture.boardAccess = { userId: "scott", source: "session", memberships: [{ companyId: "company", status: "active", membershipRole: "admin" }] };
|
||||
fixture.byView.all = [{ ...card("decision-target", { kind: "pool", userId: null, reason: "none" }), sourceKind: "decision", subject: { id: "target", kind: "decision", title: "Linked decision" } } as AttentionItem];
|
||||
await render("/decisions?decisionId=target");
|
||||
for (let tick = 0; tick < 5; tick++) await flush();
|
||||
expect(fixture.calls).toContainEqual(expect.objectContaining({ view: "all" }));
|
||||
expect(container.querySelector("[data-location]")?.textContent).not.toContain("decisionId");
|
||||
});
|
||||
|
||||
it("shows personal receipts even when there are no pending cards", async () => {
|
||||
fixture.byView = { mine: [] };
|
||||
fixture.receipts = [{
|
||||
id: "receipt-1", dismissalKey: "attention:receipt:receipt-1", outcome: "withdrawn",
|
||||
sourceKind: "issue_thread_interaction", sourceId: "interaction-1", title: "Review the plan",
|
||||
reason: "Plan changed", actorUserId: "dotta", transferredToUserId: null,
|
||||
issue: null, href: null, createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 86_400_000).toISOString(),
|
||||
}];
|
||||
await render();
|
||||
expect(container.querySelector('[data-attention-receipt="withdrawn"]')?.textContent).toContain("Plan changed");
|
||||
await act(async () => {
|
||||
const company = container.querySelector<HTMLButtonElement>('[data-attention-view="company"]')!;
|
||||
company.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));
|
||||
company.focus();
|
||||
});
|
||||
await flush();
|
||||
expect(container.querySelector("[data-attention-receipts]")).toBeNull();
|
||||
});
|
||||
|
||||
it("opens For you by default with the shared badge count and the Unassigned banner", async () => {
|
||||
await render();
|
||||
expect(fixture.calls).toContainEqual(expect.objectContaining({ all: true, view: "mine" }));
|
||||
// The views never ask for hidden cards; those live in the Archived view (PAP-749 plan §3).
|
||||
expect(fixture.calls.some((call) => "includeDismissed" in call)).toBe(false);
|
||||
expect(fixture.calls.every((call) => call.view === "mine")).toBe(true);
|
||||
const tabs = [...container.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent);
|
||||
expect(tabs).toEqual(["For you2", "Unassigned1", "Company0", "Archived3"]);
|
||||
expect(container.querySelector('[data-row="mine-1"]')?.getAttribute("data-viewer")).toBe("scott");
|
||||
expect(container.querySelector("[data-attention-unassigned-banner]")?.textContent).toContain("1 card needs an owner");
|
||||
expect(client.getQueryCache().find({ queryKey: ["attention", "company", "scott", "mine", "classic"], exact: false })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("opens Everyone for a board member with its own count (PAP-768)", async () => {
|
||||
fixture.boardAccess = { userId: "scott", source: "session", isInstanceAdmin: false, companyIds: ["company"],
|
||||
memberships: [{ companyId: "company", membershipRole: "owner", status: "active" }] };
|
||||
fixture.byView.all = [card("mine-1", { kind: "user", userId: "scott", reason: "addressee" }), card("dotta-1", { kind: "user", userId: "dotta", reason: "instigator" })];
|
||||
await render("/decisions?view=all");
|
||||
await vi.waitFor(() => expect(container.querySelector('[data-attention-view="all"]')?.getAttribute("aria-selected")).toBe("true"));
|
||||
const tabs = [...container.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent);
|
||||
expect(tabs).toEqual(["For you2", "Unassigned1", "Company0", "Archived3", "Everyone3"]);
|
||||
expect(fixture.calls).toContainEqual(expect.objectContaining({ all: true, view: "all" }));
|
||||
expect([...container.querySelectorAll("[data-row]")].map((row) => row.getAttribute("data-row"))).toEqual(["mine-1", "dotta-1"]);
|
||||
expect(container.querySelector("[data-attention-unassigned-banner]")).toBeNull();
|
||||
});
|
||||
|
||||
it("hides Everyone when the board access is unknown (PAP-768)", async () => {
|
||||
await render("/decisions?view=all");
|
||||
expect(container.querySelector('[data-attention-view="all"]')).toBeNull();
|
||||
expect(container.querySelector('[data-attention-view="mine"]')?.getAttribute("aria-selected")).toBe("true");
|
||||
expect(fixture.calls.some((call) => call.view === "all")).toBe(false);
|
||||
});
|
||||
|
||||
it("switches to Unassigned from the banner and claims a card", async () => {
|
||||
await render();
|
||||
const open = [...container.querySelectorAll("button")].find((button) => button.textContent?.includes("Open Unassigned"))!;
|
||||
await act(async () => open.click());
|
||||
await flush(); await flush();
|
||||
expect(container.querySelector("[data-location]")?.textContent).toBe("?view=unassigned");
|
||||
expect(fixture.calls).toContainEqual(expect.objectContaining({ view: "unassigned" }));
|
||||
expect(container.querySelector("[data-attention-unassigned-banner]")).toBeNull();
|
||||
const claim = [...container.querySelectorAll("button")].find((button) => button.textContent === "Claim pool-1")!;
|
||||
await act(async () => claim.click());
|
||||
await flush();
|
||||
expect(fixture.claim).toHaveBeenCalledWith("company", "issue_thread_interaction", "pool-1-interaction");
|
||||
});
|
||||
|
||||
it("keeps each person's list under their own key", async () => {
|
||||
await render();
|
||||
fixture.userId = "dotta";
|
||||
await render();
|
||||
expect(client.getQueryCache().find({ queryKey: ["attention", "company", "dotta", "mine", "classic"], exact: false })).toBeTruthy();
|
||||
expect(client.getQueryCache().find({ queryKey: ["attention", "company", "scott", "mine", "classic"], exact: false })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("moves stale cards to a collapsed Stale group and withdraws them after a confirmation (PAP-749 task 2c)", async () => {
|
||||
const stale = (id: string) => ({ ...card(id, { kind: "user", userId: "scott", reason: "addressee" }), stale: { reason: "aged" }, closeModes: ["withdraw", "archive", "snooze"] }) as unknown as AttentionItem;
|
||||
fixture.byView = { mine: [card("fresh", { kind: "user", userId: "scott", reason: "addressee" }), stale("old-1"), stale("old-2")] };
|
||||
await render();
|
||||
const group = container.querySelector<HTMLElement>("[data-attention-stale-group]")!;
|
||||
expect(group.textContent).toContain("Stale (2)");
|
||||
expect(container.querySelector('[data-row="fresh"]')).not.toBeNull();
|
||||
expect(container.querySelector('[data-row="old-1"]')).toBeNull();
|
||||
await act(async () => group.querySelector<HTMLElement>("[aria-expanded]")!.click());
|
||||
expect(group.querySelector('[data-row="old-1"]')).not.toBeNull();
|
||||
const withdrawAll = [...group.querySelectorAll("button")].find((button) => button.textContent?.includes("Withdraw all stale"))!;
|
||||
await act(async () => withdrawAll.click());
|
||||
const confirm = [...document.querySelectorAll<HTMLButtonElement>("[data-attention-stale-withdraw-dialog] button")].find((button) => button.textContent === "Withdraw 2 requests")!;
|
||||
await act(async () => confirm.click());
|
||||
await flush();
|
||||
expect(fixture.close.mock.calls.map((call) => [call[2], (call[3] as { mode: string }).mode])).toEqual([["old-1-interaction", "withdraw"], ["old-2-interaction", "withdraw"]]);
|
||||
});
|
||||
|
||||
it("archives for me through the one close API (PAP-749 task 2c)", async () => {
|
||||
fixture.byView = { mine: [{ ...card("mine-1", { kind: "user", userId: "scott", reason: "addressee" }), changeFingerprint: "fp.me", closeModes: ["archive", "snooze"] } as unknown as AttentionItem] };
|
||||
await render();
|
||||
const archive = [...container.querySelectorAll("button")].find((button) => button.textContent === "Archive mine-1")!;
|
||||
await act(async () => archive.click());
|
||||
await flush();
|
||||
expect(fixture.close).toHaveBeenCalledWith("company", "issue_thread_interaction", "mine-1-interaction", { mode: "archive", reason: undefined, until: undefined, fingerprint: "fp.me" });
|
||||
expect(container.querySelector('[data-row="mine-1"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("lists your archived cards, then a Snoozed group, with Restore and Change time (PAP-749 task 2e)", async () => {
|
||||
const hidden = (id: string, kind: "dismiss" | "snooze", snoozedUntil: string | null = null) => ({
|
||||
...card(id, { kind: "user", userId: "scott", reason: "addressee" }),
|
||||
dismissal: { kind, dismissedAt: "2026-10-29T12:00:00Z", snoozedUntil, isActive: true },
|
||||
}) as unknown as AttentionItem;
|
||||
fixture.byView = { archived: [hidden("arch-1", "dismiss"), hidden("snz-1", "snooze", "2026-10-31T09:00:00Z")] };
|
||||
await render("/decisions?view=archived");
|
||||
expect(fixture.calls).toContainEqual(expect.objectContaining({ view: "archived", all: true }));
|
||||
expect(container.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toBe("Archived3");
|
||||
// The badge stays the For you count; the Archived count is only on its tab.
|
||||
expect(container.querySelector('[data-attention-view-count="mine"]')?.textContent).toBe("2");
|
||||
const snoozedGroup = container.querySelector<HTMLElement>("[data-attention-snoozed-group]")!;
|
||||
expect(snoozedGroup.textContent).toContain("Snoozed (1)");
|
||||
expect(snoozedGroup.querySelector('[data-row="snz-1"]')).not.toBeNull();
|
||||
expect(snoozedGroup.querySelector('[data-row="arch-1"]')).toBeNull();
|
||||
expect(container.querySelector('[data-row="arch-1"]')).not.toBeNull();
|
||||
// No Archive verb here: the card is already archived.
|
||||
expect([...container.querySelectorAll("button")].some((button) => button.textContent === "Archive arch-1")).toBe(false);
|
||||
|
||||
const changeTime = [...container.querySelectorAll("button")].find((button) => button.textContent === "Change time snz-1")!;
|
||||
await act(async () => changeTime.click());
|
||||
await flush();
|
||||
expect(fixture.close).toHaveBeenCalledWith("company", "issue_thread_interaction", "snz-1-interaction", expect.objectContaining({ mode: "snooze", until: "2026-11-02T09:00:00.000Z" }));
|
||||
// A new time keeps the card in the Archived view.
|
||||
expect(container.querySelector('[data-row="snz-1"]')).not.toBeNull();
|
||||
|
||||
const restore = [...container.querySelectorAll("button")].find((button) => button.textContent === "Restore arch-1")!;
|
||||
await act(async () => restore.click());
|
||||
await flush();
|
||||
expect(fixture.restore).toHaveBeenCalledWith("company", "attention:arch-1");
|
||||
expect(container.querySelector('[data-row="arch-1"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("shows the Archived empty state and opens Decision history from the header", async () => {
|
||||
await render("/decisions?view=archived");
|
||||
expect(container.textContent).toContain("Nothing archived.");
|
||||
expect(document.querySelector("[data-history-panel]")).toBeNull();
|
||||
const history = [...container.querySelectorAll("button")].find((button) => button.textContent?.includes("Decision history"))!;
|
||||
await act(async () => history.click());
|
||||
await flush();
|
||||
expect(document.querySelector("[data-classic-decision-history] [data-history-panel]")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("shows a Company empty state from the URL", async () => {
|
||||
await render("/decisions?view=company");
|
||||
expect(fixture.calls).toContainEqual(expect.objectContaining({ view: "company" }));
|
||||
expect(container.textContent).toContain("No company alerts right now.");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user