Files
PaperClipAI/ui/src/components/CloudAccessGate.test.tsx
T
39279aa34f feat(ui): shared error, connectivity and query foundation for disconnects (#15754)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The board reads API data and keeps the current task on screen.
> - A restart or temporary network failure can interrupt those reads.
> - Separate page error handlers can hide cached data or expose raw
server codes.
> - The app needs one connection state, readable error copy and a
consistent read policy.
> - This change provides that foundation and moves affected read
surfaces onto it.
> - The dependent write layer in #17960 preserves edits and submissions
across the same failures.

## Linked Issues or Issue Description

**What happened?**

Temporary API failures could replace loaded content with errors.
Different surfaces handled the same outage differently. Some showed raw
server codes. A successful query to an unrelated service could also
falsely report that Paperclip had recovered.

**Expected behavior**

Keep cached content visible. Show one connection banner during sustained
trouble. Confirm recovery through the Paperclip health probe or its
WebSocket. Retry transient reads and show readable errors for permanent
failures.

**Steps to reproduce**

1. Open a populated task or workspace page.
2. Interrupt API requests with a 503 or a dropped connection.
3. Keep an unrelated external request in flight.
4. Confirm that cached content remains and that the external result
cannot clear the outage.
5. Restore the API and check that reads refresh.

The write layer first merged into this feature branch in #15769 now has
its own dependent PR, #17960. This PR contains the shared foundation and
read changes. Merge this PR first.

## What Changed

- Classify API errors and provide readable error copy, including
non-JSON proxy responses and Retry-After handling.
- Use one connection store and health probe with bounded backoff.
Confirm recovery from the server health probe or live-updates WebSocket.
- Pause reads while disconnected, retry transient errors, and refresh
active reads after recovery.
- Keep cached data visible through shared query views and affected page,
panel and plugin read surfaces.
- Add one app-level connection banner and support the pending-write
count consumed by the dependent write layer.
- Add a query-error rendering guard. Call it directly from the existing
CI step. Update development documentation.

## Verification

- Historical-chat lookup now follows the same ready/stale roster state
as rendering. Three regressions fail before the fix; the six new cases
pass after it, including working Retry, fresh data, no-cache error,
permanent 403 and company isolation. All six focused query/recovery
suites pass 200 tests. Final-commit CI passes and Apex is 5/5 with no
unresolved findings. Canary Dry Run initially refused a preview version
that was already on npm. It passed after one rerun with fresh registry
metadata; no check was disabled.

- Integrated current master and retained both transcript interest
registration and connectivity reporting on socket open. The seven
focused recovery/query suites pass 288 tests, and UI typecheck and
production build pass. All 9,451 UI tests across 799 files pass on the
merge commit. Final-commit CI passes and Apex is 5/5 with no unresolved
findings.

- Current head `70d9335d732219352ef0f98414439766bbcb33df`: all hosted CI
checks pass. Apex is **5/5** on that head with no unresolved findings.
The branch has no merge conflict. GitHub still requires code-owner
approval.

- The foundation passes 9,430 UI tests in 804 files. After integrating
current master page paths, 190 focused page tests pass.
- Two unrelated-success regressions fail before the latest fix. With the
fix, 62 focused UI tests, all six guard tests and UI TypeScript pass.
- The composed foundation and write layer pass **9,505 UI tests in 808
files**, UI TypeScript, a production UI build, and query-error, token
and map guards.
- A real Chromium journey on the composed source injects a 503 during
title save. The loaded task stays visible; one reconnect banner appears;
the edit saves after recovery; another task stays unchanged; the saved
title survives reload.
- Full recursive local checks were not repeated because Runner
compilation exhausted local disk during another repair. Hosted checks
must pass before merge. No new staging deployment is claimed.

- Latest review follow-up: a cached CaseDetail now survives a failed
HTTP 429 refresh. Its page regression fails before the fix and passes
after it. Eighty focused foundation tests, UI TypeScript, build and
guards pass after that change.
- Earlier CI evidence is retained: several foundation jobs received a
runner shutdown signal together. The write-layer head also failed an
unchanged Runner descriptor close test with `provider_transport_failed`.
The same Runner source passed that suite in the foundation run. New CI
runs cover the updated heads; no check or assertion was weakened.

## Risks

- Shared retry defaults change the time before transient read errors
appear. Permanent errors still fail promptly.
- ApiError.message now contains readable copy. Callers that compare raw
codes must use ApiError.code.
- Cache success can come from another service or local data. It must not
confirm Paperclip recovery.
- Durable writes are reviewed separately in #17960. This PR does not
change database or mutation contracts.

## Model Used

Anthropic Claude Opus 5.5 (`claude-opus-5-5`) produced the original work
with tool use. OpenAI Codex, GPT-6 family, assisted with restoration,
integration, tests and review fixes. The Codex session does not expose
its exact serving model ID or context window size.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Amy (Opus) <claude@users.noreply.github.com>
2026-10-27 21:22:07 -07:00

274 lines
12 KiB
TypeScript

// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { focusManager, onlineManager, QueryClientProvider, QueryObserver, type QueryClient } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CloudAccessGate } from "./CloudAccessGate";
import { ConnectionStatusBanner } from "./ConnectionStatusBanner";
import { ConnectivityProvider, createConnectivityStore, type ConnectivityStore } from "@/lib/connectivity";
import { bindConnectivity, createAppQueryClient } from "@/lib/query-client";
import { queryKeys } from "@/lib/queryKeys";
import { ApiUnavailableError } from "@/api/response";
vi.mock("@/lib/router", () => ({
useLocation: () => ({ pathname: "/CON/agents/conan/instructions", search: "?tab=edit", hash: "#draft" }),
Navigate: ({ to }: { to: string }) => <div data-redirect={to} />,
Outlet: () => <textarea aria-label="Instructions" defaultValue="Unsaved instructions" />,
}));
vi.mock("@/components/AnimatedPaperclipIcon", () => ({ PaperclipLoading: () => <div>Loading…</div> }));
vi.mock("@/components/CloudSignIn", () => ({ CloudSignIn: () => <div>Sign in to Cloud</div> }));
vi.mock("@/components/BootstrapPendingPage", () => ({ BootstrapPendingPage: () => <div>Set up instance</div> }));
const responses: Record<string, unknown> = {
"/api/health": { status: "ok", deploymentMode: "authenticated", bootstrapStatus: "ready" },
"/api/auth/get-session": {
session: { id: "session", userId: "user" },
user: { id: "user", name: "Operator", email: "operator@example.com", image: null },
sentryDsn: null,
},
"/api/cli-auth/me": { isInstanceAdmin: false, companyIds: ["company"] },
};
const checks = [
["/api/health", queryKeys.health],
["/api/auth/get-session", queryKeys.auth.session],
["/api/cli-auth/me", queryKeys.access.currentBoardAccess],
] as const;
describe("CloudAccessGate restart recovery", () => {
let root: Root;
let container: HTMLDivElement;
let client: QueryClient;
let store: ConnectivityStore;
let unbind: () => void;
/** A single failing path, or every API path for a full outage. */
let failingPath: string | null;
let failure: () => Response;
const fetchMock = vi.fn();
const callsTo = (path: string) => fetchMock.mock.calls.filter(([url]) => url === path).length;
beforeEach(() => {
vi.useFakeTimers();
failingPath = null;
failure = () => new Response("<!doctype html><h1>Restarting</h1>", { status: 200 });
fetchMock.mockImplementation(async (path: string) => {
if (failingPath === "*" || path === failingPath) return failure();
if (!(path in responses)) throw new Error(`Unexpected request: ${path}`);
return Response.json(responses[path]);
});
vi.stubGlobal("fetch", fetchMock);
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
// The app's real wiring: cache events feed the connectivity store, which
// drives onlineManager and refreshes live queries on recovery.
store = createConnectivityStore({ browserOnline: true });
client = createAppQueryClient({ connectivity: store }, { defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
unbind = bindConnectivity(client, store);
});
afterEach(() => {
flushSync(() => root.unmount());
unbind();
store.dispose();
onlineManager.setOnline(true);
client.clear();
focusManager.setFocused(undefined);
container.remove();
vi.useRealTimers();
vi.unstubAllGlobals();
vi.clearAllMocks();
});
async function flushReact() {
await vi.advanceTimersByTimeAsync(20);
flushSync(() => {});
}
async function render() {
flushSync(() => root.render(
<ConnectivityProvider store={store}>
<QueryClientProvider client={client}>
<ConnectionStatusBanner />
<CloudAccessGate />
</QueryClientProvider>
</ConnectivityProvider>,
));
await flushReact();
}
/** Long enough for the probe/retry backoff (1s, 2s, 5s, 10s) to reach its next step. */
async function waitForReconnect() {
await vi.advanceTimersByTimeAsync(16_000);
await flushReact();
}
it.each(checks)("recovers from an HTML response on %s without navigating", async (path) => {
failingPath = path;
await render();
expect(container.textContent).toContain("Reconnecting to Paperclip");
expect(container.textContent).not.toContain("Unexpected token");
expect(container.querySelector("[data-redirect]")).toBeNull();
expect(container.querySelector("textarea")).toBeNull();
// Backoff, not a tight loop: initial try plus retries at 1s and 3s.
await vi.advanceTimersByTimeAsync(4_000);
expect(callsTo(path)).toBeLessThanOrEqual(path === "/api/health" ? 6 : 3);
// The full-page screen already explains the outage.
expect(container.querySelector("[data-connection-status]")).toBeNull();
failingPath = null;
await waitForReconnect();
expect(container.querySelector("textarea")).not.toBeNull();
expect(container.textContent).not.toContain("Reconnecting");
const callsAfterRecovery = fetchMock.mock.calls.length;
await vi.advanceTimersByTimeAsync(15_000);
expect(fetchMock).toHaveBeenCalledTimes(callsAfterRecovery);
expect(fetchMock.mock.calls.every(([, init]) => !init.method || init.method === "GET")).toBe(true);
});
it.each(checks)("preserves a mounted editor through an outage that starts on %s", async (path, queryKey) => {
await render();
const editor = container.querySelector("textarea")!;
editor.value = "Keep my unsaved changes";
failingPath = "*";
failure = () => new Response("Bad gateway", { status: 502 });
void client.refetchQueries({ queryKey });
await flushReact();
expect(container.querySelector("textarea")).toBe(editor);
// One blip does not flash the banner; continued trouble does.
expect(container.textContent).not.toContain("Reconnecting automatically");
await vi.advanceTimersByTimeAsync(2_100);
await flushReact();
expect(container.textContent).toContain("Reconnecting automatically");
expect(container.querySelector("textarea")).toBe(editor);
failingPath = null;
await waitForReconnect();
expect(container.querySelector("textarea")).toBe(editor);
expect(editor.value).toBe("Keep my unsaved changes");
expect(container.textContent).not.toContain("Reconnecting");
await vi.advanceTimersByTimeAsync(3_100);
await flushReact();
expect(container.querySelector("[data-connection-status]")).toBeNull();
});
it.each(checks)("reconnects %s as soon as a hidden tab is visible again", async (path) => {
focusManager.setFocused(false);
failingPath = path;
await render();
expect(container.textContent).toContain("Reconnecting to Paperclip");
failingPath = null;
await waitForReconnect();
focusManager.setFocused(true);
await flushReact();
expect(container.querySelector("textarea")).not.toBeNull();
});
it("waits for ready health before opening the board even when access checks succeed", async () => {
failingPath = "/api/health";
failure = () => Response.json({ status: "starting", deploymentMode: "authenticated", bootstrapStatus: "ready" });
await render();
expect(container.querySelector("textarea")).toBeNull();
expect(container.textContent).toContain("Reconnecting");
// The session is checked once; later checks wait for the server to be ready.
expect(callsTo("/api/auth/get-session")).toBe(1);
await vi.advanceTimersByTimeAsync(5_100);
expect(container.querySelector("textarea")).toBeNull();
failingPath = null;
await waitForReconnect();
expect(container.querySelector("textarea")).not.toBeNull();
expect(container.textContent).not.toContain("Reconnecting");
});
it("supports manual retry while startup health is pending", async () => {
fetchMock.mockResolvedValueOnce(Response.json({ status: "starting", deploymentMode: "local_trusted" }));
await render();
expect(container.querySelector("textarea")).toBeNull();
container.querySelector("button")!.click();
await flushReact();
expect(container.querySelector("textarea")).not.toBeNull();
});
it("preserves an open editor while health reports startup recovery", async () => {
await render();
const editor = container.querySelector("textarea")!;
editor.value = "Keep my unsaved changes";
failingPath = "/api/health";
failure = () => Response.json({ status: "starting", deploymentMode: "authenticated", bootstrapStatus: "ready" });
await client.refetchQueries({ queryKey: queryKeys.health });
await vi.advanceTimersByTimeAsync(2_100);
await flushReact();
expect(container.querySelector("textarea")).toBe(editor);
expect(container.textContent).toContain("Reconnecting automatically");
failingPath = null;
await waitForReconnect();
expect(container.querySelector("textarea")).toBe(editor);
expect(editor.value).toBe("Keep my unsaved changes");
expect(container.textContent).not.toContain("Reconnecting");
});
it("offers immediate retry while waiting for the next automatic check", async () => {
failingPath = "/api/health";
await render();
await vi.advanceTimersByTimeAsync(4_000);
failingPath = null;
container.querySelector("button")!.click();
await flushReact();
expect(container.querySelector("textarea")).not.toBeNull();
});
it("retries a dropped connection and opens the requested page when it returns", async () => {
fetchMock.mockRejectedValueOnce(new TypeError("Failed to fetch"));
await render();
expect(container.textContent).toContain("Reconnecting to Paperclip");
await vi.advanceTimersByTimeAsync(5_100);
await flushReact();
expect(container.querySelector("textarea")).not.toBeNull();
expect(container.querySelector("[data-redirect]")).toBeNull();
});
it("refreshes other failed reads after the server recovers", async () => {
const read = vi.fn().mockRejectedValueOnce(new ApiUnavailableError(503)).mockResolvedValue([]);
const observer = new QueryObserver(client, { queryKey: ["companies", "test"], queryFn: read, retry: false });
const unsubscribe = observer.subscribe(() => {});
failingPath = "/api/health";
await render();
expect(read).toHaveBeenCalledTimes(1);
failingPath = null;
await waitForReconnect();
expect(read).toHaveBeenCalledTimes(2);
expect(observer.getCurrentResult().data).toEqual([]);
unsubscribe();
});
it("fails closed for access denials even with cached access, and does not poll", async () => {
await render();
failingPath = "/api/cli-auth/me";
failure = () => Response.json({ error: "Forbidden" }, { status: 403 });
await client.refetchQueries({ queryKey: queryKeys.access.currentBoardAccess });
await flushReact();
expect(container.textContent).toContain("Unable to load Paperclip");
expect(container.textContent).not.toContain("reconnect automatically");
expect(container.querySelector("textarea")).toBeNull();
const calls = fetchMock.mock.calls.length;
await vi.advanceTimersByTimeAsync(15_000);
expect(fetchMock).toHaveBeenCalledTimes(calls);
failingPath = null;
container.querySelector("button")!.click();
await flushReact();
expect(container.querySelector("textarea")).not.toBeNull();
});
it("still redirects to sign-in when the session expires", async () => {
await render();
failingPath = "/api/auth/get-session";
failure = () => Response.json({ error: "unauthorized" }, { status: 401 });
await client.refetchQueries({ queryKey: queryKeys.auth.session });
await flushReact();
expect(container.querySelector("textarea")).toBeNull();
expect(container.querySelector("[data-redirect]")?.getAttribute("data-redirect"))
.toBe("/auth?next=%2FCON%2Fagents%2Fconan%2Finstructions%3Ftab%3Dedit");
});
});