diff --git a/ui/src/lib/browser-error-context.test.ts b/ui/src/lib/browser-error-context.test.ts index 4b90c6a6341..9259dd1af84 100644 --- a/ui/src/lib/browser-error-context.test.ts +++ b/ui/src/lib/browser-error-context.test.ts @@ -4,6 +4,8 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { __resetPageDiagnostics, buildBrowserErrorContext, + buildQueryErrorContext, + queryKindFor, readPageLifecycle, sanitizeComponentStack, startPageDiagnostics, @@ -17,6 +19,34 @@ afterEach(() => { document.documentElement.className = ""; }); +describe("query error context", () => { + it("keeps only a static query key name", () => { + expect(queryKindFor(["issues", "company-uuid", "detail", "PAP-1"])).toBe("issues"); + expect(queryKindFor(["agent-commentary", "company-uuid"])).toBe("agent-commentary"); + expect(queryKindFor(["266ff1d0-6be9-47cb-b2ed-300fce5fbcd3"])).toBe("other"); + expect(queryKindFor(["abcdefab-abcd-4bcd-abcd-abcdefabcdef"])).toBe("other"); + expect(queryKindFor(["PAP-1"])).toBe("other"); + expect(queryKindFor(["person@example.com"])).toBe("other"); + expect(queryKindFor(["a".repeat(65)])).toBe("other"); + expect(queryKindFor([{ companyId: "company-uuid" }])).toBe("other"); + expect(queryKindFor([])).toBe("other"); + }); + + it("fingerprints an HTTP failure by status and query name", () => { + const error = Object.assign(new Error("Internal server error"), { status: 500 }); + expect(buildQueryErrorContext(error, ["issues", "company-uuid"])).toEqual({ + tags: { query_kind: "issues", api_status: "500" }, + fingerprint: ["api-error", "500", "issues"], + }); + }); + + it("keeps default stack grouping for an error without an HTTP status", () => { + expect(buildQueryErrorContext(new TypeError("x is undefined"), ["issues"])).toEqual({ + tags: { query_kind: "issues" }, + }); + }); +}); + describe("browser error context", () => { it("keeps React component names without locations or unrecognized content", () => { const stack = ` diff --git a/ui/src/lib/browser-error-context.ts b/ui/src/lib/browser-error-context.ts index 7660a472d07..7908070e979 100644 --- a/ui/src/lib/browser-error-context.ts +++ b/ui/src/lib/browser-error-context.ts @@ -1,3 +1,5 @@ +import { errorStatus } from "@/api/errors"; + export interface BrowserErrorDetails { boundary: "app" | "route"; componentStack?: string | null; @@ -167,6 +169,37 @@ export function __resetPageDiagnostics() { lastRejection = undefined; } +const QUERY_KIND_PATTERN = /^[a-z]+(?:[-_][a-z]+)*$/; +const MAX_QUERY_KIND_LENGTH = 64; + +/** + * The query key's static name, such as `issues`. Later key parts hold + * companies, refs and filters, and are never read. A head with a digit, + * uppercase letter or other character can be an ID or a typed value, so it + * becomes `other`. + */ +export function queryKindFor(queryKey: readonly unknown[]): string { + const head = queryKey[0]; + return typeof head === "string" && head.length <= MAX_QUERY_KIND_LENGTH && QUERY_KIND_PATTERN.test(head) + ? head + : "other"; +} + +/** + * Every failed request throws from the same `ApiError` frames, so default + * grouping puts all of them in one Sentry issue. Group an HTTP failure by its + * status and query name instead, so each failing endpoint has its own issue. + */ +export function buildQueryErrorContext(error: unknown, queryKey: readonly unknown[]) { + const queryKind = queryKindFor(queryKey); + const status = errorStatus(error); + if (status === null) return { tags: { query_kind: queryKind } }; + return { + tags: { query_kind: queryKind, api_status: String(status) }, + fingerprint: ["api-error", String(status), queryKind], + }; +} + /** A bounded snapshot, taken at the error rather than when the capture queue runs. */ export function buildBrowserErrorContext(details: BrowserErrorDetails) { const componentStack = sanitizeComponentStack(details.componentStack); diff --git a/ui/src/lib/query-client.test.ts b/ui/src/lib/query-client.test.ts index 0c0c2cb4dd1..4932a826efe 100644 --- a/ui/src/lib/query-client.test.ts +++ b/ui/src/lib/query-client.test.ts @@ -73,14 +73,14 @@ describe("createAppQueryClient", () => { let client: QueryClient; let unbind: () => void; let notifyMutationError: ReturnType void>>; - let reportError: ReturnType void>>; + let reportError: ReturnType void>>; beforeEach(() => { vi.useFakeTimers(); probe = vi.fn<() => Promise>().mockResolvedValue({ reachable: false, retryAfterMs: null }); store = createConnectivityStore({ probe, browserOnline: true }); notifyMutationError = vi.fn<(toast: MutationErrorToast) => void>(); - reportError = vi.fn<(error: unknown) => void>(); + reportError = vi.fn<(error: unknown, queryKey: readonly unknown[]) => void>(); client = createAppQueryClient({ connectivity: store, notifyMutationError, reportError }); client.mount(); unbind = bindConnectivity(client, store); @@ -275,6 +275,7 @@ describe("createAppQueryClient", () => { await observer.refetch(); expect(queryFn).toHaveBeenCalledTimes(2); expect(reportError).toHaveBeenCalledTimes(1); + expect(reportError).toHaveBeenCalledWith(expect.any(ApiError), ["broken"]); unsubscribe(); }); diff --git a/ui/src/lib/query-client.ts b/ui/src/lib/query-client.ts index 9fcc4332862..04e2988ed0f 100644 --- a/ui/src/lib/query-client.ts +++ b/ui/src/lib/query-client.ts @@ -116,7 +116,8 @@ export interface MutationErrorToast { export interface AppQueryClientDeps { connectivity: Pick; - reportError?: (error: unknown) => void; + /** Report a final query error. The key lets the reporter group by query name. */ + reportError?: (error: unknown, queryKey: QueryKey) => void; /** Show a toast for a failed opted-in mutation that has no handler of its own. */ notifyMutationError?: (toast: MutationErrorToast) => void; } @@ -178,7 +179,7 @@ export function createAppQueryClient(deps: AppQueryClientDeps, config: QueryClie const last = lastReportedAt.get(query.queryHash); if (last !== undefined && now - last < QUERY_ERROR_REPORT_WINDOW_MS) return; lastReportedAt.set(query.queryHash, now); - deps.reportError(error); + deps.reportError(error, query.queryKey); }, }); const mutationCache = new MutationCache({ diff --git a/ui/src/lib/sentry.test.ts b/ui/src/lib/sentry.test.ts index 4607f27fbd9..7970f75b050 100644 --- a/ui/src/lib/sentry.test.ts +++ b/ui/src/lib/sentry.test.ts @@ -319,6 +319,36 @@ describe("captureBrowserException", () => { }); }); +describe("captureQueryException", () => { + it("does not throw when the gate is closed", async () => { + const { captureQueryException } = await importFreshSentry(); + + expect(() => captureQueryException(new Error("boom"), ["issues"])).not.toThrow(); + }); + + it("groups each failing query's server error by status and query name", async () => { + const mocks = mockSentryPackage(); + const { initBrowserErrorMonitoring, captureQueryException } = await importFreshSentry(); + await initBrowserErrorMonitoring(DSN); + const issuesError = Object.assign(new Error("Internal server error"), { status: 500 }); + const agentsError = Object.assign(new Error("Internal server error"), { status: 500 }); + + captureQueryException(issuesError, ["issues", "company-uuid", "detail", "PAP-1"]); + captureQueryException(agentsError, ["agents", "company-uuid"]); + await initBrowserErrorMonitoring(DSN); + + expect(mocks.captureException).toHaveBeenNthCalledWith(1, issuesError, { + tags: { query_kind: "issues", api_status: "500" }, + fingerprint: ["api-error", "500", "issues"], + }); + expect(mocks.captureException).toHaveBeenNthCalledWith(2, agentsError, { + tags: { query_kind: "agents", api_status: "500" }, + fingerprint: ["api-error", "500", "agents"], + }); + expect(JSON.stringify(mocks.captureException.mock.calls)).not.toMatch(/company-uuid|PAP-1/); + }); +}); + describe("browser error diagnostics with the real SDK", () => { it("emits bounded component and translation context without page data or scope leakage", async () => { const Sentry = await vi.importActual("@sentry/browser"); diff --git a/ui/src/lib/sentry.ts b/ui/src/lib/sentry.ts index 39fac4b2adb..56e759849a2 100644 --- a/ui/src/lib/sentry.ts +++ b/ui/src/lib/sentry.ts @@ -16,12 +16,12 @@ // as long as the close call takes. Both calls are built-in Sentry client // calls — no custom filter code. // -// `initBrowserErrorMonitoring`, `teardownBrowserErrorMonitoring`, and -// `captureBrowserException` each queue their work on one shared promise -// chain (`enqueue`) instead of running at once. One operation runs at a -// time, in call order, so no operation can ever observe another one -// part-finished — a sign-out always closes the client a sign-in already -// finished starting, never one still starting. +// `initBrowserErrorMonitoring`, `teardownBrowserErrorMonitoring`, +// `captureBrowserException`, and `captureQueryException` each queue their +// work on one shared promise chain (`enqueue`) instead of running at once. +// One operation runs at a time, in call order, so no operation can ever +// observe another one part-finished — a sign-out always closes the client a +// sign-in already finished starting, never one still starting. // // `@sentry/browser` loads through a dynamic import, so Vite puts it in a // separate chunk that a browser with no DSN never fetches. @@ -40,6 +40,7 @@ import { buildBrowserErrorContext, + buildQueryErrorContext, classifyRejectionReason, readBrowserErrorState, readPageLifecycle, @@ -157,13 +158,34 @@ export function captureBrowserException(error: unknown, details?: BrowserErrorDe } catch { // Diagnostics must never replace the original exception or its recovery UI. } + enqueueCapture(error, context); +} + +/** + * Report a failed query, grouped by its HTTP status and the static name of + * its query key. Never throws, and is a no-op until the gate opens. + */ +export function captureQueryException(error: unknown, queryKey: readonly unknown[]): void { + let context: ReturnType | undefined; + try { + context = buildQueryErrorContext(error, queryKey); + } catch { + // Diagnostics must never replace the original exception. + } + enqueueCapture(error, context); +} + +function enqueueCapture( + error: unknown, + context: ReturnType | ReturnType | undefined, +): void { void enqueue(async () => { try { if (context) sentry?.captureException(error, context); else sentry?.captureException(error); } catch (err) { // eslint-disable-next-line no-console - console.error("[paperclip] Sentry captureBrowserException failed", err); + console.error("[paperclip] Sentry captureException failed", err); } }); } diff --git a/ui/src/main.tsx b/ui/src/main.tsx index f5f46e92da6..b74197acbc3 100644 --- a/ui/src/main.tsx +++ b/ui/src/main.tsx @@ -30,7 +30,7 @@ import { getOrCreatePaperclipReactRoot } from "./lib/react-root"; import { startServiceWorkerUpdates } from "./lib/service-worker-updates"; import { connectivity } from "./lib/connectivity"; import { bindConnectivity, createAppQueryClient } from "./lib/query-client"; -import { captureBrowserException } from "./lib/sentry"; +import { captureQueryException } from "./lib/sentry"; import { startPersistedQueryCache } from "./lib/persisted-query-cache"; import { hasPendingWrites, subscribePendingWrites } from "./lib/reload-safety"; import "@mdxeditor/editor/style.css"; @@ -65,7 +65,7 @@ function MutationErrorToastBridge() { const queryClient = createAppQueryClient( { connectivity, - reportError: (error) => captureBrowserException(error), + reportError: (error, queryKey) => captureQueryException(error, queryKey), notifyMutationError: ({ title, body }) => pushMutationErrorToast?.({ title, body, tone: "error" }), }, {