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
This commit is contained in:
Devin Foley authored and GitHub committed 2026-08-11 19:16:19 -07:00
1 parent 9adeb4a9d0
commit d90f4d488e
7 files changed
+401 -31

No files matched your search

@@ -63,6 +63,11 @@ class FakeWebSocket {
this.readyState = FakeWebSocket.OPEN;
this.onopen?.(new Event("open"));
}
triggerClose() {
this.readyState = FakeWebSocket.CLOSED;
this.onclose?.(new CloseEvent("close"));
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -623,4 +628,91 @@ describe("useLiveRunTranscripts", () => {
vi.useRealTimers();
}
});
it("backs off exponentially when the live event socket keeps failing", async () => {
vi.useFakeTimers();
try {
function Harness({ lastOutputBytes }: { lastOutputBytes?: number }) {
useLiveRunTranscripts({
companyId: "company-1",
runs: [{ id: "run-1", status: "running", adapterType: "codex_local", lastOutputBytes }],
});
return null;
}
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => {
root.render(<Harness />);
await Promise.resolve();
});
expect(FakeWebSocket.instances).toHaveLength(1);
// Cold backend: every handshake fails. Delays must grow 1.5s → 3s → 6s
// instead of hammering a flat interval.
await act(async () => {
FakeWebSocket.instances[0].triggerClose();
await vi.advanceTimersByTimeAsync(1_499);
});
expect(FakeWebSocket.instances).toHaveLength(1);
await act(async () => {
await vi.advanceTimersByTimeAsync(1);
});
expect(FakeWebSocket.instances).toHaveLength(2);
await act(async () => {
FakeWebSocket.instances[1].triggerClose();
await vi.advanceTimersByTimeAsync(2_999);
});
expect(FakeWebSocket.instances).toHaveLength(2);
await act(async () => {
await vi.advanceTimersByTimeAsync(1);
});
expect(FakeWebSocket.instances).toHaveLength(3);
await act(async () => {
FakeWebSocket.instances[2].triggerClose();
await vi.advanceTimersByTimeAsync(5_999);
});
expect(FakeWebSocket.instances).toHaveLength(3);
await act(async () => {
await vi.advanceTimersByTimeAsync(1);
});
expect(FakeWebSocket.instances).toHaveLength(4);
// Run-metadata changes restart the socket effect; the progressed delay
// must survive the restart instead of resetting to the base delay.
await act(async () => {
root.render(<Harness lastOutputBytes={512} />);
await Promise.resolve();
});
expect(FakeWebSocket.instances).toHaveLength(5);
await act(async () => {
FakeWebSocket.instances[4].triggerClose();
await vi.advanceTimersByTimeAsync(11_999);
});
expect(FakeWebSocket.instances).toHaveLength(5);
await act(async () => {
await vi.advanceTimersByTimeAsync(1);
});
expect(FakeWebSocket.instances).toHaveLength(6);
// A successful connection resets the backoff to the base delay.
await act(async () => {
FakeWebSocket.instances[5].triggerOpen();
FakeWebSocket.instances[5].triggerClose();
await vi.advanceTimersByTimeAsync(1_500);
});
expect(FakeWebSocket.instances).toHaveLength(7);
act(() => {
root.unmount();
});
container.remove();
} finally {
vi.useRealTimers();
}
});
});