mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-21 02:43:25 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The browser UI shows a connection banner. It checks the server with a health probe (`probeServerHealth` in `ui/src/lib/connectivity.ts`) > - The probe stops its own `fetch` after 10 seconds with a reasonless `controller.abort()`. The app catches that rejection > - A `fetch` wrapper outside the app, such as a browser extension, can drop the rejection. The browser then reports `AbortError: signal is aborted without reason` as an unhandled rejection, and Sentry records an error that has no user effect > - #22090 added a marked abort reason for the shared GET and a Sentry filter that drops only that marked object. The probe timeout did not use it > - This pull request makes the probe timeout abort with the same marked reason > - The benefit is that the probe's own timeout no longer shows as a production error, and every other `AbortError` is still reported ## Linked Issues or Issue Description No public issue exists. This is the problem, in the bug template fields: **What happened?** A hosted browser reported one unhandled rejection: `AbortError: signal is aborted without reason` (DOMException code 20, mechanism `onunhandledrejection`, native trusted promise). The stack is a `setTimeout` callback in `probeServerHealth` that calls `controller.abort()` on the `/api/health` probe. The tab was hidden and had just resumed. **Expected behavior** The probe's own timeout does not appear in error monitoring. A real abort failure still appears. **Steps to reproduce** 1. Replace `window.fetch` with a wrapper that calls the real `fetch` and attaches only `.then(() => {})` to its promise. 2. Make `/api/health` hang for more than 10 seconds. 3. The probe timeout aborts the request. The app's `try/catch` handles its own promise, but the wrapper's derived promise rejects with no handler. **Paperclip version or commit** Reported on release `651749bdb4`. `probeServerHealth` is unchanged on master up to this branch's base (`201abacd6e`). **Deployment mode** Hosted, browser UI (Chrome-family message text). Refs #22090 (same filter, shared GET call site) and #22380 (same approach, announcement card). I searched open PRs for `probeServerHealth` and `intentionalAbortReason` and found no duplicate for this call site. ## What Changed - `ui/src/lib/connectivity.ts`: the probe timeout calls `controller.abort(intentionalAbortReason())` instead of `controller.abort()`. - `ui/src/lib/connectivity.test.ts`: a new test uses a `fetch` that settles only when its signal aborts. It checks that the probe returns `{ reachable: false }` after 10 seconds and that the signal reason is the marked intentional reason. ## Verification - `cd ui && npx vitest run src/lib/connectivity.test.ts src/lib/sentry.test.ts src/api/client.test.ts` → 3 files, 80 tests pass. - Red check: without the `connectivity.ts` change, the new test fails (`isIntentionalAbortReason(signal.reason)` is `false`). - `cd ui && npx vitest related src/lib/connectivity.ts --run` → 346 of 347 files pass. The 2 failures in `src/components/Layout.viewport.test.tsx` also fail on unmodified `master` in this sandbox, so this change does not cause them. - `tsc --noEmit` for `ui` reports no errors in the changed files. - The existing real-SDK tests in `ui/src/lib/sentry.test.ts` (from #22090) prove that `beforeSend` drops a marked rejection and still sends an unmarked `AbortError`. ## Risks - Low risk. The filter matches by object identity, and only `intentionalAbortReason()` makes these objects. An `AbortError` from any other source is still reported. - The probe's abort message changes from the browser's text to "The operation was aborted.". The probe catches every rejection and does not read the message. > 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 - Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used through Claude Code with tool use (shell, file edits, test runs). ## 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
369 lines
13 KiB
TypeScript
369 lines
13 KiB
TypeScript
/**
|
|
* App-wide connectivity state.
|
|
*
|
|
* One small external store answers "can we reach the Paperclip server right
|
|
* now?" for the whole app. Inputs:
|
|
*
|
|
* - React Query cache events: a connectivity-level failure (network drop, proxy
|
|
* 5xx, gateway `tenant_app_unavailable`) makes the store suspicious. Cache
|
|
* success can come from another service, so only server health and the
|
|
* live-updates WebSocket confirm recovery.
|
|
* - The live-updates WebSocket opening (reachable) or closing (suspicious).
|
|
* - `navigator.onLine` and the window `online`/`offline` events.
|
|
*
|
|
* A suspicion is confirmed by probing `/api/health` before the state changes,
|
|
* so one busy route returning 503 cannot pause the whole app. While the state
|
|
* is not `online`, a single probe loop polls `/api/health` with backoff (1s,
|
|
* 2s, 5s, 10s, then every 15s; a longer `Retry-After` wins). It is the only
|
|
* outage poll in the app.
|
|
*
|
|
* `lib/query-client.ts` feeds this store into React Query's `onlineManager`,
|
|
* so queries and replayable mutations pause during an outage and resume on
|
|
* recovery instead of failing.
|
|
*/
|
|
|
|
import { createContext, createElement, useContext, useEffect, useSyncExternalStore, type ReactNode } from "react";
|
|
import { apiFetch } from "@/api/client";
|
|
import { isConnectivityError, isTransientError, parseRetryAfter } from "@/api/errors";
|
|
import { intentionalAbortReason } from "./intentional-abort";
|
|
|
|
export type ConnectivityStatus = "online" | "reconnecting" | "offline";
|
|
|
|
export interface ConnectivitySnapshot {
|
|
status: ConnectivityStatus;
|
|
/** When the current outage began (first failed request), or null while online. */
|
|
troubleSince: number | null;
|
|
/** When the store last recovered from an outage. */
|
|
recoveredAt: number | null;
|
|
/** Writes waiting for the connection, as reported by `usePendingWritesReporter`. */
|
|
pendingWrites: number;
|
|
}
|
|
|
|
export type ProbeResult = { reachable: true } | { reachable: false; retryAfterMs: number | null };
|
|
|
|
export interface ConnectivityStoreOptions {
|
|
/** Checks whether the server is reachable. Defaults to probing `/api/health`. */
|
|
probe?: () => Promise<ProbeResult>;
|
|
now?: () => number;
|
|
/** Initial browser connectivity; defaults to `navigator.onLine`. */
|
|
browserOnline?: boolean;
|
|
}
|
|
|
|
/** Delay before each probe while reconnecting; the last value repeats. */
|
|
export const PROBE_BACKOFF_MS = [1_000, 2_000, 5_000, 10_000, 15_000] as const;
|
|
/** Upper bound for a server-requested `Retry-After`. */
|
|
export const MAX_PROBE_DELAY_MS = 60_000;
|
|
/** Do not re-check a suspicion this soon after a probe said the server is fine. */
|
|
export const SUSPICION_COOLDOWN_MS = 2_000;
|
|
const PROBE_TIMEOUT_MS = 10_000;
|
|
|
|
export interface ConnectivityStore {
|
|
getSnapshot(): ConnectivitySnapshot;
|
|
subscribe(listener: () => void): () => void;
|
|
/** Report a failed request. Only connectivity-level errors have an effect. */
|
|
reportError(error: unknown): void;
|
|
/** Report a successful request: the server is reachable. */
|
|
reportSuccess(): void;
|
|
/**
|
|
* Health says the server is `starting`: reachable, but not ready. Unlike an
|
|
* outage, ordinary successful requests do not end this state; only a health
|
|
* probe that reports `ok` does.
|
|
*/
|
|
reportServerStarting(): void;
|
|
reportSocketStatus(status: "open" | "closed"): void;
|
|
setBrowserOnline(online: boolean): void;
|
|
/** During an outage, probe now instead of waiting out the backoff step (a Retry button). */
|
|
probeNow(): void;
|
|
/** Called once each time the store returns to `online` after an outage. */
|
|
onRecover(listener: () => void): () => void;
|
|
setPendingWrites(sourceId: string, count: number): void;
|
|
/** Attach `online`/`offline` window listeners. Returns a cleanup. */
|
|
start(): () => void;
|
|
/** Stop timers and drop listeners (tests). */
|
|
dispose(): void;
|
|
}
|
|
|
|
function readBrowserOnline(): boolean {
|
|
if (typeof navigator === "undefined" || typeof navigator.onLine !== "boolean") return true;
|
|
return navigator.onLine;
|
|
}
|
|
|
|
export function createConnectivityStore(options: ConnectivityStoreOptions = {}): ConnectivityStore {
|
|
const probe = options.probe ?? probeServerHealth;
|
|
const now = options.now ?? Date.now;
|
|
const listeners = new Set<() => void>();
|
|
const recoverListeners = new Set<() => void>();
|
|
const pendingWriteSources = new Map<string, number>();
|
|
|
|
let browserOnline = options.browserOnline ?? readBrowserOnline();
|
|
let snapshot: ConnectivitySnapshot = {
|
|
status: browserOnline ? "online" : "offline",
|
|
troubleSince: browserOnline ? null : now(),
|
|
recoveredAt: null,
|
|
pendingWrites: 0,
|
|
};
|
|
let probeTimer: ReturnType<typeof setTimeout> | null = null;
|
|
let probing = false;
|
|
let probeAttempt = 0;
|
|
/** First connectivity failure not yet confirmed or dismissed by a probe. */
|
|
let suspectedSince: number | null = null;
|
|
let lastClearProbeAt = Number.NEGATIVE_INFINITY;
|
|
let serverStarting = false;
|
|
let disposed = false;
|
|
/** Bumped by every proof of reachability; a failed probe started before one is stale. */
|
|
let recoveries = 0;
|
|
/** Bumped by every `starting` report; a reachable probe started before one is stale. */
|
|
let startingReports = 0;
|
|
|
|
const emit = () => {
|
|
for (const listener of [...listeners]) listener();
|
|
};
|
|
|
|
const update = (next: Partial<ConnectivitySnapshot>) => {
|
|
const merged = { ...snapshot, ...next };
|
|
if (
|
|
merged.status === snapshot.status
|
|
&& merged.troubleSince === snapshot.troubleSince
|
|
&& merged.recoveredAt === snapshot.recoveredAt
|
|
&& merged.pendingWrites === snapshot.pendingWrites
|
|
) return;
|
|
snapshot = merged;
|
|
emit();
|
|
};
|
|
|
|
const clearProbeTimer = () => {
|
|
if (probeTimer !== null) {
|
|
clearTimeout(probeTimer);
|
|
probeTimer = null;
|
|
}
|
|
};
|
|
|
|
const recover = () => {
|
|
recoveries += 1;
|
|
clearProbeTimer();
|
|
suspectedSince = null;
|
|
probeAttempt = 0;
|
|
if (snapshot.status === "online") return;
|
|
update({ status: "online", troubleSince: null, recoveredAt: now() });
|
|
for (const listener of [...recoverListeners]) listener();
|
|
};
|
|
|
|
const enterReconnecting = (since: number) => {
|
|
if (snapshot.status !== "online") return;
|
|
update({ status: "reconnecting", troubleSince: since });
|
|
};
|
|
|
|
const scheduleProbe = (retryAfterMs: number | null) => {
|
|
clearProbeTimer();
|
|
if (disposed || !browserOnline) return;
|
|
const backoff = PROBE_BACKOFF_MS[Math.min(probeAttempt, PROBE_BACKOFF_MS.length - 1)];
|
|
const delay = retryAfterMs === null ? backoff : Math.min(Math.max(backoff, retryAfterMs), MAX_PROBE_DELAY_MS);
|
|
probeAttempt += 1;
|
|
probeTimer = setTimeout(() => {
|
|
probeTimer = null;
|
|
runProbe();
|
|
}, delay);
|
|
};
|
|
|
|
const runProbe = () => {
|
|
if (disposed || probing || !browserOnline) return;
|
|
probing = true;
|
|
const recoveriesAtStart = recoveries;
|
|
const startingReportsAtStart = startingReports;
|
|
void probe()
|
|
.catch((): ProbeResult => ({ reachable: false, retryAfterMs: null }))
|
|
.then((result) => {
|
|
probing = false;
|
|
if (disposed || !browserOnline) return;
|
|
const stale = result.reachable
|
|
? startingReports !== startingReportsAtStart
|
|
: recoveries !== recoveriesAtStart;
|
|
if (stale) {
|
|
// Newer evidence arrived while this probe was in flight (a success,
|
|
// or a `starting` report), so it wins over this result. If that left
|
|
// the app reconnecting, keep the loop alive: nothing else will
|
|
// probe. Otherwise check again only if something failed since.
|
|
if (snapshot.status !== "online") scheduleProbe(result.reachable ? null : result.retryAfterMs);
|
|
else if (suspectedSince !== null) runProbe();
|
|
return;
|
|
}
|
|
if (result.reachable) {
|
|
if (snapshot.status === "online") lastClearProbeAt = now();
|
|
serverStarting = false;
|
|
recover();
|
|
return;
|
|
}
|
|
enterReconnecting(suspectedSince ?? now());
|
|
suspectedSince = null;
|
|
scheduleProbe(result.retryAfterMs);
|
|
});
|
|
};
|
|
|
|
const suspect = () => {
|
|
if (disposed || !browserOnline) return;
|
|
if (snapshot.status !== "online") return; // The probe loop is already running.
|
|
suspectedSince ??= now();
|
|
if (probing) return;
|
|
if (now() - lastClearProbeAt < SUSPICION_COOLDOWN_MS) {
|
|
suspectedSince = null;
|
|
return;
|
|
}
|
|
runProbe();
|
|
};
|
|
|
|
const reportSuccess = () => {
|
|
if (!browserOnline || serverStarting) return;
|
|
recover();
|
|
};
|
|
|
|
const reportServerStarting = () => {
|
|
if (disposed || serverStarting) return;
|
|
serverStarting = true;
|
|
startingReports += 1;
|
|
if (!browserOnline) return;
|
|
enterReconnecting(now());
|
|
if (probeTimer === null && !probing) scheduleProbe(null);
|
|
};
|
|
|
|
const setBrowserOnline = (online: boolean) => {
|
|
if (online === browserOnline) return;
|
|
browserOnline = online;
|
|
if (!online) {
|
|
clearProbeTimer();
|
|
suspectedSince = null;
|
|
update({ status: "offline", troubleSince: snapshot.troubleSince ?? now() });
|
|
return;
|
|
}
|
|
// The browser has a network again; confirm the server before trusting it.
|
|
update({ status: "reconnecting" });
|
|
probeAttempt = 0;
|
|
clearProbeTimer();
|
|
runProbe();
|
|
};
|
|
|
|
return {
|
|
getSnapshot: () => snapshot,
|
|
subscribe(listener) {
|
|
listeners.add(listener);
|
|
return () => {
|
|
listeners.delete(listener);
|
|
};
|
|
},
|
|
reportError(error) {
|
|
if (isConnectivityError(error)) suspect();
|
|
},
|
|
reportSuccess,
|
|
reportServerStarting,
|
|
reportSocketStatus(status) {
|
|
if (status === "open") reportSuccess();
|
|
else suspect();
|
|
},
|
|
setBrowserOnline,
|
|
probeNow() {
|
|
if (snapshot.status === "online") return;
|
|
clearProbeTimer();
|
|
runProbe();
|
|
},
|
|
onRecover(listener) {
|
|
recoverListeners.add(listener);
|
|
return () => {
|
|
recoverListeners.delete(listener);
|
|
};
|
|
},
|
|
setPendingWrites(sourceId, count) {
|
|
if (count > 0) pendingWriteSources.set(sourceId, count);
|
|
else pendingWriteSources.delete(sourceId);
|
|
let total = 0;
|
|
for (const value of pendingWriteSources.values()) total += value;
|
|
update({ pendingWrites: total });
|
|
},
|
|
start() {
|
|
if (typeof window === "undefined") return () => undefined;
|
|
const handleOnline = () => setBrowserOnline(true);
|
|
const handleOffline = () => setBrowserOnline(false);
|
|
window.addEventListener("online", handleOnline);
|
|
window.addEventListener("offline", handleOffline);
|
|
setBrowserOnline(readBrowserOnline());
|
|
return () => {
|
|
window.removeEventListener("online", handleOnline);
|
|
window.removeEventListener("offline", handleOffline);
|
|
};
|
|
},
|
|
dispose() {
|
|
disposed = true;
|
|
clearProbeTimer();
|
|
listeners.clear();
|
|
recoverListeners.clear();
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Probe `/api/health` directly (not through `healthApi`, which may trigger a
|
|
* tenant-session recovery redirect). Reachable means the server answered with
|
|
* a non-transient response; a `starting` server is not ready yet.
|
|
*/
|
|
export async function probeServerHealth(): Promise<ProbeResult> {
|
|
const controller = new AbortController();
|
|
const timeout = setTimeout(() => controller.abort(intentionalAbortReason()), PROBE_TIMEOUT_MS);
|
|
try {
|
|
const res = await apiFetch("/api/health", {
|
|
credentials: "include",
|
|
headers: { Accept: "application/json" },
|
|
cache: "no-store",
|
|
signal: controller.signal,
|
|
});
|
|
const retryAfterMs = parseRetryAfter(res.headers.get("Retry-After"));
|
|
let body: unknown = null;
|
|
try {
|
|
body = await res.json();
|
|
} catch {
|
|
// A proxy's HTML page: the app itself did not answer.
|
|
return res.ok || res.status >= 500 ? { reachable: false, retryAfterMs } : { reachable: true };
|
|
}
|
|
if (res.ok) {
|
|
const status = body && typeof body === "object" ? (body as { status?: unknown }).status : undefined;
|
|
return status === "ok" ? { reachable: true } : { reachable: false, retryAfterMs };
|
|
}
|
|
return isTransientError({ status: res.status, body })
|
|
? { reachable: false, retryAfterMs }
|
|
: { reachable: true };
|
|
} catch {
|
|
return { reachable: false, retryAfterMs: null };
|
|
} finally {
|
|
clearTimeout(timeout);
|
|
}
|
|
}
|
|
|
|
/** The app's connectivity store. */
|
|
export const connectivity = createConnectivityStore();
|
|
|
|
const ConnectivityContext = createContext<ConnectivityStore>(connectivity);
|
|
|
|
/** Override the store for a subtree (tests, Storybook). The app uses the singleton. */
|
|
export function ConnectivityProvider({ store, children }: { store: ConnectivityStore; children?: ReactNode }) {
|
|
return createElement(ConnectivityContext.Provider, { value: store }, children);
|
|
}
|
|
|
|
export function useConnectivityStore(): ConnectivityStore {
|
|
return useContext(ConnectivityContext);
|
|
}
|
|
|
|
export function useConnectivity(): ConnectivitySnapshot {
|
|
const store = useConnectivityStore();
|
|
return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
|
|
}
|
|
|
|
/**
|
|
* Report writes that are waiting for the connection (drafts queued to resend,
|
|
* autosaves held back). The banner shows the total. Durable write queues
|
|
* feed this; `bindConnectivity` counts paused replayable mutations.
|
|
*/
|
|
export function usePendingWritesReporter(sourceId: string, count: number): void {
|
|
const store = useConnectivityStore();
|
|
useEffect(() => {
|
|
store.setPendingWrites(sourceId, count);
|
|
}, [store, sourceId, count]);
|
|
useEffect(() => () => store.setPendingWrites(sourceId, 0), [store, sourceId]);
|
|
}
|