Files
PaperClipAI/ui/src/main.tsx
T
Devin FoleyandClaude Opus 5.5 f58bbefc4e fix(ui): group failed-query Sentry reports by status and query name (#21475)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The browser app can report errors to Sentry. A final query error
goes to Sentry when it is not an outage, a denial, or a missing item.
> - Every failed API request throws an `ApiError` from the same frames
in `api/client.ts`.
> - Sentry groups errors by stack. Thus all unrelated server failures go
into one issue, titled "ApiError: Internal server error".
> - The report has no route, no query name, and no status. Breadcrumbs
and URLs are removed for privacy. A person cannot find which endpoint
failed.
> - This pull request tags each failed-query report with its HTTP status
and the static name of its query key. It also sets the Sentry
fingerprint from these two values.
> - The benefit: each failing endpoint gets its own Sentry issue, and a
person can connect it to the server error.

## Linked Issues or Issue Description

**What happened?**
One browser Sentry issue collected unrelated server 500 errors from
different pages and environments. The events had no route or query name.
A person could not connect an event to a server error.

**Steps to reproduce**
1. Turn on browser error monitoring with a Sentry DSN.
2. Make two different queries fail with a 500 response, for example the
issues list and the agents list.
3. Look at Sentry. Both events are in one issue with the title
"ApiError: Internal server error". Neither event shows which query
failed.

**Expected behavior**
Each failing query has its own Sentry issue. The event shows the HTTP
status and the static query name. It shows no IDs, refs, or filters.

**Environment**
The hosted browser app, staging and production builds.

I searched open pull requests for duplicates. I found no pull request
that changes browser query-error grouping.

## What Changed

- `ui/src/lib/browser-error-context.ts`: add `queryKindFor`. It keeps
only the first query-key part, and only when it is a lowercase word list
such as `issues` or `agent-commentary`. Other values become `other`, so
an ID, a ref, an email, or a typed value is never sent.
- `ui/src/lib/browser-error-context.ts`: add `buildQueryErrorContext`.
For an error with an HTTP status, it sets the `query_kind` and
`api_status` tags and the fingerprint `["api-error", status,
queryKind]`. For an error without a status, it sets only the
`query_kind` tag and keeps default stack grouping.
- `ui/src/lib/sentry.ts`: add `captureQueryException`. It uses the same
serialized queue as `captureBrowserException`. Both functions now share
one private capture step.
- `ui/src/lib/query-client.ts`: `reportError` now also receives the
query key.
- `ui/src/main.tsx`: the query client reports through
`captureQueryException`.
- Tests for key sanitizing, the fingerprint, the reporter argument, and
the gate call.

## Verification

- Red before the fix: the 6 new assertions fail on the old source
(`queryKindFor`, `buildQueryErrorContext` and `captureQueryException` do
not exist, and `reportError` gets no key).
- Green after the fix: `cd ui && npx vitest run src/lib/sentry.test.ts
src/lib/browser-error-context.test.ts src/lib/query-client.test.ts`
passes 3 files and 78 tests.
- The privacy test makes sure that `company-uuid` and `PAP-1` from later
key parts do not go into the Sentry call. It also makes sure that UUID,
ref, email, and long heads become `other`.
- `ui` typecheck: no errors in the changed files. The local install was
filtered to the UI package, so unrelated packages (`plugin-sdk` build
output, runner dependencies) could not resolve. Required CI supplies the
full typecheck.
- I did not run browser e2e suites. This change does not touch them.

## Risks

- Low risk. Only the grouping and tags of browser query-error reports
change. The app does not change what it shows to users.
- Sentry opens new issues for future query errors, one for each status
and query name. The old catch-all issue gets no new events.
- A query key with a dynamic first part becomes `other`. Those errors
still group together, but they keep the status tag.

> 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

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code with
tool use, repository inspection, and shell code execution.

## 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: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:24:46 -08:00

160 lines
7.1 KiB
TypeScript

import { VoiceCallProvider } from "./components/voice/VoiceCallProvider";
import { useAccountIdentity } from "./api/companies-query";
import * as React from "react";
import { StrictMode, useEffect } from "react";
import * as ReactDOM from "react-dom";
import { BrowserRouter } from "@/lib/router";
import { QueryClientProvider } from "@tanstack/react-query";
import { App } from "./App";
import { AppErrorBoundary } from "./components/AppErrorBoundary";
import { SentryGate } from "./components/SentryGate";
import { CompanyProvider, useCompany } from "./context/CompanyContext";
import { LinkPreviewProvider } from "./context/LinkPreviewContext";
import { LiveUpdatesProvider } from "./context/LiveUpdatesProvider";
import { BreadcrumbProvider } from "./context/BreadcrumbContext";
import { PanelProvider } from "./context/PanelContext";
import { SidebarProvider } from "./context/SidebarContext";
import { DialogProvider } from "./context/DialogContext";
import { EditorAutocompleteProvider } from "./context/EditorAutocompleteContext";
import { applyLiveEventFreeQueryDefaults } from "./lib/live-reconcile";
import { PrimaryAgentProvider } from "./context/PrimaryAgentProvider";
import { ToastProvider, useToastActions, type ToastInput } from "./context/ToastContext";
import { ThemeProvider } from "./context/ThemeContext";
import { DesignSandboxProvider } from "./context/DesignSandboxContext";
import { TooltipProvider } from "@/components/ui/tooltip";
import { initPluginBridge } from "./plugins/bridge-init";
import { PluginLauncherProvider } from "./plugins/launchers";
import { startChunkLoadRecovery } from "./lib/chunk-load-recovery";
import { startPerfMeasureReaper } from "./lib/perf-measure-reaper";
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 { captureQueryException } from "./lib/sentry";
import { startPersistedQueryCache } from "./lib/persisted-query-cache";
import { hasPendingWrites, subscribePendingWrites } from "./lib/reload-safety";
import "@mdxeditor/editor/style.css";
import "./index.css";
initPluginBridge(React, ReactDOM);
// React 19.2 emits an unbounded stream of performance.measure() entries for its
// DevTools performance tracks and never clears them; on a long-lived tab they
// accumulate into millions of native objects (GBs). Reap them periodically.
startPerfMeasureReaper();
startChunkLoadRecovery();
// The global mutation error toast is raised from the MutationCache, outside
// React; the bridge below hands it the ToastProvider's pushToast.
let pushMutationErrorToast: ((input: ToastInput) => void) | null = null;
function MutationErrorToastBridge() {
const { pushToast } = useToastActions();
useEffect(() => {
pushMutationErrorToast = pushToast;
return () => {
if (pushMutationErrorToast === pushToast) pushMutationErrorToast = null;
};
}, [pushToast]);
return null;
}
// Retry, pause-on-outage, and error-reporting defaults live in
// lib/query-client.ts; app-specific cache tuning stays here.
const queryClient = createAppQueryClient(
{
connectivity,
reportError: (error, queryKey) => captureQueryException(error, queryKey),
notifyMutationError: ({ title, body }) => pushMutationErrorToast?.({ title, body, tone: "error" }),
},
{
defaultOptions: {
queries: {
staleTime: 30_000,
// Explicit so cross-tab-published cache entries for resources this tab
// isn't observing get collected promptly rather than lingering. Single
// tuning point if we need to trim the cache footprint further.
gcTime: 5 * 60_000,
refetchOnWindowFocus: true,
},
},
},
);
// Instance and personal preference reads have no live events; see live-reconcile.ts.
applyLiveEventFreeQueryDefaults(queryClient);
// Outages pause queries and replayable mutations instead of failing them, and
// live queries refresh once when the server answers again.
bindConnectivity(queryClient, connectivity);
startPersistedQueryCache(queryClient, {
buildId: typeof __PAPERCLIP_BUILD_COMMIT__ === "string" ? __PAPERCLIP_BUILD_COMMIT__ : null,
});
window.addEventListener("load", () => {
startServiceWorkerUpdates({
canReload: () => connectivity.getSnapshot().status === "online"
&& connectivity.getSnapshot().pendingWrites === 0 && queryClient.isMutating() === 0 && !hasPendingWrites(),
subscribeReloadSafety: listener => {
const cleanups = [connectivity.subscribe(listener), queryClient.getMutationCache().subscribe(listener), subscribePendingWrites(listener)];
return () => { for (const cleanup of cleanups) cleanup(); };
},
});
});
function CompanyAwareBreadcrumbProvider({ children }: { children: React.ReactNode }) {
const { selectedCompany } = useCompany();
return <BreadcrumbProvider companyName={selectedCompany?.name ?? null}>{children}</BreadcrumbProvider>;
}
function CompanyVoiceCalls({ children }: { children: React.ReactNode }) {
const { selectedCompanyId } = useCompany();
const { userId } = useAccountIdentity();
return <VoiceCallProvider companyId={selectedCompanyId} userId={userId}>{children}</VoiceCallProvider>;
}
function CompanyLinkPreviews({ children }: { children: React.ReactNode }) {
const { selectedCompanyId } = useCompany();
const { userId, settled } = useAccountIdentity();
return <LinkPreviewProvider companyId={settled ? selectedCompanyId : null} userId={userId}>{children}</LinkPreviewProvider>;
}
const rootElement = document.getElementById("root");
if (!rootElement) throw new Error("Paperclip root element is missing");
getOrCreatePaperclipReactRoot(window, rootElement).render(
<StrictMode>
<AppErrorBoundary>
<QueryClientProvider client={queryClient}>
<SentryGate />
<ThemeProvider>
<BrowserRouter>
<CompanyProvider>
<EditorAutocompleteProvider>
<ToastProvider>
<MutationErrorToastBridge />
<PrimaryAgentProvider>
<LiveUpdatesProvider>
<TooltipProvider>
<CompanyAwareBreadcrumbProvider>
<SidebarProvider>
<PanelProvider>
<PluginLauncherProvider>
<DialogProvider>
<DesignSandboxProvider><CompanyVoiceCalls><CompanyLinkPreviews><App /></CompanyLinkPreviews></CompanyVoiceCalls></DesignSandboxProvider>
</DialogProvider>
</PluginLauncherProvider>
</PanelProvider>
</SidebarProvider>
</CompanyAwareBreadcrumbProvider>
</TooltipProvider>
</LiveUpdatesProvider>
</PrimaryAgentProvider>
</ToastProvider>
</EditorAutocompleteProvider>
</CompanyProvider>
</BrowserRouter>
</ThemeProvider>
</QueryClientProvider>
</AppErrorBoundary>
</StrictMode>
);