diff --git a/ui/src/hooks/useInboxBadge.ts b/ui/src/hooks/useInboxBadge.ts index 1bcb008b21d..31c6da84bb1 100644 --- a/ui/src/hooks/useInboxBadge.ts +++ b/ui/src/hooks/useInboxBadge.ts @@ -74,7 +74,10 @@ export function useInboxDismissals( onMutate: async ({ itemKey, fingerprint }) => { if (!companyId) return { previous: [] as typeof dismissals }; await queryClient.cancelQueries({ queryKey }); - const previous = queryClient.getQueryData(queryKey) ?? []; + // Start from what the page shows: saved dismissals stand in until the + // first read answers, and must not be dropped by this write or its rollback. + const previous = queryClient.getQueryData(queryKey) + ?? (usesFallback ? options.fallback! : NO_DISMISSALS); const now = new Date(); queryClient.setQueryData(queryKey, [ { diff --git a/ui/src/hooks/useInboxDismissals.test.tsx b/ui/src/hooks/useInboxDismissals.test.tsx index c3495ce133e..9204a30e86e 100644 --- a/ui/src/hooks/useInboxDismissals.test.tsx +++ b/ui/src/hooks/useInboxDismissals.test.tsx @@ -5,8 +5,8 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import type { InboxDismissal } from "@paperclipai/shared"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const { list } = vi.hoisted(() => ({ list: vi.fn() })); -vi.mock("../api/inboxDismissals", () => ({ inboxDismissalsApi: { list, dismiss: vi.fn(), snooze: vi.fn(), restore: vi.fn() } })); +const { list, dismiss } = vi.hoisted(() => ({ list: vi.fn(), dismiss: vi.fn() })); +vi.mock("../api/inboxDismissals", () => ({ inboxDismissalsApi: { list, dismiss, snooze: vi.fn(), restore: vi.fn() } })); import { ApiError } from "../api/client"; import { useInboxDismissals } from "./useInboxBadge"; @@ -21,6 +21,7 @@ describe("useInboxDismissals fallback", () => { let latest: Result | null = null; beforeEach(() => { list.mockReset(); + dismiss.mockReset(); client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); root = createRoot(document.createElement("div")); }); @@ -52,6 +53,19 @@ describe("useInboxDismissals fallback", () => { await vi.waitFor(() => expect(latest!.dismissedAtByKey.size).toBe(0)); }); + it("keeps the other saved dismissals when one item is dismissed before the read answers, and after a failed dismissal", async () => { + list.mockReturnValue(new Promise(() => {})); + let fail!: (error: unknown) => void; + dismiss.mockReturnValue(new Promise((_resolve, reject) => { fail = reject; })); + await render(saved); + await act(async () => { latest!.dismiss("join:j-1"); }); + await vi.waitFor(() => expect(latest!.dismissedAtByKey.has("join:j-1")).toBe(true)); + expect(latest!.dismissedAtByKey.get("approval:a-1")).toBe(1_000); + await act(async () => fail(new ApiError("Busy", 503, null))); + await vi.waitFor(() => expect(latest!.dismissedAtByKey.has("join:j-1")).toBe(false)); + expect(latest!.dismissedAtByKey.get("approval:a-1")).toBe(1_000); + }); + it("waits as before without a saved list", async () => { list.mockReturnValue(new Promise(() => {})); await render(null); diff --git a/ui/src/pages/Inbox.test.tsx b/ui/src/pages/Inbox.test.tsx index e5e8f908e4b..df70314dbe3 100644 --- a/ui/src/pages/Inbox.test.tsx +++ b/ui/src/pages/Inbox.test.tsx @@ -2104,6 +2104,36 @@ describe("Inbox toolbar", () => { } finally { await act(() => root.unmount()); queryClient.clear(); } }); + it.each([ + ["join requests", "joinRequests"], + ["approvals", "approvals"], + ] as const)("purges saved %s from the record as soon as their read is refused, while other reads are pending", async (_label, refusedPart) => { + routerMock.location.pathname = "/inbox/mine"; + twoRows(); + apiMocks.joinRequestsList.mockResolvedValue([createJoinRequest({ id: "join-saved" })]); + const queryClient = client(); + let root = createRoot(container); + const record = () => queryClient.getQueryData(mineRevealSourcesQueryKey("company-1", "local-board")); + try { + await visitThenReturn(queryClient, root); + await vi.waitFor(() => expect(record()?.joinRequests.map((request) => request.id)).toEqual(["join-saved"])); + const refusal = new ApiError("No access", 403, null); + if (refusedPart === "joinRequests") { + // The join-request read turns 401/403 into an empty list. + apiMocks.joinRequestsList.mockRejectedValue(refusal); + apiMocks.approvalsList.mockReturnValue(new Promise(() => {})); + } else { + apiMocks.approvalsList.mockRejectedValue(refusal); + apiMocks.joinRequestsList.mockReturnValue(new Promise(() => {})); + } + root = createRoot(container); + await renderInbox(queryClient, root); + await vi.waitFor(() => expect(record()?.[refusedPart]).toEqual([])); + const other = refusedPart === "joinRequests" ? "approvals" : "joinRequests"; + expect(record()?.[other]).toHaveLength(1); + } finally { await act(() => root.unmount()); queryClient.clear(); } + }); + it("ignores saved sources stamped for another user or company and waits as a first visit does", async () => { routerMock.location.pathname = "/inbox/mine"; twoRows(); @@ -2208,6 +2238,38 @@ describe("Inbox toolbar", () => { }); }); + it("keeps selection on the successor of a removed row when a new item then arrives above it", async () => { + routerMock.location.pathname = "/inbox/mine"; + const base = new Date("2026-03-11T00:00:00.000Z").getTime(); + const issueA = createIssue({ id: "issue-a", identifier: "PAP-5001", title: "Removed row A", lastActivityAt: new Date(base + 3000) }); + const issueB = createIssue({ id: "issue-b", identifier: "PAP-5002", title: "Successor row B", lastActivityAt: new Date(base + 2000) }); + setIssueRows([issueA, issueB]); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: 0, gcTime: 0 } } }); + const root = createRoot(container); + const selectedText = () => [...container.querySelectorAll("[data-inbox-item]")] + .filter((row) => row.querySelector('[class~="bg-accent/50"]') || row.className.split(/\s+/).includes("bg-accent/50")) + .map((row) => row.textContent ?? "").join(" | "); + try { + await act(async () => { root.render(); }); + await vi.waitFor(() => expect(container.textContent).toContain("Successor row B")); + await act(async () => { document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "j", bubbles: true })); }); + expect(selectedText()).toContain("Removed row A"); + // Row A leaves; the selection falls back to B at the same index. + setIssueRows([issueB]); + await act(async () => { await queryClient.invalidateQueries(); }); + await vi.waitFor(() => expect(container.textContent).not.toContain("Removed row A")); + expect(selectedText()).toContain("Successor row B"); + // A newer approval arrives above B; the selection stays on B. + apiMocks.approvalsList.mockResolvedValue([createApproval({ id: "approval-late", payload: { name: "Late approval" }, updatedAt: new Date(base + 9000) })]); + await act(async () => { await queryClient.invalidateQueries(); }); + await vi.waitFor(() => expect(container.querySelectorAll('a[href="/approvals/approval-late"]').length).toBe(1)); + expect(selectedText()).toContain("Successor row B"); + expect(selectedText()).not.toContain("Late approval"); + } finally { + act(() => { root.unmount(); }); + } + }); + it("keeps hover→j/k selection in sync after the list reshapes (PAP-9679)", async () => { routerMock.location.pathname = "/inbox/mine"; const issueA = createIssue({ id: "issue-a", identifier: "PAP-2001", title: "Sync row A" }); diff --git a/ui/src/pages/Inbox.tsx b/ui/src/pages/Inbox.tsx index 60d3cbde407..afba4faf967 100644 --- a/ui/src/pages/Inbox.tsx +++ b/ui/src/pages/Inbox.tsx @@ -1021,19 +1021,30 @@ function StreamlinedInbox({ const approvals = approvalsFromSaved ? savedRevealSources!.approvals : serverApprovals; const joinRequests = serverJoinRequests ?? (joinRequestsFromSaved ? savedRevealSources!.joinRequests : NO_JOIN_REQUESTS); - // Save what Mine shows once every source has a server answer, for the next visit. + // Save what Mine shows for the next visit. A complete record needs a server + // answer from every source. Once one exists, each answer replaces its part at + // once, and a refusal (401/403/404) empties it, so a reload never shows what + // the server has since refused while another read is still pending. useEffect(() => { if (tab !== "mine" || !selectedCompanyId || !currentUserId || !mineSnapshot) return; - if (serverApprovals === undefined || serverJoinRequests === undefined || !hasServerDismissals) return; - const next = buildMineRevealSources({ - userId: currentUserId, companyId: selectedCompanyId, approvals: serverApprovals, joinRequests: serverJoinRequests, - dismissals: inboxDismissals, failedRunIds: mineSnapshot.failureRuns.map((run) => run.id), - }); const key = mineRevealSourcesQueryKey(selectedCompanyId, currentUserId); + const saved = readMineRevealSources(queryClient.getQueryData(key), currentUserId, selectedCompanyId); + const refused = (error: unknown) => !!error && !isTransientError(error); + const part = (server: T[] | undefined, error: unknown, previous: T[] | undefined) => + server ?? (refused(error) ? [] : previous); + const nextApprovals = part(serverApprovals, approvalsError, saved?.approvals); + const nextJoinRequests = part(serverJoinRequests, joinRequestsError, saved?.joinRequests); + const nextDismissals = part(hasServerDismissals ? inboxDismissals : undefined, dismissalsError, saved?.dismissals); + if (!nextApprovals || !nextJoinRequests || !nextDismissals) return; + const next = buildMineRevealSources({ + userId: currentUserId, companyId: selectedCompanyId, approvals: nextApprovals, joinRequests: nextJoinRequests, + dismissals: nextDismissals, failedRunIds: mineSnapshot.failureRuns.map((run) => run.id), + }); // Each write schedules a save of the query cache; skip unchanged values. if (JSON.stringify(queryClient.getQueryData(key)) === JSON.stringify(next)) return; queryClient.setQueryData(key, next); - }, [tab, selectedCompanyId, currentUserId, mineSnapshot, serverApprovals, serverJoinRequests, hasServerDismissals, inboxDismissals, queryClient]); + }, [tab, selectedCompanyId, currentUserId, mineSnapshot, serverApprovals, approvalsError, serverJoinRequests, joinRequestsError, + hasServerDismissals, inboxDismissals, dismissalsError, queryClient]); const dashboardQueryKey = queryKeys.dashboard(selectedCompanyId!); const sharedDashboard = useSharedPollingQuery({ @@ -2313,12 +2324,19 @@ function StreamlinedInbox({ return keyIndex >= 0 ? keyIndex : resolveInboxSelectionIndex(prev, flatNavItems.length); }); }, [flatNavItems]); - // Record the key only when the selection itself moves. Recording on a list - // change too would store the row now at the old index (one a refresh inserted - // above the selection) before the re-anchor above runs, and move the selection. + // Record the selected row's key when the selection moves, or when the + // recorded row has left the list (the re-anchor then falls back to the row now + // at that index, often without changing it). Recording on every list change + // would store the row a refresh inserted above the selection before the + // re-anchor runs, and move the selection onto it. + const recordedSelectedIndexRef = useRef(selectedIndex); useEffect(() => { - selectedNavKeyRef.current = selectedIndex >= 0 ? navEntryKey(flatNavItemsRef.current[selectedIndex]) : null; - }, [selectedIndex]); + const recordedKey = selectedNavKeyRef.current; + const recordedRowListed = recordedKey !== null && flatNavItems.some((entry) => navEntryKey(entry) === recordedKey); + if (selectedIndex === recordedSelectedIndexRef.current && recordedRowListed) return; + recordedSelectedIndexRef.current = selectedIndex; + selectedNavKeyRef.current = selectedIndex >= 0 ? navEntryKey(flatNavItems[selectedIndex]) : null; + }, [flatNavItems, selectedIndex]); useEffect(() => { setUndoableArchiveIssueIds((prev) =>