mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 14:20:12 +01:00
## 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>
225 lines
7.7 KiB
TypeScript
225 lines
7.7 KiB
TypeScript
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 {
|
|
useLocalInboxArchiveIssueIds,
|
|
} from "../lib/inboxArchiveCache";
|
|
import { usePublishSharedQueryData, useSharedPollingQuery } from "./useSharedPolling";
|
|
import {
|
|
buildInboxDismissedAtByKey,
|
|
loadDismissedInboxAlerts,
|
|
saveDismissedInboxAlerts,
|
|
loadReadInboxItems,
|
|
saveReadInboxItems,
|
|
READ_ITEMS_KEY,
|
|
} from "../lib/inbox";
|
|
|
|
export function useDismissedInboxAlerts() {
|
|
const [dismissed, setDismissed] = useState<Set<string>>(loadDismissedInboxAlerts);
|
|
|
|
useEffect(() => {
|
|
const handleStorage = (event: StorageEvent) => {
|
|
if (event.key !== "paperclip:inbox:dismissed") return;
|
|
setDismissed(loadDismissedInboxAlerts());
|
|
};
|
|
window.addEventListener("storage", handleStorage);
|
|
return () => window.removeEventListener("storage", handleStorage);
|
|
}, []);
|
|
|
|
const dismiss = (id: string) => {
|
|
setDismissed((prev) => {
|
|
const next = new Set(prev);
|
|
next.add(id);
|
|
saveDismissedInboxAlerts(next);
|
|
return next;
|
|
});
|
|
};
|
|
|
|
return { dismissed, dismiss };
|
|
}
|
|
|
|
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, 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 }) =>
|
|
inboxDismissalsApi.dismiss(companyId!, itemKey, fingerprint),
|
|
onMutate: async ({ itemKey, fingerprint }) => {
|
|
if (!companyId) return { previous: [] as typeof dismissals };
|
|
await queryClient.cancelQueries({ 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, [
|
|
{
|
|
id: `optimistic:${itemKey}`,
|
|
companyId,
|
|
userId: "me",
|
|
itemKey,
|
|
dismissedAt: now,
|
|
fingerprint: fingerprint ?? null,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
},
|
|
...previous.filter((dismissal) => dismissal.itemKey !== itemKey),
|
|
]);
|
|
return { previous };
|
|
},
|
|
onError: (_error, _variables, context) => {
|
|
if (!context) return;
|
|
queryClient.setQueryData(queryKey, context.previous);
|
|
},
|
|
onSettled: () => {
|
|
if (!companyId) return;
|
|
invalidateDismissalConsumers();
|
|
},
|
|
});
|
|
|
|
function invalidateDismissalConsumers() {
|
|
if (!companyId) return;
|
|
queryClient.invalidateQueries({ queryKey });
|
|
queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(companyId) });
|
|
// The attention feed derives its rows from server-side dismissals, so any
|
|
// dismiss/snooze/restore must re-pull it to keep the queue and curtains in sync.
|
|
queryClient.invalidateQueries({ queryKey: queryKeys.attention(companyId) });
|
|
}
|
|
|
|
const snoozeMutation = useMutation({
|
|
mutationFn: ({ itemKey, snoozedUntil, fingerprint }: { itemKey: string; snoozedUntil: string; fingerprint?: string }) =>
|
|
inboxDismissalsApi.snooze(companyId!, itemKey, snoozedUntil, fingerprint),
|
|
onSettled: invalidateDismissalConsumers,
|
|
});
|
|
|
|
const restoreMutation = useMutation({
|
|
mutationFn: ({ itemKey }: { itemKey: string }) => inboxDismissalsApi.restore(companyId!, itemKey),
|
|
onSettled: invalidateDismissalConsumers,
|
|
});
|
|
|
|
const dismissedAtByKey = useMemo(
|
|
() => buildInboxDismissedAtByKey(dismissals),
|
|
[dismissals],
|
|
);
|
|
|
|
// Stable identities (react-query keeps `mutate` referentially stable) so
|
|
// consumers can hand these to memoized rows without breaking memoization.
|
|
const dismissMutate = dismissMutation.mutate;
|
|
const snoozeMutate = snoozeMutation.mutate;
|
|
const restoreMutate = restoreMutation.mutate;
|
|
const dismiss = useCallback(
|
|
(itemKey: string, fingerprint?: string) => dismissMutate({ itemKey, fingerprint }),
|
|
[dismissMutate],
|
|
);
|
|
const snooze = useCallback(
|
|
(itemKey: string, snoozedUntil: string, fingerprint?: string) =>
|
|
snoozeMutate({ itemKey, snoozedUntil, fingerprint }),
|
|
[snoozeMutate],
|
|
);
|
|
const restore = useCallback((itemKey: string) => restoreMutate({ itemKey }), [restoreMutate]);
|
|
|
|
return {
|
|
dismissals,
|
|
isLoading,
|
|
hasServerData: data !== undefined,
|
|
error,
|
|
dismissedAtByKey,
|
|
dismiss,
|
|
snooze,
|
|
restore,
|
|
isPending: dismissMutation.isPending || snoozeMutation.isPending || restoreMutation.isPending,
|
|
};
|
|
}
|
|
|
|
export function useReadInboxItems() {
|
|
const [readItems, setReadItems] = useState<Set<string>>(loadReadInboxItems);
|
|
|
|
useEffect(() => {
|
|
const handleStorage = (event: StorageEvent) => {
|
|
if (event.key !== READ_ITEMS_KEY) return;
|
|
setReadItems(loadReadInboxItems());
|
|
};
|
|
window.addEventListener("storage", handleStorage);
|
|
return () => window.removeEventListener("storage", handleStorage);
|
|
}, []);
|
|
|
|
const markRead = (id: string) => {
|
|
setReadItems((prev) => {
|
|
const next = new Set(prev);
|
|
next.add(id);
|
|
saveReadInboxItems(next);
|
|
return next;
|
|
});
|
|
};
|
|
|
|
const markUnread = (id: string) => {
|
|
setReadItems((prev) => {
|
|
const next = new Set(prev);
|
|
next.delete(id);
|
|
saveReadInboxItems(next);
|
|
return next;
|
|
});
|
|
};
|
|
|
|
return { readItems, markRead, markUnread };
|
|
}
|
|
|
|
export function useInboxBadge(companyId: string | null | undefined) {
|
|
const locallyArchivedIssueIds = useLocalInboxArchiveIssueIds(companyId);
|
|
const badgeQueryKey = queryKeys.sidebarBadges(companyId ?? "__disabled__");
|
|
const sharedBadges = useSharedPollingQuery({
|
|
companyId,
|
|
resourceKey: "inbox-badge",
|
|
queryKey: badgeQueryKey,
|
|
enabled: !!companyId,
|
|
});
|
|
const { data: badges, dataUpdatedAt } = useQuery({
|
|
queryKey: badgeQueryKey,
|
|
queryFn: () => sidebarBadgesApi.get(companyId!),
|
|
enabled: !!companyId,
|
|
refetchOnWindowFocus: false,
|
|
staleTime: 30_000,
|
|
});
|
|
usePublishSharedQueryData(sharedBadges, badges, dataUpdatedAt);
|
|
|
|
return useMemo(() => {
|
|
const unreadIssueIds = badges?.unreadIssueIds ?? [];
|
|
const archivedUnread = unreadIssueIds.filter((id) => locallyArchivedIssueIds.has(id)).length;
|
|
return {
|
|
inbox: Math.max(0, (badges?.inbox ?? 0) - archivedUnread),
|
|
approvals: badges?.approvals ?? 0,
|
|
failedRuns: badges?.failedRuns ?? 0,
|
|
joinRequests: badges?.joinRequests ?? 0,
|
|
mineIssues: unreadIssueIds.length - archivedUnread,
|
|
alerts: 0,
|
|
};
|
|
}, [badges, locallyArchivedIssueIds]);
|
|
}
|