Files
PaperClipAI/ui/src/hooks/useSharedPolling.ts
T
DottaandPaperclip 59eee4829c fix(inbox): stop archived items from resurfacing (#9931)
## Thinking Path

> - Paperclip is the control plane operators use to coordinate AI-agent
companies and review work needing attention.
> - The Inbox is the operator-facing surface that aggregates tasks
requiring attention across server state and shared client polling.
> - Archiving a task optimistically removed it, but ordinary background
activity and stale polling responses could make it reappear seconds
later.
> - The server therefore needs to distinguish genuine user-attention
events from routine agent/system activity.
> - The client also needs a bounded local archive guard across every
Inbox query path while the server mutation and in-flight polls settle.
> - This pull request fixes both resurrection paths and adds
race-focused regression coverage.
> - The benefit is stable archive behavior without hiding a genuine
archive failure after reconciliation or reload.

## Linked Issues or Issue Description

### Pre-submission checklist

- [x] Searched existing open and closed issues and pull requests; no
duplicate implementation was found.
- [x] Reproduced on `master` before this branch.
- [x] Confirmed this is a Paperclip core bug, not adapter or provider
behavior.

### What happened?

Archiving an Inbox task hid it optimistically, then background refresh
activity could insert it back into the list seconds later.

### Expected behavior

A successfully archived task remains hidden during normal polling. A
genuine failed archive may become visible again after reconciliation or
reload.

### Steps to reproduce

1. Open Inbox with a visible task.
2. Archive the task.
3. Wait for shared polling or routine agent activity to refresh task
data.
4. Observe the archived task reappear without a hard page refresh.

### Paperclip version or commit

`master` before this branch.

### Deployment mode

Built from source using the local development application.

### Installation method

Built from source (`pnpm`).

### Agent adapter(s) involved

Not adapter-specific; this is a core Inbox bug.

### Database mode

Not database-mode-specific.

### Access context

Board (human operator).

### Additional context

The failure had independent server and client causes: routine activity
could resurface archived rows server-side, while stale shared-poll
responses could bypass optimistic client removal.

## What Changed

- Restrict server-side Inbox resurfacing to explicit user-attention
events rather than any issue activity write.
- Add a bounded client-side archive guard with confirmation, failure
restoration, and cache reconciliation behavior.
- Apply the guard to Inbox rendering, badge counts, optimistic cache
updates, and shared-poll result application.
- Classify the generic compact Inbox query so stale shared-poll data
cannot bypass the guard.
- Add server visibility-matrix tests and UI race-condition regression
tests.

## Verification

- `pnpm --filter @paperclipai/ui exec vitest run
src/hooks/useSharedPolling.test.ts src/lib/inboxArchiveCache.test.ts
src/pages/Inbox.test.tsx` — 25 passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issues-service.test.ts` — 107 passed.
- Branch rebased cleanly onto current `origin/master` before push.

## Risks

- Low-to-moderate behavioral risk: resurfacing is intentionally
narrower, so the server tests cover human comments, mentions,
interactions, and status transitions that must still regain attention.
- The client guard is bounded and cleared on mutation failure, limiting
the risk of hiding a task whose archive did not persist.
- No schema, migration, public API, workflow, dependency-lock, or
visual-token changes.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Anthropic Claude via Claude Code (`claude_local`; prior
implementation/review run, exact underlying model ID and context window
were not retained in the handoff metadata), with repository tool use and
test execution.
- OpenAI `gpt-5.5` via Codex CLI for final review repair and PR
preparation, with reasoning, repository editing, GitHub tooling, and
code execution.

## 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/described the result 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 and contains no internal
Paperclip task identifier
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation where needed; no
documentation change is required for this bug fix
- [x] I have considered and documented risks above
- [x] All Paperclip-authored commits include the required co-author
trailer

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-07-21 08:13:14 -05:00

151 lines
5.1 KiB
TypeScript

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { type QueryClient, type QueryKey, useQueryClient } from "@tanstack/react-query";
import {
SharedPollingCoordinator,
type SharedMessage,
type SharedPollingSnapshot,
} from "../lib/cross-tab-poll";
import { filterLocalInboxArchivedQueryData } from "../lib/inboxArchiveCache";
type RefetchInterval = number | false;
export interface SharedPollingQueryOptions {
companyId: string | null | undefined;
resourceKey: string;
queryKey: QueryKey;
enabled?: boolean;
refetchInterval?: RefetchInterval;
/**
* When true, non-leader tabs disable their active polling/query fetch for this
* resource and render from broadcast/cache data. Use for interval-polled hot
* endpoints. Leave false for one-shot reads where blank first paint is worse
* than a duplicated initial fetch.
*/
leaderOnly?: boolean;
}
export interface SharedPollingQueryState<TData> {
isLeader: boolean;
enabled: boolean;
refetchInterval: RefetchInterval;
publish: (data: TData | undefined, dataUpdatedAt: number) => void;
}
type RegistryEntry = {
coordinator: SharedPollingCoordinator;
refs: number;
};
const coordinators = new Map<string, RegistryEntry>();
function acquireCoordinator(companyId: string): SharedPollingCoordinator {
const existing = coordinators.get(companyId);
if (existing) {
existing.refs += 1;
return existing.coordinator;
}
const coordinator = new SharedPollingCoordinator(companyId);
coordinator.start();
coordinators.set(companyId, { coordinator, refs: 1 });
return coordinator;
}
function releaseCoordinator(companyId: string): void {
const existing = coordinators.get(companyId);
if (!existing) return;
existing.refs -= 1;
if (existing.refs > 0) return;
existing.coordinator.stop();
coordinators.delete(companyId);
}
function resourceKey(companyId: string, key: string, queryKeyHash: string): string {
return `${companyId}:${key}:${queryKeyHash}`;
}
export function applySharedPollingResult<TData>(
queryClient: Pick<QueryClient, "getQueryState" | "setQueryData">,
queryKey: QueryKey,
message: SharedMessage,
): boolean {
if (message.type !== "result") return false;
const incomingUpdatedAt = message.dataUpdatedAt ?? message.at;
if (incomingUpdatedAt <= 0) return false;
const localUpdatedAt = queryClient.getQueryState(queryKey)?.dataUpdatedAt ?? 0;
if (localUpdatedAt >= incomingUpdatedAt) return false;
const data = filterLocalInboxArchivedQueryData(queryKey, message.data as TData);
queryClient.setQueryData(queryKey, data, { updatedAt: incomingUpdatedAt });
return true;
}
export function useSharedPollingQuery<TData>({
companyId,
resourceKey: rawResourceKey,
queryKey,
enabled = true,
refetchInterval = false,
leaderOnly = false,
}: SharedPollingQueryOptions): SharedPollingQueryState<TData> {
const queryClient = useQueryClient();
const activeCompanyId = enabled && companyId ? companyId : null;
const queryKeyHash = useMemo(() => JSON.stringify(queryKey), [queryKey]);
const fullResourceKey = activeCompanyId ? resourceKey(activeCompanyId, rawResourceKey, queryKeyHash) : null;
const queryKeyRef = useRef(queryKey);
const [snapshot, setSnapshot] = useState<SharedPollingSnapshot>({ isLeader: true });
useEffect(() => {
queryKeyRef.current = queryKey;
}, [queryKey, queryKeyHash]);
useEffect(() => {
if (!activeCompanyId || !fullResourceKey) {
setSnapshot({ isLeader: true });
return;
}
const coordinator = acquireCoordinator(activeCompanyId);
const unsubscribeState = coordinator.subscribe(setSnapshot);
const unsubscribeResource = coordinator.subscribeResource(fullResourceKey, (message) => {
applySharedPollingResult(queryClient, queryKeyRef.current, message);
});
coordinator.request(fullResourceKey);
return () => {
unsubscribeResource();
unsubscribeState();
releaseCoordinator(activeCompanyId);
};
}, [activeCompanyId, fullResourceKey, leaderOnly, queryClient, queryKeyHash]);
const isLeader = !leaderOnly || snapshot.isLeader;
const queryEnabled = enabled && (!leaderOnly || snapshot.isLeader);
const coordinatedInterval = leaderOnly && !snapshot.isLeader ? false : refetchInterval;
const publish = useCallback((data: TData | undefined, dataUpdatedAt: number) => {
if (!activeCompanyId || !fullResourceKey || data === undefined) return;
const entry = coordinators.get(activeCompanyId);
entry?.coordinator.publish(fullResourceKey, data, dataUpdatedAt);
}, [activeCompanyId, fullResourceKey]);
return useMemo(
() => ({
isLeader,
enabled: queryEnabled,
refetchInterval: coordinatedInterval,
publish,
}),
[coordinatedInterval, isLeader, publish, queryEnabled],
);
}
export function usePublishSharedQueryData<TData>(
shared: Pick<SharedPollingQueryState<TData>, "publish" | "isLeader">,
data: TData | undefined,
dataUpdatedAt: number,
): void {
useEffect(() => {
if (!shared.isLeader || dataUpdatedAt <= 0) return;
shared.publish(data, dataUpdatedAt);
}, [data, dataUpdatedAt, shared]);
}