Files
PaperClipAI/ui/src/hooks/useSharedPolling.ts
T
Devin Foley d90f4d488e fix(ui): survive first load against a cold backend without a blank page (#11246)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The web UI holds live websocket connections for run events,
coordinates cross-tab polling through a leader-election store, and
renders app chrome (sidebar, providers) around a routed outlet
> - When the backend is still cold-starting (managed hosting wake,
server restart, reverse proxy up before the app), the event websockets
refuse connections and the first SPA load mounts against a dead backend
> - In that state the mount cascade can exceed React's nested update
limit (minified error #185); the crash originates in shell hooks outside
the routed error boundary, so React unmounts the entire root to a blank
page, and the dead page keeps retrying the websocket on a flat 1.5s
timer until the user hard-refreshes
> - This pull request removes the wasted nested commits from the
shared-polling subscription path, adds exponential backoff to the
transcript websocket reconnect, and adds a last-resort app-shell error
boundary
> - The benefit is that a cold or briefly unreachable backend degrades
to a recoverable state instead of a blank page that hammers the server

## Linked Issues or Issue Description

No existing issue. Description follows the bug template:

**What happened?**

On the first load against a backend that was still starting, the app
showed its loading animation and then a blank page. The console showed
repeated `WebSocket connection to 'wss://…/api/companies/<id>/events/ws'
failed` lines and `Uncaught Error: Minified React error #185` with a
stack through the shared-polling coordinator's `subscribe`. The
websocket retries continued indefinitely on the dead page. A manual
refresh fixed it.

**Expected behavior**

A backend that is briefly unreachable degrades gracefully: websocket
reconnects back off, the UI keeps rendering from cache, and even a
worst-case crash shows a reload prompt instead of a blank page.

**Steps to reproduce**

1. Serve the UI while the backend API is still starting (websocket
upgrades and API calls refused).
2. Load any company page with several shared-polling consumers mounted
(dashboard with sidebar).
3. Observe repeated websocket failures; on affected loads the page goes
blank with React error #185.

## What Changed

- `ui/src/hooks/useSharedPolling.ts`: coordinator snapshot notifications
now keep the previous state object when leadership did not change, so
React bails out instead of scheduling a nested re-render. `subscribe`
invokes its listener synchronously from inside the mount effect with a
fresh object each time; before this change every mount and notify burned
nested-update budget even with no value change — the crash frame in the
field report was exactly this `subscribe → setState` call.
- `ui/src/components/transcript/useLiveRunTranscripts.ts`: the live
event websocket reconnect backs off exponentially (1.5s → 15s cap, reset
on successful open), mirroring `LiveUpdatesProvider`, instead of a flat
1.5s retry.
- `ui/src/components/AppErrorBoundary.tsx` (+ wiring in
`ui/src/main.tsx`): a dependency-free boundary above the router and
providers. `RouteErrorBoundary` only guards the routed `<Outlet />`; a
crash in the shell around it had no boundary, so React unmounted the
root to a blank page. The boundary renders a reload prompt with the
error message.
- Tests: `useSharedPollingSnapshot.test.tsx` (mount costs no extra
commit — fails against the previous code; a real leadership change
re-renders exactly once and ticks stay quiet), a backoff test in
`useLiveRunTranscripts.test.tsx` (delays grow 1.5s → 3s → 6s and reset
after a successful open), and `AppErrorBoundary.test.tsx` (render throw,
effect throw, healthy pass-through).

## Verification

- `pnpm vitest run` in `ui/` over the touched suites (shared polling,
cross-tab poll, transcripts, boundary): 34 tests pass.
- `pnpm typecheck` in `ui/` — clean.
- The snapshot regression test was verified to fail against the
pre-change hook (extra commit per mount).
- Not reproduced end-to-end: the exact 50-update cascade from the field
crash needs a live cold backend; the change removes the identified
per-mount/per-notify nested commits at the reported crash frame, bounds
the reconnect load, and guarantees the shell can no longer blank the
page.

## Risks

Low risk. The snapshot change only suppresses re-renders whose state is
value-identical; leadership changes propagate exactly as before. The
backoff only lengthens retry delays after consecutive failures and
resets on success. The new boundary renders children untouched unless an
error reaches it; behavior on healthy loads is unchanged. Self-hosted
deployments see the same code paths — the cold-backend window simply
rarely occurs there.

## Model Used

- Claude (Anthropic), Claude Fable 5 (`claude-fable-5`), via Claude Code
CLI with extended thinking and tool use (code search, edit, test
execution; diagnosis included mapping the production minified stack to
source).

## 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
2026-08-11 19:16:19 -07:00

164 lines
5.9 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 });
// Coordinator notifications arrive as fresh snapshot objects, and
// `subscribe` invokes its listener synchronously from inside the mount
// effect. Passing `setSnapshot` straight through would schedule a nested
// re-render for every notification — including value-equal ones — and those
// wasted commits count toward React's nested-update limit. Under a hostile
// mount cascade (many shared-polling hooks mounting while the backend is
// cold) that budget is shared with every other effect-driven update, so
// keep the previous state object whenever leadership did not change and
// let React bail out instead.
const applySnapshot = useCallback((next: SharedPollingSnapshot) => {
setSnapshot((prev) => (prev.isLeader === next.isLeader ? prev : next));
}, []);
useEffect(() => {
queryKeyRef.current = queryKey;
}, [queryKey, queryKeyHash]);
useEffect(() => {
if (!activeCompanyId || !fullResourceKey) {
applySnapshot({ isLeader: true });
return;
}
const coordinator = acquireCoordinator(activeCompanyId);
const unsubscribeState = coordinator.subscribe(applySnapshot);
const unsubscribeResource = coordinator.subscribeResource(fullResourceKey, (message) => {
applySharedPollingResult(queryClient, queryKeyRef.current, message);
});
coordinator.request(fullResourceKey);
return () => {
unsubscribeResource();
unsubscribeState();
releaseCoordinator(activeCompanyId);
};
}, [activeCompanyId, applySnapshot, 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]);
}