Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(analytics): require metadata for every toast (#18554)

Nikita Kabardinb93c7b7a8e3a
diff --git a/web/AGENTS.md b/web/AGENTS.md
index feebcac26c..00c2c00684 100644
--- a/web/AGENTS.md
+++ b/web/AGENTS.md
@@ -296,6 +296,25 @@ Sentry instrumentation skill first and decide whether it should capture at all
2. Let `BaseError`s bubble up to the tRPC and REST middlewares (eg. don't `try/catch` and rethrow in to `TRPCError` the handler)
3. Extend the `BaseError` or its subclasses in [`packages/shared/src/errors/`](../packages/shared/src/errors/) as needed.
+### Toasts
+
+- Use the typed helpers exported by `src/features/notifications`; importing the
+ Sonner `toast` API outside their implementation is lint-prohibited.
+- Every toast requires a static `operation` from `toastOperations.ts` or a typed
+ tRPC procedure path. Register a new semantic intent when needed; never use
+ resource identifiers, names, messages, URLs, or form values.
+- Errors and warnings additionally require `errorOrigin` and `errorCategory`.
+ For tRPC catches, use `classifyTrpcToastError(error, operation)` to retain
+ classification, request path, response code/status, and error ID. Local
+ validation, clipboard, and product-state branches must classify explicitly.
+- `showToast` preserves native Sonner presentation; `showErrorToast` and
+ `showSuccessToast` render the custom cards. Analytics captures metadata only,
+ never the title, description, or exception payload.
+- Direct TanStack queries or mutations that can show global error toasts must include a
+ registered `meta.toastOperation`. Unattributed global failures use explicit
+ gap markers (`query.execute` / `mutation.execute`, `isOperationFallback=true`),
+ not an inferred intent from customer-controlled query keys.
+
### Add frontend feature
1. Prefer `src/features/<feature>/*` for feature-local code.
diff --git a/web/eslint.config.mjs b/web/eslint.config.mjs
index c5936d3632..212ec763b3 100644
--- a/web/eslint.config.mjs
+++ b/web/eslint.config.mjs
@@ -53,6 +53,13 @@ const sentryCapturePattern = {
"Do not capture directly — route through the reportError seam (@/src/utils/reportError) or a helper that wraps it (captureUnknownError, reportParserWorkerError), so one seam owns error classification. See the reportError doc comment and .agents/skills/sentry-instrumentation/SKILL.md.",
};
+const toastImportPattern = {
+ regex: "^sonner(?:/|$)",
+ importNames: ["toast", "default"],
+ message:
+ "Use the notifications feature's typed toast helpers. Every toast must declare its static operation and errors/warnings must declare origin and category.",
+};
+
const designSystemInternalPattern = {
regex: "(^|/)design-system/internal(?:/|$)",
message:
@@ -523,6 +530,7 @@ export default [
patterns: [
...restrictedImportPatterns,
sentryCapturePattern,
+ toastImportPattern,
designSystemInternalPattern,
],
},
@@ -537,7 +545,11 @@ export default [
"no-restricted-imports": [
"error",
{
- patterns: [...restrictedImportPatterns, sentryCapturePattern],
+ patterns: [
+ ...restrictedImportPatterns,
+ sentryCapturePattern,
+ toastImportPattern,
+ ],
},
],
},
@@ -586,7 +598,54 @@ export default [
"no-restricted-imports": [
"error",
{
- patterns: [...restrictedImportPatterns, designSystemInternalPattern],
+ patterns: [
+ ...restrictedImportPatterns,
+ designSystemInternalPattern,
+ toastImportPattern,
+ ],
+ },
+ ],
+ },
+ },
+ {
+ name: "langfuse/web/toast-seam",
+ files: [
+ "src/features/notifications/showErrorToast.tsx",
+ "src/features/notifications/showSuccessToast.tsx",
+ "src/features/notifications/showToast.tsx",
+ ],
+ rules: {
+ "no-restricted-imports": [
+ "error",
+ {
+ patterns: [
+ ...restrictedImportPatterns,
+ sentryCapturePattern,
+ designSystemInternalPattern,
+ ],
+ },
+ ],
+ },
+ },
+ {
+ name: "langfuse/web/no-dynamic-toast-bypass",
+ files: ["src/**/*.{ts,tsx}"],
+ rules: {
+ "no-restricted-syntax": [
+ "error",
+ {
+ selector: "ImportExpression[source.value=/^sonner(?:\\/|$)/]",
+ message: toastImportPattern.message,
+ },
+ {
+ selector:
+ "CallExpression[callee.name='require'][arguments.0.value=/^sonner(?:\\/|$)/]",
+ message: toastImportPattern.message,
+ },
+ {
+ selector:
+ "TSImportEqualsDeclaration[moduleReference.expression.value=/^sonner(?:\\/|$)/]",
+ message: toastImportPattern.message,
},
],
},
diff --git a/web/src/__tests__/account-settings-sign-out-all-sessions.clienttest.tsx b/web/src/__tests__/account-settings-sign-out-all-sessions.clienttest.tsx
index 7e56940209..2c20c4e940 100644
--- a/web/src/__tests__/account-settings-sign-out-all-sessions.clienttest.tsx
+++ b/web/src/__tests__/account-settings-sign-out-all-sessions.clienttest.tsx
@@ -126,10 +126,7 @@ describe("SignOutAllSessionsButton", () => {
operation: "account.revoke_sessions",
});
});
- expect(showErrorToastMock).not.toHaveBeenCalledWith(
- "Failed to Sign Out of All Sessions",
- expect.anything(),
- );
+ expect(showErrorToastMock).not.toHaveBeenCalled();
expect(reportNonTrpcErrorMock).toHaveBeenCalled();
});
@@ -151,6 +148,11 @@ describe("SignOutAllSessionsButton", () => {
expect(showErrorToastMock).toHaveBeenCalledWith(
"Failed to Sign Out of All Sessions",
"UNAUTHORIZED",
+ {
+ operation: "account.revoke_sessions",
+ errorOrigin: "frontend",
+ errorCategory: "internal",
+ },
);
});
expect(signOutCleanlyMock).not.toHaveBeenCalled();
diff --git a/web/src/components/JSONSchemaEditor.tsx b/web/src/components/JSONSchemaEditor.tsx
index 71c4f09ac3..db1954a041 100644
--- a/web/src/components/JSONSchemaEditor.tsx
+++ b/web/src/components/JSONSchemaEditor.tsx
@@ -57,6 +57,11 @@ export const JSONSchemaEditor: React.FC<JSONSchemaEditorProps> = ({
showErrorToast(
"Failed to prettify JSON",
"Please verify your input is valid JSON",
+ {
+ operation: "json_schema.prettify",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
"WARNING",
);
}
diff --git a/web/src/components/publish-object-switch.tsx b/web/src/components/publish-object-switch.tsx
index 37834fbf64..f07f4813eb 100644
--- a/web/src/components/publish-object-switch.tsx
+++ b/web/src/components/publish-object-switch.tsx
@@ -50,6 +50,7 @@ export function usePublishObject(props: PublishObjectProps) {
const sessionQueryInput = { projectId, sessionId: objectId };
const mutation = useMutation({
+ meta: { toastOperation: "sharing.update" },
mutationFn: (isPublic: boolean) =>
kind === "trace"
? utils.client.traces.publish.mutate({
@@ -117,7 +118,7 @@ export function usePublishObject(props: PublishObjectProps) {
return { previousTrace };
},
- onError: (err, _input, context) => {
+ onError: (err, input, context) => {
if (kind === "session") {
utils.sessions.byIdWithScores.setData(
sessionQueryInput,
@@ -138,7 +139,7 @@ export function usePublishObject(props: PublishObjectProps) {
context?.previousTrace,
);
}
- trpcErrorToast(err);
+ trpcErrorToast(err, input ? "sharing.enable" : "sharing.disable");
},
onSuccess: async () => {
if (kind === "session") {
diff --git a/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx b/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx
index 404a4170c1..d1e91b9cbd 100644
--- a/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx
+++ b/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx
@@ -104,6 +104,11 @@ const copyPermalinkAndToast = (href: string) => {
showErrorToast(
"Failed to copy permalink",
"Could not write to the clipboard. Please copy the page URL manually.",
+ {
+ operation: "saved_view.permalink_copy",
+ errorOrigin: "frontend",
+ errorCategory: "permission",
+ },
"WARNING",
),
);
@@ -576,6 +581,11 @@ function TableViewPresetsDrawerContentBody({
showErrorToast(
"Failed to generate permalink",
"Please reach out to langfuse support and report this issue.",
+ {
+ operation: "saved_view.permalink_generate",
+ errorOrigin: "frontend",
+ errorCategory: "internal",
+ },
"WARNING",
);
}
diff --git a/web/src/components/table/table-view-presets/hooks/useDefaultViewMutations.ts b/web/src/components/table/table-view-presets/hooks/useDefaultViewMutations.ts
index 4de70f8970..2c1f9eec60 100644
--- a/web/src/components/table/table-view-presets/hooks/useDefaultViewMutations.ts
+++ b/web/src/components/table/table-view-presets/hooks/useDefaultViewMutations.ts
@@ -1,6 +1,7 @@
import { api } from "@/src/utils/api";
import { showSuccessToast, showErrorToast } from "@/src/features/notifications";
import { type DefaultViewScope } from "@langfuse/shared/src/server";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
interface UseDefaultViewMutationsProps {
tableName: string;
@@ -31,7 +32,11 @@ export function useDefaultViewMutations({
});
},
onError: (error) => {
- showErrorToast("Failed to set default", error.message);
+ showErrorToast(
+ "Failed to set default",
+ error.message,
+ classifyTrpcToastError(error, "saved_view.default_set"),
+ );
},
});
@@ -53,7 +58,11 @@ export function useDefaultViewMutations({
});
},
onError: (error) => {
- showErrorToast("Failed to clear default", error.message);
+ showErrorToast(
+ "Failed to clear default",
+ error.message,
+ classifyTrpcToastError(error, "saved_view.default_clear"),
+ );
},
});
diff --git a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
index 9dda0585f9..949afbebb9 100644
--- a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
+++ b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
@@ -23,6 +23,7 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { validateOrderBy, validateFilters } from "../validation";
import { isSystemPresetId } from "../components/data-table-view-presets-drawer";
import type { FilterStateMigration } from "@/src/features/filters/lib/filter-config";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
/** How a saved view / preset apply was initiated — the `trigger` analytics
* dimension on `saved_views:applied` (LFE-10781). `system_preset_cleared` is a
@@ -361,6 +362,11 @@ export function useTableViewManager({
showErrorToast(
"Outdated view",
"This view is outdated. Some old filters or ordering may have been ignored. Please update your view.",
+ {
+ operation: "saved_view.apply",
+ errorOrigin: "frontend",
+ errorCategory: "product_state",
+ },
"WARNING",
);
}
@@ -610,12 +616,14 @@ export function useTableViewManager({
showErrorToast(
"View no longer available",
"This suggested view was retired — showing the default view instead.",
+ classifyTrpcToastError(selectedViewError, "saved_view.apply"),
"WARNING",
);
} else {
showErrorToast(
"Error applying view",
selectedViewError.message,
+ classifyTrpcToastError(selectedViewError, "saved_view.apply"),
"WARNING",
);
}
diff --git a/web/src/components/table/table-view-presets/hooks/useViewMutations.ts b/web/src/components/table/table-view-presets/hooks/useViewMutations.ts
index 3c9cf43ac1..cbc1efad29 100644
--- a/web/src/components/table/table-view-presets/hooks/useViewMutations.ts
+++ b/web/src/components/table/table-view-presets/hooks/useViewMutations.ts
@@ -66,6 +66,11 @@ export const useViewMutations = ({
showErrorToast(
"Failed to copy permalink",
"Could not write to the clipboard. Please copy the link manually.",
+ {
+ operation: "saved_view.permalink_copy",
+ errorOrigin: "frontend",
+ errorCategory: "permission",
+ },
"WARNING",
),
);
diff --git a/web/src/components/ui/sonner.tsx b/web/src/components/ui/sonner.tsx
index b908f21106..3e38d34bf7 100644
--- a/web/src/components/ui/sonner.tsx
+++ b/web/src/components/ui/sonner.tsx
@@ -1,6 +1,7 @@
"use client";
import { Toaster as Sonner } from "sonner";
+import { cn } from "@/src/utils/tailwind";
type ToasterProps = React.ComponentProps<typeof Sonner>;
@@ -8,7 +9,6 @@ const Toaster = ({ ...props }: ToasterProps) => {
return (
<Sonner
theme="light"
- className="toaster group"
position="top-right"
toastOptions={{
classNames: {
@@ -22,6 +22,7 @@ const Toaster = ({ ...props }: ToasterProps) => {
},
}}
{...props}
+ className={cn("toaster group ph-no-capture", props.className)}
/>
);
};
diff --git a/web/src/ee/features/billing/components/BillingDiscountCodeButton.tsx b/web/src/ee/features/billing/components/BillingDiscountCodeButton.tsx
index 0fdcaf364e..1c58027008 100644
--- a/web/src/ee/features/billing/components/BillingDiscountCodeButton.tsx
+++ b/web/src/ee/features/billing/components/BillingDiscountCodeButton.tsx
@@ -13,8 +13,8 @@ import {
} from "@/src/components/ui/dialog";
import { Input } from "@/src/components/ui/input";
import { api } from "@/src/utils/api";
-import { showSuccessToast } from "@/src/features/notifications";
-import { toast } from "sonner";
+import { showSuccessToast, showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { nanoid } from "nanoid";
export const BillingDiscountCodeButton = ({ orgId }: { orgId: string }) => {
@@ -43,7 +43,19 @@ export const BillingDiscountCodeButton = ({ orgId }: { orgId: string }) => {
},
onError: (err) => {
setProcessing(false);
- toast.error(err.message || "Failed to apply promotion code");
+ const analytics = classifyTrpcToastError(err, "billing_discount.apply");
+ showToast({
+ type: "ERROR",
+ title: err.message || "Failed to apply promotion code",
+ analytics:
+ analytics.trpcCode === "BAD_REQUEST"
+ ? {
+ ...analytics,
+ errorOrigin: "backend",
+ errorCategory: "user_input",
+ }
+ : analytics,
+ });
},
});
diff --git a/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx b/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx
index bb365cdc2d..177037ad9c 100644
--- a/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx
+++ b/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx
@@ -14,7 +14,8 @@ import {
DialogTrigger,
DialogBody,
} from "@/src/components/ui/dialog";
-import { toast } from "sonner";
+import { showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
// planLabels used inside StripeSwitchPlanButton
import {
@@ -55,10 +56,14 @@ export const BillingSwitchPlanDialog = ({
setProcessingPlanId(null);
setOpId(null);
},
- onError: () => {
+ onError: (error) => {
setProcessingPlanId(null);
setOpId(null);
- toast.error("Failed to start checkout session");
+ showToast({
+ type: "ERROR",
+ title: "Failed to start checkout session",
+ analytics: classifyTrpcToastError(error, "billing_checkout.start"),
+ });
},
});
diff --git a/web/src/ee/features/billing/components/SpendAlerts/DeleteSpendAlertDialog.tsx b/web/src/ee/features/billing/components/SpendAlerts/DeleteSpendAlertDialog.tsx
index 167acc081c..45d3b364fa 100644
--- a/web/src/ee/features/billing/components/SpendAlerts/DeleteSpendAlertDialog.tsx
+++ b/web/src/ee/features/billing/components/SpendAlerts/DeleteSpendAlertDialog.tsx
@@ -10,8 +10,8 @@ import {
import { Button } from "@/src/components/ui/button";
import { api, reportNonTrpcError } from "@/src/utils/api";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
-import { showSuccessToast } from "@/src/features/notifications";
-import { toast } from "sonner";
+import { showSuccessToast, showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
interface DeleteSpendAlertDialogProps {
orgId: string;
@@ -52,7 +52,11 @@ export function DeleteSpendAlertDialog({
onSuccess();
} catch (error) {
reportNonTrpcError(error, "billing");
- toast.error("Failed to delete spend alert. Please try again.");
+ showToast({
+ type: "ERROR",
+ title: "Failed to delete spend alert. Please try again.",
+ analytics: classifyTrpcToastError(error, "spend_alert.delete"),
+ });
} finally {
setIsDeleting(false);
}
diff --git a/web/src/ee/features/billing/components/SpendAlerts/SpendAlertDialog.tsx b/web/src/ee/features/billing/components/SpendAlerts/SpendAlertDialog.tsx
index df7385ad20..b007f7a2a6 100644
--- a/web/src/ee/features/billing/components/SpendAlerts/SpendAlertDialog.tsx
+++ b/web/src/ee/features/billing/components/SpendAlerts/SpendAlertDialog.tsx
@@ -21,8 +21,8 @@ import { Input } from "@/src/components/ui/input";
import { Button } from "@/src/components/ui/button";
import { api, reportNonTrpcError } from "@/src/utils/api";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
-import { showSuccessToast } from "@/src/features/notifications";
-import { toast } from "sonner";
+import { showSuccessToast, showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { Info } from "lucide-react";
const spendAlertSchema = z.object({
@@ -113,9 +113,14 @@ export function SpendAlertDialog({
onSuccess();
} catch (error) {
reportNonTrpcError(error, "billing");
- toast.error(
- `Failed to ${alert ? "update" : "create"} spend alert. Please try again.`,
- );
+ showToast({
+ type: "ERROR",
+ title: `Failed to ${alert ? "update" : "create"} spend alert. Please try again.`,
+ analytics: classifyTrpcToastError(
+ error,
+ alert ? "spend_alert.update" : "spend_alert.create",
+ ),
+ });
} finally {
setIsSubmitting(false);
}
diff --git a/web/src/ee/features/billing/components/StripeCancellationButton.tsx b/web/src/ee/features/billing/components/StripeCancellationButton.tsx
index 7f145cb425..5052879327 100644
--- a/web/src/ee/features/billing/components/StripeCancellationButton.tsx
+++ b/web/src/ee/features/billing/components/StripeCancellationButton.tsx
@@ -13,8 +13,8 @@ import {
import { useBillingInformation } from "./useBillingInformation";
import { api } from "@/src/utils/api";
import { useState } from "react";
-import { showSuccessToast } from "@/src/features/notifications";
-import { toast } from "sonner";
+import { showSuccessToast, showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { nanoid } from "nanoid";
export const StripeCancellationButton = ({
@@ -41,10 +41,14 @@ export const StripeCancellationButton = ({
setOpId(null);
setTimeout(() => window.location.reload(), 500);
},
- onError: () => {
+ onError: (error) => {
setLoading(false);
setOpId(null);
- toast.error("Failed to cancel subscription");
+ showToast({
+ type: "ERROR",
+ title: "Failed to cancel subscription",
+ analytics: classifyTrpcToastError(error, "subscription.cancel"),
+ });
},
});
@@ -60,10 +64,14 @@ export const StripeCancellationButton = ({
setOpId(null);
setTimeout(() => window.location.reload(), 500);
},
- onError: () => {
+ onError: (error) => {
setLoading(false);
setOpId(null);
- toast.error("Failed to reactivate subscription");
+ showToast({
+ type: "ERROR",
+ title: "Failed to reactivate subscription",
+ analytics: classifyTrpcToastError(error, "subscription.reactivate"),
+ });
},
});
@@ -77,8 +85,12 @@ export const StripeCancellationButton = ({
setOpId(opId);
}
await reactivateMutation.mutateAsync({ orgId, opId });
- } catch (_e) {
- toast.error("Failed to reactivate subscription");
+ } catch (error) {
+ showToast({
+ type: "ERROR",
+ title: "Failed to reactivate subscription",
+ analytics: classifyTrpcToastError(error, "subscription.reactivate"),
+ });
}
};
@@ -92,8 +104,12 @@ export const StripeCancellationButton = ({
setOpId(opId);
}
await cancelMutation.mutateAsync({ orgId, opId });
- } catch (_e) {
- toast.error("Failed to cancel subscription");
+ } catch (error) {
+ showToast({
+ type: "ERROR",
+ title: "Failed to cancel subscription",
+ analytics: classifyTrpcToastError(error, "subscription.cancel"),
+ });
}
};
diff --git a/web/src/ee/features/billing/components/StripeCustomerPortalButton.tsx b/web/src/ee/features/billing/components/StripeCustomerPortalButton.tsx
index 9f22af78bf..5e701aa1fd 100644
--- a/web/src/ee/features/billing/components/StripeCustomerPortalButton.tsx
+++ b/web/src/ee/features/billing/components/StripeCustomerPortalButton.tsx
@@ -1,7 +1,8 @@
import { Button } from "@/src/components/ui/button";
import { api } from "@/src/utils/api";
import { useEffect, useState } from "react";
-import { toast } from "sonner";
+import { showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
export const StripeCustomerPortalButton = ({
orgId,
@@ -52,10 +53,22 @@ export const StripeCustomerPortalButton = ({
if (data) {
window.location.href = data;
} else {
- toast.error("Could not open billing portal");
+ showToast({
+ type: "ERROR",
+ title: "Could not open billing portal",
+ analytics: {
+ operation: "billing_portal.open",
+ errorOrigin: "backend",
+ errorCategory: "product_state",
+ },
+ });
}
- } catch (_e) {
- toast.error("Failed to open billing portal");
+ } catch (error) {
+ showToast({
+ type: "ERROR",
+ title: "Failed to open billing portal",
+ analytics: classifyTrpcToastError(error, "billing_portal.open"),
+ });
} finally {
// do not reset to avoid flickering when opening the portal
// setLoading(false);
diff --git a/web/src/ee/features/billing/components/StripeKeepPlanButton.tsx b/web/src/ee/features/billing/components/StripeKeepPlanButton.tsx
index 3522525c77..90ccb40edb 100644
--- a/web/src/ee/features/billing/components/StripeKeepPlanButton.tsx
+++ b/web/src/ee/features/billing/components/StripeKeepPlanButton.tsx
@@ -12,8 +12,8 @@ import {
DialogTrigger,
} from "@/src/components/ui/dialog";
import { api } from "@/src/utils/api";
-import { showSuccessToast } from "@/src/features/notifications";
-import { toast } from "sonner";
+import { showSuccessToast, showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { nanoid } from "nanoid";
export const StripeKeepPlanButton = ({
@@ -40,10 +40,14 @@ export const StripeKeepPlanButton = ({
setOpId(null);
setTimeout(() => window.location.reload(), 500);
},
- onError: () => {
+ onError: (error) => {
onProcessing(null);
setOpId(null);
- toast.error("Failed to keep current plan");
+ showToast({
+ type: "ERROR",
+ title: "Failed to keep current plan",
+ analytics: classifyTrpcToastError(error, "billing_plan.keep"),
+ });
},
});
diff --git a/web/src/ee/features/billing/components/StripeSwitchPlanButton.tsx b/web/src/ee/features/billing/components/StripeSwitchPlanButton.tsx
index 562d625236..b6a92d5937 100644
--- a/web/src/ee/features/billing/components/StripeSwitchPlanButton.tsx
+++ b/web/src/ee/features/billing/components/StripeSwitchPlanButton.tsx
@@ -15,8 +15,8 @@ import {
import { ActionButton } from "@/src/components/ActionButton";
import { planLabels } from "@langfuse/shared";
import { api } from "@/src/utils/api";
-import { showSuccessToast } from "@/src/features/notifications";
-import { toast } from "sonner";
+import { showSuccessToast, showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { nanoid } from "nanoid";
export const StripeSwitchPlanButton = ({
@@ -52,10 +52,14 @@ export const StripeSwitchPlanButton = ({
setOpId(null);
setTimeout(() => window.location.reload(), 500);
},
- onError: () => {
+ onError: (error) => {
onProcessing(null);
setOpId(null);
- toast.error("Failed to change plan");
+ showToast({
+ type: "ERROR",
+ title: "Failed to change plan",
+ analytics: classifyTrpcToastError(error, "billing_plan.change"),
+ });
},
});
diff --git a/web/src/ee/features/sso-settings/components/DeleteSsoConfigDialogController.tsx b/web/src/ee/features/sso-settings/components/DeleteSsoConfigDialogController.tsx
index d6f89b5f25..e9aedd7f9e 100644
--- a/web/src/ee/features/sso-settings/components/DeleteSsoConfigDialogController.tsx
+++ b/web/src/ee/features/sso-settings/components/DeleteSsoConfigDialogController.tsx
@@ -2,6 +2,7 @@ import { useState } from "react";
import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
export function DeleteSsoConfigDialogController({
orgId,
@@ -25,7 +26,11 @@ export function DeleteSsoConfigDialogController({
});
},
onError: (err) => {
- showErrorToast("Failed to remove SSO", err.message);
+ showErrorToast(
+ "Failed to remove SSO",
+ err.message,
+ classifyTrpcToastError(err, "sso.disable"),
+ );
},
});
diff --git a/web/src/ee/features/sso-settings/components/SsoConfigDialogController.tsx b/web/src/ee/features/sso-settings/components/SsoConfigDialogController.tsx
index f5789fceec..1b83f68474 100644
--- a/web/src/ee/features/sso-settings/components/SsoConfigDialogController.tsx
+++ b/web/src/ee/features/sso-settings/components/SsoConfigDialogController.tsx
@@ -32,6 +32,7 @@ import { useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { useCopyToClipboard } from "@/src/hooks/useCopyToClipboard";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import {
type SsoConfigRow,
type SsoConfigTableRow,
@@ -180,6 +181,7 @@ function SsoConfigDialogContent({
showErrorToast(
existing ? "Update failed" : "SSO configuration failed",
err.message,
+ classifyTrpcToastError(err, existing ? "sso.update" : "sso.configure"),
);
},
});
@@ -220,6 +222,11 @@ function SsoConfigDialogContent({
showErrorToast(
existing ? "Update failed" : "SSO configuration failed",
firstIssue.message,
+ {
+ operation: existing ? "sso.update" : "sso.configure",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
}
return;
diff --git a/web/src/ee/features/verified-domains/components/VerifiedDomainsSettingsTable/ConnectedVerifiedDomainsSettingsTable.tsx b/web/src/ee/features/verified-domains/components/VerifiedDomainsSettingsTable/ConnectedVerifiedDomainsSettingsTable.tsx
index b3bfbcf3ee..2c11947e67 100644
--- a/web/src/ee/features/verified-domains/components/VerifiedDomainsSettingsTable/ConnectedVerifiedDomainsSettingsTable.tsx
+++ b/web/src/ee/features/verified-domains/components/VerifiedDomainsSettingsTable/ConnectedVerifiedDomainsSettingsTable.tsx
@@ -3,6 +3,7 @@ import { ConfirmationDialogController } from "@/src/components/design-system/Con
import { type AsyncTableData } from "@/src/components/design-system/table/Table";
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import {
VerifiedDomainsSettingsTable,
type DomainRowData,
@@ -31,7 +32,12 @@ export function ConnectedVerifiedDomainsSettingsTable({
description: `${domain?.domain ?? "Domain"} is now verified.`,
});
},
- onError: (err) => showErrorToast("Verification failed", err.message),
+ onError: (err) =>
+ showErrorToast(
+ "Verification failed",
+ err.message,
+ classifyTrpcToastError(err, "verified_domain.verify"),
+ ),
onSettled: () => setVerifyingDomainId(null),
});
@@ -45,7 +51,12 @@ export function ConnectedVerifiedDomainsSettingsTable({
description: `${domain?.domain ?? "Domain"} has been removed.`,
});
},
- onError: (err) => showErrorToast("Failed to remove domain", err.message),
+ onError: (err) =>
+ showErrorToast(
+ "Failed to remove domain",
+ err.message,
+ classifyTrpcToastError(err, "verified_domain.remove"),
+ ),
});
const data = useMemo<AsyncTableData<DomainRowData[]>>(() => {
diff --git a/web/src/features/account/AccountSettingsPage.tsx b/web/src/features/account/AccountSettingsPage.tsx
index d65b24f245..5b6c461847 100644
--- a/web/src/features/account/AccountSettingsPage.tsx
+++ b/web/src/features/account/AccountSettingsPage.tsx
@@ -35,6 +35,7 @@ import Link from "next/link";
import { showSuccessToast, showErrorToast } from "@/src/features/notifications";
import { useV4UpgradeUiFlag } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";
import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
const displayNameSchema = z.object({
name: StringNoHTML.min(1, "Name cannot be empty").max(
@@ -163,6 +164,7 @@ function DeleteAccountButton() {
showErrorToast(
"Failed to Delete Account",
error instanceof Error ? error.message : "An unexpected error occurred",
+ classifyTrpcToastError(error, "account.delete"),
);
}
};
@@ -258,6 +260,7 @@ function SignOutAllSessionsButton() {
showErrorToast(
"Failed to Sign Out of All Sessions",
error instanceof Error ? error.message : "An unexpected error occurred",
+ classifyTrpcToastError(error, "account.revoke_sessions"),
);
throw error;
}
diff --git a/web/src/features/annotation-queues/components/AnnotationQueueFormDialogController.tsx b/web/src/features/annotation-queues/components/AnnotationQueueFormDialogController.tsx
index fd2df3a805..4a499ffb5a 100644
--- a/web/src/features/annotation-queues/components/AnnotationQueueFormDialogController.tsx
+++ b/web/src/features/annotation-queues/components/AnnotationQueueFormDialogController.tsx
@@ -12,6 +12,7 @@ import { AnnotationQueueFormDialogContent } from "@/src/features/annotation-queu
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
type AnnotationQueueFormDialogControllerProps = {
projectId: string;
@@ -120,10 +121,11 @@ export function AnnotationQueueFormDialogController(
setCreatedQueueId(undefined);
onSuccess(targetQueueId);
setOpen(false);
- } catch {
+ } catch (error) {
showErrorToast(
"Operation failed",
"Failed to create or update queue or assign users. Please try again.",
+ classifyTrpcToastError(error, "annotation_queue.save"),
);
}
},
diff --git a/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsx b/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsx
index f10bb5db8f..9257d49ef6 100644
--- a/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsx
+++ b/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsx
@@ -149,6 +149,7 @@ function AnnotationQueueRunLoader({
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
+ meta: { toastOperation: "annotation_queue.load" },
});
if (bootstrap.isPending) return <Skeleton className="h-full w-full" />;
if (bootstrap.isError) {
diff --git a/web/src/features/automations/components/automationForm.tsx b/web/src/features/automations/components/automationForm.tsx
index c8edfc8247..ff52c63680 100644
--- a/web/src/features/automations/components/automationForm.tsx
+++ b/web/src/features/automations/components/automationForm.tsx
@@ -535,6 +535,11 @@ export const AutomationForm = ({
showErrorToast(
"Permission Denied",
"You don't have permission to modify automations.",
+ {
+ operation: isEditing ? "automation.update" : "automation.create",
+ errorOrigin: "frontend",
+ errorCategory: "permission",
+ },
);
return;
}
@@ -547,6 +552,11 @@ export const AutomationForm = ({
showErrorToast(
"Validation Error",
validation.errors?.join(", ") || "Please fill in all required fields",
+ {
+ operation: isEditing ? "automation.update" : "automation.create",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
return;
}
diff --git a/web/src/features/background-migrations/components/retry-background-migration.tsx b/web/src/features/background-migrations/components/retry-background-migration.tsx
index 6e14c1310a..2c127b99aa 100644
--- a/web/src/features/background-migrations/components/retry-background-migration.tsx
+++ b/web/src/features/background-migrations/components/retry-background-migration.tsx
@@ -5,8 +5,8 @@ import type * as React from "react";
import { PopoverController } from "@/src/components/ui/popover";
import { Input } from "@/src/components/ui/input";
import { Label } from "@/src/components/ui/label";
-import { showSuccessToast } from "@/src/features/notifications";
-import { toast } from "sonner";
+import { showSuccessToast, showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
type RetryBackgroundMigrationPopoverControllerProps = {
backgroundMigrationName: string;
@@ -34,7 +34,14 @@ export function RetryBackgroundMigrationPopoverController({
});
},
onError: (error) => {
- toast.error(error?.message || "Failed to retry migration");
+ showToast({
+ type: "ERROR",
+ title: error?.message || "Failed to retry migration",
+ analytics: classifyTrpcToastError(
+ error,
+ "background_migration.retry",
+ ),
+ });
},
onSettled: () => {
setIsLoading(false);
@@ -43,7 +50,15 @@ export function RetryBackgroundMigrationPopoverController({
const handleRetry = async (closePopover: () => void) => {
if (!adminApiKey.trim()) {
- toast.error("Admin API key is required");
+ showToast({
+ type: "ERROR",
+ title: "Admin API key is required",
+ analytics: {
+ operation: "background_migration.retry",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
+ });
return;
}
setIsLoading(true);
diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/index.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/index.tsx
index c2ab9aa9ef..7124b0c245 100644
--- a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/index.tsx
+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/index.tsx
@@ -11,6 +11,7 @@ import {
} from "@/src/components/ui/dialog";
import { api, sendAsPostOption } from "@/src/utils/api";
import { showErrorToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { DatasetCreateStep } from "./DatasetCreateStep";
import { DatasetMappingEditor } from "./DatasetMappingEditor";
import { StatusStep } from "./StatusStep";
@@ -94,7 +95,11 @@ export function AddObservationsToDatasetDialog(
const previewQuery = source.isV4 ? eventQuery : observationQuery;
const mutation = api.batchAction.addToDataset.create.useMutation({
onError: (error) =>
- showErrorToast("Failed to schedule action", error.message),
+ showErrorToast(
+ "Failed to schedule action",
+ error.message,
+ classifyTrpcToastError(error, "dataset.add_observations"),
+ ),
});
return (
<Dialog
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
index 5bc92b065c..3b3cf5c245 100644
--- a/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
@@ -23,6 +23,7 @@ import { Button } from "@/src/components/ui/button";
import { Skeleton } from "@/src/components/ui/skeleton";
import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { ChevronLeft, ExternalLink, Plus } from "lucide-react";
import {
EvaluatorSelectionStep,
@@ -126,7 +127,11 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
const runEvaluationMutation =
api.batchAction.runEvaluation.create.useMutation({
onError: (error) => {
- showErrorToast("Failed to schedule evaluation", error.message);
+ showErrorToast(
+ "Failed to schedule evaluation",
+ error.message,
+ classifyTrpcToastError(error, "evaluation.queue"),
+ );
},
});
diff --git a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx
index 259cf2a0f3..718697b429 100644
--- a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx
+++ b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx
@@ -7,6 +7,7 @@ import {
} from "@/src/features/analytics-integrations";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import {
type V4WriteMode,
type BlobStorageIntegration,
@@ -65,7 +66,11 @@ export const BlobStorageIntegrationContainer = ({
utils.blobStorageIntegration.invalidate();
},
onError: (error) => {
- showErrorToast("Failed to save integration", error.message);
+ showErrorToast(
+ "Failed to save integration",
+ error.message,
+ classifyTrpcToastError(error, "blob_storage.save"),
+ );
},
});
const mutDelete = api.blobStorageIntegration.delete.useMutation({
@@ -87,7 +92,11 @@ export const BlobStorageIntegrationContainer = ({
});
},
onError: (error) => {
- showErrorToast("Validation failed", error.message);
+ showErrorToast(
+ "Validation failed",
+ error.message,
+ classifyTrpcToastError(error, "blob_storage.validate"),
+ );
},
});
diff --git a/web/src/features/chart-view/components/AddToDashboardButton.tsx b/web/src/features/chart-view/components/AddToDashboardButton.tsx
index ece9f898a7..b038c127ff 100644
--- a/web/src/features/chart-view/components/AddToDashboardButton.tsx
+++ b/web/src/features/chart-view/components/AddToDashboardButton.tsx
@@ -4,6 +4,7 @@ import { LayoutDashboard } from "lucide-react";
import { Button } from "@/src/components/ui/button";
import { api } from "@/src/utils/api";
import { showErrorToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { SelectDashboardDialog } from "@/src/features/dashboard/components/SelectDashboardDialog";
import { type ChartWidgetInput } from "../lib/chartConfigToWidget";
@@ -48,7 +49,11 @@ export const AddToDashboardButton = React.memo(function AddToDashboardButton({
// Surface failures instead of leaving the dialog open with no feedback;
// keep it open so the user can retry or pick another dashboard.
onError: (error) =>
- showErrorToast("Failed to add chart to dashboard", error.message),
+ showErrorToast(
+ "Failed to add chart to dashboard",
+ error.message,
+ classifyTrpcToastError(error, "dashboard_chart.add"),
+ ),
},
);
},
diff --git a/web/src/features/dashboard/DashboardDetailPage.tsx b/web/src/features/dashboard/DashboardDetailPage.tsx
index cb1169e825..081e1edceb 100644
--- a/web/src/features/dashboard/DashboardDetailPage.tsx
+++ b/web/src/features/dashboard/DashboardDetailPage.tsx
@@ -87,6 +87,7 @@ import {
RouteParamsPendingFallback,
useReadyRouteParams,
} from "@/src/hooks/useReadyRouteParams";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
// Position for a tile inserted "next to" an anchor tile: same size,
// immediately to the right when that fits the 12-column grid, otherwise
@@ -230,7 +231,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
);
},
onError: (error) => {
- showErrorToast("Error updating dashboard", error.message);
+ showErrorToast(
+ "Error updating dashboard",
+ error.message,
+ classifyTrpcToastError(error, "dashboard.update"),
+ );
},
});
@@ -248,7 +253,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
utils.dashboard.getHomeDashboard.invalidate();
},
onError: (error) => {
- showErrorToast("Failed to update home dashboard", error.message);
+ showErrorToast(
+ "Failed to update home dashboard",
+ error.message,
+ classifyTrpcToastError(error, "dashboard_home.update"),
+ );
},
});
@@ -259,7 +268,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
utils.dashboard.invalidate();
},
onError: (error) => {
- showErrorToast("Error renaming dashboard", error.message);
+ showErrorToast(
+ "Error renaming dashboard",
+ error.message,
+ classifyTrpcToastError(error, "dashboard.update"),
+ );
},
});
@@ -271,7 +284,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
setSavedFilters(currentFilters);
},
onError: (error) => {
- showErrorToast("Error saving filters", error.message);
+ showErrorToast(
+ "Error saving filters",
+ error.message,
+ classifyTrpcToastError(error, "dashboard_filters.update"),
+ );
},
});
@@ -482,6 +499,7 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
showErrorToast(
"Failed to duplicate widget",
e instanceof Error ? e.message : "Unknown error",
+ classifyTrpcToastError(e, "widget.clone"),
);
}
},
@@ -502,7 +520,16 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
reason: "invalid",
dashboard_id: dashboardId,
});
- showErrorToast("Cannot paste widget", parsed.reason, "WARNING");
+ showErrorToast(
+ "Cannot paste widget",
+ parsed.reason,
+ {
+ operation: "widget.paste",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
+ "WARNING",
+ );
return;
}
// Don't create a widget row the placement step couldn't attach — a
@@ -529,6 +556,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
showErrorToast(
"Widget filters were adjusted",
"Some pasted filters were removed because they are not available in this view.",
+ {
+ operation: "widget.paste",
+ errorOrigin: "frontend",
+ errorCategory: "product_state",
+ },
"WARNING",
);
}
@@ -536,6 +568,7 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
showErrorToast(
"Failed to paste widget",
e instanceof Error ? e.message : "Unknown error",
+ classifyTrpcToastError(e, "widget.paste"),
);
}
},
@@ -558,6 +591,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
showErrorToast(
"Clipboard unavailable",
"Your browser did not allow reading the clipboard. Paste with Cmd/Ctrl+V on the dashboard instead.",
+ {
+ operation: "widget.paste",
+ errorOrigin: "frontend",
+ errorCategory: "permission",
+ },
"WARNING",
);
return;
@@ -575,7 +613,16 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
reason: "invalid",
dashboard_id: dashboardId,
});
- showErrorToast("Cannot paste card", preset.reason, "WARNING");
+ showErrorToast(
+ "Cannot paste card",
+ preset.reason,
+ {
+ operation: "dashboard_card.paste",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
+ "WARNING",
+ );
return;
}
capture("dashboard:widget_paste_rejected", {
@@ -586,6 +633,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
showErrorToast(
"No widget in clipboard",
"The clipboard does not contain a Langfuse widget JSON. Copy one via a widget's ⋯ menu first.",
+ {
+ operation: "widget.paste",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
"WARNING",
);
return;
@@ -625,7 +677,16 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
reason: "invalid",
dashboard_id: dashboardId,
});
- showErrorToast("Cannot paste card", preset.reason, "WARNING");
+ showErrorToast(
+ "Cannot paste card",
+ preset.reason,
+ {
+ operation: "dashboard_card.paste",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
+ "WARNING",
+ );
return;
}
handlePastedPreset(preset.presetId, "cmd_v");
@@ -695,6 +756,7 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
firstError instanceof Error
? firstError.message
: "Could not create the dashboard's widgets.",
+ classifyTrpcToastError(firstError, "dashboard.import"),
);
return;
}
@@ -758,6 +820,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
showErrorToast(
"Widget filters were adjusted",
"Some imported filters were removed because they are not available in this view.",
+ {
+ operation: "dashboard.import",
+ errorOrigin: "frontend",
+ errorCategory: "product_state",
+ },
"WARNING",
);
}
@@ -765,6 +832,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
showErrorToast(
"Some cards were skipped",
`${imported.skippedPresetCount} preset card(s) in the file are not available in this Langfuse version.`,
+ {
+ operation: "dashboard.import",
+ errorOrigin: "frontend",
+ errorCategory: "product_state",
+ },
"WARNING",
);
}
@@ -772,6 +844,7 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
showErrorToast(
"Failed to import dashboard",
e instanceof Error ? e.message : "Unknown error",
+ classifyTrpcToastError(e, "dashboard.import"),
);
}
},
@@ -805,6 +878,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
showErrorToast(
"Cannot import dashboard",
dashboardResult.reason,
+ {
+ operation: "dashboard.import",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
"WARNING",
);
return;
@@ -823,7 +901,16 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
reason: "invalid",
dashboard_id: dashboardId,
});
- showErrorToast("Cannot import card", preset.reason, "WARNING");
+ showErrorToast(
+ "Cannot import card",
+ preset.reason,
+ {
+ operation: "dashboard_card.import",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
+ "WARNING",
+ );
return;
}
capture("dashboard:widget_paste_rejected", {
@@ -834,6 +921,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
showErrorToast(
"Unsupported file",
"Only Langfuse dashboard or widget JSON files can be dropped here.",
+ {
+ operation: "dashboard.import",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
"WARNING",
);
return;
@@ -1056,7 +1148,11 @@ function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
}
},
onError: (e) => {
- showErrorToast("Failed to clone dashboard", e.message);
+ showErrorToast(
+ "Failed to clone dashboard",
+ e.message,
+ classifyTrpcToastError(e, "dashboard.clone"),
+ );
},
});
diff --git a/web/src/features/dashboard/NewDashboardPage.tsx b/web/src/features/dashboard/NewDashboardPage.tsx
index 0438c1cd58..f6dcb6a224 100644
--- a/web/src/features/dashboard/NewDashboardPage.tsx
+++ b/web/src/features/dashboard/NewDashboardPage.tsx
@@ -8,6 +8,7 @@ import { Textarea } from "@/src/components/ui/textarea";
import { Label } from "@/src/components/ui/label";
import { showSuccessToast, showErrorToast } from "@/src/features/notifications";
import { useHasProjectAccess } from "@/src/features/rbac";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
export default function NewDashboardPage() {
const router = useRouter();
@@ -35,7 +36,11 @@ export default function NewDashboardPage() {
router.push(`/project/${projectId}/dashboards/${data.id}`);
},
onError: (error) => {
- showErrorToast("Error creating dashboard", error.message);
+ showErrorToast(
+ "Error creating dashboard",
+ error.message,
+ classifyTrpcToastError(error, "dashboard.create"),
+ );
},
});
@@ -48,7 +53,11 @@ export default function NewDashboardPage() {
description: dashboardDescription,
});
} else {
- showErrorToast("Validation error", "Dashboard name is required");
+ showErrorToast("Validation error", "Dashboard name is required", {
+ operation: "dashboard.create",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ });
}
};
diff --git a/web/src/features/dashboard/ProjectHomePage.tsx b/web/src/features/dashboard/ProjectHomePage.tsx
index 3a4ed2641b..f861c6bc75 100644
--- a/web/src/features/dashboard/ProjectHomePage.tsx
+++ b/web/src/features/dashboard/ProjectHomePage.tsx
@@ -43,6 +43,7 @@ import {
import Link from "next/link";
import { LockIcon, PencilIcon } from "lucide-react";
import { showErrorToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { useHasProjectAccess } from "@/src/features/rbac";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { Button } from "@/src/components/ui/button";
@@ -237,7 +238,11 @@ function HomeDashboard({ readPath }: { readPath: ResolvedReadPath }) {
setPeekId(null);
},
onError: (e) => {
- showErrorToast("Failed to set the default Home dashboard", e.message);
+ showErrorToast(
+ "Failed to set the default Home dashboard",
+ e.message,
+ classifyTrpcToastError(e, "dashboard_home.update"),
+ );
},
});
diff --git a/web/src/features/dashboard/components/CloneFirstDialogController.tsx b/web/src/features/dashboard/components/CloneFirstDialogController.tsx
index ad640ee0ce..12d8d7e8cb 100644
--- a/web/src/features/dashboard/components/CloneFirstDialogController.tsx
+++ b/web/src/features/dashboard/components/CloneFirstDialogController.tsx
@@ -13,6 +13,7 @@ import { Button } from "@/src/components/ui/button";
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import type { DashboardPlacement } from "@/src/features/widgets";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
/**
* Clone-first flow for Langfuse-managed (read-only) dashboards: any edit
@@ -148,7 +149,11 @@ function CloneFirstDialogContent({
},
onError: (e) => {
onPendingChange(false);
- showErrorToast("Failed to create copy", e.message);
+ showErrorToast(
+ "Failed to create copy",
+ e.message,
+ classifyTrpcToastError(e, "dashboard.clone"),
+ );
},
});
diff --git a/web/src/features/dashboard/components/DashboardTable/ConnectedDashboardTable.tsx b/web/src/features/dashboard/components/DashboardTable/ConnectedDashboardTable.tsx
index 592a55b820..e2c2ab047e 100644
--- a/web/src/features/dashboard/components/DashboardTable/ConnectedDashboardTable.tsx
+++ b/web/src/features/dashboard/components/DashboardTable/ConnectedDashboardTable.tsx
@@ -17,6 +17,7 @@ import { PaginationBar } from "@/src/components/design-system/PaginationBar/Pagi
import { type AsyncTableData } from "@/src/components/design-system/table/Table";
import { assertUnreachable } from "@/src/utils/types";
import { DashboardTable, type DashboardTableRow } from "./DashboardTable";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
export function ConnectedDashboardTable() {
const projectId = useProjectIdFromURL() as string;
@@ -37,7 +38,11 @@ export function ConnectedDashboardTable() {
});
},
onError: (error) => {
- showErrorToast("Failed to clone dashboard", error.message);
+ showErrorToast(
+ "Failed to clone dashboard",
+ error.message,
+ classifyTrpcToastError(error, "dashboard.clone"),
+ );
},
});
const deleteDashboard = api.dashboard.delete.useMutation({
@@ -51,7 +56,11 @@ export function ConnectedDashboardTable() {
utils.dashboard.invalidate();
},
onError: (error) => {
- showErrorToast("Failed to delete dashboard", error.message);
+ showErrorToast(
+ "Failed to delete dashboard",
+ error.message,
+ classifyTrpcToastError(error, "dashboard.delete"),
+ );
},
});
diff --git a/web/src/features/dashboard/components/EditDialogDashboardContent.tsx b/web/src/features/dashboard/components/EditDialogDashboardContent.tsx
index df90cd5077..a9c614999d 100644
--- a/web/src/features/dashboard/components/EditDialogDashboardContent.tsx
+++ b/web/src/features/dashboard/components/EditDialogDashboardContent.tsx
@@ -11,6 +11,7 @@ import { Input } from "@/src/components/ui/input";
import { Label } from "@/src/components/ui/label";
import { Textarea } from "@/src/components/ui/textarea";
import { showErrorToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
interface EditDialogDashboardContentProps {
closeDialog: () => void;
@@ -37,13 +38,21 @@ export function EditDialogDashboardContent({
closeDialog();
},
onError: (e) => {
- showErrorToast("Failed to update dashboard", e.message);
+ showErrorToast(
+ "Failed to update dashboard",
+ e.message,
+ classifyTrpcToastError(e, "dashboard.update"),
+ );
},
});
const handleSave = () => {
if (!name.trim()) {
- showErrorToast("Validation error", "Dashboard name is required");
+ showErrorToast("Validation error", "Dashboard name is required", {
+ operation: "dashboard.update",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ });
return;
}
diff --git a/web/src/features/dashboard/hooks/useDashboardQueryScheduler.tsx b/web/src/features/dashboard/hooks/useDashboardQueryScheduler.tsx
index f49f09e402..ca5ee5131f 100644
--- a/web/src/features/dashboard/hooks/useDashboardQueryScheduler.tsx
+++ b/web/src/features/dashboard/hooks/useDashboardQueryScheduler.tsx
@@ -361,7 +361,7 @@ export const useScheduledDashboardExecuteQuery = (
refetchOnReconnect: queryOptions.refetchOnReconnect ?? false,
refetchOnMount: queryOptions.refetchOnMount ?? false,
enabled: enabled && canFetch && !useSSE,
- meta,
+ meta: { ...meta, toastOperation: "dashboard.query" },
});
// SSE path (opt-in) — same cache key as the tRPC path, so identical widgets
diff --git a/web/src/features/datasets/components/NewDatasetItemForm.tsx b/web/src/features/datasets/components/NewDatasetItemForm.tsx
index d4605b9e83..9a056c0eb6 100644
--- a/web/src/features/datasets/components/NewDatasetItemForm.tsx
+++ b/web/src/features/datasets/components/NewDatasetItemForm.tsx
@@ -189,6 +189,7 @@ export function NewDatasetItemForm(props: NewDatasetItemFormProps) {
enabled: datasets.data !== undefined,
staleTime: Infinity,
gcTime: 0,
+ meta: { toastOperation: "dataset_item.prepare" },
});
if (datasets.isError && !datasets.data) {
@@ -283,6 +284,11 @@ function InitializedNewDatasetItemForm({
showErrorToast(
"Select a dataset first",
"Choose a dataset before attaching media.",
+ {
+ operation: "dataset_item_media.upload",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
return null;
}
diff --git a/web/src/features/datasets/components/UploadDatasetCsv.tsx b/web/src/features/datasets/components/UploadDatasetCsv.tsx
index ff0e23a6b8..d1bc8c21d0 100644
--- a/web/src/features/datasets/components/UploadDatasetCsv.tsx
+++ b/web/src/features/datasets/components/UploadDatasetCsv.tsx
@@ -33,12 +33,20 @@ export const UploadDatasetCsv = ({
const result = FileSchema.safeParse(file);
if (!result.success) {
- showErrorToast("Invalid file type", "Please select a valid CSV file");
+ showErrorToast("Invalid file type", "Please select a valid CSV file", {
+ operation: "dataset_items.import",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ });
return;
}
if (file.size > MAX_FILE_SIZE_BYTES) {
- showErrorToast("File too large", "Maximum file size is 10MB");
+ showErrorToast("File too large", "Maximum file size is 10MB", {
+ operation: "dataset_items.import",
+ errorOrigin: "frontend",
+ errorCategory: "resource_limit",
+ });
return;
}
@@ -50,7 +58,11 @@ export const UploadDatasetCsv = ({
});
if (!Boolean(preview.columns.length)) {
- showErrorToast("Invalid CSV", "CSV must have at least 1 column");
+ showErrorToast("Invalid CSV", "CSV must have at least 1 column", {
+ operation: "dataset_items.import",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ });
return;
}
@@ -59,6 +71,11 @@ export const UploadDatasetCsv = ({
showErrorToast(
"Failed to parse CSV",
error instanceof Error ? error.message : "Unknown error",
+ {
+ operation: "dataset_items.import",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
}
};
diff --git a/web/src/features/datasets/contexts/ActiveCellContext.tsx b/web/src/features/datasets/contexts/ActiveCellContext.tsx
index 467701989f..909d493c4b 100644
--- a/web/src/features/datasets/contexts/ActiveCellContext.tsx
+++ b/web/src/features/datasets/contexts/ActiveCellContext.tsx
@@ -1,8 +1,8 @@
import { type ScoreAggregate } from "@langfuse/shared";
import { createContext, useContext, useState, type ReactNode } from "react";
-import { toast } from "sonner";
import { useStore } from "zustand";
import { createStore } from "zustand/vanilla";
+import { showToast } from "@/src/features/notifications";
type ActiveCell = {
datasetRunId: string;
@@ -38,7 +38,15 @@ function createActiveCellStore() {
const { activeCell, hasCommentDraft } = get();
const sameTarget = isSameTarget(activeCell, cell);
if (!sameTarget && hasCommentDraft) {
- toast.error("Please save or discard your comment before proceeding");
+ showToast({
+ type: "ERROR",
+ title: "Please save or discard your comment before proceeding",
+ analytics: {
+ operation: "dataset_annotation.navigate",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
+ });
return false;
}
set({
diff --git a/web/src/features/datasets/hooks/useCsvImport.ts b/web/src/features/datasets/hooks/useCsvImport.ts
index 2c777c519a..b3cad4fa8e 100644
--- a/web/src/features/datasets/hooks/useCsvImport.ts
+++ b/web/src/features/datasets/hooks/useCsvImport.ts
@@ -1,6 +1,7 @@
import { useState } from "react";
import { type RouterInputs, api } from "@/src/utils/api";
import { showErrorToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { MAX_FILE_SIZE_BYTES } from "@/src/features/datasets/components/UploadDatasetCsv";
import { type BulkDatasetItemValidationError } from "@langfuse/shared";
import chunk from "lodash/chunk";
@@ -85,7 +86,11 @@ export function useCsvImport(options: UseCsvImportOptions) {
if (!csvFile) return false;
if (csvFile.size > MAX_FILE_SIZE_BYTES) {
- showErrorToast("File too large", "Maximum file size is 10MB");
+ showErrorToast("File too large", "Maximum file size is 10MB", {
+ operation: "dataset_items.import",
+ errorOrigin: "frontend",
+ errorCategory: "resource_limit",
+ });
return false;
}
@@ -128,6 +133,7 @@ export function useCsvImport(options: UseCsvImportOptions) {
const metadataColumns = metadata.map((c) => c.name);
+ let hasStartedUpload = false;
try {
await parseCsvClient(csvFile, {
processor: {
@@ -202,6 +208,7 @@ export function useCsvImport(options: UseCsvImportOptions) {
const chunks = chunk(items, optimalChunkSize);
for (const [index, chunkItems] of chunks.entries()) {
+ hasStartedUpload = true;
const result = await mutCreateManyDatasetItems.mutateAsync({
projectId,
items: chunkItems,
@@ -241,11 +248,22 @@ export function useCsvImport(options: UseCsvImportOptions) {
status: "not-started",
});
if (error instanceof Error && processedCount === 0) {
- showErrorToast("Failed to import all dataset items", error.message);
+ showErrorToast(
+ "Failed to import all dataset items",
+ error.message,
+ hasStartedUpload
+ ? classifyTrpcToastError(error, "dataset_items.import")
+ : {
+ operation: "dataset_items.import",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
+ );
} else {
showErrorToast(
"Failed to import all dataset items",
`Please try again starting from row ${processedCount + 1}.`,
+ classifyTrpcToastError(error, "dataset_items.import"),
);
}
return false;
diff --git a/web/src/features/datasets/hooks/useDatasetItemMediaUpload.ts b/web/src/features/datasets/hooks/useDatasetItemMediaUpload.ts
index e11c8b8aa0..41f4fb031d 100644
--- a/web/src/features/datasets/hooks/useDatasetItemMediaUpload.ts
+++ b/web/src/features/datasets/hooks/useDatasetItemMediaUpload.ts
@@ -2,8 +2,10 @@ import { Sha256 } from "@aws-crypto/sha256-browser";
import { useCallback, useState } from "react";
import { showErrorToast } from "@/src/features/notifications";
+import type { ToastErrorAnalytics } from "@/src/features/notifications/toastAnalytics";
import { MediaContentType } from "@/src/features/media";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { safeRandomUUID } from "@/src/utils/safe-random-uuid";
import { type DatasetItemMediaField } from "@langfuse/shared";
@@ -74,6 +76,11 @@ export function useDatasetItemMediaUpload({
showErrorToast(
"Unsupported file type",
`${file.type || "Unknown type"} is not supported for media uploads.`,
+ {
+ operation: "dataset_item_media.upload",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
return null;
}
@@ -82,6 +89,11 @@ export function useDatasetItemMediaUpload({
showErrorToast(
"File too large",
`Maximum file size is ${MAX_BROWSER_MEDIA_UPLOAD_SIZE_MB}MB`,
+ {
+ operation: "dataset_item_media.upload",
+ errorOrigin: "frontend",
+ errorCategory: "resource_limit",
+ },
);
return null;
}
@@ -92,10 +104,12 @@ export function useDatasetItemMediaUpload({
{ id: pendingId, fileName: file.name },
]);
+ let failurePhase: MediaUploadFailurePhase = "frontend";
try {
const buffer = await file.arrayBuffer();
const sha256Hash = await sha256Base64(buffer);
+ failurePhase = "trpc";
const { mediaId, uploadUrl, uploadHeaders } =
await getUploadUrl.mutateAsync({
projectId,
@@ -109,6 +123,7 @@ export function useDatasetItemMediaUpload({
// uploadUrl is null when the content already exists (dedupe by hash)
if (uploadUrl) {
+ failurePhase = "network";
const uploadStart = Date.now();
const headers = new Headers({ "Content-Type": file.type });
Object.entries(uploadHeaders).forEach(([key, value]) => {
@@ -121,6 +136,7 @@ export function useDatasetItemMediaUpload({
headers,
});
+ failurePhase = "trpc";
await markUploadComplete.mutateAsync({
projectId,
mediaId,
@@ -131,6 +147,7 @@ export function useDatasetItemMediaUpload({
});
if (!response.ok) {
+ failurePhase = "network";
throw new Error(`Upload failed with status ${response.status}`);
}
}
@@ -140,6 +157,7 @@ export function useDatasetItemMediaUpload({
showErrorToast(
"Media upload failed",
error instanceof Error ? error.message : "Please try again.",
+ getMediaUploadFailureAnalytics(failurePhase, error),
);
return null;
} finally {
@@ -151,3 +169,27 @@ export function useDatasetItemMediaUpload({
return { uploadFile, pendingUploads, resetPendingUploads };
}
+
+function getMediaUploadFailureAnalytics(
+ phase: MediaUploadFailurePhase,
+ error: unknown,
+): ToastErrorAnalytics {
+ switch (phase) {
+ case "trpc":
+ return classifyTrpcToastError(error, "dataset_item_media.upload");
+ case "network":
+ return {
+ operation: "dataset_item_media.upload",
+ errorOrigin: "network",
+ errorCategory: "transient",
+ };
+ case "frontend":
+ return {
+ operation: "dataset_item_media.upload",
+ errorOrigin: "frontend",
+ errorCategory: "internal",
+ };
+ }
+}
+
+type MediaUploadFailurePhase = "frontend" | "trpc" | "network";
diff --git a/web/src/features/datasets/utils/datasetItemUtils.ts b/web/src/features/datasets/utils/datasetItemUtils.ts
index 048a2f3e78..0ca01b9b8d 100644
--- a/web/src/features/datasets/utils/datasetItemUtils.ts
+++ b/web/src/features/datasets/utils/datasetItemUtils.ts
@@ -14,6 +14,11 @@ export const stringifyDatasetItemData = (data: unknown): string => {
showErrorToast(
"Failed to stringify data",
"We are working on fixing this issue.",
+ {
+ operation: "dataset_item.stringify",
+ errorOrigin: "frontend",
+ errorCategory: "internal",
+ },
);
return "";
}
diff --git a/web/src/features/evals/components/code-eval-template-form-body.clienttest.tsx b/web/src/features/evals/components/code-eval-template-form-body.clienttest.tsx
index 3394fb860d..c4c1a44d08 100644
--- a/web/src/features/evals/components/code-eval-template-form-body.clienttest.tsx
+++ b/web/src/features/evals/components/code-eval-template-form-body.clienttest.tsx
@@ -149,6 +149,11 @@ describe("CodeEvalTemplateFormBody", () => {
expect(mocks.showErrorToast).toHaveBeenCalledWith(
"Formatting failed",
"Invalid syntax",
+ {
+ operation: "evaluator_code.format",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
});
});
diff --git a/web/src/features/evals/components/code-eval-template-form-body.tsx b/web/src/features/evals/components/code-eval-template-form-body.tsx
index d28fdcdf8c..073f9efba0 100644
--- a/web/src/features/evals/components/code-eval-template-form-body.tsx
+++ b/web/src/features/evals/components/code-eval-template-form-body.tsx
@@ -321,6 +321,11 @@ export function CodeEvalTemplateFormBody({
error instanceof Error
? error.message
: "The formatter could not process this code.",
+ {
+ operation: "evaluator_code.format",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
} finally {
isFormattingRef.current = false;
diff --git a/web/src/features/evals/components/code-eval-test-run-card.tsx b/web/src/features/evals/components/code-eval-test-run-card.tsx
index 0e21e6bdef..8109449cfa 100644
--- a/web/src/features/evals/components/code-eval-test-run-card.tsx
+++ b/web/src/features/evals/components/code-eval-test-run-card.tsx
@@ -23,7 +23,7 @@ import {
import { ExternalLink, ListTree, Play, RotateCcw } from "lucide-react";
import Link from "next/link";
import { useMemo } from "react";
-import { toast } from "sonner";
+import { showToast } from "@/src/features/notifications";
import { type EvalFormType } from "@/src/features/evals/utils/evaluator-form-utils";
@@ -96,7 +96,15 @@ export function CodeEvalTestRunCard({
return;
}
- toast.error(result.error.message);
+ showToast({
+ type: "ERROR",
+ title: result.error.message,
+ analytics: {
+ operation: "evaluator.test",
+ errorOrigin: "backend",
+ errorCategory: getCodeEvalErrorCategory(result.error.code),
+ },
+ });
},
});
@@ -337,3 +345,31 @@ function toUserFacingCodeEvalScore(
return userFacingScore;
}
+
+function getCodeEvalErrorCategory(
+ code: string,
+): "resource_limit" | "rate_limit" | "user_input" | "internal" {
+ if (
+ [
+ "PAYLOAD_TOO_LARGE",
+ "RESULT_TOO_LARGE",
+ "SOURCE_TOO_LARGE",
+ "TIMEOUT",
+ "OUT_OF_MEMORY",
+ ].includes(code)
+ ) {
+ return "resource_limit";
+ }
+ if (code === "LAMBDA_CONCURRENCY_LIMIT") return "rate_limit";
+ if (
+ [
+ "INVALID_RESULT",
+ "INVALID_SOURCE",
+ "UNSUPPORTED_RUNTIME",
+ "USER_CODE_ERROR",
+ ].includes(code)
+ ) {
+ return "user_input";
+ }
+ return "internal";
+}
diff --git a/web/src/features/evals/components/default-eval-model-setup.tsx b/web/src/features/evals/components/default-eval-model-setup.tsx
index ee78b64e5f..a9a9b6b2d0 100644
--- a/web/src/features/evals/components/default-eval-model-setup.tsx
+++ b/web/src/features/evals/components/default-eval-model-setup.tsx
@@ -6,6 +6,7 @@ import { useModelParams } from "@/src/features/playground";
import { Button } from "@/src/components/ui/button";
import { api } from "@/src/utils/api";
import { showSuccessToast } from "@/src/features/notifications";
+import type { ToastOperation } from "@/src/features/notifications/toastAnalytics";
import { Skeleton } from "@/src/components/ui/skeleton";
import { useEvaluationModel } from "@/src/features/evals/hooks/useEvaluationModel";
import { DeleteEvaluationModelButton } from "@/src/components/deleteButton";
@@ -22,7 +23,7 @@ import { Pencil } from "lucide-react";
import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";
type DefaultEvalModelSuccessMessage = {
- operation: string;
+ operation: ToastOperation;
title: string;
description: string;
};
diff --git a/web/src/features/evals/components/delete-eval-template-dialog.tsx b/web/src/features/evals/components/delete-eval-template-dialog.tsx
index 63ce9a9cf1..478cfd760d 100644
--- a/web/src/features/evals/components/delete-eval-template-dialog.tsx
+++ b/web/src/features/evals/components/delete-eval-template-dialog.tsx
@@ -8,6 +8,7 @@ import { Input } from "@/src/components/ui/input";
import { Label } from "@/src/components/ui/label";
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
type ReferencingEvaluator = {
id: string;
@@ -72,7 +73,11 @@ export function DeleteEvalTemplateDialog({
utils.evals.invalidate();
},
onError: (error) =>
- showErrorToast("Failed to delete evaluator", error.message),
+ showErrorToast(
+ "Failed to delete evaluator",
+ error.message,
+ classifyTrpcToastError(error, "evaluator.delete"),
+ ),
});
// Once deletion starts, the usage query must go inactive so post-delete
diff --git a/web/src/features/evals/components/evaluator-paused-callout.tsx b/web/src/features/evals/components/evaluator-paused-callout.tsx
index 9285625986..5b7267e310 100644
--- a/web/src/features/evals/components/evaluator-paused-callout.tsx
+++ b/web/src/features/evals/components/evaluator-paused-callout.tsx
@@ -1,6 +1,7 @@
import { Button } from "@/src/components/ui/button";
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { formatDistanceToNow } from "date-fns";
import {
type EvalTemplate,
@@ -65,7 +66,11 @@ export function EvaluatorPausedCallout({
});
},
onError: (error) => {
- showErrorToast("Reactivation failed", error.message);
+ showErrorToast(
+ "Reactivation failed",
+ error.message,
+ classifyTrpcToastError(error, "evaluator.reactivate"),
+ );
},
});
diff --git a/web/src/features/evals/hooks/useExtractVariables.ts b/web/src/features/evals/hooks/useExtractVariables.ts
index 2cab17edeb..3ed9a7ba37 100644
--- a/web/src/features/evals/hooks/useExtractVariables.ts
+++ b/web/src/features/evals/hooks/useExtractVariables.ts
@@ -79,7 +79,17 @@ export function useExtractVariables({
extractionError.kind === "jsonPath"
? "Invalid JSONPath in variable mapping"
: "Failed to extract variable";
- showErrorToast(title, extractionError.message, "WARNING");
+ showErrorToast(
+ title,
+ extractionError.message,
+ {
+ operation: "evaluator_variable.extract",
+ errorOrigin: "frontend",
+ errorCategory:
+ extractionError.kind === "jsonPath" ? "user_input" : "internal",
+ },
+ "WARNING",
+ );
}, [extractionError]);
useEffect(() => {
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorSavedDialogContainer/EvaluatorSavedDialogContainer.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorSavedDialogContainer/EvaluatorSavedDialogContainer.tsx
index 9cce3c1a9d..70b08249e9 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorSavedDialogContainer/EvaluatorSavedDialogContainer.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorSavedDialogContainer/EvaluatorSavedDialogContainer.tsx
@@ -141,11 +141,11 @@ export function EvaluatorSavedDialogContainer({
(rule) => rule.id === selectedRuleId,
);
const attach = api.evalsV2.rules.attach.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.attach"),
});
const createOrAttachFromEvaluatorFilters =
api.evalsV2.rules.createOrAttachFromEvaluatorFilters.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.create"),
});
const finish = async () => {
@@ -635,14 +635,18 @@ export function EvaluatorSavedDialogContainer({
});
createRuleHandoffPending.current = false;
setDialogPhase("closed");
- onDismiss().catch(trpcErrorToast);
+ onDismiss().catch((error) =>
+ trpcErrorToast(error, "evaluator_saved_dialog.dismiss"),
+ );
}}
onSecondaryAction={() => {
onboardingAnalytics?.track("eval:onboarding_execution_skipped", {
method: "skip_button",
});
setDialogPhase("closed");
- finish().catch(trpcErrorToast);
+ finish().catch((error) =>
+ trpcErrorToast(error, "evaluator_saved_dialog.finish"),
+ );
}}
onPrimaryAction={handlePrimaryAction}
onCloseAnimationEnd={completeCreateRuleHandoff}
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorSavedDialogContainer/hooks/useEvaluatorSavedBackfill.ts b/web/src/features/evals/v2/components/Evaluators/EvaluatorSavedDialogContainer/hooks/useEvaluatorSavedBackfill.ts
index 3d1a705540..73c3807864 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorSavedDialogContainer/hooks/useEvaluatorSavedBackfill.ts
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorSavedDialogContainer/hooks/useEvaluatorSavedBackfill.ts
@@ -78,7 +78,7 @@ export function useEvaluatorSavedBackfill({
}) {
const utils = api.useUtils();
const runEvaluation = api.batchAction.runEvaluation.create.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_backfill.run"),
});
const [enabled, setEnabledState] = useState(false);
const [window, setWindow] = useState<EvaluatorBackfillWindow>("7-days");
@@ -124,7 +124,7 @@ export function useEvaluatorSavedBackfill({
if (estimateRequestId.current === requestId) {
setMatchingObservations(0);
setTestRunCostUsd(null);
- trpcErrorToast(error);
+ trpcErrorToast(error, "evaluator_backfill.estimate");
}
} finally {
if (estimateRequestId.current === requestId) {
diff --git a/web/src/features/evals/v2/components/Rules/CreateRuleDialog/components/CreateRuleDialogContent/CreateRuleDialogContent.tsx b/web/src/features/evals/v2/components/Rules/CreateRuleDialog/components/CreateRuleDialogContent/CreateRuleDialogContent.tsx
index 80bad0b293..2fa0f9b14e 100644
--- a/web/src/features/evals/v2/components/Rules/CreateRuleDialog/components/CreateRuleDialogContent/CreateRuleDialogContent.tsx
+++ b/web/src/features/evals/v2/components/Rules/CreateRuleDialog/components/CreateRuleDialogContent/CreateRuleDialogContent.tsx
@@ -81,7 +81,7 @@ export function CreateRuleDialogContent({
);
const hasRequestedName = useRef(false);
const suggestName = api.evalsV2.rules.suggestName.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule_name.generate"),
});
const requestNameSuggestion = async () => {
@@ -98,7 +98,7 @@ export function CreateRuleDialogContent({
return name;
};
const createRule = api.evalsV2.rules.create.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.create"),
});
const create = async () => {
diff --git a/web/src/features/evals/v2/components/Rules/EditRuleDialog/components/EditRuleDialogContent/EditRuleDialogContent.tsx b/web/src/features/evals/v2/components/Rules/EditRuleDialog/components/EditRuleDialogContent/EditRuleDialogContent.tsx
index 4a2cfc2df7..9448d048e1 100644
--- a/web/src/features/evals/v2/components/Rules/EditRuleDialog/components/EditRuleDialogContent/EditRuleDialogContent.tsx
+++ b/web/src/features/evals/v2/components/Rules/EditRuleDialog/components/EditRuleDialogContent/EditRuleDialogContent.tsx
@@ -64,7 +64,7 @@ export function EditRuleDialogContent({
}),
);
const update = api.evalsV2.rules.update.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.update"),
});
const save = async () => {
diff --git a/web/src/features/evals/v2/components/Rules/EvaluatorRuleRelationships/EvaluatorRuleRelationships.tsx b/web/src/features/evals/v2/components/Rules/EvaluatorRuleRelationships/EvaluatorRuleRelationships.tsx
index e9f1370a3c..1825016c58 100644
--- a/web/src/features/evals/v2/components/Rules/EvaluatorRuleRelationships/EvaluatorRuleRelationships.tsx
+++ b/web/src/features/evals/v2/components/Rules/EvaluatorRuleRelationships/EvaluatorRuleRelationships.tsx
@@ -143,7 +143,7 @@ function EvaluatorRuleRelationshipsSheet({
utils.evalsV2.list.invalidate({ projectId }),
]);
const attach = api.evalsV2.rules.attach.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.attach"),
onSuccess: async () => {
capture("evaluation_rules:attach_evaluator", {
evaluatorCount: 1,
@@ -154,7 +154,7 @@ function EvaluatorRuleRelationshipsSheet({
},
});
const detach = api.evalsV2.rules.detach.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.detach"),
onSuccess: async () => {
capture("evaluation_rules:detach_evaluator", {
evaluatorCount: 1,
diff --git a/web/src/features/evals/v2/components/Rules/RulesTable/RulesTable.tsx b/web/src/features/evals/v2/components/Rules/RulesTable/RulesTable.tsx
index b3e0e208bf..bd1fab228d 100644
--- a/web/src/features/evals/v2/components/Rules/RulesTable/RulesTable.tsx
+++ b/web/src/features/evals/v2/components/Rules/RulesTable/RulesTable.tsx
@@ -220,7 +220,7 @@ export function RulesTable({
{ enabled: ruleIds.length > 0, meta: { silentHttpCodes: [503] } },
);
const deleteMany = api.evalsV2.rules.deleteMany.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.delete"),
onSuccess: async (result) => {
capture("evaluation_rules:delete", {
ruleCount: result.ruleIds.length,
diff --git a/web/src/features/evals/v2/components/Rules/RulesTable/components/RuleActiveSwitchCell/RuleActiveSwitchCell.tsx b/web/src/features/evals/v2/components/Rules/RulesTable/components/RuleActiveSwitchCell/RuleActiveSwitchCell.tsx
index 387b4e6756..7c61dbc287 100644
--- a/web/src/features/evals/v2/components/Rules/RulesTable/components/RuleActiveSwitchCell/RuleActiveSwitchCell.tsx
+++ b/web/src/features/evals/v2/components/Rules/RulesTable/components/RuleActiveSwitchCell/RuleActiveSwitchCell.tsx
@@ -19,7 +19,7 @@ export function RuleActiveSwitchCell({
const capture = usePostHogClientCapture();
const utils = api.useUtils();
const setEnabled = api.evalsV2.rules.setEnabled.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.status_update"),
onSuccess: async (_result, variables) => {
capture("evaluation_rules:status_change", {
isEnabled: variables.enabled,
diff --git a/web/src/features/evals/v2/components/Rules/RulesTable/components/RulesOverviewSelectionBar/RulesOverviewSelectionBar.tsx b/web/src/features/evals/v2/components/Rules/RulesTable/components/RulesOverviewSelectionBar/RulesOverviewSelectionBar.tsx
index e45c0e5448..656dea3bf9 100644
--- a/web/src/features/evals/v2/components/Rules/RulesTable/components/RulesOverviewSelectionBar/RulesOverviewSelectionBar.tsx
+++ b/web/src/features/evals/v2/components/Rules/RulesTable/components/RulesOverviewSelectionBar/RulesOverviewSelectionBar.tsx
@@ -35,7 +35,7 @@ export function RulesOverviewSelectionBar({
: selectedIds.length;
const selectionActions = selectionStore.getState().actions;
const setEnabled = api.evalsV2.rules.setManyEnabled.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.status_update"),
onSuccess: async (result, variables) => {
capture("evaluation_rules:status_change", {
isEnabled: variables.enabled,
@@ -46,7 +46,7 @@ export function RulesOverviewSelectionBar({
},
});
const deleteMany = api.evalsV2.rules.deleteMany.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.delete"),
onSuccess: async (result) => {
capture("evaluation_rules:delete", {
ruleCount: result.ruleIds.length,
diff --git a/web/src/features/evals/v2/hooks/useActivationConfirmation.ts b/web/src/features/evals/v2/hooks/useActivationConfirmation.ts
index b0f536ccc1..6f14bc7470 100644
--- a/web/src/features/evals/v2/hooks/useActivationConfirmation.ts
+++ b/web/src/features/evals/v2/hooks/useActivationConfirmation.ts
@@ -91,7 +91,7 @@ export function useActivationConfirmation({
return result;
} catch (error) {
setEstimate((current) => ({ ...current, status: "idle" }));
- trpcErrorToast(error);
+ trpcErrorToast(error, "evaluator_rule.estimate_activation");
return null;
}
},
diff --git a/web/src/features/evals/v2/hooks/useProjectDefaultModel.ts b/web/src/features/evals/v2/hooks/useProjectDefaultModel.ts
index b022b8dc8f..707b1ce4ad 100644
--- a/web/src/features/evals/v2/hooks/useProjectDefaultModel.ts
+++ b/web/src/features/evals/v2/hooks/useProjectDefaultModel.ts
@@ -54,7 +54,8 @@ export function useProjectDefaultModel({
const connections = connectionsQuery.data?.data ?? [];
const upsertDefaultModel = api.defaultLlmModel.upsertDefaultModel.useMutation(
{
- onError: trpcErrorToast,
+ onError: (error) =>
+ trpcErrorToast(error, "default_evaluation_model.update"),
},
);
diff --git a/web/src/features/evals/v2/pages/EvaluatorSetupPage.tsx b/web/src/features/evals/v2/pages/EvaluatorSetupPage.tsx
index eb4f60bd55..300f7c0bd5 100644
--- a/web/src/features/evals/v2/pages/EvaluatorSetupPage.tsx
+++ b/web/src/features/evals/v2/pages/EvaluatorSetupPage.tsx
@@ -36,6 +36,7 @@ import { draftsToQuestions } from "@/src/features/evals/v2/fns/evaluators/decisi
import type { NormalizedEvaluatorDefinition } from "../server/evaluators/evaluatorTypes";
import { api } from "@/src/utils/api";
import { trpcErrorToast } from "@/src/utils/trpcErrorToast";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { detailPageListKeys } from "@/src/features/navigate-detail-pages";
import { TableHeaderControls } from "@/src/components/table/table-header-controls";
@@ -406,11 +407,15 @@ export function EvaluatorSetupPage(
}
},
onError: (error) => {
- showErrorToast("Reactivation failed", error.message);
+ showErrorToast(
+ "Reactivation failed",
+ error.message,
+ classifyTrpcToastError(error, "evaluator.reactivate"),
+ );
},
});
const deleteEvaluator = api.evalsV2.delete.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator.delete"),
onSuccess: async () => {
capture("evaluators:delete", {
source: "detail",
@@ -441,7 +446,7 @@ export function EvaluatorSetupPage(
},
onError: (error) => {
setTestResult({ requestError: error.message });
- trpcErrorToast(error);
+ trpcErrorToast(error, "evaluator.test");
},
});
const suggestName = api.evalsV2.suggestName.useMutation();
@@ -490,6 +495,11 @@ export function EvaluatorSetupPage(
showErrorToast(
"Couldn't generate an evaluator name",
"Please enter a name manually.",
+ {
+ operation: "evaluator_name.generate",
+ errorOrigin: "backend",
+ errorCategory: "internal",
+ },
);
}
} catch (error) {
@@ -497,6 +507,7 @@ export function EvaluatorSetupPage(
showErrorToast(
"Couldn't generate an evaluator name",
"Please enter a name manually.",
+ classifyTrpcToastError(error, "evaluator_name.generate"),
);
}
};
@@ -509,12 +520,22 @@ export function EvaluatorSetupPage(
evaluatorSetupStore.getState().actions.setDescription,
);
if (applied) return;
- } catch {
- // The field-specific message below is more actionable than the request error.
+ } catch (error) {
+ showErrorToast(
+ "Couldn't generate an evaluator description",
+ "Please enter a description manually.",
+ classifyTrpcToastError(error, "evaluator_description.generate"),
+ );
+ return;
}
showErrorToast(
"Couldn't generate an evaluator description",
"Please enter a description manually.",
+ {
+ operation: "evaluator_description.generate",
+ errorOrigin: "backend",
+ errorCategory: "internal",
+ },
);
};
@@ -529,7 +550,9 @@ export function EvaluatorSetupPage(
!state.name &&
!hasRequestedName.current
) {
- requestNameSuggestion().catch(trpcErrorToast);
+ requestNameSuggestion().catch((error) =>
+ trpcErrorToast(error, "evaluator_name.generate"),
+ );
}
};
@@ -539,7 +562,7 @@ export function EvaluatorSetupPage(
const requestClose = () => {
const currentSnapshot = getCurrentSnapshot();
if (currentSnapshot !== initialSnapshot.current) setDiscardOpen(true);
- else close().catch(trpcErrorToast);
+ else close().catch((error) => trpcErrorToast(error, "evaluator.navigate"));
};
const save = async () => {
@@ -558,7 +581,7 @@ export function EvaluatorSetupPage(
try {
return await generateDescriptionSuggestion();
} catch (error) {
- trpcErrorToast(error);
+ trpcErrorToast(error, "evaluator_description.generate");
return null;
}
}
@@ -570,6 +593,11 @@ export function EvaluatorSetupPage(
showErrorToast(
"Evaluator name required",
"We couldn't generate a name. Please enter one manually and try again.",
+ {
+ operation: "evaluator.save",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
return;
}
@@ -706,7 +734,7 @@ export function EvaluatorSetupPage(
) {
setVersionConflictOpen(true);
} else {
- trpcErrorToast(error);
+ trpcErrorToast(error, "evaluator.save");
}
} finally {
saveInFlightRef.current = false;
@@ -783,7 +811,9 @@ export function EvaluatorSetupPage(
"eval:onboarding_ai_generate_requested",
{ field: "name" },
);
- requestNameSuggestion(true).catch(trpcErrorToast);
+ requestNameSuggestion(true).catch((error) =>
+ trpcErrorToast(error, "evaluator_name.generate"),
+ );
},
}
}
diff --git a/web/src/features/evals/v2/pages/EvaluatorsPage.tsx b/web/src/features/evals/v2/pages/EvaluatorsPage.tsx
index ae146070bb..a13aff7807 100644
--- a/web/src/features/evals/v2/pages/EvaluatorsPage.tsx
+++ b/web/src/features/evals/v2/pages/EvaluatorsPage.tsx
@@ -333,7 +333,7 @@ export default function EvaluatorsPage() {
);
const utils = api.useUtils();
const deleteMany = api.evalsV2.deleteMany.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator.delete"),
onSuccess: async () => {
selectionStore.getState().actions.clearSelection();
setDeleteIds([]);
diff --git a/web/src/features/events/actions/setReadPath.ts b/web/src/features/events/actions/setReadPath.ts
index 92cc425468..5dcee1957f 100644
--- a/web/src/features/events/actions/setReadPath.ts
+++ b/web/src/features/events/actions/setReadPath.ts
@@ -5,6 +5,7 @@ import { readPathToggleStore } from "@/src/features/events/stores/readPathToggle
import { showErrorToast } from "@/src/features/notifications";
import { V4_BETA_ENABLED_POSTHOG_PROPERTY } from "@/src/features/posthog-analytics";
import { setV4BetaEnabledSentryTag } from "@/src/utils/sentryV4BetaTag";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
type SetReadPathDeps = {
/** `api.userAccount.setV4BetaEnabled` mutateAsync, wired by the toggle surface. */
@@ -59,6 +60,7 @@ export async function setReadPath(
showErrorToast(
target === "v4" ? "Could not switch to V4" : "Could not switch to V3",
error instanceof Error ? error.message : "Please try again.",
+ classifyTrpcToastError(error, "read_path.switch"),
);
return;
}
diff --git a/web/src/features/experiments/components/MultiStepExperimentForm.tsx b/web/src/features/experiments/components/MultiStepExperimentForm.tsx
index c373750197..1e87daa8f8 100644
--- a/web/src/features/experiments/components/MultiStepExperimentForm.tsx
+++ b/web/src/features/experiments/components/MultiStepExperimentForm.tsx
@@ -23,6 +23,7 @@ import Link from "next/link";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm, type UseFormReturn } from "react-hook-form";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { useModelParams } from "@/src/features/playground";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { useEvaluatorDefaults } from "@/src/features/experiments/hooks/useEvaluatorDefaults";
@@ -264,6 +265,7 @@ export const MultiStepExperimentForm = ({
showErrorToast(
error.message || "Failed to trigger dataset run",
"Please try again.",
+ classifyTrpcToastError(error, "experiment.create"),
);
},
onSettled: handleExperimentSettled ?? (() => {}),
@@ -322,6 +324,11 @@ export const MultiStepExperimentForm = ({
showErrorToast(
PROMPT_TOOL_STRUCTURED_OUTPUT_CONFLICT_MESSAGE,
"Disable structured output or choose a prompt without tools.",
+ {
+ operation: "experiment.create",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
return;
}
diff --git a/web/src/features/experiments/components/RemoteExperimentTriggerModal.tsx b/web/src/features/experiments/components/RemoteExperimentTriggerModal.tsx
index 04648b09da..dcbbc537b0 100644
--- a/web/src/features/experiments/components/RemoteExperimentTriggerModal.tsx
+++ b/web/src/features/experiments/components/RemoteExperimentTriggerModal.tsx
@@ -67,6 +67,11 @@ export const RemoteExperimentTriggerModal = ({
showErrorToast(
"Trigger is disabled",
"Enable the trigger in settings to run remote experiments.",
+ {
+ operation: "remote_experiment.trigger",
+ errorOrigin: "backend",
+ errorCategory: "product_state",
+ },
"WARNING",
);
} else if (data.success) {
@@ -81,6 +86,11 @@ export const RemoteExperimentTriggerModal = ({
"Failed to trigger remote experiment",
data.error ||
"Please try again or check your remote experiment configuration.",
+ {
+ operation: "remote_experiment.trigger",
+ errorOrigin: "backend",
+ errorCategory: "internal",
+ },
);
}
setShowTriggerModal(false);
diff --git a/web/src/features/experiments/components/RemoteExperimentUpsertForm.tsx b/web/src/features/experiments/components/RemoteExperimentUpsertForm.tsx
index b74f14e138..830bb5eecb 100644
--- a/web/src/features/experiments/components/RemoteExperimentUpsertForm.tsx
+++ b/web/src/features/experiments/components/RemoteExperimentUpsertForm.tsx
@@ -28,6 +28,7 @@ import {
import { Input } from "@/src/components/ui/input";
import { Switch } from "@/src/components/design-system/Switch/Switch";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { useHasProjectAccess } from "@/src/features/rbac";
import { CodeMirrorEditor } from "@/src/components/editor/CodeMirrorEditor";
import { CodeSection } from "@/src/components/design-system/CodeSection/CodeSection";
@@ -135,6 +136,7 @@ export const RemoteExperimentUpsertForm = ({
showErrorToast(
error.message || "Failed to setup",
"Please check your URL and config and try again.",
+ classifyTrpcToastError(error, "remote_experiment.update"),
);
},
});
@@ -158,6 +160,7 @@ export const RemoteExperimentUpsertForm = ({
showErrorToast(
error.message || "Failed to delete remote dataset run trigger",
"Please try again.",
+ classifyTrpcToastError(error, "remote_experiment.delete"),
);
},
});
diff --git a/web/src/features/experiments/hooks/useExperimentV2EvaluatorSelection.ts b/web/src/features/experiments/hooks/useExperimentV2EvaluatorSelection.ts
index 7496bb5496..c33bfa16ec 100644
--- a/web/src/features/experiments/hooks/useExperimentV2EvaluatorSelection.ts
+++ b/web/src/features/experiments/hooks/useExperimentV2EvaluatorSelection.ts
@@ -140,10 +140,10 @@ export function useExperimentV2EvaluatorSelection({
}, [datasetRules]);
const createRule = api.evalsV2.rules.create.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.create"),
});
const updateRule = api.evalsV2.rules.update.useMutation({
- onError: trpcErrorToast,
+ onError: (error) => trpcErrorToast(error, "evaluator_rule.update"),
});
const isUpdating = createRule.isPending || updateRule.isPending;
diff --git a/web/src/features/external-media-storage/ExternalMediaStoragePage.tsx b/web/src/features/external-media-storage/ExternalMediaStoragePage.tsx
index 19f6814f44..6ef6a0bd9e 100644
--- a/web/src/features/external-media-storage/ExternalMediaStoragePage.tsx
+++ b/web/src/features/external-media-storage/ExternalMediaStoragePage.tsx
@@ -17,6 +17,7 @@ import { type ExternalMediaStorageFormValues } from "@/src/features/external-med
import { useHasProjectAccess } from "@/src/features/rbac";
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
const EXTERNAL_MEDIA_STORAGE_FORM_ID = "external-media-storage-form";
@@ -60,7 +61,11 @@ export default function ExternalMediaStoragePage() {
});
},
onError: (error) => {
- showErrorToast("Failed to save external media storage", error.message);
+ showErrorToast(
+ "Failed to save external media storage",
+ error.message,
+ classifyTrpcToastError(error, "external_media_storage.save"),
+ );
},
});
const deleteMutation = api.externalMediaStorage.delete.useMutation({
@@ -73,7 +78,11 @@ export default function ExternalMediaStoragePage() {
});
},
onError: (error) => {
- showErrorToast("Failed to delete external media storage", error.message);
+ showErrorToast(
+ "Failed to delete external media storage",
+ error.message,
+ classifyTrpcToastError(error, "external_media_storage.delete"),
+ );
},
});
const testMutation = api.externalMediaStorage.testObject.useMutation();
@@ -99,11 +108,13 @@ export default function ExternalMediaStoragePage() {
<TestMediaObjectDialog
isPending={testMutation.isPending}
onTest={async (uri) => {
+ let failureOrigin: "trpc" | "network" = "trpc";
try {
const result = await testMutation.mutateAsync({
projectId,
uri,
});
+ failureOrigin = "network";
await testSignedMediaUrlCors(result.signedUrl);
return result.signedUrl;
} catch (error) {
@@ -112,6 +123,16 @@ export default function ExternalMediaStoragePage() {
error instanceof Error
? error.message
: "The media object could not be loaded.",
+ failureOrigin === "trpc"
+ ? classifyTrpcToastError(
+ error,
+ "external_media_storage.test",
+ )
+ : {
+ operation: "external_media_storage.test",
+ errorOrigin: "network",
+ errorCategory: "transient",
+ },
);
return null;
}
diff --git a/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.tsx b/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.tsx
index 3a370c668c..9d0f41360c 100644
--- a/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.tsx
+++ b/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.tsx
@@ -24,6 +24,7 @@ import {
} from "@/src/features/feature-flags/available-flags";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
type ProposedChange = {
flag: FeaturePreviewFlag;
@@ -66,7 +67,11 @@ export function OrganizationFeaturePreviewsSettings({
},
onError: (error) => {
setProposedChange(null);
- showErrorToast("Failed to update feature preview", error.message);
+ showErrorToast(
+ "Failed to update feature preview",
+ error.message,
+ classifyTrpcToastError(error, "organization_feature_preview.update"),
+ );
},
});
diff --git a/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.tsx b/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.tsx
index 71e0a1a15c..5d3c160783 100644
--- a/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.tsx
+++ b/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.tsx
@@ -13,6 +13,7 @@ import {
} from "@/src/features/feature-flags/available-flags";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
type FeaturePreviewManagement = {
allowed: boolean;
@@ -59,11 +60,12 @@ export function UserFeaturePreviewsControl({
} for this user.`,
});
},
- onError: async () => {
+ onError: async (error) => {
await utils.members.allFromOrg.invalidate();
showErrorToast(
"Failed to update feature preview",
"Your access may have changed. Refresh and try again.",
+ classifyTrpcToastError(error, "user_feature_preview.update"),
);
},
});
diff --git a/web/src/features/feature-flags/hooks/useInternalViewMode.ts b/web/src/features/feature-flags/hooks/useInternalViewMode.ts
index 09db351c27..957db8685c 100644
--- a/web/src/features/feature-flags/hooks/useInternalViewMode.ts
+++ b/web/src/features/feature-flags/hooks/useInternalViewMode.ts
@@ -1,6 +1,7 @@
import { useSession } from "next-auth/react";
import { api } from "@/src/utils/api";
import { showErrorToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { hasInternalAccess } from "../utils";
import { useInternalFeaturesEnabled } from "./useInternalFeaturesEnabled";
@@ -17,7 +18,11 @@ export function useInternalViewMode() {
await session.update();
},
onError: (error) =>
- showErrorToast("Failed to update view mode", error.message),
+ showErrorToast(
+ "Failed to update view mode",
+ error.message,
+ classifyTrpcToastError(error, "account_view_mode.update"),
+ ),
});
const mode = enabled ? "INTERNAL" : "EXTERNAL";
return {
diff --git a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
index d3c26163f3..e2b90d1ca2 100644
--- a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
+++ b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
@@ -5,6 +5,7 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { useReadPath, V4_PREVIEW_LABEL } from "@/src/features/events";
import { featurePreviewLabels } from "@/src/features/feature-flags";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import {
FeaturePreviewModal,
@@ -39,7 +40,11 @@ export function ControlledFeaturePreviewModal({
});
},
onError: (error) => {
- showErrorToast("Failed to update feature preview", error.message);
+ showErrorToast(
+ "Failed to update feature preview",
+ error.message,
+ classifyTrpcToastError(error, "user_feature_preview.update"),
+ );
},
});
diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
index 170e5359bf..3984caed88 100644
--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
@@ -69,6 +69,7 @@ import type { InAppAgentSubmitOptions } from "@/src/features/in-app-agent/quickA
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { evaluateSetStateAction } from "@/src/utils/evaluate-set-state-action";
import { InAppAgentDisabledDialog } from "@/src/features/in-app-agent/components/InAppAgentDisabledDialog";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import {
getCompletedToolCalls,
performToolSideEffectsForCompletedToolCalls,
@@ -592,7 +593,11 @@ function InAppAiAgentProviderInner({
fetchNextConversationsPage().catch((error) => {
const errorMessage = getAgentErrorMessage(error);
- showErrorToast("Failed to load conversations", errorMessage);
+ showErrorToast(
+ "Failed to load conversations",
+ errorMessage,
+ classifyTrpcToastError(error, "in_app_agent_conversations.load"),
+ );
console.error("Failed to load in-app agent conversations", error);
});
}, [
@@ -613,7 +618,14 @@ function InAppAiAgentProviderInner({
}
const errorMessage = getAgentErrorMessage(conversationListQuery.error);
- showErrorToast("Failed to load conversations", errorMessage);
+ showErrorToast(
+ "Failed to load conversations",
+ errorMessage,
+ classifyTrpcToastError(
+ conversationListQuery.error,
+ "in_app_agent_conversations.load",
+ ),
+ );
console.error("Failed to load in-app agent conversations", {
error: conversationListQuery.error,
projectId,
@@ -1000,7 +1012,11 @@ function InAppAiAgentProviderInner({
]);
} catch (error) {
const errorMessage = getAgentErrorMessage(error);
- showErrorToast("Failed to delete conversation", errorMessage);
+ showErrorToast(
+ "Failed to delete conversation",
+ errorMessage,
+ classifyTrpcToastError(error, "in_app_agent_conversation.delete"),
+ );
console.error("Failed to delete in-app agent conversation", error);
throw error;
}
@@ -1168,7 +1184,11 @@ function InAppAiAgentProviderInner({
});
} catch (error) {
const errorMessage = getAgentErrorMessage(error);
- showErrorToast("Failed to save feedback", errorMessage);
+ showErrorToast(
+ "Failed to save feedback",
+ errorMessage,
+ classifyTrpcToastError(error, "in_app_agent_feedback.save"),
+ );
console.error("Failed to save in-app agent feedback", error);
throw error;
}
@@ -1292,7 +1312,11 @@ function InAppAiAgentProviderInner({
);
backgroundSession.cancel().catch((error: unknown) => {
- showErrorToast("Failed to stop the run", getAgentErrorMessage(error));
+ showErrorToast(
+ "Failed to stop the run",
+ getAgentErrorMessage(error),
+ classifyTrpcToastError(error, "in_app_agent_run.stop"),
+ );
});
}, [
conversationQuery.data,
diff --git a/web/src/features/monitors/components/MonitorForm.tsx b/web/src/features/monitors/components/MonitorForm.tsx
index c8ff2e7e34..279566ffc4 100644
--- a/web/src/features/monitors/components/MonitorForm.tsx
+++ b/web/src/features/monitors/components/MonitorForm.tsx
@@ -11,6 +11,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { startCase } from "lodash";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { AIAssistedInput } from "@/src/components/ui/ai-assisted-input";
import { Button } from "@/src/components/ui/button";
import {
@@ -46,7 +47,10 @@ import { WidgetPropertySelectItem } from "@/src/features/widgets";
import { MetricsFilterBuilder } from "@/src/features/metrics";
import { partitionWidgetUiTableFiltersToView } from "@/src/features/dashboard";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
-import { resolveMonitorNameForSave } from "@/src/features/monitors/fns/resolveMonitorNameForSave";
+import {
+ resolveMonitorNameForSave,
+ type MonitorNameResolution,
+} from "@/src/features/monitors/fns/resolveMonitorNameForSave";
import { cn } from "@/src/utils/tailwind";
import {
@@ -229,21 +233,32 @@ export const MonitorForm = ({
const suggestName = api.monitors.suggestName.useMutation();
const generateNameSuggestion = async (): Promise<string | null> => {
if (!nameAIAssistanceAvailable) return null;
- try {
- return await suggestName.mutateAsync({
- projectId,
- description: namePlaceholderRef.current,
- });
- } catch {
- return null;
- }
+ return suggestName.mutateAsync({
+ projectId,
+ description: namePlaceholderRef.current,
+ });
};
const requestNameSuggestion = async () => {
- const generatedName = await generateNameSuggestion();
+ let generatedName: string | null;
+ try {
+ generatedName = await generateNameSuggestion();
+ } catch (error) {
+ showErrorToast(
+ "Couldn't generate an alert title",
+ "Please enter a title manually.",
+ classifyTrpcToastError(error, "monitor_title.generate"),
+ );
+ return;
+ }
if (!generatedName) {
showErrorToast(
"Couldn't generate an alert title",
"Please enter a title manually.",
+ {
+ operation: "monitor_title.generate",
+ errorOrigin: "backend",
+ errorCategory: "internal",
+ },
);
return;
}
@@ -269,7 +284,12 @@ export const MonitorForm = ({
});
router.replace(`/project/${projectId}/alerts`);
},
- onError: (e) => showErrorToast("Failed to create alert", e.message),
+ onError: (e) =>
+ showErrorToast(
+ "Failed to create alert",
+ e.message,
+ classifyTrpcToastError(e, "monitor.create"),
+ ),
});
/** updateMutation saves edits to an existing monitor and returns to the monitors list on success. */
@@ -283,29 +303,61 @@ export const MonitorForm = ({
});
router.replace(`/project/${projectId}/alerts`);
},
- onError: (e) => showErrorToast("Failed to save alert", e.message),
+ onError: (e) =>
+ showErrorToast(
+ "Failed to save alert",
+ e.message,
+ classifyTrpcToastError(e, "monitor.update"),
+ ),
});
/** onSubmit strips unsupported filter rows and dispatches the create or update mutation. */
const onSubmit = form.handleSubmit(
async (values) => {
- const resolvedName = await resolveMonitorNameForSave({
- name: form.getValues("name"),
- fallbackName: namePlaceholderRef.current,
- aiAvailable: nameAIAssistanceAvailable,
- generateName: generateNameSuggestion,
- });
- if (!resolvedName) {
+ let nameResolution: MonitorNameResolution;
+ try {
+ nameResolution = await resolveMonitorNameForSave({
+ name: form.getValues("name"),
+ fallbackName: namePlaceholderRef.current,
+ aiAvailable: nameAIAssistanceAvailable,
+ generateName: generateNameSuggestion,
+ });
+ } catch (error) {
+ showErrorToast(
+ "Couldn't generate an alert title",
+ "Please enter a title manually and try again.",
+ classifyTrpcToastError(error, "monitor_title.generate"),
+ );
+ return;
+ }
+ if (nameResolution.status === "generation-failed") {
+ showErrorToast(
+ "Couldn't generate an alert title",
+ "Please enter a title manually and try again.",
+ {
+ operation: "monitor_title.generate",
+ errorOrigin: "backend",
+ errorCategory: "internal",
+ },
+ );
+ return;
+ }
+ if (nameResolution.status === "validation-failed") {
showErrorToast(
"Couldn't generate an alert title",
"Please enter a title manually and try again.",
+ {
+ operation: isEdit ? "monitor.update" : "monitor.create",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
return;
}
const normalizedValues = {
...values,
- name: resolvedName,
+ name: nameResolution.name,
filters: partitionWidgetUiTableFiltersToView(
values.view as Parameters<
typeof partitionWidgetUiTableFiltersToView
diff --git a/web/src/features/monitors/components/MonitorsTable.tsx b/web/src/features/monitors/components/MonitorsTable.tsx
index 65bec6c944..f6c563cc62 100644
--- a/web/src/features/monitors/components/MonitorsTable.tsx
+++ b/web/src/features/monitors/components/MonitorsTable.tsx
@@ -30,6 +30,7 @@ import { TagList } from "@/src/features/tag";
import { usePaginationState } from "@/src/hooks/usePaginationState";
import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
import { api, type RouterInputs, type RouterOutputs } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { cn } from "@/src/utils/tailwind";
import { type FilterState, TableViewPresetTableName } from "@langfuse/shared";
import {
@@ -92,7 +93,12 @@ export function MonitorsTable() {
: "Evaluations have resumed.",
});
},
- onError: (e) => showErrorToast("Failed to update alert status", e.message),
+ onError: (e) =>
+ showErrorToast(
+ "Failed to update alert status",
+ e.message,
+ classifyTrpcToastError(e, "monitor.status_update"),
+ ),
});
/** paginationState is the bound page index + size, defaulting to 50 per page and synced to the `pageIndex`/`pageSize` URL params. */
diff --git a/web/src/features/monitors/fns/resolveMonitorNameForSave.clienttest.ts b/web/src/features/monitors/fns/resolveMonitorNameForSave.clienttest.ts
index ab185bbd5a..e20cbc8e22 100644
--- a/web/src/features/monitors/fns/resolveMonitorNameForSave.clienttest.ts
+++ b/web/src/features/monitors/fns/resolveMonitorNameForSave.clienttest.ts
@@ -15,7 +15,7 @@ describe("resolveMonitorNameForSave", () => {
aiAvailable: true,
generateName,
}),
- ).resolves.toBe("Cost spike");
+ ).resolves.toEqual({ status: "resolved", name: "Cost spike" });
expect(generateName).not.toHaveBeenCalled();
});
@@ -29,7 +29,10 @@ describe("resolveMonitorNameForSave", () => {
aiAvailable: true,
generateName,
}),
- ).resolves.toBe("Evaluator cost spike");
+ ).resolves.toEqual({
+ status: "resolved",
+ name: "Evaluator cost spike",
+ });
});
it("uses the deterministic fallback when AI assistance is unavailable", async () => {
@@ -42,11 +45,14 @@ describe("resolveMonitorNameForSave", () => {
aiAvailable: false,
generateName,
}),
- ).resolves.toBe("Count of observations is above 5");
+ ).resolves.toEqual({
+ status: "resolved",
+ name: "Count of observations is above 5",
+ });
expect(generateName).not.toHaveBeenCalled();
});
- it("returns null when generation fails", async () => {
+ it("identifies an unsuccessful AI generation", async () => {
await expect(
resolveMonitorNameForSave({
name: "",
@@ -54,6 +60,20 @@ describe("resolveMonitorNameForSave", () => {
aiAvailable: true,
generateName: vi.fn().mockResolvedValue(null),
}),
- ).resolves.toBeNull();
+ ).resolves.toEqual({ status: "generation-failed" });
+ });
+
+ it("identifies a missing local fallback without requesting generation", async () => {
+ const generateName = vi.fn();
+
+ await expect(
+ resolveMonitorNameForSave({
+ name: "",
+ fallbackName: "",
+ aiAvailable: false,
+ generateName,
+ }),
+ ).resolves.toEqual({ status: "validation-failed" });
+ expect(generateName).not.toHaveBeenCalled();
});
});
diff --git a/web/src/features/monitors/fns/resolveMonitorNameForSave.ts b/web/src/features/monitors/fns/resolveMonitorNameForSave.ts
index 588a45dfa3..b808c74e23 100644
--- a/web/src/features/monitors/fns/resolveMonitorNameForSave.ts
+++ b/web/src/features/monitors/fns/resolveMonitorNameForSave.ts
@@ -1,4 +1,4 @@
-/** Resolves a monitor name at save time, generating blank names when AI assistance is available. */
+/** Resolves a monitor name at save time, preserving why a blank name could not be resolved. */
export async function resolveMonitorNameForSave({
name,
fallbackName,
@@ -9,11 +9,22 @@ export async function resolveMonitorNameForSave({
fallbackName: string;
aiAvailable: boolean;
generateName: () => Promise<string | null>;
-}): Promise<string | null> {
+}): Promise<MonitorNameResolution> {
const enteredName = name?.trim();
- if (enteredName) return enteredName;
- if (!aiAvailable) return fallbackName;
+ if (enteredName) return { status: "resolved", name: enteredName };
+ if (!aiAvailable) {
+ return fallbackName
+ ? { status: "resolved", name: fallbackName }
+ : { status: "validation-failed" };
+ }
const generatedName = (await generateName())?.trim();
- return generatedName || null;
+ return generatedName
+ ? { status: "resolved", name: generatedName }
+ : { status: "generation-failed" };
}
+
+export type MonitorNameResolution =
+ | { status: "resolved"; name: string }
+ | { status: "generation-failed" }
+ | { status: "validation-failed" };
diff --git a/web/src/features/monitors/pages/EditMonitorPage.tsx b/web/src/features/monitors/pages/EditMonitorPage.tsx
index f61a102b57..6791d2e989 100644
--- a/web/src/features/monitors/pages/EditMonitorPage.tsx
+++ b/web/src/features/monitors/pages/EditMonitorPage.tsx
@@ -10,6 +10,7 @@ import { invalidateMonitorQueriesAfterDelete } from "@/src/features/monitors/fns
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
import { useHasProjectAccess } from "@/src/features/rbac";
import { api, type APIError } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { type Monitor } from "@langfuse/shared/monitors";
/** EditMonitorPage gates the edit-monitor route and defers all data fetching to EditMonitorPageContent so blocked users never trigger the monitor query. */
@@ -62,7 +63,12 @@ const EditMonitorFormPage = ({ monitor }: { monitor: Monitor }) => {
});
await router.replace(`/project/${monitor.projectId}/alerts`);
},
- onError: (error) => showErrorToast("Failed to delete alert", error.message),
+ onError: (error) =>
+ showErrorToast(
+ "Failed to delete alert",
+ error.message,
+ classifyTrpcToastError(error, "monitor.delete"),
+ ),
});
return (
diff --git a/web/src/features/notifications/ErrorNotification.clienttest.tsx b/web/src/features/notifications/ErrorNotification.clienttest.tsx
index 50cbea59e9..075bacbc6e 100644
--- a/web/src/features/notifications/ErrorNotification.clienttest.tsx
+++ b/web/src/features/notifications/ErrorNotification.clienttest.tsx
@@ -41,9 +41,11 @@ describe("ErrorNotification", () => {
path: "traces.byId",
traceId: "0123456789abcdef",
analytics: {
+ operation: "traces.byId" as const,
+ trpcPath: "traces.byId" as const,
errorOrigin: "backend" as const,
errorCategory: "internal" as const,
- trpcCode: "INTERNAL_SERVER_ERROR",
+ trpcCode: "INTERNAL_SERVER_ERROR" as const,
httpStatus: 500,
},
};
@@ -54,12 +56,14 @@ describe("ErrorNotification", () => {
expect(mocks.capture).toHaveBeenCalledWith("toast:shown", {
toastType: "ERROR",
source: "trpc",
+ operation: "traces.byId",
path: "traces.byId",
hasErrorId: true,
+ isOperationFallback: false,
errorId: props.traceId,
errorOrigin: "backend",
errorCategory: "internal",
- trpcCode: "INTERNAL_SERVER_ERROR",
+ trpcCode: "INTERNAL_SERVER_ERROR" as const,
httpStatus: 500,
});
});
@@ -87,6 +91,11 @@ describe("ErrorNotification", () => {
type="WARNING"
dismissToast={vi.fn()}
toast="toast-2"
+ analytics={{
+ operation: "project_api_key.create",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ }}
/>,
);
@@ -95,8 +104,10 @@ describe("ErrorNotification", () => {
toastType: "WARNING",
source: "application",
hasErrorId: false,
- errorOrigin: "unknown",
- errorCategory: "unknown",
+ isOperationFallback: false,
+ operation: "project_api_key.create",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
});
});
expect(mocks.capture.mock.calls[0]?.[1]).not.toHaveProperty("errorId");
@@ -111,6 +122,11 @@ describe("ErrorNotification", () => {
source="trpc"
dismissToast={vi.fn()}
toast="toast-3"
+ analytics={{
+ operation: "project_api_key.create",
+ errorOrigin: "network",
+ errorCategory: "transient",
+ }}
/>,
);
@@ -119,8 +135,10 @@ describe("ErrorNotification", () => {
toastType: "WARNING",
source: "trpc",
hasErrorId: false,
- errorOrigin: "unknown",
- errorCategory: "unknown",
+ isOperationFallback: false,
+ operation: "project_api_key.create",
+ errorOrigin: "network",
+ errorCategory: "transient",
});
});
});
@@ -137,7 +155,7 @@ describe("ErrorNotification", () => {
analytics={{
errorOrigin: "frontend",
errorCategory: "user_input",
- operation: "form.submit",
+ operation: "project_api_key.create",
}}
/>,
);
@@ -152,7 +170,8 @@ describe("ErrorNotification", () => {
source: "application",
errorOrigin: "frontend",
errorCategory: "user_input",
- operation: "form.submit",
+ operation: "project_api_key.create",
+ isOperationFallback: false,
});
fireEvent.click(screen.getByRole("button", { name: "Close" }));
@@ -161,7 +180,8 @@ describe("ErrorNotification", () => {
source: "application",
errorOrigin: "frontend",
errorCategory: "user_input",
- operation: "form.submit",
+ operation: "project_api_key.create",
+ isOperationFallback: false,
});
expect(dismissToast).toHaveBeenCalledWith("toast-4");
expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain("Sensitive");
diff --git a/web/src/features/notifications/ErrorNotification.tsx b/web/src/features/notifications/ErrorNotification.tsx
index 04db2c5bb3..e2733ba719 100644
--- a/web/src/features/notifications/ErrorNotification.tsx
+++ b/web/src/features/notifications/ErrorNotification.tsx
@@ -1,7 +1,7 @@
import { Button } from "@/src/components/ui/button";
import {
type ToastErrorAnalytics,
- type ToastErrorEventProperties,
+ getToastErrorProperties,
} from "@/src/features/notifications/toastAnalytics";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { useSupportDrawer } from "@/src/features/support-chat";
@@ -19,7 +19,7 @@ interface ErrorNotificationProps {
source?: "application" | "trpc";
path?: string;
traceId?: string;
- analytics?: ToastErrorAnalytics;
+ analytics: ToastErrorAnalytics;
}
export const ErrorNotification: React.FC<ErrorNotificationProps> = ({
@@ -42,23 +42,18 @@ export const ErrorNotification: React.FC<ErrorNotificationProps> = ({
const textColor = isError
? "text-destructive-foreground"
: "text-dark-yellow";
- const interactionProperties = {
- toastType: type,
+ const eventProperties = getToastErrorProperties(
+ analytics,
+ type,
source,
- ...(path ? { path } : {}),
- errorOrigin: analytics?.errorOrigin ?? "unknown",
- errorCategory: analytics?.errorCategory ?? "unknown",
- ...(analytics?.operation ? { operation: analytics.operation } : {}),
- ...(analytics?.trpcCode ? { trpcCode: analytics.trpcCode } : {}),
- ...(analytics?.httpStatus !== undefined
- ? { httpStatus: analytics.httpStatus }
- : {}),
- };
- const eventProperties: ToastErrorEventProperties = {
- ...interactionProperties,
- hasErrorId: Boolean(traceId),
- ...(traceId ? { errorId: traceId } : {}),
- };
+ analytics.trpcPath,
+ traceId,
+ );
+ const {
+ hasErrorId: _hasErrorId,
+ errorId: _errorId,
+ ...interactionProperties
+ } = eventProperties;
const captureShown = (element: HTMLDivElement | null) => {
if (!element || didCaptureShown.current) return;
diff --git a/web/src/features/notifications/SuccessNotification.clienttest.tsx b/web/src/features/notifications/SuccessNotification.clienttest.tsx
index de7a5064f6..f653aa24b3 100644
--- a/web/src/features/notifications/SuccessNotification.clienttest.tsx
+++ b/web/src/features/notifications/SuccessNotification.clienttest.tsx
@@ -38,7 +38,7 @@ describe("SuccessNotification", () => {
<SuccessNotification
title="Another title"
description="Another description"
- operation="dashboard.update"
+ operation="dashboard.clone"
onDismiss={vi.fn()}
/>,
);
@@ -56,7 +56,7 @@ describe("SuccessNotification", () => {
<SuccessNotification
title="Saved"
description="Done"
- operation="dashboard.update"
+ operation="dashboard.clone"
onDismiss={onDismiss}
/>,
);
@@ -67,7 +67,7 @@ describe("SuccessNotification", () => {
expect(mocks.capture).toHaveBeenLastCalledWith("toast:dismiss", {
toastType: "SUCCESS",
source: "application",
- operation: "dashboard.update",
+ operation: "dashboard.clone",
});
expect(onDismiss).toHaveBeenCalledOnce();
});
diff --git a/web/src/features/notifications/SuccessNotification.tsx b/web/src/features/notifications/SuccessNotification.tsx
index 48200f3d34..8bf9a92e28 100644
--- a/web/src/features/notifications/SuccessNotification.tsx
+++ b/web/src/features/notifications/SuccessNotification.tsx
@@ -2,11 +2,12 @@ import { ActionButton } from "@/src/components/ActionButton";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { BadgeCheck, X } from "lucide-react";
import { useRef } from "react";
+import type { ToastOperation } from "./toastAnalytics";
export type SuccessNotificationProps = {
title: string;
description: string;
- operation: string;
+ operation: ToastOperation;
onDismiss: () => void;
link?: {
href: string;
diff --git a/web/src/features/notifications/index.ts b/web/src/features/notifications/index.ts
index 23ea4b343d..db7cc86cbd 100644
--- a/web/src/features/notifications/index.ts
+++ b/web/src/features/notifications/index.ts
@@ -7,3 +7,7 @@
export { showErrorToast } from "@/src/features/notifications/showErrorToast";
export { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+export {
+ showToast,
+ showCustomToast,
+} from "@/src/features/notifications/showToast";
diff --git a/web/src/features/notifications/showErrorToast.tsx b/web/src/features/notifications/showErrorToast.tsx
index a587b9edc4..d4381a4f7d 100644
--- a/web/src/features/notifications/showErrorToast.tsx
+++ b/web/src/features/notifications/showErrorToast.tsx
@@ -20,13 +20,13 @@ const toastWarningStyleProps = {
export const showErrorToast = (
error: string,
description: string,
+ analytics: ToastErrorAnalytics,
type: "WARNING" | "ERROR" = "ERROR",
path?: string,
traceId?: string,
source: "application" | "trpc" = "application",
- analytics?: ToastErrorAnalytics,
) => {
- toast.custom(
+ return toast.custom(
(t) => (
<ErrorNotification
error={error}
@@ -34,7 +34,7 @@ export const showErrorToast = (
type={type}
source={source}
path={path}
- traceId={traceId}
+ traceId={traceId ?? analytics.errorId}
analytics={analytics}
dismissToast={toast.dismiss}
toast={t}
diff --git a/web/src/features/notifications/showSuccessToast.tsx b/web/src/features/notifications/showSuccessToast.tsx
index abd2292051..79f8554255 100644
--- a/web/src/features/notifications/showSuccessToast.tsx
+++ b/web/src/features/notifications/showSuccessToast.tsx
@@ -8,7 +8,7 @@ export const showSuccessToast = ({
duration = 5000,
...params
}: Omit<SuccessNotificationProps, "onDismiss"> & { duration?: number }) => {
- toast.custom(
+ return toast.custom(
(t) => (
<SuccessNotification {...params} onDismiss={() => toast.dismiss(t)} />
),
diff --git a/web/src/features/notifications/showToast.clienttest.tsx b/web/src/features/notifications/showToast.clienttest.tsx
new file mode 100644
index 0000000000..e67d20fc18
--- /dev/null
+++ b/web/src/features/notifications/showToast.clienttest.tsx
@@ -0,0 +1,248 @@
+import { StrictMode, type ReactNode } from "react";
+import { render, screen, waitFor } from "@testing-library/react";
+import { vi } from "vitest";
+import { showCustomToast, showToast } from "@/src/features/notifications";
+
+vi.mock("@/src/features/notifications/showErrorToast", () => ({
+ showErrorToast: vi.fn(),
+}));
+vi.mock("@/src/features/notifications/showSuccessToast", () => ({
+ showSuccessToast: vi.fn(),
+}));
+
+const mocks = vi.hoisted(() => ({
+ capture: vi.fn(),
+ custom: vi.fn<
+ (render: (id: string | number) => unknown, options?: unknown) => string
+ >(() => "custom-return-id"),
+ error: vi.fn<(content: unknown, options?: unknown) => string>(
+ () => "error-return-id",
+ ),
+ info: vi.fn<(content: unknown, options?: unknown) => string>(
+ () => "info-return-id",
+ ),
+ loading: vi.fn<(content: unknown, options?: unknown) => string>(
+ () => "loading-return-id",
+ ),
+ message: vi.fn<(content: unknown, options?: unknown) => string>(
+ () => "message-return-id",
+ ),
+ success: vi.fn<(content: unknown, options?: unknown) => string>(
+ () => "success-return-id",
+ ),
+ warning: vi.fn<(content: unknown, options?: unknown) => string>(
+ () => "warning-return-id",
+ ),
+}));
+
+vi.mock("sonner", () => ({
+ toast: {
+ custom: mocks.custom,
+ error: mocks.error,
+ info: mocks.info,
+ loading: mocks.loading,
+ message: mocks.message,
+ success: mocks.success,
+ warning: mocks.warning,
+ },
+}));
+
+vi.mock("@/src/features/posthog-analytics", () => ({
+ usePostHogClientCapture: () => mocks.capture,
+}));
+
+describe("showToast", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it.each([
+ ["SUCCESS", "success"],
+ ["INFO", "info"],
+ ["LOADING", "loading"],
+ ["MESSAGE", "message"],
+ ["CUSTOM", "message"],
+ ] as const)(
+ "routes %s through native Sonner and captures on mount",
+ async (type, method) => {
+ const options = { duration: 321, id: `${type.toLowerCase()}-toast-id` };
+ const result = showToast(
+ {
+ type,
+ title: `PRIVATE-${type}-TITLE`,
+ analytics: { operation: "dashboard.create" },
+ },
+ options,
+ );
+ const toastMock = mocks[method];
+
+ expect(result).toBe(`${method}-return-id`);
+ expect(toastMock).toHaveBeenCalledOnce();
+ expect(toastMock.mock.calls[0]?.[1]).toBe(options);
+ expect(mocks.capture).not.toHaveBeenCalled();
+
+ render(toastMock.mock.calls[0]?.[0] as ReactNode);
+
+ await waitFor(() => {
+ expect(mocks.capture).toHaveBeenCalledWith("toast:shown", {
+ toastType: type,
+ source: "application",
+ operation: "dashboard.create",
+ hasErrorId: false,
+ });
+ });
+ expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(
+ `PRIVATE-${type}-TITLE`,
+ );
+ },
+ );
+
+ it.each([
+ ["ERROR", "error"],
+ ["WARNING", "warning"],
+ ] as const)(
+ "allowlists %s metadata and forwards the error ID",
+ async (type, method) => {
+ const titleSentinel = `PRIVATE-${type}-TITLE`;
+ const errorId = `${type.toLowerCase()}-error-id`;
+ const result = showToast({
+ type,
+ title: titleSentinel,
+ analytics: {
+ operation: "dashboard.create",
+ errorOrigin: "backend",
+ errorCategory: "internal",
+ trpcCode: "INTERNAL_SERVER_ERROR",
+ httpStatus: 500,
+ errorId,
+ },
+ });
+ const toastMock = mocks[method];
+
+ expect(result).toBe(`${method}-return-id`);
+ expect(mocks.capture).not.toHaveBeenCalled();
+ render(toastMock.mock.calls[0]?.[0] as ReactNode);
+
+ await waitFor(() => {
+ expect(mocks.capture).toHaveBeenCalledWith("toast:shown", {
+ toastType: type,
+ source: "application",
+ operation: "dashboard.create",
+ errorOrigin: "backend",
+ errorCategory: "internal",
+ trpcCode: "INTERNAL_SERVER_ERROR",
+ httpStatus: 500,
+ hasErrorId: true,
+ errorId,
+ isOperationFallback: false,
+ });
+ });
+ expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(
+ titleSentinel,
+ );
+ },
+ );
+
+ it("captures a queued toast exactly once across StrictMode and rerenders", async () => {
+ showToast({
+ type: "SUCCESS",
+ title: "PRIVATE-QUEUED-TITLE",
+ analytics: { operation: "dashboard.create" },
+ });
+ const content = mocks.success.mock.calls[0]?.[0] as ReactNode;
+
+ expect(mocks.capture).not.toHaveBeenCalled();
+ const view = render(<StrictMode>{content}</StrictMode>);
+ await waitFor(() => expect(mocks.capture).toHaveBeenCalledOnce());
+
+ view.rerender(<StrictMode>{content}</StrictMode>);
+ expect(mocks.capture).toHaveBeenCalledOnce();
+ });
+
+ it("captures a loading toast's success transition when the same ID is reused", async () => {
+ const options = { id: "shared-toast-id" };
+ showToast(
+ {
+ type: "LOADING",
+ title: "Preparing",
+ analytics: { operation: "dashboard.create" },
+ },
+ options,
+ );
+ const view = render(mocks.loading.mock.calls[0]?.[0] as ReactNode);
+ await waitFor(() => expect(mocks.capture).toHaveBeenCalledOnce());
+
+ showToast(
+ {
+ type: "SUCCESS",
+ title: "Created",
+ analytics: { operation: "dashboard.create" },
+ },
+ options,
+ );
+ view.rerender(mocks.success.mock.calls[0]?.[0] as ReactNode);
+
+ await waitFor(() => expect(mocks.capture).toHaveBeenCalledTimes(2));
+ expect(mocks.capture.mock.calls.map((call) => call[1].toastType)).toEqual([
+ "LOADING",
+ "SUCCESS",
+ ]);
+ });
+
+ it("preserves custom render IDs and options without exporting content", async () => {
+ const options = { duration: 777, id: "custom-option-id" };
+ const result = showCustomToast(
+ (id) => <span>PRIVATE-CUSTOM-CONTENT {id}</span>,
+ {
+ type: "CUSTOM",
+ analytics: { operation: "dashboard.create" },
+ },
+ options,
+ );
+
+ expect(result).toBe("custom-return-id");
+ expect(mocks.custom.mock.calls[0]?.[1]).toBe(options);
+ expect(mocks.capture).not.toHaveBeenCalled();
+
+ const renderToast = mocks.custom.mock.calls[0]?.[0];
+ const view = render(
+ <StrictMode>{renderToast?.("sonner-custom-id") as ReactNode}</StrictMode>,
+ );
+ expect(screen.getByText(/sonner-custom-id/)).toBeInTheDocument();
+ await waitFor(() => expect(mocks.capture).toHaveBeenCalledOnce());
+
+ view.rerender(
+ <StrictMode>{renderToast?.("sonner-custom-id") as ReactNode}</StrictMode>,
+ );
+ expect(mocks.capture).toHaveBeenCalledOnce();
+ expect(mocks.capture).toHaveBeenCalledWith("toast:shown", {
+ toastType: "CUSTOM",
+ source: "application",
+ operation: "dashboard.create",
+ hasErrorId: false,
+ });
+ expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(
+ "PRIVATE-CUSTOM-CONTENT",
+ );
+ });
+});
+
+// These invalid calls guard the TypeScript contract without invoking UI code.
+if (false) {
+ // @ts-expect-error analytics are mandatory for every native toast
+ showToast({ type: "SUCCESS", title: "Saved" });
+ showToast({
+ type: "SUCCESS",
+ title: "Saved",
+ // @ts-expect-error success operations must be registered static IDs
+ analytics: { operation: "resource.dynamic" },
+ });
+ // @ts-expect-error errors require both origin and category
+ showToast({
+ type: "ERROR",
+ title: "Failed",
+ analytics: { operation: "dashboard.create", errorOrigin: "backend" },
+ });
+ // @ts-expect-error custom rendering requires metadata too
+ showCustomToast(() => "Rendered");
+}
diff --git a/web/src/features/notifications/showToast.tsx b/web/src/features/notifications/showToast.tsx
new file mode 100644
index 0000000000..6fb52e5285
--- /dev/null
+++ b/web/src/features/notifications/showToast.tsx
@@ -0,0 +1,90 @@
+import { toast, type ExternalToast } from "sonner";
+import { useRef, type ReactNode } from "react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
+import {
+ getToastErrorProperties,
+ type ToastErrorAnalytics,
+ type ToastOperation,
+ type ToastShownEventProperties,
+} from "./toastAnalytics";
+
+/** Native Sonner presentation with the same mandatory metadata contract as custom cards. */
+export const showToast = (
+ params: ToastMetadata & { title: ReactNode },
+ options?: ExternalToast,
+) => {
+ const properties = getProperties(params);
+ const content = (
+ <ToastContent
+ key={`${properties.toastType}:${properties.operation}`}
+ properties={properties}
+ >
+ {params.title}
+ </ToastContent>
+ );
+ const show = {
+ ERROR: toast.error,
+ WARNING: toast.warning,
+ SUCCESS: toast.success,
+ INFO: toast.info,
+ LOADING: toast.loading,
+ MESSAGE: toast.message,
+ CUSTOM: toast.message,
+ }[params.type];
+ return show(content, options);
+};
+
+/** Custom rendering must declare metadata too; dismissal does not create a new shown event. */
+export const showCustomToast = (
+ render: (id: string | number) => ReactNode,
+ metadata: ToastMetadata,
+ options?: ExternalToast,
+) =>
+ toast.custom(
+ (id) => (
+ <ToastContent
+ key={`${metadata.type}:${metadata.analytics.operation}`}
+ properties={getProperties(metadata)}
+ >
+ {render(id)}
+ </ToastContent>
+ ),
+ options,
+ );
+
+/** Captures on mount and guards rerenders and StrictMode reattachments. */
+const ToastContent = ({ children, properties }: ToastContentProps) => {
+ const capture = usePostHogClientCapture();
+ const captured = useRef(false);
+ const captureShown = (element: HTMLSpanElement | null) => {
+ if (!element || captured.current) return;
+ captured.current = true;
+ capture("toast:shown", properties);
+ };
+
+ return <span ref={captureShown}>{children}</span>;
+};
+
+function getProperties(metadata: ToastMetadata): ToastShownEventProperties {
+ if (metadata.type === "ERROR" || metadata.type === "WARNING") {
+ return getToastErrorProperties(metadata.analytics, metadata.type);
+ }
+ return {
+ toastType: metadata.type,
+ source: "application",
+ operation: metadata.analytics.operation,
+ hasErrorId: false,
+ };
+}
+
+type ToastContentProps = {
+ children: ReactNode;
+ properties: ToastShownEventProperties;
+};
+
+type ToastMetadata =
+ | { type: "ERROR" | "WARNING"; analytics: ToastErrorAnalytics }
+ | {
+ type: "SUCCESS" | "INFO" | "LOADING" | "MESSAGE" | "CUSTOM";
+ analytics: { operation: ToastOperation };
+ };
diff --git a/web/src/features/notifications/toastAnalytics.ts b/web/src/features/notifications/toastAnalytics.ts
index c27ca50faa..1215bfc678 100644
--- a/web/src/features/notifications/toastAnalytics.ts
+++ b/web/src/features/notifications/toastAnalytics.ts
@@ -1,6 +1,20 @@
+import type { AnyTRPCProcedure } from "@trpc/server";
+import type { TRPC_ERROR_CODE_KEY } from "@trpc/server/rpc";
+import type { AppRouter } from "@/src/server/api/root";
+import type { ApplicationToastOperation } from "./toastOperations";
+
+type ProcedurePaths<T> = {
+ [K in keyof T & string]: T[K] extends AnyTRPCProcedure
+ ? K
+ : `${K}.${ProcedurePaths<T[K]>}`;
+}[keyof T & string];
+
+export type TrpcToastOperation = ProcedurePaths<AppRouter["_def"]["record"]>;
+export type ToastOperation = ApplicationToastOperation | TrpcToastOperation;
+
type ToastSource = "application" | "trpc";
-type ToastErrorOrigin = "frontend" | "backend" | "network" | "unknown";
+type ToastErrorOrigin = "frontend" | "backend" | "network";
type ToastErrorCategory =
| "user_input"
@@ -9,36 +23,66 @@ type ToastErrorCategory =
| "rate_limit"
| "resource_limit"
| "transient"
- | "internal"
- | "unknown";
+ | "internal";
export type ToastErrorAnalytics = {
errorOrigin: ToastErrorOrigin;
errorCategory: ToastErrorCategory;
- operation?: string;
- trpcCode?: string;
+ operation: ToastOperation;
+ trpcCode?: TRPC_ERROR_CODE_KEY;
httpStatus?: number;
+ errorId?: string;
+ trpcPath?: TrpcToastOperation;
};
-export type ToastErrorEventProperties = ToastErrorAnalytics & {
+export type ToastErrorEventProperties = Omit<
+ ToastErrorAnalytics,
+ "trpcPath"
+> & {
toastType: "WARNING" | "ERROR";
source: ToastSource;
- path?: string;
+ path?: TrpcToastOperation;
hasErrorId: boolean;
+ isOperationFallback: boolean;
errorId?: string;
};
-type ToastSuccessEventProperties = {
- toastType: "SUCCESS";
+type ToastNonErrorEventProperties = {
+ toastType: "SUCCESS" | "INFO" | "LOADING" | "MESSAGE" | "CUSTOM";
source: "application";
- operation: string;
+ operation: ToastOperation;
hasErrorId: false;
};
export type ToastShownEventProperties =
| ToastErrorEventProperties
- | ToastSuccessEventProperties;
+ | ToastNonErrorEventProperties;
export type ToastInteractionEventProperties =
| Omit<ToastErrorEventProperties, "hasErrorId" | "errorId">
- | Omit<ToastSuccessEventProperties, "hasErrorId">;
+ | Omit<ToastNonErrorEventProperties, "hasErrorId">;
+
+/** Build from an allowlist: UI content and arbitrary caller fields never reach analytics. */
+export const getToastErrorProperties = (
+ analytics: ToastErrorAnalytics,
+ type: "WARNING" | "ERROR",
+ source: ToastSource = "application",
+ path = analytics.trpcPath,
+ errorId = analytics.errorId,
+): ToastErrorEventProperties => ({
+ toastType: type,
+ source,
+ operation: analytics.operation,
+ errorOrigin: analytics.errorOrigin,
+ errorCategory: analytics.errorCategory,
+ ...(path ? { path } : {}),
+ ...(analytics.trpcCode ? { trpcCode: analytics.trpcCode } : {}),
+ ...(analytics.httpStatus !== undefined
+ ? { httpStatus: analytics.httpStatus }
+ : {}),
+ hasErrorId: Boolean(errorId),
+ isOperationFallback:
+ analytics.operation === "query.execute" ||
+ analytics.operation === "mutation.execute",
+ ...(errorId ? { errorId } : {}),
+});
diff --git a/web/src/features/notifications/toastOperations.ts b/web/src/features/notifications/toastOperations.ts
new file mode 100644
index 0000000000..47ff21464d
--- /dev/null
+++ b/web/src/features/notifications/toastOperations.ts
@@ -0,0 +1,194 @@
+/** Static user intents only. Never register resource IDs, names, messages or URLs. */
+export const applicationToastOperations = [
+ "account.delete",
+ "account.display_name_update",
+ "account.revoke_sessions",
+ "account_view_mode.update",
+ "annotation_queue.load",
+ "annotation_queue.save",
+ "annotation_queue_assignment.remove",
+ "audit_log.export",
+ "automation.create",
+ "automation.delete",
+ "automation.update",
+ "background_migration.retry",
+ "billing_checkout.start",
+ "billing_discount.apply",
+ "billing_plan.change",
+ "billing_plan.keep",
+ "billing_portal.open",
+ "blob_storage.save",
+ "blob_storage.validate",
+ "correction.delete",
+ "dashboard.clone",
+ "dashboard.create",
+ "dashboard.delete",
+ "dashboard.import",
+ "dashboard.query",
+ "dashboard.update",
+ "dashboard_card.copy",
+ "dashboard_card.import",
+ "dashboard_card.paste",
+ "dashboard_chart.add",
+ "dashboard_filters.update",
+ "dashboard_home.update",
+ "dataset.add_observations",
+ "dataset.bulk_delete",
+ "dataset_annotation.navigate",
+ "dataset_item.prepare",
+ "dataset_item.stringify",
+ "dataset_item_media.upload",
+ "dataset_items.import",
+ "dataset_version_timestamp.copy",
+ "default_evaluation_model.update",
+ "evaluation.queue",
+ "evaluation_model.delete",
+ "evaluation_model.set",
+ "evaluation_model.update",
+ "evaluation_rule.create",
+ "evaluation_rule.update",
+ "evaluator.bulk_delete",
+ "evaluator.clone",
+ "evaluator.create",
+ "evaluator.delete",
+ "evaluator.navigate",
+ "evaluator.reactivate",
+ "evaluator.save",
+ "evaluator.test",
+ "evaluator.update",
+ "evaluator_backfill.estimate",
+ "evaluator_backfill.run",
+ "evaluator_code.format",
+ "evaluator_description.generate",
+ "evaluator_name.generate",
+ "evaluator_rule.attach",
+ "evaluator_rule.create",
+ "evaluator_rule.delete",
+ "evaluator_rule.detach",
+ "evaluator_rule.estimate_activation",
+ "evaluator_rule.status_update",
+ "evaluator_rule.update",
+ "evaluator_rule_name.generate",
+ "evaluator_saved_dialog.dismiss",
+ "evaluator_saved_dialog.finish",
+ "evaluator_variable.extract",
+ "experiment.create",
+ "experiment.trigger",
+ "export.queue",
+ "external_media_storage.delete",
+ "external_media_storage.save",
+ "external_media_storage.test",
+ "filter_ai.generate",
+ "gateway_configuration.save",
+ "in_app_agent_conversation.delete",
+ "in_app_agent_conversations.load",
+ "in_app_agent_feedback.save",
+ "in_app_agent_run.stop",
+ "json_schema.prettify",
+ "media.resolveExternalMedia",
+ "model.create",
+ "model.update",
+ "monitor.create",
+ "monitor.delete",
+ "monitor.pause",
+ "monitor.resume",
+ "monitor.status_update",
+ "monitor.update",
+ "monitor_title.generate",
+ "mutation.execute",
+ "observation.add_to_annotation_queue",
+ "observation.download",
+ "observation.parse",
+ "onboarding.complete",
+ "onboarding.continue",
+ "onboarding_prompt.copy",
+ "organization.delete",
+ "organization_feature_preview.update",
+ "organization_role.update",
+ "playground.execute",
+ "playground_schema.prettify",
+ "playground_tool.prettify",
+ "playground_window.add",
+ "playground_window.remove",
+ "project.transfer",
+ "project_api_key.create",
+ "project_default_model.update",
+ "project_role.update",
+ "prompt.copy",
+ "prompt.export",
+ "prompt_tags.update",
+ "query.execute",
+ "read_path.switch",
+ "remote_experiment.configure",
+ "remote_experiment.delete",
+ "remote_experiment.trigger",
+ "remote_experiment.update",
+ "saved_view.apply",
+ "saved_view.default_clear",
+ "saved_view.default_set",
+ "saved_view.permalink_copy",
+ "saved_view.permalink_generate",
+ "saved_view.update",
+ "score.bulk_delete",
+ "score.create",
+ "score.delete",
+ "score.update",
+ "score_category.create",
+ "session.add_to_annotation_queue",
+ "sharing.disable",
+ "sharing.enable",
+ "sharing.update",
+ "skill_draft.resume",
+ "skill_file.create",
+ "skill_file.move",
+ "skill_file.restore",
+ "skill_files.add",
+ "skill_folder.create",
+ "skill_folder.move",
+ "skill_labels.update",
+ "skill_tags.update",
+ "skill_version.create",
+ "skill_version.download",
+ "skills.import",
+ "slack.connect",
+ "slack.disconnect",
+ "slack.test_message_send",
+ "spend_alert.create",
+ "spend_alert.delete",
+ "spend_alert.update",
+ "sso.configure",
+ "sso.disable",
+ "sso.update",
+ "subscription.cancel",
+ "subscription.reactivate",
+ "support_attachment.upload",
+ "support_request.submit",
+ "topics.load",
+ "trace.add_to_annotation_queue",
+ "trace.bulk_delete",
+ "trace.delete",
+ "trace.download",
+ "trace.parse",
+ "trace_log.copy",
+ "user_feature_preview.update",
+ "verified_domain.add",
+ "verified_domain.remove",
+ "verified_domain.verify",
+ "web_callout.invoke",
+ "web_callout_endpoint.create",
+ "web_callout_endpoint.delete",
+ "web_callout_endpoint.update",
+ "webhook_secret.regenerate",
+ "widget.clone",
+ "widget.copy",
+ "widget.create",
+ "widget.delete",
+ "widget.download",
+ "widget.import",
+ "widget.paste",
+ "widget.update",
+ "widget.validate",
+] as const;
+
+export type ApplicationToastOperation =
+ (typeof applicationToastOperations)[number];
diff --git a/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx b/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx
index 56ec80d3bd..a77503051f 100644
--- a/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx
+++ b/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx
@@ -5,6 +5,7 @@ import { showErrorToast } from "@/src/features/notifications";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { getDemoCallbackRedirectPath } from "../lib/demoCallbackRedirect";
import {
getSurveySubmittedEvent,
@@ -80,6 +81,7 @@ export function ConnectedOnboardingSurvey() {
showErrorToast(
"Failed to finish onboarding",
error instanceof Error ? error.message : "Please try again.",
+ classifyTrpcToastError(error, "onboarding.complete"),
);
}
},
@@ -108,6 +110,11 @@ export function ConnectedOnboardingSurvey() {
showErrorToast(
"Failed to continue onboarding",
error instanceof Error ? error.message : "Please try again.",
+ {
+ operation: "onboarding.continue",
+ errorOrigin: "frontend",
+ errorCategory: "internal",
+ },
);
}
},
diff --git a/web/src/features/playground/page/components/CreateOrEditLLMSchemaDialog.tsx b/web/src/features/playground/page/components/CreateOrEditLLMSchemaDialog.tsx
index 0fef922552..0d2a409937 100644
--- a/web/src/features/playground/page/components/CreateOrEditLLMSchemaDialog.tsx
+++ b/web/src/features/playground/page/components/CreateOrEditLLMSchemaDialog.tsx
@@ -142,6 +142,11 @@ export const CreateOrEditLLMSchemaDialog: React.FC<
showErrorToast(
"Failed to prettify JSON",
"Please verify your input is valid JSON",
+ {
+ operation: "playground_schema.prettify",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
"WARNING",
);
}
diff --git a/web/src/features/playground/page/components/CreateOrEditLLMToolDialog.tsx b/web/src/features/playground/page/components/CreateOrEditLLMToolDialog.tsx
index d24005769d..0627e414ff 100644
--- a/web/src/features/playground/page/components/CreateOrEditLLMToolDialog.tsx
+++ b/web/src/features/playground/page/components/CreateOrEditLLMToolDialog.tsx
@@ -142,6 +142,11 @@ export const CreateOrEditLLMToolDialog: React.FC<CreateOrEditLLMToolDialog> = (
showErrorToast(
"Failed to prettify JSON",
"Please verify your input is valid JSON",
+ {
+ operation: "playground_tool.prettify",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
"WARNING",
);
}
diff --git a/web/src/features/playground/page/context/index.tsx b/web/src/features/playground/page/context/index.tsx
index 3474577fa8..11abd148ca 100644
--- a/web/src/features/playground/page/context/index.tsx
+++ b/web/src/features/playground/page/context/index.tsx
@@ -476,7 +476,11 @@ export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = ({
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : "An error occurred";
- showErrorToast("Error", errorMessage);
+ showErrorToast("Error", errorMessage, {
+ operation: "playground.execute",
+ errorOrigin: err instanceof TypeError ? "network" : "backend",
+ errorCategory: err instanceof TypeError ? "transient" : "internal",
+ });
} finally {
setIsStreaming(false);
}
diff --git a/web/src/features/playground/page/hooks/usePersistedWindowIds.ts b/web/src/features/playground/page/hooks/usePersistedWindowIds.ts
index 349c1ee58f..6c24ece7bf 100644
--- a/web/src/features/playground/page/hooks/usePersistedWindowIds.ts
+++ b/web/src/features/playground/page/hooks/usePersistedWindowIds.ts
@@ -8,7 +8,7 @@ import {
removeWindowState,
clearAllPlaygroundData,
} from "../storage/windowStorage";
-import { toast } from "sonner";
+import { showToast } from "@/src/features/notifications";
/**
* Hook to persist window IDs across page refreshes.
@@ -43,9 +43,15 @@ export function usePersistedWindowIds() {
return windowId;
}
if (windowIds.length >= MULTI_WINDOW_CONFIG.MAX_WINDOWS) {
- toast.error(
- `Maximum window limit of ${MULTI_WINDOW_CONFIG.MAX_WINDOWS} reached`,
- );
+ showToast({
+ type: "ERROR",
+ title: `Maximum window limit of ${MULTI_WINDOW_CONFIG.MAX_WINDOWS} reached`,
+ analytics: {
+ operation: "playground_window.add",
+ errorOrigin: "frontend",
+ errorCategory: "resource_limit",
+ },
+ });
return null;
}
setWindowIds((prev) => [...prev, windowId]);
@@ -62,9 +68,15 @@ export function usePersistedWindowIds() {
const addWindowWithCopy = useCallback(
(sourceWindowId?: string) => {
if (windowIds.length >= MULTI_WINDOW_CONFIG.MAX_WINDOWS) {
- toast.error(
- `Maximum window limit of ${MULTI_WINDOW_CONFIG.MAX_WINDOWS} reached`,
- );
+ showToast({
+ type: "ERROR",
+ title: `Maximum window limit of ${MULTI_WINDOW_CONFIG.MAX_WINDOWS} reached`,
+ analytics: {
+ operation: "playground_window.add",
+ errorOrigin: "frontend",
+ errorCategory: "resource_limit",
+ },
+ });
return null;
}
@@ -88,7 +100,15 @@ export function usePersistedWindowIds() {
const removeWindowId = useCallback(
(windowId: string) => {
if (windowIds.length <= 1) {
- toast.error("Cannot remove the last remaining window");
+ showToast({
+ type: "ERROR",
+ title: "Cannot remove the last remaining window",
+ analytics: {
+ operation: "playground_window.remove",
+ errorOrigin: "frontend",
+ errorCategory: "product_state",
+ },
+ });
return;
}
diff --git a/web/src/features/playground/page/hooks/useWindowCoordination.ts b/web/src/features/playground/page/hooks/useWindowCoordination.ts
index ba5a8a7ef3..e6f121666a 100644
--- a/web/src/features/playground/page/hooks/useWindowCoordination.ts
+++ b/web/src/features/playground/page/hooks/useWindowCoordination.ts
@@ -143,6 +143,11 @@ export const useWindowCoordination = (): WindowCoordinationReturn => {
showErrorToast(
"No content to execute",
"Please add at least one message with content to any window.",
+ {
+ operation: "playground.execute",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
setIsExecutingAll(false);
} else {
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 795c9e74fd..3412b50b49 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -524,8 +524,9 @@ export const usePostHogClientCapture = () => {
return useCallback(
function capture<E extends EventName>(
eventName: E,
- properties?: EventProperties[E],
- options?: CaptureOptions,
+ ...[properties, options]: E extends keyof ToastEventMap
+ ? [properties: EventProperties[E], options?: CaptureOptions]
+ : [properties?: EventProperties[E], options?: CaptureOptions]
): CaptureResult | void {
return posthog.capture(eventName, properties, options);
},
diff --git a/web/src/features/prompts/PromptsPage.tsx b/web/src/features/prompts/PromptsPage.tsx
index 245446884d..2e5db462ab 100644
--- a/web/src/features/prompts/PromptsPage.tsx
+++ b/web/src/features/prompts/PromptsPage.tsx
@@ -16,7 +16,8 @@ import { ImportPromptsButtonDialogController } from "@/src/features/prompts/comp
import { Button } from "@/src/components/ui/button";
import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
-import { toast } from "sonner";
+import { showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
export default function PromptsPage() {
const router = useRouter();
@@ -73,8 +74,12 @@ export default function PromptsPage() {
a.click();
URL.revokeObjectURL(url);
capture("prompts:bulk_export", { mode });
- } catch {
- toast.error("Failed to export prompts. Please try again.");
+ } catch (error) {
+ showToast({
+ type: "ERROR",
+ title: "Failed to export prompts. Please try again.",
+ analytics: classifyTrpcToastError(error, "prompt.export"),
+ });
} finally {
setIsExporting(false);
}
diff --git a/web/src/features/scores/components/AddScoreCategoryDialog.tsx b/web/src/features/scores/components/AddScoreCategoryDialog.tsx
index f7d9444d3e..b52662438c 100644
--- a/web/src/features/scores/components/AddScoreCategoryDialog.tsx
+++ b/web/src/features/scores/components/AddScoreCategoryDialog.tsx
@@ -1,5 +1,4 @@
import { useState } from "react";
-import { toast } from "sonner";
import { isPresent, type ScoreConfigDomain } from "@langfuse/shared";
import { Button } from "@/src/components/ui/button";
import {
@@ -17,6 +16,8 @@ import { api } from "@/src/utils/api";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { validateNewCategoryLabel } from "@/src/features/scores/lib/annotationFormHelpers";
import { type AnnotationAnalyticsContext } from "@/src/features/scores/lib/annotationAnalytics";
+import { showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
export function AddScoreCategoryDialog({
projectId,
@@ -57,7 +58,11 @@ export function AddScoreCategoryDialog({
onClose();
},
onError: (error) => {
- toast.error(error.message ?? "Failed to add category");
+ showToast({
+ type: "ERROR",
+ title: error.message ?? "Failed to add category",
+ analytics: classifyTrpcToastError(error, "score_category.create"),
+ });
},
});
diff --git a/web/src/features/scores/hooks/useScoreMutations.ts b/web/src/features/scores/hooks/useScoreMutations.ts
index a5f18f9ece..3fd57040e7 100644
--- a/web/src/features/scores/hooks/useScoreMutations.ts
+++ b/web/src/features/scores/hooks/useScoreMutations.ts
@@ -5,6 +5,7 @@ import {
} from "@/src/features/scores/lib/helpers";
import { useScoreCache } from "@/src/features/scores/contexts/ScoreCacheContext";
import { showErrorToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
export function useScoreMutations() {
const {
@@ -55,7 +56,12 @@ export function useScoreMutations() {
if (!variables.id) return;
// Rollback failed create from cache
cacheRollbackSet(variables.id);
- showErrorToast("Failed to create score", err.message, "WARNING");
+ showErrorToast(
+ "Failed to create score",
+ err.message,
+ classifyTrpcToastError(err, "score.create"),
+ "WARNING",
+ );
},
});
@@ -105,7 +111,12 @@ export function useScoreMutations() {
// No cache entry → was DB-persisted → rollback optimistic update
cacheRollbackSet(variables.id);
}
- showErrorToast("Failed to update score", err.message, "WARNING");
+ showErrorToast(
+ "Failed to update score",
+ err.message,
+ classifyTrpcToastError(err, "score.update"),
+ "WARNING",
+ );
},
});
@@ -122,7 +133,12 @@ export function useScoreMutations() {
onError: (err, variables, context) => {
// Rollback
cacheRollbackDelete(variables.id, context?.previousCacheValue);
- showErrorToast("Failed to delete score", err.message, "WARNING");
+ showErrorToast(
+ "Failed to delete score",
+ err.message,
+ classifyTrpcToastError(err, "score.delete"),
+ "WARNING",
+ );
},
});
diff --git a/web/src/features/search-bar/components/SearchBarAiPrompt.tsx b/web/src/features/search-bar/components/SearchBarAiPrompt.tsx
index 403c7eeae1..d67dd31505 100644
--- a/web/src/features/search-bar/components/SearchBarAiPrompt.tsx
+++ b/web/src/features/search-bar/components/SearchBarAiPrompt.tsx
@@ -194,6 +194,11 @@ export function SearchBarAiPrompt({
showErrorToast(
"Score filter skipped",
unknownScoresMessage(result.unknownScoreNames),
+ {
+ operation: "filter_ai.generate",
+ errorOrigin: "backend",
+ errorCategory: "user_input",
+ },
"WARNING",
);
}
diff --git a/web/src/features/sessions/SessionObservationIO.tsx b/web/src/features/sessions/SessionObservationIO.tsx
index 9d04d17ddd..eb9c5e900d 100644
--- a/web/src/features/sessions/SessionObservationIO.tsx
+++ b/web/src/features/sessions/SessionObservationIO.tsx
@@ -15,6 +15,7 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { compactNumberFormatter } from "@/src/utils/numbers";
import { decodeUnicodeEscapesOnly } from "@/src/utils/unicode";
import { parseJsonIfString } from "@langfuse/shared";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
export type SessionTraceObservation =
RouterOutputs["sessions"]["observationsForTraceFromEvents"][number];
@@ -164,10 +165,11 @@ export const SessionObservationIO = ({
},
fileName: `observation-${observation.id}.json`,
});
- } catch {
+ } catch (error) {
showErrorToast(
"Download failed",
"Could not fetch the observation's full I/O. Please try again.",
+ classifyTrpcToastError(error, "observation.download"),
);
} finally {
setIsDownloading(false);
diff --git a/web/src/features/setup/components/TracesSetupOnboardingCard.tsx b/web/src/features/setup/components/TracesSetupOnboardingCard.tsx
index 5b217f8026..7c5b1a9234 100644
--- a/web/src/features/setup/components/TracesSetupOnboardingCard.tsx
+++ b/web/src/features/setup/components/TracesSetupOnboardingCard.tsx
@@ -12,7 +12,8 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { Check, Copy, LockIcon, Sparkles } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
-import { toast } from "sonner";
+import { showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
const SKILLS_INSTALL_COMMAND =
"Install the Langfuse AI skill from github.com/langfuse/skills and use it to add tracing to this application with Langfuse following best practices.";
@@ -35,7 +36,15 @@ function CopyableSnippet({
setCopied(true);
setTimeout(() => setCopied(false), 1000);
} catch {
- toast.error("Failed to copy to clipboard");
+ showToast({
+ type: "ERROR",
+ title: "Failed to copy to clipboard",
+ analytics: {
+ operation: "onboarding_prompt.copy",
+ errorOrigin: "frontend",
+ errorCategory: "internal",
+ },
+ });
}
};
@@ -90,7 +99,11 @@ export function TracesSetupOnboardingCard({
await mutCreateApiKey.mutateAsync({ projectId });
} catch (error) {
reportNonTrpcError(error, "setup");
- toast.error("Failed to create API key");
+ showToast({
+ type: "ERROR",
+ title: "Failed to create API key",
+ analytics: classifyTrpcToastError(error, "project_api_key.create"),
+ });
}
};
diff --git a/web/src/features/skills/components/SkillEditor.tsx b/web/src/features/skills/components/SkillEditor.tsx
index 90801a618d..eca3c0ffc8 100644
--- a/web/src/features/skills/components/SkillEditor.tsx
+++ b/web/src/features/skills/components/SkillEditor.tsx
@@ -46,6 +46,7 @@ import {
} from "@/src/features/skills/components/SkillFileExplorer";
import { importSkillFiles } from "@/src/features/skills/actions/importSkillFiles";
import { getParentFolderPaths } from "@/src/features/skills/components/skillFileTree";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { getSkillFileLanguageExtensions } from "@/src/features/skills/utils/getSkillFileLanguageExtensions";
import {
createSkillDraftFile,
@@ -239,6 +240,7 @@ export function SkillEditor({
showErrorToast(
"Failed to create skill version",
error instanceof Error ? error.message : "Please try again.",
+ classifyTrpcToastError(error, "skill_version.create"),
);
return false;
} finally {
@@ -283,6 +285,7 @@ export function SkillEditor({
showErrorToast(
"Failed to update skill labels",
error instanceof Error ? error.message : "Please try again.",
+ classifyTrpcToastError(error, "skill_labels.update"),
);
return false;
}
@@ -316,6 +319,7 @@ export function SkillEditor({
showErrorToast(
"Failed to update skill tags",
error instanceof Error ? error.message : "Please try again.",
+ classifyTrpcToastError(error, "skill_tags.update"),
);
return false;
}
@@ -333,10 +337,11 @@ export function SkillEditor({
getFileContents: (input) => utils.skills.fileContents.fetch(input),
});
capture("skills:version_download", { fileCount: result.fileCount });
- } catch {
+ } catch (error) {
showErrorToast(
"Download failed",
"Could not download this skill version. Please try again.",
+ classifyTrpcToastError(error, "skill_version.download"),
);
} finally {
setIsDownloading(false);
@@ -591,7 +596,11 @@ export function SkillEditor({
minSize={undefined}
isDisabled={isImporting}
onError={(error) => {
- showErrorToast("Could not add files", error.message);
+ showErrorToast("Could not add files", error.message, {
+ operation: "skill_files.add",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ });
uploadPanelRef.current?.focus();
}}
onDrop={async (files) => {
diff --git a/web/src/features/skills/components/SkillEditorPage.tsx b/web/src/features/skills/components/SkillEditorPage.tsx
index 5a06e0c2e2..d86bec8f8f 100644
--- a/web/src/features/skills/components/SkillEditorPage.tsx
+++ b/web/src/features/skills/components/SkillEditorPage.tsx
@@ -19,6 +19,7 @@ import {
import { parseSkillFrontmatterMetadata } from "@/src/features/skills/utils/parseSkillFrontmatterMetadata";
import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
export function NewSkillPage() {
const router = useRouter();
@@ -216,6 +217,7 @@ function ExistingSkillSession({
showErrorToast(
"Could not resume draft",
error instanceof Error ? error.message : "Please try again.",
+ classifyTrpcToastError(error, "skill_draft.resume"),
);
return;
}
diff --git a/web/src/features/skills/components/SkillFileExplorer.tsx b/web/src/features/skills/components/SkillFileExplorer.tsx
index 498477104d..3707a2ec67 100644
--- a/web/src/features/skills/components/SkillFileExplorer.tsx
+++ b/web/src/features/skills/components/SkillFileExplorer.tsx
@@ -132,6 +132,11 @@ export function SkillFileExplorer({
showErrorToast(
`Could not move ${isFolder ? "folder" : "file"}`,
"The destination conflicts with an existing file or folder, or the move is invalid.",
+ {
+ operation: isFolder ? "skill_folder.move" : "skill_file.move",
+ errorOrigin: "frontend",
+ errorCategory: "product_state",
+ },
);
return;
}
@@ -191,6 +196,14 @@ export function SkillFileExplorer({
pendingEntry.kind === "folder"
? "Use a single normalized path segment."
: validationMessage,
+ {
+ operation:
+ pendingEntry.kind === "folder"
+ ? "skill_folder.create"
+ : "skill_file.create",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
);
return;
}
@@ -199,6 +212,11 @@ export function SkillFileExplorer({
showErrorToast(
"Could not add file",
`A skill can contain at most ${MAX_SKILL_FILES} files.`,
+ {
+ operation: "skill_file.create",
+ errorOrigin: "frontend",
+ errorCategory: "resource_limit",
+ },
);
return;
}
@@ -211,6 +229,14 @@ export function SkillFileExplorer({
showErrorToast(
`${pendingEntry.kind === "folder" ? "Folder" : "File"} already exists`,
path,
+ {
+ operation:
+ pendingEntry.kind === "folder"
+ ? "skill_folder.create"
+ : "skill_file.create",
+ errorOrigin: "frontend",
+ errorCategory: "product_state",
+ },
);
return;
}
@@ -312,6 +338,11 @@ export function SkillFileExplorer({
showErrorToast(
"Could not restore file",
`A skill can contain at most ${MAX_SKILL_FILES} files. Delete another file before restoring this one.`,
+ {
+ operation: "skill_file.restore",
+ errorOrigin: "frontend",
+ errorCategory: "resource_limit",
+ },
);
}
}}
diff --git a/web/src/features/slack/components/SlackConnectButton.tsx b/web/src/features/slack/components/SlackConnectButton.tsx
index 3ed0236f5c..ccf8f8e0ee 100644
--- a/web/src/features/slack/components/SlackConnectButton.tsx
+++ b/web/src/features/slack/components/SlackConnectButton.tsx
@@ -80,7 +80,11 @@ export const SlackConnectButton: React.FC<SlackConnectButtonProps> = ({
if (!integrationStatus?.installUrl) {
const errorMessage = "Install URL not available. Please try again.";
onError?.(new Error(errorMessage));
- showErrorToast("Connection Failed", errorMessage);
+ showErrorToast("Connection Failed", errorMessage, {
+ operation: "slack.connect",
+ errorOrigin: "backend",
+ errorCategory: "product_state",
+ });
return;
}
@@ -132,7 +136,11 @@ export const SlackConnectButton: React.FC<SlackConnectButtonProps> = ({
popup.close();
setIsConnecting(false);
- showErrorToast("Connection Failed", event.data.error);
+ showErrorToast("Connection Failed", event.data.error, {
+ operation: "slack.connect",
+ errorOrigin: "backend",
+ errorCategory: "internal",
+ });
onError?.(new Error(event.data.error));
// Clean up event listener and interval
@@ -171,7 +179,11 @@ export const SlackConnectButton: React.FC<SlackConnectButtonProps> = ({
const errorMessage =
error instanceof Error ? error.message : "Failed to connect to Slack";
onError?.(new Error(errorMessage));
- showErrorToast("Connection Failed", errorMessage);
+ showErrorToast("Connection Failed", errorMessage, {
+ operation: "slack.connect",
+ errorOrigin: "frontend",
+ errorCategory: "product_state",
+ });
}
};
diff --git a/web/src/features/slack/components/SlackDisconnectButton.tsx b/web/src/features/slack/components/SlackDisconnectButton.tsx
index da7679a5c0..fade1e6520 100644
--- a/web/src/features/slack/components/SlackDisconnectButton.tsx
+++ b/web/src/features/slack/components/SlackDisconnectButton.tsx
@@ -14,6 +14,7 @@ import {
import { showSuccessToast, showErrorToast } from "@/src/features/notifications";
import { api, reportTrpcErrorWithoutToast } from "@/src/utils/api";
import { Spinner } from "@/src/components/design-system/Spinner/Spinner";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
/**
* Props for the SlackDisconnectButton component
@@ -103,7 +104,11 @@ export const SlackDisconnectButton: React.FC<SlackDisconnectButtonProps> = ({
const errorMessage = error.message || "Failed to disconnect from Slack";
- showErrorToast("Disconnection Failed", errorMessage);
+ showErrorToast(
+ "Disconnection Failed",
+ errorMessage,
+ classifyTrpcToastError(error, "slack.disconnect"),
+ );
onError?.(new Error(errorMessage));
},
diff --git a/web/src/features/slack/components/SlackTestMessageButton.tsx b/web/src/features/slack/components/SlackTestMessageButton.tsx
index fc8dcb4d04..501520e8ce 100644
--- a/web/src/features/slack/components/SlackTestMessageButton.tsx
+++ b/web/src/features/slack/components/SlackTestMessageButton.tsx
@@ -4,6 +4,7 @@ import { Zap } from "lucide-react";
import { api } from "@/src/utils/api";
import { showSuccessToast, showErrorToast } from "@/src/features/notifications";
import { type SlackChannel } from "./ChannelSelector";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
/**
* Props for the SlackTestMessageButton component
@@ -64,7 +65,11 @@ export const SlackTestMessageButton: React.FC<SlackTestMessageButtonProps> = ({
onSuccess?.(data.channelInfo);
},
onError: (error) => {
- showErrorToast("Failed to Send Test Message", error.message);
+ showErrorToast(
+ "Failed to Send Test Message",
+ error.message,
+ classifyTrpcToastError(error, "slack.test_message_send"),
+ );
onError?.(new Error(error.message));
},
});
diff --git a/web/src/features/support-chat/ConnectedSupportFormSection.tsx b/web/src/features/support-chat/ConnectedSupportFormSection.tsx
index 0b49a42311..f2cb093f5f 100644
--- a/web/src/features/support-chat/ConnectedSupportFormSection.tsx
+++ b/web/src/features/support-chat/ConnectedSupportFormSection.tsx
@@ -106,6 +106,11 @@ export function ConnectedSupportFormSection({
showErrorToast(
"Support request was not sent",
"Please contact [email protected]",
+ {
+ operation: "support_request.submit",
+ errorOrigin: "backend",
+ errorCategory: "internal",
+ },
);
return "kept";
}
@@ -131,7 +136,16 @@ export function ConnectedSupportFormSection({
onSuccess={onSuccess}
onSubmit={handleSubmit}
onFileError={(message) =>
- showErrorToast("File Upload Error", message, "WARNING")
+ showErrorToast(
+ "File Upload Error",
+ message,
+ {
+ operation: "support_attachment.upload",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
+ "WARNING",
+ )
}
/>
</div>
diff --git a/web/src/features/tag/components/TagPromptDetailsPopover.tsx b/web/src/features/tag/components/TagPromptDetailsPopover.tsx
index 127b8446c2..23b7ec9991 100644
--- a/web/src/features/tag/components/TagPromptDetailsPopover.tsx
+++ b/web/src/features/tag/components/TagPromptDetailsPopover.tsx
@@ -44,7 +44,7 @@ export function TagPromptDetailsPopover({
return { prev };
},
onError: (err, _newTags, context) => {
- trpcErrorToast(err);
+ trpcErrorToast(err, "prompt_tags.update");
// Rollback to the previous value if mutation fails
utils.prompts.allVersions.setData(allVersionsInput, context?.prev);
},
diff --git a/web/src/features/tag/components/TagPromptPopover.tsx b/web/src/features/tag/components/TagPromptPopover.tsx
index 1097e9486c..4c1396a646 100644
--- a/web/src/features/tag/components/TagPromptPopover.tsx
+++ b/web/src/features/tag/components/TagPromptPopover.tsx
@@ -36,7 +36,7 @@ export function TagPromptPopover({
},
onError: (err, _newTags, context) => {
utils.prompts.all.setData(promptsFilter, context?.prevPrompt);
- trpcErrorToast(err);
+ trpcErrorToast(err, "prompt_tags.update");
setIsLoading(false);
},
onSettled: (data, error, { name, tags }) => {
diff --git a/web/src/features/topics/CurrentTopics.tsx b/web/src/features/topics/CurrentTopics.tsx
index 844d185c95..217f238ca3 100644
--- a/web/src/features/topics/CurrentTopics.tsx
+++ b/web/src/features/topics/CurrentTopics.tsx
@@ -489,6 +489,7 @@ export function useCurrentTopics({
placeholderData: keepPreviousData,
refetchInterval: running ? 3000 : false,
enabled: isValidTopicTimeRange(timeRange),
+ meta: { toastOperation: "topics.load" },
});
}
diff --git a/web/src/features/traces/components/IOPreview/hooks/useCorrectionMutations.ts b/web/src/features/traces/components/IOPreview/hooks/useCorrectionMutations.ts
index fcee20ca97..0dddfc4903 100644
--- a/web/src/features/traces/components/IOPreview/hooks/useCorrectionMutations.ts
+++ b/web/src/features/traces/components/IOPreview/hooks/useCorrectionMutations.ts
@@ -2,8 +2,9 @@ import { useState, useCallback } from "react";
import { api } from "@/src/utils/api";
import { useCorrectionCache } from "@/src/features/corrections";
import { type ScoreDomain } from "@langfuse/shared";
-import { toast } from "sonner";
import { v4 } from "uuid";
+import { showToast } from "@/src/features/notifications";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
interface UseCorrectionMutationsParams {
projectId: string;
@@ -80,7 +81,11 @@ export function useCorrectionMutations({
return { previousValue, correctionId: effectiveCorrection.id };
},
onError: (error, _, context) => {
- toast.error("Failed to delete correction");
+ showToast({
+ type: "ERROR",
+ title: "Failed to delete correction",
+ analytics: classifyTrpcToastError(error, "correction.delete"),
+ });
// Rollback delete - restore to cache if we had a previous value
if (context?.correctionId) {
correctionCache.rollbackDelete(
diff --git a/web/src/features/traces/components/TraceLogView/useLogViewDownload.ts b/web/src/features/traces/components/TraceLogView/useLogViewDownload.ts
index 28e95221eb..11f8a8c804 100644
--- a/web/src/features/traces/components/TraceLogView/useLogViewDownload.ts
+++ b/web/src/features/traces/components/TraceLogView/useLogViewDownload.ts
@@ -7,10 +7,9 @@
*/
import { useState, useCallback } from "react";
-import { toast } from "sonner";
import { stringify } from "@langfuse/shared";
import { copyTextToClipboard } from "@/src/utils/clipboard";
-import { showSuccessToast } from "@/src/features/notifications";
+import { showSuccessToast, showToast } from "@/src/features/notifications";
import { type ObservationIOData } from "./useLogViewAllObservationsIO";
export interface UseLogViewDownloadParams {
@@ -69,9 +68,15 @@ export function useLogViewDownload({
copyTextToClipboard(stringify(allObservationsData, undefined, 2));
// Show warning if some observations failed to load
if (failedObservationIds.length > 0) {
- toast.warning(
- `Copied to clipboard. ${failedObservationIds.length} observation${failedObservationIds.length === 1 ? "" : "s"} failed to load and ${failedObservationIds.length === 1 ? "is" : "are"} missing I/O data.`,
- );
+ showToast({
+ type: "WARNING",
+ title: `Copied to clipboard. ${failedObservationIds.length} observation${failedObservationIds.length === 1 ? "" : "s"} failed to load and ${failedObservationIds.length === 1 ? "is" : "are"} missing I/O data.`,
+ analytics: {
+ operation: "trace_log.copy",
+ errorOrigin: "backend",
+ errorCategory: "transient",
+ },
+ });
} else {
showSuccessToast({
operation: "trace_log.copy",
@@ -86,9 +91,15 @@ export function useLogViewDownload({
copyTextToClipboard(stringify(data, undefined, 2));
// Check for failures after loading
if (failedObservationIds.length > 0) {
- toast.warning(
- `Copied to clipboard. ${failedObservationIds.length} observation${failedObservationIds.length === 1 ? "" : "s"} failed to load and ${failedObservationIds.length === 1 ? "is" : "are"} missing I/O data.`,
- );
+ showToast({
+ type: "WARNING",
+ title: `Copied to clipboard. ${failedObservationIds.length} observation${failedObservationIds.length === 1 ? "" : "s"} failed to load and ${failedObservationIds.length === 1 ? "is" : "are"} missing I/O data.`,
+ analytics: {
+ operation: "trace_log.copy",
+ errorOrigin: "backend",
+ errorCategory: "transient",
+ },
+ });
} else {
showSuccessToast({
operation: "trace_log.copy",
diff --git a/web/src/features/traces/hooks/useDownloadTraceAsJson.ts b/web/src/features/traces/hooks/useDownloadTraceAsJson.ts
index 9c6084d7c1..1e3dad1e4c 100644
--- a/web/src/features/traces/hooks/useDownloadTraceAsJson.ts
+++ b/web/src/features/traces/hooks/useDownloadTraceAsJson.ts
@@ -1,9 +1,9 @@
import { useMemo } from "react";
-import { toast } from "sonner";
import { StringParam, useQueryParam } from "use-query-params";
import { useReadPath } from "@/src/features/events";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
+import { showToast } from "@/src/features/notifications";
import { TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD } from "@/src/features/traces/constants/traceDownloadConfig";
import {
downloadLegacyTraceAsJson,
@@ -60,16 +60,29 @@ export function useDownloadTraceAsJson({
});
if (observations.length >= TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD) {
- toast.warning(
- `Trace download excludes IO, metadata, toolDefinitions, and toolCalls for traces with ${TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD}+ observations.`,
- );
+ showToast({
+ type: "WARNING",
+ title: `Trace download excludes IO, metadata, toolDefinitions, and toolCalls for traces with ${TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD}+ observations.`,
+ analytics: {
+ operation: "trace.download",
+ errorOrigin: "frontend",
+ errorCategory: "resource_limit",
+ },
+ });
}
} catch (error) {
- toast.error(
- error instanceof Error
- ? error.message
- : "Failed to download trace JSON",
- );
+ showToast({
+ type: "ERROR",
+ title:
+ error instanceof Error
+ ? error.message
+ : "Failed to download trace JSON",
+ analytics: {
+ operation: "trace.download",
+ errorOrigin: isV4 ? "network" : "frontend",
+ errorCategory: isV4 ? "transient" : "internal",
+ },
+ });
}
}, [isV4, observations, trace, capture, traceContext]);
}
diff --git a/web/src/features/traces/hooks/useParsedObservation.ts b/web/src/features/traces/hooks/useParsedObservation.ts
index 11ed9b1a79..e7fcf2d74c 100644
--- a/web/src/features/traces/hooks/useParsedObservation.ts
+++ b/web/src/features/traces/hooks/useParsedObservation.ts
@@ -160,6 +160,7 @@ export function useParsedObservation({
enabled: !!mergedObservation, // Only run when we have data
staleTime: Infinity, // Parsed data never goes stale (input data is the source of truth)
gcTime: 10 * 60 * 1000, // Keep in cache for 10 minutes after unmount
+ meta: { toastOperation: "observation.parse" },
});
return {
diff --git a/web/src/features/v4-migration/V4MigrationContent.tsx b/web/src/features/v4-migration/V4MigrationContent.tsx
index 1129815229..ed02c75d8e 100644
--- a/web/src/features/v4-migration/V4MigrationContent.tsx
+++ b/web/src/features/v4-migration/V4MigrationContent.tsx
@@ -57,6 +57,7 @@ import {
} from "@/src/features/v4-migration/useV4UpgradeAssistantSupport";
import { useHasProjectAccess } from "@/src/features/rbac";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { encodeFiltersGeneric, type FilterState } from "@langfuse/shared";
import { EvaluatorMigrationDialog } from "@/src/features/v4-migration/EvaluatorMigrationDialog";
import { buildDeprecatedRulesUrl } from "@/src/features/v4-migration/evaluatorMigrationUrls";
@@ -1393,6 +1394,7 @@ export function V4MigrationAgentUpgradeSection({
showErrorToast(
"Could not create API keys",
"Something went wrong. Please try again.",
+ classifyTrpcToastError(error, "project_api_key.create"),
);
});
};
diff --git a/web/src/features/web-callouts/components/WebCalloutMenuItem.tsx b/web/src/features/web-callouts/components/WebCalloutMenuItem.tsx
index 5ccdbfb734..c7126cc7b4 100644
--- a/web/src/features/web-callouts/components/WebCalloutMenuItem.tsx
+++ b/web/src/features/web-callouts/components/WebCalloutMenuItem.tsx
@@ -8,6 +8,7 @@ import {
} from "@/src/components/ui/tooltip";
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
type WebCalloutTarget = {
projectId: string;
@@ -36,7 +37,11 @@ export function useWebCalloutAction(props: WebCalloutTarget, enabled: boolean) {
});
},
onError: (error) => {
- showErrorToast("Web callout failed", error.message);
+ showErrorToast(
+ "Web callout failed",
+ error.message,
+ classifyTrpcToastError(error, "web_callout.invoke"),
+ );
},
});
diff --git a/web/src/features/web-callouts/components/WebCalloutSettingsPage.tsx b/web/src/features/web-callouts/components/WebCalloutSettingsPage.tsx
index 4c5c76d1c4..908f04c0d3 100644
--- a/web/src/features/web-callouts/components/WebCalloutSettingsPage.tsx
+++ b/web/src/features/web-callouts/components/WebCalloutSettingsPage.tsx
@@ -40,6 +40,7 @@ import {
WEB_CALLOUT_HEADER_NAME_PATTERN,
} from "@/src/features/web-callouts/headerRules";
import { api, type RouterOutputs } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { ConnectedWebCalloutSettingsTable } from "./WebCalloutSettingsTable/ConnectedWebCalloutSettingsTable";
type WebCalloutEndpoint = RouterOutputs["webCallouts"]["all"][number];
@@ -187,7 +188,16 @@ function WebCalloutEndpointDialog(props: {
props.closeDialog();
},
onError: (error) => {
- showErrorToast("Failed to save callout endpoint", error.message);
+ showErrorToast(
+ "Failed to save callout endpoint",
+ error.message,
+ classifyTrpcToastError(
+ error,
+ props.endpoint
+ ? "web_callout_endpoint.update"
+ : "web_callout_endpoint.create",
+ ),
+ );
},
});
diff --git a/web/src/features/web-callouts/components/WebCalloutSettingsTable/ConnectedWebCalloutSettingsTable.tsx b/web/src/features/web-callouts/components/WebCalloutSettingsTable/ConnectedWebCalloutSettingsTable.tsx
index 31278b5326..78d880ee9b 100644
--- a/web/src/features/web-callouts/components/WebCalloutSettingsTable/ConnectedWebCalloutSettingsTable.tsx
+++ b/web/src/features/web-callouts/components/WebCalloutSettingsTable/ConnectedWebCalloutSettingsTable.tsx
@@ -4,6 +4,7 @@ import { ConfirmationDialogController } from "@/src/components/design-system/Con
import { type AsyncTableData } from "@/src/components/design-system/table/Table";
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import {
WebCalloutSettingsTable,
type WebCalloutEndpoint,
@@ -30,7 +31,11 @@ export function ConnectedWebCalloutSettingsTable({
});
},
onError: (error) => {
- showErrorToast("Failed to delete callout endpoint", error.message);
+ showErrorToast(
+ "Failed to delete callout endpoint",
+ error.message,
+ classifyTrpcToastError(error, "web_callout_endpoint.delete"),
+ );
},
});
diff --git a/web/src/features/widgets/EditWidgetPage.tsx b/web/src/features/widgets/EditWidgetPage.tsx
index 424131653c..01abe4477a 100644
--- a/web/src/features/widgets/EditWidgetPage.tsx
+++ b/web/src/features/widgets/EditWidgetPage.tsx
@@ -8,6 +8,7 @@ import { type metricAggregations, type views } from "@langfuse/shared/query";
import { type z } from "zod";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { useReadPath } from "@/src/features/events";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
export default function EditWidgetPage() {
const router = useRouter();
@@ -64,7 +65,11 @@ export default function EditWidgetPage() {
}
},
onError: (error) => {
- showErrorToast("Failed to update widget", error.message);
+ showErrorToast(
+ "Failed to update widget",
+ error.message,
+ classifyTrpcToastError(error, "widget.update"),
+ );
},
});
diff --git a/web/src/features/widgets/NewWidgetPage.tsx b/web/src/features/widgets/NewWidgetPage.tsx
index 82a0099389..15eeb36180 100644
--- a/web/src/features/widgets/NewWidgetPage.tsx
+++ b/web/src/features/widgets/NewWidgetPage.tsx
@@ -12,6 +12,7 @@ import { useReadPath } from "@/src/features/events";
import { getDefaultView } from "@/src/features/widgets/utils";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import {
asSingleQueryParam,
RouteParamsPendingFallback,
@@ -80,13 +81,21 @@ function NewWidgetView({ projectId }: { projectId: string }) {
}
},
onError: (error) => {
- showErrorToast("Failed to save widget", error.message);
+ showErrorToast(
+ "Failed to save widget",
+ error.message,
+ classifyTrpcToastError(error, "widget.create"),
+ );
},
});
const handleSaveWidget = (widgetData: WidgetSavePayload) => {
if (!widgetData.name.trim()) {
- showErrorToast("Error", "Widget name is required");
+ showErrorToast("Error", "Widget name is required", {
+ operation: "widget.create",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ });
return;
}
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index 6913896f28..ac6b058802 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -2,6 +2,7 @@
import { showErrorToast, showSuccessToast } from "@/src/features/notifications";
import { useCallback, useEffect, useMemo, useState } from "react";
import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import {
buildWidgetOrderBy,
getResultUnit,
@@ -523,7 +524,11 @@ export function DashboardWidget({
});
},
onError: (e) => {
- showErrorToast("Failed to clone widget", e.message);
+ showErrorToast(
+ "Failed to clone widget",
+ e.message,
+ classifyTrpcToastError(e, "widget.clone"),
+ );
},
});
const handleCopy = () => {
@@ -596,7 +601,11 @@ export function DashboardWidget({
description: "Paste it on any dashboard with Cmd/Ctrl+V.",
});
} catch {
- showErrorToast("Copy failed", "Could not write to the clipboard.");
+ showErrorToast("Copy failed", "Could not write to the clipboard.", {
+ operation: "widget.copy",
+ errorOrigin: "frontend",
+ errorCategory: "permission",
+ });
}
};
diff --git a/web/src/features/widgets/components/PresetDashboardWidget.tsx b/web/src/features/widgets/components/PresetDashboardWidget.tsx
index 74602da4ee..f4ebf53d77 100644
--- a/web/src/features/widgets/components/PresetDashboardWidget.tsx
+++ b/web/src/features/widgets/components/PresetDashboardWidget.tsx
@@ -213,7 +213,11 @@ export function PresetDashboardWidget({
description: "Paste it on any dashboard with Cmd/Ctrl+V.",
});
} catch {
- showErrorToast("Copy failed", "Could not write to the clipboard.");
+ showErrorToast("Copy failed", "Could not write to the clipboard.", {
+ operation: "dashboard_card.copy",
+ errorOrigin: "frontend",
+ errorCategory: "permission",
+ });
}
};
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index 07240adfb3..2bd7bcf2ff 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -835,7 +835,11 @@ export function WidgetForm({
const onSubmit = form.handleSubmit((submitted) => {
if (!queryValidation.valid) {
- showErrorToast("Invalid query", queryValidation.reason);
+ showErrorToast("Invalid query", queryValidation.reason, {
+ operation: "widget.validate",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ });
return;
}
const s = deriveWidgetSuggestions(submitted);
diff --git a/web/src/features/widgets/components/WidgetImporter.clienttest.tsx b/web/src/features/widgets/components/WidgetImporter.clienttest.tsx
index 261e76ed2e..e2eed852b3 100644
--- a/web/src/features/widgets/components/WidgetImporter.clienttest.tsx
+++ b/web/src/features/widgets/components/WidgetImporter.clienttest.tsx
@@ -78,6 +78,11 @@ describe("runImport", () => {
expect(showErrorToast).toHaveBeenCalledWith(
"Malformed input",
expect.any(String),
+ {
+ operation: "widget.import",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
"WARNING",
);
});
@@ -106,6 +111,11 @@ describe("runImport", () => {
expect(showErrorToast).toHaveBeenCalledWith(
"Widget filters were adjusted",
expect.any(String),
+ {
+ operation: "widget.import",
+ errorOrigin: "frontend",
+ errorCategory: "product_state",
+ },
"WARNING",
);
});
diff --git a/web/src/features/widgets/components/WidgetImporter.tsx b/web/src/features/widgets/components/WidgetImporter.tsx
index f1e387381a..5fb3f832f9 100644
--- a/web/src/features/widgets/components/WidgetImporter.tsx
+++ b/web/src/features/widgets/components/WidgetImporter.tsx
@@ -197,6 +197,11 @@ async function runImport(params: {
showErrorToast(
"Widget filters were adjusted",
"Some imported filters or filter values were removed because they are not available in this project.",
+ {
+ operation: "widget.import",
+ errorOrigin: "frontend",
+ errorCategory: "product_state",
+ },
"WARNING",
);
}
@@ -204,6 +209,11 @@ async function runImport(params: {
showErrorToast(
"Malformed input",
"This operation can't be done due to the malformed input",
+ {
+ operation: "widget.import",
+ errorOrigin: "frontend",
+ errorCategory: "user_input",
+ },
"WARNING",
);
}
diff --git a/web/src/features/widgets/components/WidgetTable/ConnectedWidgetTable.tsx b/web/src/features/widgets/components/WidgetTable/ConnectedWidgetTable.tsx
index bb092c1e04..f407d427dc 100644
--- a/web/src/features/widgets/components/WidgetTable/ConnectedWidgetTable.tsx
+++ b/web/src/features/widgets/components/WidgetTable/ConnectedWidgetTable.tsx
@@ -21,6 +21,7 @@ import { type z } from "zod";
import { PaginationBar } from "@/src/components/design-system/PaginationBar/PaginationBar";
import { type AsyncTableData } from "@/src/components/design-system/table/Table";
import { assertUnreachable } from "@/src/utils/types";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { DashboardWidgetTable, type WidgetTableRow } from "./WidgetTable";
export function ConnectedDashboardWidgetTable() {
@@ -40,11 +41,16 @@ export function ConnectedDashboardWidgetTable() {
showErrorToast(
"Widget in use",
"Widget is still in use. Please remove it from all dashboards before deleting it.",
+ classifyTrpcToastError(error, "widget.delete"),
);
return;
}
- showErrorToast("Failed to delete widget", error.message);
+ showErrorToast(
+ "Failed to delete widget",
+ error.message,
+ classifyTrpcToastError(error, "widget.delete"),
+ );
},
});
@@ -131,6 +137,7 @@ function ConnectedDashboardWidgetTableContent({
showErrorToast(
"Failed to download widget",
error instanceof Error ? error.message : "Unknown error",
+ classifyTrpcToastError(error, "widget.download"),
);
}
},
@@ -139,8 +146,10 @@ function ConnectedDashboardWidgetTableContent({
const handleCopyToClipboard = useCallback(
async (widgetId: string) => {
+ let failurePhase: "trpc" | "clipboard" = "trpc";
try {
const exportSource = await fetchExportSource(widgetId);
+ failurePhase = "clipboard";
await copyTextToClipboard(
JSON.stringify(buildWidgetExport(exportSource), null, 2),
);
@@ -158,6 +167,13 @@ function ConnectedDashboardWidgetTableContent({
showErrorToast(
"Failed to copy widget",
error instanceof Error ? error.message : "Unknown error",
+ failurePhase === "trpc"
+ ? classifyTrpcToastError(error, "widget.copy")
+ : {
+ operation: "widget.copy",
+ errorOrigin: "frontend",
+ errorCategory: "permission",
+ },
);
}
},
@@ -191,6 +207,7 @@ function ConnectedDashboardWidgetTableContent({
showErrorToast(
"Failed to duplicate widget",
error instanceof Error ? error.message : "Unknown error",
+ classifyTrpcToastError(error, "widget.clone"),
);
}
},
diff --git a/web/src/hooks/useParsedTrace.ts b/web/src/hooks/useParsedTrace.ts
index 2e724ed252..af002f9468 100644
--- a/web/src/hooks/useParsedTrace.ts
+++ b/web/src/hooks/useParsedTrace.ts
@@ -52,6 +52,7 @@ export function useParsedTrace({
enabled: !!(input || output || metadata), // Only run if we have data
staleTime: Infinity, // Parsed data never goes stale (input data is the source of truth)
gcTime: 10 * 60 * 1000, // Keep in cache for 10 minutes after unmount
+ meta: { toastOperation: "trace.parse" },
});
return {
diff --git a/web/src/utils/api.clienttest.ts b/web/src/utils/api.clienttest.ts
index 27e6d79b5e..dc48fdbcda 100644
--- a/web/src/utils/api.clienttest.ts
+++ b/web/src/utils/api.clienttest.ts
@@ -1,11 +1,14 @@
// @vitest-environment node
import { TRPCClientError } from "@trpc/client";
+import { observable } from "@trpc/server/observable";
import { vi } from "vitest";
+import type { AppRouter } from "@/src/server/api/root";
import {
EXPECTED_TRPC_BAD_REQUEST_PATHS,
EXPECTED_TRPC_CONFLICT_PATHS,
EXPECTED_TRPC_ERROR_CODES,
+ buildIdLink,
captureBuildId,
fetchWithParseErrorStatus,
getApproxTrpcGetUrlBytes,
@@ -21,6 +24,7 @@ import {
reportTrpcErrorWithoutToast,
shouldSendQueryAsPost,
} from "@/src/utils/api";
+import { getTrpcToastOperation } from "@/src/utils/trpcToastOperation";
const {
captureExceptionMock,
@@ -92,6 +96,41 @@ const ZOD4_TOO_SMALL_MESSAGE = JSON.stringify([
},
]);
+describe("buildIdLink toast operation context", () => {
+ it("records the typed request path before forwarding a transport error", async () => {
+ const requestError = new TypeError("Failed to fetch");
+ const execute = buildIdLink()({} as never);
+ const result = execute({
+ op: {
+ id: 1,
+ type: "query",
+ path: "projects.create",
+ input: undefined,
+ context: {},
+ signal: undefined,
+ },
+ next: () =>
+ observable((observer) => {
+ // Exercise the defensive runtime seam even though compliant tRPC
+ // links normally wrap transport failures in TRPCClientError.
+ observer.error(requestError as unknown as TRPCClientError<AppRouter>);
+ }),
+ });
+
+ await new Promise<void>((resolve, reject) => {
+ result.subscribe({
+ next: () => reject(new Error("expected request to fail")),
+ error: (error) => {
+ expect(error).toBe(requestError);
+ expect(getTrpcToastOperation(error)).toBe("projects.create");
+ resolve();
+ },
+ complete: () => reject(new Error("expected request to fail")),
+ });
+ });
+ });
+});
+
describe("isNetworkConnectivityError", () => {
it("detects the reported failed fetch error without a response", () => {
const error = TRPCClientError.from(new TypeError("Failed to fetch"));
diff --git a/web/src/utils/api.ts b/web/src/utils/api.ts
index 9db45d7dd3..c17c916873 100644
--- a/web/src/utils/api.ts
+++ b/web/src/utils/api.ts
@@ -22,12 +22,21 @@ import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";
import { observable } from "@trpc/server/observable";
import superjson from "superjson";
import { env } from "@/src/env.mjs";
+import type {
+ ToastOperation,
+ TrpcToastOperation,
+} from "@/src/features/notifications/toastAnalytics";
import { versionUpdateStore } from "@/src/features/version-update/versionUpdateStore";
import { type AppRouter } from "@/src/server/api/root";
import { reportError } from "@/src/utils/reportError";
import { setUpSuperjson } from "@/src/utils/superjson";
import { EXPECTED_TRPC_BAD_REQUEST_PATHS } from "@/src/utils/trpcErrorClassification";
import { trpcErrorToast } from "@/src/utils/trpcErrorToast";
+import {
+ createToastOperationMutationCache,
+ rememberTrpcToastOperation,
+ resolveToastOperation,
+} from "@/src/utils/trpcToastOperation";
import { isTrpcZodValidationError } from "@/src/utils/trpcValidationError";
export { isTrpcZodValidationError } from "@/src/utils/trpcValidationError";
@@ -415,7 +424,11 @@ const shouldShowToast = (error: unknown): boolean => {
return true;
};
-const handleTrpcError = (error: unknown, shouldSilenceError = false) => {
+const handleTrpcError = (
+ error: unknown,
+ operation: ToastOperation,
+ shouldSilenceError = false,
+) => {
if (error instanceof TRPCClientError) {
const httpStatus: number =
typeof error.data?.httpStatus === "number" ? error.data.httpStatus : 500;
@@ -487,7 +500,7 @@ const handleTrpcError = (error: unknown, shouldSilenceError = false) => {
}
if (!shouldSilenceError && shouldShowToast(error)) {
- trpcErrorToast(error);
+ trpcErrorToast(error, operation);
}
};
@@ -525,7 +538,11 @@ export const reportTrpcErrorWithoutToast = (
area: string,
): void => {
if (error instanceof TRPCClientError) {
- handleTrpcError(error, true);
+ handleTrpcError(
+ error,
+ resolveToastOperation(error, undefined, "mutation.execute"),
+ true,
+ );
return;
}
reportError(error, { area });
@@ -545,7 +562,7 @@ export const captureBuildId = (response: unknown) => {
};
// Track the build id serving tRPC responses to compare against the running one.
-const buildIdLink = (): TRPCLink<AppRouter> => () => {
+export const buildIdLink = (): TRPCLink<AppRouter> => () => {
return ({ next, op }) => {
return observable((observer) => {
const unsubscribe = next(op).subscribe({
@@ -557,6 +574,10 @@ const buildIdLink = (): TRPCLink<AppRouter> => () => {
captureBuildId(
err.meta && err.meta.response ? err.meta.response : undefined,
);
+ // `op.path` comes from the typed AppRouter operation, not from the
+ // response body. Record it before React Query and local handlers see
+ // the error so transport and pathless failures retain their origin.
+ rememberTrpcToastOperation(err, op.path as TrpcToastOperation);
observer.error(err);
},
complete() {
@@ -717,16 +738,25 @@ export const api = createTRPCNext<AppRouter>({
},
},
mutations: {
- onError: (error) => handleTrpcError(error),
+ onError: (error) =>
+ handleTrpcError(
+ error,
+ resolveToastOperation(error, undefined, "mutation.execute"),
+ ),
// react query defaults to `online`, but we want to disable it as it caused issues for some users
networkMode: "always",
},
},
queryCache: new QueryCache({
onError: (error, query) => {
- handleTrpcError(error, shouldSilenceError(query.meta ?? {}, error));
+ handleTrpcError(
+ error,
+ resolveToastOperation(error, query.meta, "query.execute"),
+ shouldSilenceError(query.meta ?? {}, error),
+ );
},
}),
+ mutationCache: createToastOperationMutationCache(),
},
};
},
diff --git a/web/src/utils/trpcErrorClassification.clienttest.ts b/web/src/utils/trpcErrorClassification.clienttest.ts
index 632d0aad61..b9e28f7fef 100644
--- a/web/src/utils/trpcErrorClassification.clienttest.ts
+++ b/web/src/utils/trpcErrorClassification.clienttest.ts
@@ -6,6 +6,7 @@ import {
classifyTrpcToastError,
EXPECTED_TRPC_BAD_REQUEST_PATHS,
} from "@/src/utils/trpcErrorClassification";
+import { rememberTrpcToastOperation } from "@/src/utils/trpcToastOperation";
const trpcError = (code: string, httpStatus: number, path = "test.procedure") =>
TRPCClientError.from({
@@ -17,6 +18,28 @@ const trpcError = (code: string, httpStatus: number, path = "test.procedure") =>
});
describe("classifyTrpcToastError", () => {
+ it("recognizes a raw failed fetch without relabeling a linked client bug", () => {
+ const offline = new TypeError("Failed to fetch");
+ const clientBug = new Error("Transformer invariant failed");
+ rememberTrpcToastOperation(offline, "projectApiKeys.create");
+ rememberTrpcToastOperation(clientBug, "projectApiKeys.create");
+
+ expect(
+ classifyTrpcToastError(offline, "project_api_key.create"),
+ ).toMatchObject({
+ operation: "project_api_key.create",
+ trpcPath: "projectApiKeys.create",
+ errorOrigin: "network",
+ errorCategory: "transient",
+ });
+ expect(
+ classifyTrpcToastError(clientBug, "project_api_key.create"),
+ ).toMatchObject({
+ errorOrigin: "frontend",
+ errorCategory: "internal",
+ });
+ });
+
it.each([
["BAD_REQUEST", 400, "frontend", "internal"],
["FORBIDDEN", 403, "backend", "permission"],
@@ -25,14 +48,16 @@ describe("classifyTrpcToastError", () => {
["UNPROCESSABLE_CONTENT", 422, "backend", "resource_limit"],
["SERVICE_UNAVAILABLE", 503, "network", "transient"],
["INTERNAL_SERVER_ERROR", 500, "backend", "internal"],
- ["PARSE_ERROR", 418, "backend", "unknown"],
+ ["PARSE_ERROR", 418, "backend", "internal"],
] as const)(
"maps %s (%i) to %s/%s",
(code, httpStatus, errorOrigin, errorCategory) => {
- expect(classifyTrpcToastError(trpcError(code, httpStatus))).toEqual({
+ expect(
+ classifyTrpcToastError(trpcError(code, httpStatus), "prompts.create"),
+ ).toEqual({
errorOrigin,
errorCategory,
- operation: "test.procedure",
+ operation: "prompts.create",
trpcCode: code,
httpStatus,
});
@@ -43,7 +68,7 @@ describe("classifyTrpcToastError", () => {
"classifies user-configured BAD_REQUEST path %s as user input",
(path) => {
expect(
- classifyTrpcToastError(trpcError("BAD_REQUEST", 400, path)),
+ classifyTrpcToastError(trpcError("BAD_REQUEST", 400, path), path),
).toEqual({
errorOrigin: "backend",
errorCategory: "user_input",
@@ -59,7 +84,8 @@ describe("classifyTrpcToastError", () => {
cause: new SyntaxError("Sensitive response body"),
});
- expect(classifyTrpcToastError(error)).toEqual({
+ expect(classifyTrpcToastError(error, "prompts.create")).toEqual({
+ operation: "prompts.create",
errorOrigin: "network",
errorCategory: "transient",
});
@@ -70,7 +96,8 @@ describe("classifyTrpcToastError", () => {
cause: new TypeError("Failed to fetch"),
});
- expect(classifyTrpcToastError(error)).toEqual({
+ expect(classifyTrpcToastError(error, "prompts.create")).toEqual({
+ operation: "prompts.create",
errorOrigin: "network",
errorCategory: "transient",
});
@@ -81,7 +108,8 @@ describe("classifyTrpcToastError", () => {
cause: new Error("Transformer failed"),
});
- expect(classifyTrpcToastError(error)).toEqual({
+ expect(classifyTrpcToastError(error, "prompts.create")).toEqual({
+ operation: "prompts.create",
errorOrigin: "frontend",
errorCategory: "internal",
});
@@ -96,8 +124,12 @@ describe("classifyTrpcToastError", () => {
cause.responseStatus = 431;
expect(
- classifyTrpcToastError(new TRPCClientError("parse failed", { cause })),
+ classifyTrpcToastError(
+ new TRPCClientError("parse failed", { cause }),
+ "prompts.create",
+ ),
).toEqual({
+ operation: "prompts.create",
errorOrigin: "frontend",
errorCategory: "internal",
httpStatus: 431,
@@ -105,9 +137,12 @@ describe("classifyTrpcToastError", () => {
});
it("classifies values outside the tRPC seam as frontend failures", () => {
- expect(classifyTrpcToastError(new Error("boom"))).toEqual({
- errorOrigin: "frontend",
- errorCategory: "internal",
- });
+ expect(classifyTrpcToastError(new Error("boom"), "prompts.create")).toEqual(
+ {
+ operation: "prompts.create",
+ errorOrigin: "frontend",
+ errorCategory: "internal",
+ },
+ );
});
});
diff --git a/web/src/utils/trpcErrorClassification.ts b/web/src/utils/trpcErrorClassification.ts
index 7a7c15affb..f16308fe50 100644
--- a/web/src/utils/trpcErrorClassification.ts
+++ b/web/src/utils/trpcErrorClassification.ts
@@ -1,6 +1,14 @@
import { TRPCClientError } from "@trpc/client";
-import { type ToastErrorAnalytics } from "@/src/features/notifications/toastAnalytics";
+import {
+ TRPC_ERROR_CODES_BY_KEY,
+ type TRPC_ERROR_CODE_KEY,
+} from "@trpc/server/rpc";
+import {
+ type ToastErrorAnalytics,
+ type ToastOperation,
+} from "@/src/features/notifications/toastAnalytics";
import { isTrpcZodValidationError } from "@/src/utils/trpcValidationError";
+import { getTrpcToastOperation } from "@/src/utils/trpcToastOperation";
type SyntaxErrorWithResponseStatus = SyntaxError & { responseStatus?: number };
@@ -30,8 +38,13 @@ const getResponseStatus = (error: TRPCClientError<any>): number | undefined => {
: undefined;
};
-const getCode = (error: TRPCClientError<any>): string | undefined =>
- typeof error.data?.code === "string" ? error.data.code : undefined;
+const getCode = (
+ error: TRPCClientError<any>,
+): TRPC_ERROR_CODE_KEY | undefined =>
+ typeof error.data?.code === "string" &&
+ Object.hasOwn(TRPC_ERROR_CODES_BY_KEY, error.data.code)
+ ? (error.data.code as TRPC_ERROR_CODE_KEY)
+ : undefined;
const getPath = (error: TRPCClientError<any>): string | undefined =>
typeof error.data?.path === "string" ? error.data.path : undefined;
@@ -44,24 +57,54 @@ const getHttpStatus = (error: TRPCClientError<any>): number | undefined =>
const withTransportMetadata = (
error: TRPCClientError<any>,
classification: Pick<ToastErrorAnalytics, "errorOrigin" | "errorCategory">,
+ operation: ToastOperation,
): ToastErrorAnalytics => {
- const operation = getPath(error);
const trpcCode = getCode(error);
const httpStatus = getHttpStatus(error);
+ const trpcPath = getTrpcToastOperation(error);
return {
...classification,
- ...(operation ? { operation } : {}),
+ operation,
...(trpcCode ? { trpcCode } : {}),
...(httpStatus !== undefined ? { httpStatus } : {}),
+ ...(typeof error.data?.traceId === "string"
+ ? { errorId: error.data.traceId }
+ : {}),
+ ...(trpcPath ? { trpcPath } : {}),
};
};
-export const classifyTrpcToastError = (error: unknown): ToastErrorAnalytics => {
+export const classifyTrpcToastError = (
+ error: unknown,
+ operation: ToastOperation,
+): ToastErrorAnalytics => {
if (!(error instanceof TRPCClientError)) {
- return { errorOrigin: "frontend", errorCategory: "internal" };
+ const trpcPath = getTrpcToastOperation(error);
+ if (
+ trpcPath &&
+ error instanceof TypeError &&
+ FAILED_FETCH_MESSAGE.test(error.message)
+ ) {
+ return {
+ operation,
+ errorOrigin: "network",
+ errorCategory: "transient",
+ trpcPath,
+ };
+ }
+ return {
+ operation,
+ errorOrigin: "frontend",
+ errorCategory: "internal",
+ ...(trpcPath ? { trpcPath } : {}),
+ };
}
+ const classify = (
+ classification: Pick<ToastErrorAnalytics, "errorOrigin" | "errorCategory">,
+ ) => withTransportMetadata(error, classification, operation);
+
const code = getCode(error);
const path = getPath(error);
const httpStatus = getHttpStatus(error);
@@ -70,14 +113,14 @@ export const classifyTrpcToastError = (error: unknown): ToastErrorAnalytics => {
error.cause instanceof SyntaxError &&
![414, 431].includes(httpStatus ?? 0)
) {
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "network",
errorCategory: "transient",
});
}
if ([414, 431].includes(httpStatus ?? 0)) {
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "frontend",
errorCategory: "internal",
});
@@ -90,7 +133,7 @@ export const classifyTrpcToastError = (error: unknown): ToastErrorAnalytics => {
FAILED_FETCH_MESSAGE.test(error.cause.message)) ||
FAILED_FETCH_MESSAGE.test(error.message))
) {
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "network",
errorCategory: "transient",
});
@@ -102,7 +145,7 @@ export const classifyTrpcToastError = (error: unknown): ToastErrorAnalytics => {
path !== undefined &&
(EXPECTED_TRPC_BAD_REQUEST_PATHS as readonly string[]).includes(path))
) {
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "backend",
errorCategory: "user_input",
});
@@ -114,7 +157,7 @@ export const classifyTrpcToastError = (error: unknown): ToastErrorAnalytics => {
httpStatus === 401 ||
httpStatus === 403
) {
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "backend",
errorCategory: "permission",
});
@@ -126,14 +169,14 @@ export const classifyTrpcToastError = (error: unknown): ToastErrorAnalytics => {
code === "PRECONDITION_FAILED" ||
[404, 409, 412].includes(httpStatus ?? 0)
) {
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "backend",
errorCategory: "product_state",
});
}
if (code === "TOO_MANY_REQUESTS" || httpStatus === 429) {
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "backend",
errorCategory: "rate_limit",
});
@@ -145,7 +188,7 @@ export const classifyTrpcToastError = (error: unknown): ToastErrorAnalytics => {
httpStatus === 413 ||
httpStatus === 422
) {
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "backend",
errorCategory: "resource_limit",
});
@@ -157,14 +200,14 @@ export const classifyTrpcToastError = (error: unknown): ToastErrorAnalytics => {
code === "SERVICE_UNAVAILABLE" ||
[408, 499, 502, 503, 504, 524].includes(httpStatus ?? 0)
) {
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "network",
errorCategory: "transient",
});
}
if (code === "INTERNAL_SERVER_ERROR" || (httpStatus ?? 0) >= 500) {
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "backend",
errorCategory: "internal",
});
@@ -175,14 +218,14 @@ export const classifyTrpcToastError = (error: unknown): ToastErrorAnalytics => {
code === "BAD_REQUEST" ||
code === "METHOD_NOT_SUPPORTED"
) {
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "frontend",
errorCategory: "internal",
});
}
- return withTransportMetadata(error, {
+ return classify({
errorOrigin: "backend",
- errorCategory: "unknown",
+ errorCategory: "internal",
});
};
diff --git a/web/src/utils/trpcErrorToast.clienttest.ts b/web/src/utils/trpcErrorToast.clienttest.ts
index 6e72058644..1fb93415af 100644
--- a/web/src/utils/trpcErrorToast.clienttest.ts
+++ b/web/src/utils/trpcErrorToast.clienttest.ts
@@ -115,19 +115,21 @@ describe("trpcErrorToast", () => {
new TRPCClientError("Unexpected token", {
cause: new SyntaxError("Unexpected token"),
}),
+ "prompts.create",
);
expect(showErrorToastMock).toHaveBeenCalledWith(
"Unexpected Response",
"The request could not be completed. Please try again or contact support if this persists.",
- "WARNING",
- undefined,
- undefined,
- "trpc",
{
+ operation: "prompts.create",
errorOrigin: "network",
errorCategory: "transient",
},
+ "WARNING",
+ undefined,
+ undefined,
+ "trpc",
);
});
@@ -139,15 +141,12 @@ describe("trpcErrorToast", () => {
path: "prompts.create",
message: ZOD4_TOO_SMALL_MESSAGE,
}),
+ "prompts.create",
);
expect(showErrorToastMock).toHaveBeenCalledWith(
"Invalid input",
"name: Too small: expected string to have >=1 characters",
- "WARNING",
- "prompts.create",
- undefined,
- "trpc",
{
errorOrigin: "backend",
errorCategory: "user_input",
@@ -155,6 +154,10 @@ describe("trpcErrorToast", () => {
trpcCode: "BAD_REQUEST",
httpStatus: 400,
},
+ "WARNING",
+ "prompts.create",
+ undefined,
+ "trpc",
);
});
@@ -166,15 +169,12 @@ describe("trpcErrorToast", () => {
path: "prompts.create",
message: "Invalid input, projectId is required",
}),
+ "prompts.create",
);
expect(showErrorToastMock).toHaveBeenCalledWith(
"Bad Request",
"Invalid input, projectId is required",
- "WARNING",
- "prompts.create",
- undefined,
- "trpc",
{
errorOrigin: "frontend",
errorCategory: "internal",
@@ -182,6 +182,10 @@ describe("trpcErrorToast", () => {
trpcCode: "BAD_REQUEST",
httpStatus: 400,
},
+ "WARNING",
+ "prompts.create",
+ undefined,
+ "trpc",
);
});
@@ -194,22 +198,24 @@ describe("trpcErrorToast", () => {
message: "Something went wrong",
traceId: "abc123def456",
}),
+ "prompts.create",
);
expect(showErrorToastMock).toHaveBeenCalledWith(
"Internal Server Error",
"Something went wrong",
- "ERROR",
- "prompts.create",
- "abc123def456",
- "trpc",
{
+ errorId: "abc123def456",
errorOrigin: "backend",
errorCategory: "internal",
operation: "prompts.create",
trpcCode: "INTERNAL_SERVER_ERROR",
httpStatus: 500,
},
+ "ERROR",
+ "prompts.create",
+ "abc123def456",
+ "trpc",
);
});
@@ -229,15 +235,12 @@ describe("trpcErrorToast", () => {
path: "prompts.create",
message: "Expected failure",
}),
+ "prompts.create",
);
expect(showErrorToastMock).toHaveBeenCalledWith(
expect.any(String),
"Expected failure",
- expect.any(String),
- "prompts.create",
- undefined,
- "trpc",
{
errorOrigin: errorCategory === "transient" ? "network" : "backend",
errorCategory,
@@ -245,6 +248,10 @@ describe("trpcErrorToast", () => {
trpcCode: code,
httpStatus,
},
+ expect.any(String),
+ "prompts.create",
+ undefined,
+ "trpc",
);
},
);
diff --git a/web/src/utils/trpcErrorToast.tsx b/web/src/utils/trpcErrorToast.tsx
index b9bc433381..c79ba915cc 100644
--- a/web/src/utils/trpcErrorToast.tsx
+++ b/web/src/utils/trpcErrorToast.tsx
@@ -2,6 +2,7 @@ import { TRPCClientError } from "@trpc/client";
import { showErrorToast } from "@/src/features/notifications";
import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { formatTrpcZodValidationDescription } from "@/src/utils/trpcValidationError";
+import type { ToastOperation } from "@/src/features/notifications/toastAnalytics";
// Catch network level errors, e.g. by proxy rate-limiting
@@ -81,7 +82,7 @@ const getErrorDescription = (httpStatus: number) => {
}
};
-export const trpcErrorToast = (error: unknown) => {
+export const trpcErrorToast = (error: unknown, operation: ToastOperation) => {
if (error instanceof TRPCClientError) {
// Handle infrastructure-level errors that return non-JSON responses
// (e.g., 431 with empty body, 502/503/504 with HTML error pages)
@@ -89,18 +90,19 @@ export const trpcErrorToast = (error: unknown) => {
showErrorToast(
"Unexpected Response",
"The request could not be completed. Please try again or contact support if this persists.",
+ classifyTrpcToastError(error, operation),
"WARNING",
undefined,
undefined,
"trpc",
- classifyTrpcToastError(error),
);
return;
}
const { errorTitle, httpStatus } = getErrorTitleAndHttpCode(error);
- const path = error.data?.path;
+ const path =
+ typeof error.data?.path === "string" ? error.data.path : undefined;
// OTEL trace id attached by the tRPC errorFormatter; absent when OTEL is not
// running (self-hosted / unsampled). Surfaced so users can share it in
// support tickets for correlation.
@@ -113,21 +115,21 @@ export const trpcErrorToast = (error: unknown) => {
showErrorToast(
validationDescription ? "Invalid input" : errorTitle,
description,
+ classifyTrpcToastError(error, operation),
httpStatus >= 500 && httpStatus < 600 ? "ERROR" : "WARNING",
path,
traceId,
"trpc",
- classifyTrpcToastError(error),
);
} else {
showErrorToast(
"Unexpected Error",
"An unexpected error occurred.",
+ classifyTrpcToastError(error, operation),
"ERROR",
undefined,
undefined,
"trpc",
- classifyTrpcToastError(error),
);
}
};
diff --git a/web/src/utils/trpcToastOperation.clienttest.ts b/web/src/utils/trpcToastOperation.clienttest.ts
new file mode 100644
index 0000000000..ef2efe4e7b
--- /dev/null
+++ b/web/src/utils/trpcToastOperation.clienttest.ts
@@ -0,0 +1,142 @@
+// @vitest-environment node
+
+import { MutationObserver, QueryClient } from "@tanstack/react-query";
+import { vi } from "vitest";
+import {
+ createToastOperationMutationCache,
+ getTrpcToastOperation,
+ rememberTrpcToastOperation,
+ resolveToastOperation,
+} from "@/src/utils/trpcToastOperation";
+
+describe("tRPC toast operation context", () => {
+ it("keeps operation context isolated per error object", () => {
+ const createError = new Error("create failed");
+ const deleteError = new Error("delete failed");
+
+ rememberTrpcToastOperation(createError, "projects.create");
+ rememberTrpcToastOperation(deleteError, "projects.delete");
+
+ expect(getTrpcToastOperation(createError)).toBe("projects.create");
+ expect(getTrpcToastOperation(deleteError)).toBe("projects.delete");
+ });
+
+ it("does not mutate the error object or attach analytics fields", () => {
+ const error = Object.freeze(new Error("request failed"));
+
+ expect(() =>
+ rememberTrpcToastOperation(error, "projects.create"),
+ ).not.toThrow();
+ expect(Object.keys(error)).toEqual([]);
+ expect(getTrpcToastOperation(error)).toBe("projects.create");
+ });
+
+ it("ignores primitive throw values", () => {
+ rememberTrpcToastOperation("request failed", "projects.create");
+
+ expect(getTrpcToastOperation("request failed")).toBeUndefined();
+ });
+
+ it("prefers the exact linked procedure path over semantic query metadata", () => {
+ const error = new Error("request failed");
+ rememberTrpcToastOperation(error, "topics.currentResults");
+
+ expect(
+ resolveToastOperation(
+ error,
+ { toastOperation: "topics.load" },
+ "query.execute",
+ ),
+ ).toBe("topics.currentResults");
+ });
+
+ it("uses registered static metadata for non-tRPC query errors", () => {
+ expect(
+ resolveToastOperation(
+ new Error("parse failed"),
+ { toastOperation: "trace.parse" },
+ "query.execute",
+ ),
+ ).toBe("trace.parse");
+ });
+
+ it("uses an explicit instrumentation-gap fallback for unattributed errors", () => {
+ expect(
+ resolveToastOperation(
+ new Error("unknown source"),
+ undefined,
+ "query.execute",
+ ),
+ ).toBe("query.execute");
+ });
+
+ it("rejects unregistered metadata instead of forwarding dynamic values", () => {
+ expect(
+ resolveToastOperation(
+ new Error("request failed"),
+ { toastOperation: "project_123" } as never,
+ "query.execute",
+ ),
+ ).toBe("query.execute");
+ });
+
+ it("makes static mutation metadata available to the default error handler", async () => {
+ const error = new Error("post-success callback failed");
+ const report = vi.fn();
+ const queryClient = new QueryClient({
+ mutationCache: createToastOperationMutationCache(),
+ defaultOptions: {
+ mutations: {
+ onError: (receivedError) => {
+ report(
+ resolveToastOperation(
+ receivedError,
+ undefined,
+ "mutation.execute",
+ ),
+ );
+ },
+ },
+ },
+ });
+ const observer = new MutationObserver(queryClient, {
+ mutationFn: async () => Promise.reject(error),
+ meta: { toastOperation: "sharing.update" },
+ });
+
+ await expect(observer.mutate()).rejects.toBe(error);
+
+ expect(report).toHaveBeenCalledOnce();
+ expect(report).toHaveBeenCalledWith("sharing.update");
+ });
+
+ it("keeps a linked tRPC path ahead of remembered mutation metadata", async () => {
+ const error = new Error("request failed");
+ rememberTrpcToastOperation(error, "projects.create");
+ const observedOperations: string[] = [];
+ const queryClient = new QueryClient({
+ mutationCache: createToastOperationMutationCache(),
+ defaultOptions: {
+ mutations: {
+ onError: (receivedError) => {
+ observedOperations.push(
+ resolveToastOperation(
+ receivedError,
+ undefined,
+ "mutation.execute",
+ ),
+ );
+ },
+ },
+ },
+ });
+ const observer = new MutationObserver(queryClient, {
+ mutationFn: async () => Promise.reject(error),
+ meta: { toastOperation: "sharing.update" },
+ });
+
+ await expect(observer.mutate()).rejects.toBe(error);
+
+ expect(observedOperations).toEqual(["projects.create"]);
+ });
+});
diff --git a/web/src/utils/trpcToastOperation.ts b/web/src/utils/trpcToastOperation.ts
new file mode 100644
index 0000000000..c879177bd0
--- /dev/null
+++ b/web/src/utils/trpcToastOperation.ts
@@ -0,0 +1,110 @@
+import { MutationCache, type Register } from "@tanstack/react-query";
+import type {
+ ToastOperation,
+ TrpcToastOperation,
+} from "@/src/features/notifications/toastAnalytics";
+import {
+ applicationToastOperations,
+ type ApplicationToastOperation,
+} from "@/src/features/notifications/toastOperations";
+
+type ToastOperationMeta = {
+ /**
+ * Static application intent for direct TanStack hooks. It stays optional at
+ * the library level because tRPC hooks get an exact path from the link and
+ * fully silenced queries never emit a toast. Never use ids, names, URLs, or
+ * query input.
+ */
+ toastOperation?: ApplicationToastOperation;
+ [key: string]: unknown;
+};
+
+declare module "@tanstack/react-query" {
+ interface Register {
+ queryMeta: ToastOperationMeta;
+ mutationMeta: ToastOperationMeta;
+ }
+}
+
+const trpcToastOperationByError = new WeakMap<object, TrpcToastOperation>();
+const applicationToastOperationByError = new WeakMap<
+ object,
+ ApplicationToastOperation
+>();
+
+const isWeakMapKey = (value: unknown): value is object =>
+ (typeof value === "object" && value !== null) || typeof value === "function";
+
+/**
+ * Associates the typed procedure path from a tRPC operation with its emitted
+ * error without mutating or serializing the error.
+ */
+export const rememberTrpcToastOperation = (
+ error: unknown,
+ operation: TrpcToastOperation,
+): void => {
+ if (isWeakMapKey(error)) {
+ trpcToastOperationByError.set(error, operation);
+ }
+};
+
+export const getTrpcToastOperation = (
+ error: unknown,
+): TrpcToastOperation | undefined =>
+ isWeakMapKey(error) ? trpcToastOperationByError.get(error) : undefined;
+
+const isApplicationToastOperation = (
+ value: unknown,
+): value is ApplicationToastOperation =>
+ typeof value === "string" &&
+ (applicationToastOperations as readonly string[]).includes(value);
+
+const rememberToastOperationFromMeta = (
+ error: unknown,
+ meta: Register["mutationMeta"] | undefined,
+): void => {
+ if (
+ isWeakMapKey(error) &&
+ isApplicationToastOperation(meta?.toastOperation)
+ ) {
+ applicationToastOperationByError.set(error, meta.toastOperation);
+ }
+};
+
+/**
+ * React Query exposes mutation metadata to the cache callback before invoking
+ * the mutation's default or local error handler. This cache records only the
+ * validated static intent; reporting and toast presentation remain owned by
+ * the existing handlers.
+ */
+export const createToastOperationMutationCache = (): MutationCache =>
+ new MutationCache({
+ onError: (error, _variables, _context, mutation) => {
+ rememberToastOperationFromMeta(error, mutation.meta);
+ },
+ });
+
+/**
+ * Resolves bounded analytics context for the global React Query error seam.
+ * Exact tRPC paths win; direct TanStack queries can provide a registered static
+ * intent in metadata. The caller supplies an explicit gap marker as a last
+ * resort. Query and mutation keys are deliberately excluded because they can
+ * contain tenant and resource identifiers.
+ */
+export const resolveToastOperation = (
+ error: unknown,
+ meta: Register["queryMeta"] | Register["mutationMeta"] | undefined,
+ fallback: ToastOperation,
+): ToastOperation => {
+ const linkedOperation = getTrpcToastOperation(error);
+ if (linkedOperation) return linkedOperation;
+
+ const rememberedApplicationOperation = isWeakMapKey(error)
+ ? applicationToastOperationByError.get(error)
+ : undefined;
+ if (rememberedApplicationOperation) return rememberedApplicationOperation;
+
+ return isApplicationToastOperation(meta?.toastOperation)
+ ? meta.toastOperation
+ : fallback;
+};