mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 22:49:00 +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>
306 lines
12 KiB
TypeScript
306 lines
12 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { ApiError } from "@/api/client";
|
|
import { ApiUnavailableError } from "@/api/response";
|
|
import { createConnectivityStore, probeServerHealth, type ConnectivityStore, type ProbeResult } from "./connectivity";
|
|
import { isIntentionalAbortReason } from "./intentional-abort";
|
|
|
|
const outage = new ApiError("Paperclip is restarting", 503, { error: "tenant_app_unavailable" });
|
|
const down: ProbeResult = { reachable: false, retryAfterMs: null };
|
|
const up: ProbeResult = { reachable: true };
|
|
|
|
describe("connectivity store", () => {
|
|
let probe: ReturnType<typeof vi.fn<() => Promise<ProbeResult>>>;
|
|
let store: ConnectivityStore;
|
|
|
|
beforeEach(() => {
|
|
vi.useFakeTimers();
|
|
probe = vi.fn<() => Promise<ProbeResult>>().mockResolvedValue(down);
|
|
store = createConnectivityStore({ probe, browserOnline: true });
|
|
});
|
|
|
|
afterEach(() => {
|
|
store.dispose();
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
const flush = () => vi.advanceTimersByTimeAsync(0);
|
|
|
|
it("starts online", () => {
|
|
expect(store.getSnapshot()).toMatchObject({ status: "online", troubleSince: null, pendingWrites: 0 });
|
|
});
|
|
|
|
it("confirms a connectivity error with a probe before reconnecting", async () => {
|
|
store.reportError(outage);
|
|
expect(store.getSnapshot().status).toBe("online");
|
|
expect(probe).toHaveBeenCalledTimes(1);
|
|
await flush();
|
|
expect(store.getSnapshot().status).toBe("reconnecting");
|
|
expect(store.getSnapshot().troubleSince).not.toBeNull();
|
|
});
|
|
|
|
it("stays online when the probe finds the server healthy (one busy route)", async () => {
|
|
probe.mockResolvedValue(up);
|
|
const listener = vi.fn();
|
|
store.subscribe(listener);
|
|
store.reportError(new ApiUnavailableError(503));
|
|
await flush();
|
|
expect(store.getSnapshot().status).toBe("online");
|
|
expect(listener).not.toHaveBeenCalled();
|
|
// Repeated failures right after a clear probe do not re-probe.
|
|
store.reportError(new ApiUnavailableError(503));
|
|
expect(probe).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("ignores errors that are not server-wide", () => {
|
|
store.reportError(new ApiError("Too many requests", 429, null));
|
|
store.reportError(new ApiError("Forbidden", 403, null));
|
|
store.reportError(new ApiError("Plugin worker restarting", 503, { code: "WORKER_UNAVAILABLE", message: "x" }));
|
|
store.reportError(new TypeError("Cannot read properties of undefined"));
|
|
expect(probe).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("probes with backoff 1s, 2s, 5s, 10s, then every 15s", async () => {
|
|
store.reportError(outage);
|
|
await flush();
|
|
const probeTimes: number[] = [];
|
|
const start = Date.now();
|
|
probe.mockImplementation(async () => {
|
|
probeTimes.push(Date.now() - start);
|
|
return down;
|
|
});
|
|
await vi.advanceTimersByTimeAsync(1_000 + 2_000 + 5_000 + 10_000 + 15_000 + 15_000);
|
|
expect(probeTimes).toEqual([1_000, 3_000, 8_000, 18_000, 33_000, 48_000]);
|
|
});
|
|
|
|
it("honors a longer Retry-After", async () => {
|
|
probe.mockResolvedValueOnce({ reachable: false, retryAfterMs: 7_000 });
|
|
store.reportError(outage);
|
|
await flush();
|
|
await vi.advanceTimersByTimeAsync(6_999);
|
|
expect(probe).toHaveBeenCalledTimes(1);
|
|
await vi.advanceTimersByTimeAsync(1);
|
|
expect(probe).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("recovers on a successful probe and notifies recovery listeners once", async () => {
|
|
const recovered = vi.fn();
|
|
store.onRecover(recovered);
|
|
store.reportError(outage);
|
|
await flush();
|
|
probe.mockResolvedValue(up);
|
|
await vi.advanceTimersByTimeAsync(1_000);
|
|
expect(store.getSnapshot()).toMatchObject({ status: "online", troubleSince: null });
|
|
expect(store.getSnapshot().recoveredAt).not.toBeNull();
|
|
expect(recovered).toHaveBeenCalledTimes(1);
|
|
// No more probes once online.
|
|
await vi.advanceTimersByTimeAsync(60_000);
|
|
expect(probe).toHaveBeenCalledTimes(2);
|
|
expect(recovered).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("recovers when any request succeeds during an outage", async () => {
|
|
const recovered = vi.fn();
|
|
store.onRecover(recovered);
|
|
store.reportError(outage);
|
|
await flush();
|
|
store.reportSuccess();
|
|
expect(store.getSnapshot().status).toBe("online");
|
|
expect(recovered).toHaveBeenCalledTimes(1);
|
|
await vi.advanceTimersByTimeAsync(60_000);
|
|
expect(probe).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("ignores a failed probe that started before a newer success", async () => {
|
|
store.reportError(outage);
|
|
await flush();
|
|
let finishProbe: (result: ProbeResult) => void = () => undefined;
|
|
probe.mockImplementationOnce(() => new Promise((resolve) => {
|
|
finishProbe = resolve;
|
|
}));
|
|
await vi.advanceTimersByTimeAsync(1_000);
|
|
expect(probe).toHaveBeenCalledTimes(2);
|
|
|
|
store.reportSuccess();
|
|
expect(store.getSnapshot().status).toBe("online");
|
|
finishProbe(down);
|
|
await flush();
|
|
expect(store.getSnapshot().status).toBe("online");
|
|
await vi.advanceTimersByTimeAsync(60_000);
|
|
expect(probe).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("re-checks after a stale probe when something failed after the newer success", async () => {
|
|
let finishProbe: (result: ProbeResult) => void = () => undefined;
|
|
probe.mockImplementationOnce(() => new Promise((resolve) => {
|
|
finishProbe = resolve;
|
|
}));
|
|
store.reportError(outage);
|
|
store.reportSuccess();
|
|
store.reportError(outage);
|
|
expect(probe).toHaveBeenCalledTimes(1);
|
|
|
|
finishProbe(down);
|
|
await flush();
|
|
expect(probe).toHaveBeenCalledTimes(2);
|
|
expect(store.getSnapshot().status).toBe("reconnecting");
|
|
});
|
|
|
|
it("does not report recovery for a success while already online", () => {
|
|
const recovered = vi.fn();
|
|
store.onRecover(recovered);
|
|
store.reportSuccess();
|
|
expect(recovered).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("probes immediately on probeNow during an outage", async () => {
|
|
store.reportError(outage);
|
|
await flush();
|
|
probe.mockResolvedValue(up);
|
|
store.probeNow();
|
|
await flush();
|
|
expect(store.getSnapshot().status).toBe("online");
|
|
expect(probe).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("treats a closed socket as a suspicion and an open socket as success", async () => {
|
|
store.reportSocketStatus("closed");
|
|
expect(probe).toHaveBeenCalledTimes(1);
|
|
await flush();
|
|
expect(store.getSnapshot().status).toBe("reconnecting");
|
|
store.reportSocketStatus("open");
|
|
expect(store.getSnapshot().status).toBe("online");
|
|
});
|
|
|
|
it("goes offline with the browser and confirms the server when the network returns", async () => {
|
|
store.setBrowserOnline(false);
|
|
expect(store.getSnapshot().status).toBe("offline");
|
|
store.reportError(outage);
|
|
store.reportSuccess();
|
|
expect(store.getSnapshot().status).toBe("offline");
|
|
expect(probe).not.toHaveBeenCalled();
|
|
|
|
probe.mockResolvedValue(up);
|
|
store.setBrowserOnline(true);
|
|
expect(store.getSnapshot().status).toBe("reconnecting");
|
|
await flush();
|
|
expect(store.getSnapshot().status).toBe("online");
|
|
});
|
|
|
|
it("keeps a starting server reconnecting until health reports ok", async () => {
|
|
store.reportServerStarting();
|
|
expect(store.getSnapshot().status).toBe("reconnecting");
|
|
// Other routes answering does not mean the server is ready.
|
|
store.reportSuccess();
|
|
expect(store.getSnapshot().status).toBe("reconnecting");
|
|
probe.mockResolvedValue(up);
|
|
await vi.advanceTimersByTimeAsync(1_000);
|
|
expect(store.getSnapshot().status).toBe("online");
|
|
});
|
|
|
|
it("keeps probing when the server reports starting after a success while a probe is in flight", async () => {
|
|
let finishProbe: (result: ProbeResult) => void = () => undefined;
|
|
probe.mockImplementationOnce(() => new Promise((resolve) => {
|
|
finishProbe = resolve;
|
|
}));
|
|
store.reportError(outage);
|
|
// A health query answers `starting`: the cache reports the success first,
|
|
// then the gate reports the starting server.
|
|
store.reportSuccess();
|
|
store.reportServerStarting();
|
|
expect(store.getSnapshot().status).toBe("reconnecting");
|
|
expect(probe).toHaveBeenCalledTimes(1);
|
|
|
|
finishProbe(down);
|
|
await flush();
|
|
expect(store.getSnapshot().status).toBe("reconnecting");
|
|
probe.mockResolvedValue(up);
|
|
await vi.advanceTimersByTimeAsync(1_000);
|
|
expect(probe).toHaveBeenCalledTimes(2);
|
|
expect(store.getSnapshot().status).toBe("online");
|
|
});
|
|
|
|
it("ignores a healthy probe that started before the server reported starting", async () => {
|
|
let finishProbe: (result: ProbeResult) => void = () => undefined;
|
|
probe.mockImplementationOnce(() => new Promise((resolve) => {
|
|
finishProbe = resolve;
|
|
}));
|
|
store.reportError(outage);
|
|
store.reportServerStarting();
|
|
|
|
finishProbe(up);
|
|
await flush();
|
|
expect(store.getSnapshot().status).toBe("reconnecting");
|
|
await vi.advanceTimersByTimeAsync(1_000);
|
|
expect(probe).toHaveBeenCalledTimes(2);
|
|
expect(store.getSnapshot().status).toBe("reconnecting");
|
|
});
|
|
|
|
it("sums pending writes across sources", () => {
|
|
store.setPendingWrites("composer", 2);
|
|
store.setPendingWrites("autosave", 1);
|
|
expect(store.getSnapshot().pendingWrites).toBe(3);
|
|
store.setPendingWrites("composer", 0);
|
|
expect(store.getSnapshot().pendingWrites).toBe(1);
|
|
});
|
|
|
|
it("returns a stable snapshot until something changes", async () => {
|
|
const first = store.getSnapshot();
|
|
store.reportSuccess();
|
|
expect(store.getSnapshot()).toBe(first);
|
|
store.reportError(outage);
|
|
await flush();
|
|
expect(store.getSnapshot()).not.toBe(first);
|
|
});
|
|
});
|
|
|
|
describe("probeServerHealth", () => {
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
it.each<[string, Response | Error, ProbeResult["reachable"]]>([
|
|
["ok health", Response.json({ status: "ok" }), true],
|
|
["a starting server", Response.json({ status: "starting" }), false],
|
|
["the gateway code", Response.json({ error: "tenant_app_unavailable" }, { status: 503 }), false],
|
|
["the gateway code with a 404", Response.json({ error: "tenant_app_unavailable" }, { status: 404 }), false],
|
|
["a proxy HTML page", new Response("<html>Bad gateway</html>", { status: 502 }), false],
|
|
["an HTML fallback with 200", new Response("<html></html>", { status: 200 }), false],
|
|
["a 401 (server is up)", Response.json({ error: "Unauthorized" }, { status: 401 }), true],
|
|
["a network failure", new TypeError("Failed to fetch"), false],
|
|
])("reports %s", async (_label, outcome, reachable) => {
|
|
vi.stubGlobal("fetch", vi.fn(async () => {
|
|
if (outcome instanceof Error) throw outcome;
|
|
return outcome;
|
|
}));
|
|
expect((await probeServerHealth()).reachable).toBe(reachable);
|
|
});
|
|
|
|
it("passes Retry-After through", async () => {
|
|
vi.stubGlobal("fetch", vi.fn(async () => Response.json(
|
|
{ error: "tenant_app_unavailable" },
|
|
{ status: 503, headers: { "Retry-After": "4" } },
|
|
)));
|
|
expect(await probeServerHealth()).toEqual({ reachable: false, retryAfterMs: 4_000 });
|
|
});
|
|
|
|
it("marks its own timeout abort as intentional", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
let probeSignal: AbortSignal | undefined;
|
|
vi.stubGlobal("fetch", vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {
|
|
probeSignal = init?.signal ?? undefined;
|
|
return new Promise<Response>((_resolve, reject) => {
|
|
probeSignal?.addEventListener("abort", () => reject(probeSignal?.reason), { once: true });
|
|
});
|
|
}));
|
|
const result = probeServerHealth();
|
|
await vi.advanceTimersByTimeAsync(10_000);
|
|
expect(await result).toEqual({ reachable: false, retryAfterMs: null });
|
|
expect(probeSignal?.aborted).toBe(true);
|
|
expect(isIntentionalAbortReason(probeSignal?.reason)).toBe(true);
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
});
|