perf(ui): reveal a returning Mine visit from the saved cache (#20594)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Mine inbox is the board's main list of work for one person; the
app saves its query cache in `localStorage` so a returning visit can
paint from it
> - On a hard load the saved cache gave no benefit: Mine restored its
rows but still held them until the first approvals, join-request and
dismissal reads answered, because those items sort in among task rows by
time and a late one would push rows down (#20407)
> - Those three reads were not saved, so every returning visit waited on
the network for items it showed a minute before
> - This pull request saves what Mine showed from those reads, as one
record per user and company, and lets it answer the wait on a returning
visit while every read refreshes in the background
> - The benefit is that a returning visit shows its rows with no API
response at all; the first visit keeps its bounded wait unchanged

## Linked Issues or Issue Description

**What happened?**
A returning hard load of `/:companyPrefix/issues?view=mine` with the
saved cache present (`paperclip:query-cache:v1:<user>:<company>`) showed
rows no sooner than with the cache cleared. On the hosted staging
instance, rows appeared about 40 ms after `GET
/companies/:id/join-requests?status=pending_approval` returned in 7 of
10 runs.

**Steps to reproduce**
1. Open Mine once so the app saves its query cache.
2. Delay API responses (for example 300 ms) and reload.
3. Rows appear only after the approvals and join-request reads answer.

**Expected behavior**
Rows show from the saved cache at once. The reads refresh in the
background.

Related: #20407 (kept approvals and join requests in the reveal gate),
#20408 and #20419 (Mine snapshot and its perf guard), #20591 (removes
the second wave of reads; merged), #20592 (task chat preload; merged).

## What Changed

- `ui/src/lib/inbox-mine-reveal-sources.ts` (new): the record `["inbox",
companyId, "mine-reveal-sources", userId]` holds the approvals visible
in Mine, the pending join requests, and the dismissals of those items
and of Mine's failed runs. A record over 256 KB is replaced by an empty
`incomplete` record that never answers the wait. `readMineRevealSources`
accepts a record only for the same user and company.
- `ui/src/lib/persisted-query-cache.ts`: the saved cache keeps that
record per user and company, only when its data names the same user and
company as its key.
- `ui/src/pages/Inbox.tsx`:
- Mine writes the record once approvals, join requests and dismissals
all have server answers.
- On a returning visit with a restored Mine snapshot, the saved
approvals, join requests and dismissals stand in while their reads are
pending, and after a transient failure. A refusal (401/403/404) or a
server answer replaces them. The first-attempt wait is skipped only when
saved values stand in; the first visit is unchanged.
- Selection fix: the selected row's key is recorded only when the
selection moves. Before, every list change recorded the row now at the
old index before the re-anchor ran, so a row inserted above the
selection (a late approval, or any live insert) moved the selection to
another row.
- `ui/src/hooks/useInboxBadge.ts`: `useInboxDismissals` takes an
optional saved `fallback` and returns `hasServerData`. Other callers are
unchanged.
- Tests:
- `Inbox.test.tsx`: a returning visit reveals rows and the saved
approval while the reads are pending, then keeps selection on the same
row when a newer approval arrives above it; a transient failure keeps
the saved approval and a 403 drops it; a record stamped for another user
is ignored and the page waits as a first visit does.
- `inbox-mine-reveal-sources.test.ts`: projection, size limit,
user/company checks, persistence scope.
- `persisted-query-cache.test.ts`: the record round-trips for the same
user, restores as invalidated, and another user's record is not saved.
- `useInboxDismissals.test.tsx`: fallback while pending, after a
transient failure, dropped after a refusal, and no fallback.
- `tests/perf/collections/mine-returning-visit.spec.ts` +
`returning-visit-fixture.ts`: production-build browser checks and the
timing case; README updated.

## Verification

- `cd ui && pnpm exec vitest run src/pages src/lib src/hooks
src/components/coordinator`: 453 files, 5574 tests pass.
- Browser checks on a disposable local instance (production UI build,
`local_trusted`, embedded PostgreSQL, Chromium headless, 1440×900):
`PAPERCLIP_COLLECTION_PERF_BASE_URL=http://127.0.0.1:<port> pnpm exec
playwright test --config tests/perf/collections/playwright.config.ts
mine-returning-visit.spec.ts`
- With every read of the company held, task rows and saved approvals
show and no company read has answered. Fails on `master`, passes here.
- An approval dismissed after the cache was saved stands in, then leaves
when the reads answer. Fails on `master` (no saved approvals), passes
here.
- Another company's Mine never shows the saved company's rows. Passes on
both.
- Timing (5 fresh contexts per arm, alternating saved/cleared, every API
response +300 ms, same instance and fixture, host load average about
20). "Responses before rows" counts API responses that finished before
the first row:

| Build | Saved cache: median (range) | Responses before rows | Cleared
cache: median (range) |
  | --- | --- | --- | --- |
| `master` (`99edcd28a7`) | 1028 ms (906–3011) | 16–19 | 1502 ms
(1423–1592) |
  | This PR | 625 ms (589–672) | 0 | 1632 ms (1359–1692) |
  | This PR + #20591 | 625 ms (604–671) | 0 | 1495 ms (1398–1585) |

Saved cache: difference of medians 403 ms. The remaining 625 ms is
JavaScript download and route-chunk loading in a fresh browser context;
no API response precedes the rows. Cleared cache: no change is claimed;
the spread overlaps.
- Existing collection specs on this build: `parent-context.spec.ts`
passes; `startup-regressions.spec.ts` has 4 failures (partial
failure/context error and two 429 cases) that fail the same way on the
`master` build. `mine-workspaces.spec.ts` was not run (needs a database
URL for its fixture).
- Review follow-up (9da56b5515), each with a red/green test that fails
on the previous head:
- Once a saved record exists, each source's answer replaces its part at
once and a refusal (401/403/404) empties it, without waiting for the
other reads, so a reload never shows refused join requests or approvals.
- The selected row's key is also recorded when the recorded row has left
the list, so a new item arriving above the fallback row never becomes
the selection or the archive target.
- An optimistic dismissal and its rollback start from the saved
dismissals that stand in, not from an empty list.
After the rebase onto `origin/master`: `cd ui && pnpm exec vitest run
src/pages src/lib src/hooks src/context src/components/coordinator`
passes (a first run under host load average ~35 had 4 timeouts and two
files missing new dependencies; after `agent-preflight` the affected
files pass, 223 tests).
- `pnpm check:token-gates`: clean. `pnpm verify` selected broader
coverage (exit 2, perf fixture is a global CI input); required CI
supplies it.
- Not run: the hosted staging page, the full local Vitest suite.

## Risks

- Saved approvals can be stale until the read answers (or after a
transient failure). A stale approval shows briefly and its actions go to
the server, which answers with the current state. A 401/403/404 drops
the saved values.
- The record holds approval payloads and join requests for the signed-in
user's company in `localStorage`. It uses the saved cache's existing
projection (secret-like fields removed), the same per-user revocation on
sign-out, and a 256 KB limit.
- #20591 is merged, so this branch (rebased on it) gets one read of each
shell request. Without it, a returning visit still reconnects the live
socket when the session is verified; because rows now reveal sooner,
that reconnect refetches more reads (here: session, health, company list
and agents twice). With both, every shell read runs once.
- Relation to #20592 (task chat preload): both edit
`ui/src/pages/Inbox.tsx` in different places and merge cleanly in either
order (checked with `git merge-tree`). This PR does not preload
anything. #20592 starts its chat preload when `allLoaded` turns true;
with this PR that happens sooner on a returning visit, while the reads
still refresh in the background, so its preload overlaps that refresh.
#20592 is merged and this branch is rebased on it with no conflicts.
- The selection change affects every Inbox tab: the key is recorded when
the selection moves, not on every list change. Archive and removal still
clamp as before.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits, Playwright). Standard context window,
reasoning enabled.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-13 21:49:17 -06:00
1 parent b7922570e1
commit 87d363a5c0
10 files changed
+636 -17

No files matched your search

+16
View File
@@ -87,6 +87,22 @@ click to the latest comment on screen over at least 5 fresh browser contexts
added to every API response. They also record the idle page's API request
count. The timings are attached evidence, not budgets.
`mine-returning-visit.spec.ts` hard loads Mine with the saved query cache
(`paperclip:query-cache:v1:<user>:<company>`, primed by one earlier visit in
the same browser context). Its fixture (`returning-visit-fixture.ts`) is a
company with 24 Mine tasks and three pending board approvals, retained in
`test-results/collections/mine-returning-visit-fixture.json`. With every read
of that company held, Mine must show its task rows and saved approvals before
any of those reads answers. An approval dismissed after the cache was saved
stands in until the reads answer and then leaves. Another company's Mine never
shows the saved company's rows. Its timing case records time from navigation
start to the first Mine row with the saved cache and with it cleared, with
every API response delayed `PAPERCLIP_COLLECTION_PERF_API_DELAY_MS` (default
300 ms), over `PAPERCLIP_COLLECTION_PERF_TIMING_RUNS` alternating runs (default
and minimum 5). Each sample names the last API response before the rows and
counts the load's requests; `PAPERCLIP_COLLECTION_PERF_OUTPUT` writes the
report to a file. The timings are attached evidence, not budgets.
Run these focused browser checks before the full collection suite:
```sh
@@ -0,0 +1,146 @@
import fs from "node:fs/promises";
import { expect, test, type Page } from "@playwright/test";
import {
freshContext, median, minePath, observeMineLoad, returningVisitFixture, savedQueryCache, type ReturningVisitFixture,
} from "./returning-visit-fixture";
// A returning visit to Mine restores its rows, approvals, join requests and
// dismissals from the saved query cache, so rows show before any company read
// answers. The reads still run and replace the saved values.
let fixture: ReturningVisitFixture;
test.beforeAll(async ({ request }) => {
test.setTimeout(120_000);
fixture = await returningVisitFixture(request);
});
const companyRead = (companyId: string) => (url: URL) => url.pathname.startsWith(`/api/companies/${companyId}/`);
const taskLink = (page: Page, identifier: string) => page.locator(`[data-inbox-issue-link][href$="/${identifier}"]`);
const approvalRow = (page: Page, approvalId: string) => page.locator(`a[href$="/approvals/${approvalId}"]`);
function holdReads(page: Page, matches: (url: URL) => boolean) {
let release!: () => void;
const held = new Promise<void>(resolve => { release = resolve; });
const answered: string[] = [];
page.on("requestfinished", request => {
const url = new URL(request.url());
if (matches(url)) answered.push(url.pathname);
});
const ready = page.route(matches, async route => {
await held;
await route.continue().catch(() => {});
});
return { ready, release, answered };
}
test("a returning visit shows Mine rows and approvals from the saved cache before any company read answers", async ({ browser, baseURL }) => {
const storageState = await savedQueryCache(browser, baseURL, fixture);
const context = await freshContext(browser, baseURL, storageState);
try {
const page = await context.newPage();
const hold = holdReads(page, companyRead(fixture.company.id));
await hold.ready;
try {
await page.goto(minePath(fixture));
for (const task of fixture.tasks.slice(0, 5)) {
await expect(taskLink(page, task.identifier), "Mine rows waited for a company read").toBeVisible({ timeout: 10_000 });
}
for (const id of fixture.approvalIds) await expect(approvalRow(page, id)).toBeVisible();
expect(hold.answered, "No company read may answer before the saved rows show").toEqual([]);
} finally { hold.release(); }
// The held reads then answer and leave the same rows in place.
await expect.poll(() => hold.answered.some(path => path.endsWith("/inbox/mine"))).toBe(true);
await expect(taskLink(page, fixture.tasks[0]!.identifier)).toBeVisible();
} finally { await context.close(); }
});
test("a saved approval that left Mine since the last visit goes when the reads answer", async ({ browser, baseURL, request }) => {
const created = await request.post(`/api/companies/${fixture.company.id}/approvals`, { data: {
type: "request_board_approval", payload: { title: "Returning visit stale approval", summary: "Dismissed after the cache was saved." },
} });
expect(created.ok(), await created.text()).toBeTruthy();
const stale = (await created.json()).id as string;
const storageState = await savedQueryCache(browser, baseURL, fixture);
// Dismissed from another device after this browser saved its cache.
const dismissed = await request.post(`/api/companies/${fixture.company.id}/inbox-dismissals`, { data: { itemKey: `approval:${stale}` } });
expect(dismissed.ok(), await dismissed.text()).toBeTruthy();
const context = await freshContext(browser, baseURL, storageState);
try {
const page = await context.newPage();
const hold = holdReads(page, companyRead(fixture.company.id));
await hold.ready;
await page.goto(minePath(fixture));
await expect(approvalRow(page, stale), "The saved approval stands in until the reads answer").toBeVisible();
hold.release();
await expect(approvalRow(page, stale)).toHaveCount(0);
await expect(taskLink(page, fixture.tasks[0]!.identifier)).toBeVisible();
} finally { await context.close(); }
});
test("a saved cache never shows one company's rows in another company's Mine", async ({ browser, baseURL, request }) => {
const other = await request.post("/api/companies", { data: { name: "Returning visit other company" } });
expect(other.ok(), await other.text()).toBeTruthy();
const otherCompany = await other.json() as { id: string; issuePrefix: string };
const storageState = await savedQueryCache(browser, baseURL, fixture);
const context = await freshContext(browser, baseURL, storageState);
try {
const page = await context.newPage();
const hold = holdReads(page, companyRead(otherCompany.id));
await hold.ready;
try {
await page.goto(`/${otherCompany.issuePrefix}/issues?view=mine`);
await page.waitForTimeout(1_500);
await expect(page.locator("[data-inbox-issue-link]")).toHaveCount(0);
for (const id of fixture.approvalIds) await expect(approvalRow(page, id)).toHaveCount(0);
} finally { hold.release(); }
} finally {
await context.close();
await request.delete(`/api/companies/${otherCompany.id}`);
}
});
// Time from navigation start to the first Mine row (two frames after mount),
// with every API response delayed by PAPERCLIP_COLLECTION_PERF_API_DELAY_MS
// (default 300 ms), in fresh browser contexts with and without the saved cache.
// Each sample names the last API response that finished before the rows and
// counts the load's API requests. Timings are evidence, not budgets.
test("records returning-visit time to Mine rows", async ({ browser, baseURL }, testInfo) => {
const runs = Number(process.env.PAPERCLIP_COLLECTION_PERF_TIMING_RUNS ?? 5);
const delayMs = Number(process.env.PAPERCLIP_COLLECTION_PERF_API_DELAY_MS ?? 300);
expect(Number.isInteger(runs) && runs >= 5, "Record at least five samples").toBe(true);
test.setTimeout(60_000 + runs * 2 * 30_000);
const storageState = await savedQueryCache(browser, baseURL, fixture);
const sample = async (cache: "saved" | "cleared") => {
const context = await freshContext(browser, baseURL, cache === "saved" ? storageState : undefined);
try {
const page = await context.newPage();
const { reads, rowsAt, shellReadCounts } = await observeMineLoad(page, delayMs);
await page.goto(minePath(fixture));
const rows = await rowsAt();
const navigationStart = await page.evaluate(() => performance.timeOrigin);
await page.waitForTimeout(5_000);
const before = reads.filter(read => read.finishedAt !== null && read.finishedAt <= rows)
.sort((a, b) => b.finishedAt! - a.finishedAt!);
return {
timeToRowsMs: Math.round(rows - navigationStart),
releasedBy: before[0] ? { path: before[0].path, msBeforeRows: Math.round(rows - before[0].finishedAt!) } : null,
responsesBeforeRows: before.length,
apiRequests: reads.length,
shellReads: shellReadCounts(),
};
} finally { await context.close(); }
};
type Sample = Awaited<ReturnType<typeof sample>>;
const samples: Record<"saved" | "cleared", Sample[]> = { saved: [], cleared: [] };
for (let run = 0; run < runs; run++) {
samples.saved.push(await sample("saved"));
samples.cleared.push(await sample("cleared"));
}
const report = (["saved", "cleared"] as const).map(cache => {
const times = samples[cache].map(entry => entry.timeToRowsMs);
console.log(`Mine time to rows, ${cache} cache, API +${delayMs} ms: median ${median(times)} ms over ${runs} runs (${[...times].sort((a, b) => a - b).join(", ")} ms); API requests ${samples[cache].map(entry => entry.apiRequests).join(", ")}`);
return { cache, apiDelayMs: delayMs, medianMs: median(times), samples: samples[cache] };
});
await testInfo.attach("mine-returning-visit-timing", { contentType: "application/json", body: Buffer.from(JSON.stringify(report, null, 2)) });
const output = process.env.PAPERCLIP_COLLECTION_PERF_OUTPUT;
if (output) await fs.writeFile(output, JSON.stringify(report, null, 2));
});
+23 -3
View File
@@ -1,6 +1,8 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { sidebarBadgesApi } from "../api/sidebarBadges";
import type { InboxDismissal } from "@paperclipai/shared";
import { isTransientError } from "../api/errors";
import { inboxDismissalsApi } from "../api/inboxDismissals";
import { queryKeys } from "../lib/queryKeys";
import {
@@ -40,17 +42,31 @@ export function useDismissedInboxAlerts() {
return { dismissed, dismiss };
}
export function useInboxDismissals(companyId: string | null | undefined) {
const NO_DISMISSALS: InboxDismissal[] = [];
/**
* `fallback` is a saved list for this company (see
* `lib/inbox-mine-reveal-sources.ts`). It stands in until the server answers,
* and after a transient failure. While it does, `isLoading` is false and
* `hasServerData` is false.
*/
export function useInboxDismissals(
companyId: string | null | undefined,
options: { fallback?: InboxDismissal[] | null } = {},
) {
const queryClient = useQueryClient();
const queryKey = companyId
? queryKeys.inboxDismissals(companyId)
: ["inbox-dismissals", "__disabled__"] as const;
const { data: dismissals = [], isLoading, error } = useQuery({
const { data, isLoading: isQueryLoading, error } = useQuery({
queryKey,
queryFn: () => inboxDismissalsApi.list(companyId!),
enabled: !!companyId,
});
const usesFallback = data === undefined && !!options.fallback && (!error || isTransientError(error));
const dismissals = data ?? (usesFallback ? options.fallback! : NO_DISMISSALS);
const isLoading = isQueryLoading && !usesFallback;
const dismissMutation = useMutation({
mutationFn: ({ itemKey, fingerprint }: { itemKey: string; fingerprint?: string }) =>
@@ -58,7 +74,10 @@ export function useInboxDismissals(companyId: string | null | undefined) {
onMutate: async ({ itemKey, fingerprint }) => {
if (!companyId) return { previous: [] as typeof dismissals };
await queryClient.cancelQueries({ queryKey });
const previous = queryClient.getQueryData<typeof dismissals>(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<typeof dismissals>(queryKey)
?? (usesFallback ? options.fallback! : NO_DISMISSALS);
const now = new Date();
queryClient.setQueryData(queryKey, [
{
@@ -129,6 +148,7 @@ export function useInboxDismissals(companyId: string | null | undefined) {
return {
dismissals,
isLoading,
hasServerData: data !== undefined,
error,
dismissedAtByKey,
dismiss,
+74
View File
@@ -0,0 +1,74 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { InboxDismissal } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
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";
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const saved = [{ id: "d-1", companyId: "company-1", userId: "user-1", itemKey: "approval:a-1", dismissedAt: new Date(1_000) }] as unknown as InboxDismissal[];
type Result = ReturnType<typeof useInboxDismissals>;
describe("useInboxDismissals fallback", () => {
let root: Root;
let client: QueryClient;
let latest: Result | null = null;
beforeEach(() => {
list.mockReset();
dismiss.mockReset();
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
root = createRoot(document.createElement("div"));
});
afterEach(async () => { await act(async () => root.unmount()); client.clear(); });
async function render(fallback: InboxDismissal[] | null) {
function Probe() { latest = useInboxDismissals("company-1", { fallback }); return null; }
await act(async () => root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>));
}
it("stands in while the read is pending and yields to the server answer", async () => {
let resolve!: (value: InboxDismissal[]) => void;
list.mockReturnValue(new Promise(r => { resolve = r; }));
await render(saved);
expect(latest).toMatchObject({ isLoading: false, hasServerData: false });
expect(latest!.dismissedAtByKey.get("approval:a-1")).toBe(1_000);
await act(async () => resolve([]));
await vi.waitFor(() => expect(latest).toMatchObject({ isLoading: false, hasServerData: true }));
expect(latest!.dismissedAtByKey.size).toBe(0);
});
it("keeps the saved list after a transient failure and drops it after a refusal", async () => {
list.mockRejectedValue(new ApiError("Busy", 503, null));
await render(saved);
await vi.waitFor(() => expect(latest!.error).toBeTruthy());
expect(latest!.dismissedAtByKey.get("approval:a-1")).toBe(1_000);
list.mockRejectedValue(new ApiError("No access", 403, null));
await act(async () => { await client.refetchQueries(); });
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);
expect(latest).toMatchObject({ isLoading: true, hasServerData: false });
});
});
@@ -0,0 +1,63 @@
import { describe, expect, it } from "vitest";
import type { Approval, InboxDismissal, JoinRequest } from "@paperclipai/shared";
import {
buildMineRevealSources, MINE_REVEAL_SOURCES_MAX_BYTES, mineRevealSourcesQueryKey, readMineRevealSources,
} from "./inbox-mine-reveal-sources";
import { persistedQueryScope } from "./persisted-query-cache";
const approval = (id: string, overrides: Partial<Approval> = {}) => ({
id, companyId: "company-1", type: "hire_agent", status: "pending", requestedByUserId: null, requestedByAgentId: "agent-1",
decidedByUserId: null, payload: { name: id }, createdAt: new Date(0), updatedAt: new Date(0), ...overrides,
}) as unknown as Approval;
const joinRequest = (id: string) => ({ id, companyId: "company-1", status: "pending_approval" }) as unknown as JoinRequest;
const dismissal = (itemKey: string) => ({ id: itemKey, companyId: "company-1", userId: "user-1", itemKey, dismissedAt: new Date(0) }) as unknown as InboxDismissal;
describe("Mine reveal sources", () => {
it("keeps only what Mine renders and the dismissals of those items", () => {
const sources = buildMineRevealSources({
userId: "user-1", companyId: "company-1",
approvals: [
approval("pending"),
approval("mine-resolved", { status: "approved", requestedByUserId: "user-1" }),
approval("other-resolved", { status: "approved", requestedByUserId: "user-2" }),
],
joinRequests: [joinRequest("join-1")],
dismissals: [dismissal("approval:pending"), dismissal("join:join-1"), dismissal("run:run-1"), dismissal("approval:other-resolved"), dismissal("run:other")],
failedRunIds: ["run-1"],
});
expect(sources.approvals.map((entry) => entry.id)).toEqual(["pending", "mine-resolved"]);
expect(sources.joinRequests.map((entry) => entry.id)).toEqual(["join-1"]);
expect(sources.dismissals.map((entry) => entry.itemKey)).toEqual(["approval:pending", "join:join-1", "run:run-1"]);
expect(readMineRevealSources(sources, "user-1", "company-1")).toBe(sources);
});
it("replaces an oversized record with an empty incomplete one that never answers the reveal", () => {
const big = "x".repeat(MINE_REVEAL_SOURCES_MAX_BYTES);
const sources = buildMineRevealSources({
userId: "user-1", companyId: "company-1", approvals: [approval("big", { payload: { summary: big } })],
joinRequests: [], dismissals: [], failedRunIds: [],
});
expect(sources).toEqual({ userId: "user-1", companyId: "company-1", approvals: [], joinRequests: [], dismissals: [], incomplete: true });
expect(readMineRevealSources(sources, "user-1", "company-1")).toBeNull();
});
it("answers only for the same user and company", () => {
const sources = buildMineRevealSources({ userId: "user-1", companyId: "company-1", approvals: [], joinRequests: [], dismissals: [], failedRunIds: [] });
expect(readMineRevealSources(sources, "user-2", "company-1")).toBeNull();
expect(readMineRevealSources(sources, "user-1", "company-2")).toBeNull();
expect(readMineRevealSources(sources, null, "company-1")).toBeNull();
expect(readMineRevealSources({ userId: "user-1", companyId: "company-1" }, "user-1", "company-1")).toBeNull();
expect(readMineRevealSources(undefined, "user-1", "company-1")).toBeNull();
});
it("is saved per user and company by the persisted query cache, and only when its data matches its key", () => {
const sources = buildMineRevealSources({ userId: "user-1", companyId: "company-1", approvals: [], joinRequests: [], dismissals: [], failedRunIds: [] });
const key = mineRevealSourcesQueryKey("company-1", "user-1");
expect(persistedQueryScope(key, sources, "user-1", ["company-1"])).toBe("company-1");
expect(persistedQueryScope(key, sources, "user-2", ["company-1"])).toBeUndefined();
expect(persistedQueryScope(key, sources, "user-1", ["company-2"])).toBeUndefined();
expect(persistedQueryScope(key, { ...sources, userId: "user-2" }, "user-1", ["company-1"])).toBeUndefined();
expect(persistedQueryScope(key, { ...sources, companyId: "company-2" }, "user-1", ["company-1"])).toBeUndefined();
expect(persistedQueryScope([...key, "extra"], sources, "user-1", ["company-1"])).toBeUndefined();
});
});
+63
View File
@@ -0,0 +1,63 @@
import type { Approval, InboxDismissal, JoinRequest } from "@paperclipai/shared";
import { isApprovalVisibleInMine } from "./inbox";
/**
* The approvals, join requests and dismissals that Mine showed on its last
* settled visit, for one user in one company.
*
* Approvals and join requests sort in among Mine's task rows by time, so on a
* first visit Mine waits for their first answer before it shows rows. The
* saved query cache already restores Mine's own snapshot, so on a returning
* visit this record answers that wait too: rows show from saved data at once,
* and every read refreshes in the background. The persisted query cache saves
* this record per user and company (`persistedQueryScope`).
*
* Only what Mine renders is kept: approvals visible in Mine, pending join
* requests, and the dismissals of those items and of Mine's failed runs. When
* that is larger than MINE_REVEAL_SOURCES_MAX_BYTES, an empty record marked
* `incomplete` replaces any older one, so a returning visit waits as a first
* visit does.
*/
export type MineRevealSources = {
userId: string;
companyId: string;
approvals: Approval[];
joinRequests: JoinRequest[];
dismissals: InboxDismissal[];
incomplete?: true;
};
export const MINE_REVEAL_SOURCES_MAX_BYTES = 256 * 1024;
export const mineRevealSourcesQueryKey = (companyId: string, userId: string | null) =>
["inbox", companyId, "mine-reveal-sources", userId] as const;
export function buildMineRevealSources(input: {
userId: string;
companyId: string;
approvals: readonly Approval[];
joinRequests: readonly JoinRequest[];
dismissals: readonly InboxDismissal[];
failedRunIds: readonly string[];
}): MineRevealSources {
const approvals = input.approvals.filter((approval) => isApprovalVisibleInMine(approval, input.userId));
const joinRequests = [...input.joinRequests];
const itemKeys = new Set([
...approvals.map((approval) => `approval:${approval.id}`),
...joinRequests.map((request) => `join:${request.id}`),
...input.failedRunIds.map((id) => `run:${id}`),
]);
const dismissals = input.dismissals.filter((dismissal) => itemKeys.has(dismissal.itemKey));
const sources: MineRevealSources = { userId: input.userId, companyId: input.companyId, approvals, joinRequests, dismissals };
return JSON.stringify(sources).length <= MINE_REVEAL_SOURCES_MAX_BYTES ? sources
: { userId: input.userId, companyId: input.companyId, approvals: [], joinRequests: [], dismissals: [], incomplete: true };
}
/** The saved record, only when it belongs to this user and company. */
export function readMineRevealSources(value: unknown, userId: string | null, companyId: string | null): MineRevealSources | null {
if (!value || typeof value !== "object" || !userId || !companyId) return null;
const record = value as Partial<MineRevealSources>;
if (record.userId !== userId || record.companyId !== companyId || record.incomplete) return null;
if (!Array.isArray(record.approvals) || !Array.isArray(record.joinRequests) || !Array.isArray(record.dismissals)) return null;
return record as MineRevealSources;
}
+15
View File
@@ -5,6 +5,7 @@ import { ApiError, api, detachInflightGets } from "@/api/client";
import { bindAccount } from "./account-scope";
import { hasUnverifiedSession, markCachedSession } from "./cached-session";
import { queryKeys } from "./queryKeys";
import { mineRevealSourcesQueryKey } from "./inbox-mine-reveal-sources";
import { readComposerRunSettings } from "../components/task-chat/composer-run-settings";
import { agentConnection, agentDefaultModel } from "./bulk-agent-settings";
import { clearPersistedQueryCache, persistedQueryScope, QUERY_CACHE_ACTIVE, QUERY_CACHE_CLEARED, QUERY_CACHE_MAX_AGE, QUERY_CACHE_PREFIX, startPersistedQueryCache } from "./persisted-query-cache";
@@ -529,6 +530,20 @@ describe("persisted read cache", () => {
expect(persistedQueryScope(["agent-chats", "company-one", "bob"], [], "alice", ["company-one"])).toBeUndefined();
});
it("restores Mine's reveal sources for the same user and company only", () => {
const first = setup(); seed(first.client);
const sources = { userId: "alice", companyId: "company-one", approvals: [{ id: "approval-1", status: "pending" }], joinRequests: [], dismissals: [] };
first.client.setQueryData(mineRevealSourcesQueryKey("company-one", "alice"), sources);
first.client.setQueryData(mineRevealSourcesQueryKey("company-one", "bob"), { ...sources, userId: "bob" });
first.handle.flush();
const restored = setup(first.storage);
const state = restored.client.getQueryState(mineRevealSourcesQueryKey("company-one", "alice"));
expect(state?.data).toEqual(sources);
// Restored reads are marked stale, so every consumer still refreshes them.
expect(state?.isInvalidated).toBe(true);
expect(restored.client.getQueryData(mineRevealSourcesQueryKey("company-one", "bob"))).toBeUndefined();
});
it.each(["build", "expiry"])("discards snapshots after %s changes", kind => {
vi.useFakeTimers();
const startedAt = Date.now();
+2
View File
@@ -111,6 +111,8 @@ export function persistedQueryScope(key: readonly unknown[], data: unknown, user
if (root === "agent-chats" && key.length === 3 && third === userId) return second;
if (root === "primary-agent" && third === userId && key.length === 3) return second;
if (root === "issues" && third === "mine-context" && key.length === 4 && key[3] === userId && object(data)?.userId === userId) return second;
if (root === "inbox" && third === "mine-reveal-sources" && key.length === 4 && key[3] === userId
&& object(data)?.userId === userId && object(data)?.companyId === second) return second;
if (root === "issues" && ["mine-by-me", "touched-by-me"].includes(String(third))
&& key[3] === "index" && key[4] === "with-routine-executions" && key[5] === "live-descendant-summary"
&& key[6] === 100 && (third === "mine-by-me" ? key.length === 8 && key[7] === userId : key.length === 7)) return second;
+168 -9
View File
@@ -2,6 +2,7 @@
import { CoordinatorPresentation } from "../components/coordinator/CoordinatorPresentation";
import { queryKeys } from "../lib/queryKeys";
import { mineRevealSourcesQueryKey, type MineRevealSources } from "../lib/inbox-mine-reveal-sources";
import type { ComponentProps } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
@@ -150,15 +151,19 @@ vi.mock("../lib/inbox", async () => {
};
});
vi.mock("../hooks/useInboxBadge", () => ({
useDismissedInboxAlerts: () => ({ dismissed: new Set(), dismiss: vi.fn() }),
useInboxDismissals: () => ({ dismissedAtByKey: new Map(), dismiss: vi.fn() }),
useReadInboxItems: () => ({
readItems: new Set(),
markRead: vi.fn(),
markUnread: vi.fn(),
}),
}));
vi.mock("../hooks/useInboxBadge", () => {
// Stable values, as the real hook's query data is between renders.
const dismissals = { dismissedAtByKey: new Map(), dismiss: vi.fn(), dismissals: [], hasServerData: true, isLoading: false, error: null };
return {
useDismissedInboxAlerts: () => ({ dismissed: new Set(), dismiss: vi.fn() }),
useInboxDismissals: () => dismissals,
useReadInboxItems: () => ({
readItems: new Set(),
markRead: vi.fn(),
markUnread: vi.fn(),
}),
};
});
vi.mock("../hooks/useIssueExternalObjects", () => ({
useIssueExternalObjectSummaries: () => ({
@@ -2028,6 +2033,128 @@ describe("Inbox toolbar", () => {
} finally { await act(() => root.unmount()); client.clear(); }
});
describe("returning visit with saved reveal sources", () => {
const savedApproval = createApproval({ id: "approval-saved", payload: { name: "Saved approval" }, updatedAt: new Date("2026-03-11T00:00:01.500Z") });
const approvalRowCount = () => container.querySelectorAll('a[href="/approvals/approval-saved"]').length;
// First visit: every read answers and Mine saves what it showed. Then the
// optional reads leave the cache, as on a hard load that restored only
// the saved query cache, and the page mounts again.
const visitThenReturn = async (client: QueryClient, root: ReturnType<typeof createRoot>) => {
apiMocks.approvalsList.mockResolvedValue([savedApproval]);
await renderInbox(client, root);
await vi.waitFor(() => expect(approvalRowCount()).toBe(1));
await vi.waitFor(() => expect(client.getQueryData<MineRevealSources>(mineRevealSourcesQueryKey("company-1", "local-board"))?.approvals
.map((approval) => approval.id)).toEqual(["approval-saved"]));
await act(async () => root.unmount());
client.removeQueries({ queryKey: queryKeys.approvals.list("company-1") });
client.removeQueries({ queryKey: queryKeys.access.joinRequests("company-1") });
apiMocks.approvalsList.mockClear();
};
const client = () => new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } });
it("reveals rows and the saved approval while the reads are pending, then keeps selection when a new approval arrives", async () => {
routerMock.location.pathname = "/inbox/mine";
twoRows();
const queryClient = client();
let root = createRoot(container);
try {
await visitThenReturn(queryClient, root);
let resolveApprovals: (value: Approval[]) => void = () => {};
apiMocks.approvalsList.mockReturnValue(new Promise((resolve) => { resolveApprovals = resolve; }));
apiMocks.joinRequestsList.mockReturnValue(new Promise(() => {}));
root = createRoot(container);
await renderInbox(queryClient, root);
await vi.waitFor(() => expect(apiMocks.approvalsList).toHaveBeenCalled());
expect(rowKeys().filter(Boolean)).toEqual(["PAP-4001", "PAP-4002"]);
expect(approvalRowCount()).toBe(1);
for (let press = 0; press < 3; press += 1) {
await act(async () => { document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "j", bubbles: true })); });
}
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(" | ");
const before = selectedText();
expect(before).not.toBe("");
await act(async () => {
resolveApprovals([savedApproval, createApproval({ id: "approval-new", payload: { name: "Late approval" }, updatedAt: new Date("2026-03-11T00:00:05.000Z") })]);
});
await vi.waitFor(() => expect(container.querySelectorAll('a[href="/approvals/approval-new"]').length).toBe(1));
expect(selectedText()).toBe(before);
} finally { await act(() => root.unmount()); queryClient.clear(); }
});
it("keeps the saved approval through a transient failure and drops it after a refusal", async () => {
routerMock.location.pathname = "/inbox/mine";
twoRows();
const queryClient = client();
let root = createRoot(container);
try {
await visitThenReturn(queryClient, root);
apiMocks.approvalsList.mockRejectedValue(new ApiError("Busy", 503, null));
root = createRoot(container);
await renderInbox(queryClient, root);
await vi.waitFor(() => expect(apiMocks.approvalsList).toHaveBeenCalled());
await vi.waitFor(() => expect(queryClient.getQueryState(queryKeys.approvals.list("company-1"))?.status).toBe("error"));
expect(rowKeys().filter(Boolean)).toEqual(["PAP-4001", "PAP-4002"]);
expect(approvalRowCount()).toBe(1);
apiMocks.approvalsList.mockRejectedValue(new ApiError("No access", 403, null));
await act(async () => { await queryClient.refetchQueries({ queryKey: queryKeys.approvals.list("company-1") }); });
await vi.waitFor(() => expect(approvalRowCount()).toBe(0));
expect(rowKeys().filter(Boolean)).toEqual(["PAP-4001", "PAP-4002"]);
} 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<MineRevealSources>(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();
const queryClient = client();
queryClient.setQueryData(mineRevealSourcesQueryKey("company-1", "local-board"), {
userId: "someone-else", companyId: "company-1", approvals: [savedApproval], joinRequests: [], dismissals: [],
} satisfies MineRevealSources);
apiMocks.approvalsList.mockReturnValue(new Promise(() => {}));
const root = createRoot(container);
try {
await renderInbox(queryClient, root);
await vi.waitFor(() => {
const mineQueries = queryClient.getQueryCache().findAll({ queryKey: queryKeys.issues.listMineByMe("company-1") });
expect(mineQueries.some((query) => query.state.status === "success")).toBe(true);
});
expect(container.querySelector("[data-inbox-item]")).toBeNull();
expect(approvalRowCount()).toBe(0);
} finally { await act(() => root.unmount()); queryClient.clear(); }
});
});
it("bounds a stalled approvals read so rows do not stay behind a skeleton", async () => {
routerMock.location.pathname = "/inbox/mine";
twoRows();
@@ -2111,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(<QueryClientProvider client={queryClient}><Inbox /></QueryClientProvider>); });
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" });
+66 -5
View File
@@ -35,6 +35,7 @@ import { useToastActions } from "../context/ToastContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { useSidebar } from "../context/SidebarContext";
import { queryKeys } from "../lib/queryKeys";
import { buildMineRevealSources, mineRevealSourcesQueryKey, readMineRevealSources, type MineRevealSources } from "../lib/inbox-mine-reveal-sources";
import { useDialogActions } from "../context/DialogContext";
import { useIssueExternalObjectSummaries } from "../hooks/useIssueExternalObjects";
import {
@@ -207,6 +208,7 @@ const INBOX_ISSUE_LIST_LIMIT = 100;
const INBOX_HOT_PATH_STALE_MS = 30_000;
// Stable fallback so memos over unloaded or disabled issue reads do not rerun on every render.
const NO_ISSUES: Issue[] = [];
const NO_JOIN_REQUESTS: JoinRequest[] = [];
/** Bounds an optional read that can hold task rows hidden; a timeout reveals rows and retries in the background. */
const INBOX_OPTIONAL_READ_TIMEOUT_MS = 10_000;
const INBOX_COLLECTION_KEY = "inbox";
@@ -886,7 +888,6 @@ function StreamlinedInbox({
() => loadInboxCollectionPreferences(selectedCompanyId).columns,
);
const { dismissed: dismissedAlerts, dismiss: dismissAlert } = useDismissedInboxAlerts();
const { dismissedAtByKey, dismiss: dismissInboxItem, isLoading: isDismissalsLoading, error: dismissalsError } = useInboxDismissals(selectedCompanyId);
const { readItems, markRead: markItemRead, markUnread: markItemUnread } = useReadInboxItems();
const { allCategoryFilter, allApprovalFilter, issueFilters } = filterPreferences;
@@ -918,6 +919,21 @@ function StreamlinedInbox({
const currentUserId = session?.user.id ?? session?.session.userId ?? null;
const mineContextQueryKey = [...queryKeys.issues.list(selectedCompanyId!), "mine-context", currentUserId] as const;
const { data: mineSnapshot } = useQuery<InboxMineSnapshot>({ queryKey: mineContextQueryKey, enabled: false });
// On a returning visit the saved query cache restores Mine's snapshot and the
// approvals, join requests and dismissals it showed. Those stand in until the
// reads answer, so rows show without waiting on the network.
const revealSourcesQueryKey = mineRevealSourcesQueryKey(selectedCompanyId!, currentUserId);
const { data: savedRevealSourcesData } = useQuery<MineRevealSources>({ queryKey: revealSourcesQueryKey, enabled: false });
const savedRevealSources = tab === "mine" && mineSnapshot
? readMineRevealSources(savedRevealSourcesData, currentUserId, selectedCompanyId) : null;
const {
dismissals: inboxDismissals,
dismissedAtByKey,
dismiss: dismissInboxItem,
isLoading: isDismissalsLoading,
hasServerData: hasServerDismissals,
error: dismissalsError,
} = useInboxDismissals(selectedCompanyId, { fallback: savedRevealSources?.dismissals });
const { data: agents, isLoading: isAgentsLoading } = useQuery({
@@ -962,7 +978,7 @@ function StreamlinedInbox({
}, [selectedCompanyId]);
const {
data: approvals,
data: serverApprovals,
isLoading: isApprovalsLoading,
failureCount: approvalsFailureCount,
error: approvalsError,
@@ -974,7 +990,7 @@ function StreamlinedInbox({
});
const {
data: joinRequests = [],
data: serverJoinRequests,
isLoading: isJoinRequestsLoading,
failureCount: joinRequestsFailureCount,
error: joinRequestsError,
@@ -996,6 +1012,40 @@ function StreamlinedInbox({
enabled: !!selectedCompanyId,
});
// Saved values stand in while a read is pending or after a transient failure;
// a refusal (403/404) or a server answer replaces them.
const savedStandsIn = (data: unknown, error: unknown) =>
data === undefined && savedRevealSources !== null && (!error || isTransientError(error));
const approvalsFromSaved = savedStandsIn(serverApprovals, approvalsError);
const joinRequestsFromSaved = savedStandsIn(serverJoinRequests, joinRequestsError);
const approvals = approvalsFromSaved ? savedRevealSources!.approvals : serverApprovals;
const joinRequests = serverJoinRequests ?? (joinRequestsFromSaved ? savedRevealSources!.joinRequests : NO_JOIN_REQUESTS);
// 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;
const key = mineRevealSourcesQueryKey(selectedCompanyId, currentUserId);
const saved = readMineRevealSources(queryClient.getQueryData(key), currentUserId, selectedCompanyId);
const refused = (error: unknown) => !!error && !isTransientError(error);
const part = <T,>(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, approvalsError, serverJoinRequests, joinRequestsError,
hasServerDismissals, inboxDismissals, dismissalsError, queryClient]);
const dashboardQueryKey = queryKeys.dashboard(selectedCompanyId!);
const sharedDashboard = useSharedPollingQuery({
companyId: selectedCompanyId,
@@ -2274,7 +2324,17 @@ function StreamlinedInbox({
return keyIndex >= 0 ? keyIndex : resolveInboxSelectionIndex(prev, flatNavItems.length);
});
}, [flatNavItems]);
// 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(() => {
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]);
@@ -2581,8 +2641,9 @@ function StreamlinedInbox({
// rows down. Wait for their first bounded attempt only; a failure or timeout reveals rows.
const approvalsAffectRows = tab !== "blocked" && (tab !== "all" || showApprovalsCategory);
const joinRequestsAffectRows = tab !== "blocked" && (tab !== "all" || showJoinRequestsCategory);
const isApprovalsFirstAttemptPending = isApprovalsLoading && approvalsFailureCount === 0;
const isJoinRequestsFirstAttemptPending = isJoinRequestsLoading && joinRequestsFailureCount === 0;
// Saved values from the last visit answer this wait on a returning visit.
const isApprovalsFirstAttemptPending = isApprovalsLoading && approvalsFailureCount === 0 && !approvalsFromSaved;
const isJoinRequestsFirstAttemptPending = isJoinRequestsLoading && joinRequestsFailureCount === 0 && !joinRequestsFromSaved;
// User names only fill row text, except when they name and order assignee groups.
const userLabelsAffectRows = groupBy === "assignee";
const isMembersFirstAttemptPending = isMembersLoading && membersFailureCount === 0;