:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): improve the error boundary (#101169)
Shy Alterf4cfa42fe582
diff --git a/products/desktop/apps/code/.storybook/main.ts b/products/desktop/apps/code/.storybook/main.tsindex a29e04ff9371..ce9cc4764b41 100644--- a/products/desktop/apps/code/.storybook/main.ts+++ b/products/desktop/apps/code/.storybook/main.ts@@ -37,6 +37,10 @@ const config: StorybookConfig = {async viteFinal(config) {return mergeConfig(config, {plugins: [tailwindcss(), react()],+ // The brand hoggie modules locate their PNGs with+ // `new URL("./x.png", import.meta.url)`. Pre-bundling moves the module+ // into the deps cache, where that URL 404s, so serve it from node_modules.+ optimizeDeps: { exclude: ["@posthog/brand"] },resolve: {alias: [{diff --git a/products/desktop/packages/ui/src/primitives/ErrorBoundary.stories.tsx b/products/desktop/packages/ui/src/primitives/ErrorBoundary.stories.tsxnew file mode 100644index 000000000000..b5a90a23b7b0--- /dev/null+++ b/products/desktop/packages/ui/src/primitives/ErrorBoundary.stories.tsx@@ -0,0 +1,73 @@+import { ErrorBoundaryFallback } from "@posthog/ui/primitives/ErrorBoundaryFallback";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { fn } from "storybook/test";++function renderError(message: string, frames: number): Error {+ const error = new TypeError(message);+ const stack = Array.from(+ { length: frames },+ (_, index) =>+ ` at renderItem (app://posthog/assets/index-4f2a9c.js:1${index}:2${index})`,+ );+ error.stack = [`TypeError: ${message}`, ...stack].join("\n");+ return error;+}++const COMPONENT_STACK = [+ " at SessionView",+ " at TaskLogsPanel",+ " at ErrorBoundary",+ " at App",+].join("\n");++const meta = {+ title: "Primitives/ErrorBoundary",+ component: ErrorBoundaryFallback,+ parameters: { layout: "fullscreen" },+ args: {+ error: renderError("Cannot read properties of undefined (reading 'id')", 6),+ componentStack: COMPONENT_STACK,+ boundaryName: "SessionView",+ onRefresh: fn(),+ },+ render: (args) => (+ <div className="flex h-screen">+ <ErrorBoundaryFallback {...args} />+ </div>+ ),+} satisfies Meta<typeof ErrorBoundaryFallback>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {};++export const LongMessage: Story = {+ args: {+ error: renderError(+ "Failed to fetch dynamically imported module: app://posthog/assets/TaskDetailView-9b1c0e7d3f2a4b5c.js because the network request returned an unexpected status code",+ 24,+ ),+ },+};++export const WithoutStack: Story = {+ args: {+ error: Object.assign(new Error("Unexpected token < in JSON"), {+ stack: undefined,+ }),+ componentStack: null,+ boundaryName: undefined,+ },+};++/** The fallback inside a narrow pane, as when a side panel crashes next to the sidebar. */+export const NarrowPane: Story = {+ render: (args) => (+ <div className="flex h-screen items-stretch justify-center p-6">+ <div className="flex h-full w-[360px] rounded-md border border-border">+ <ErrorBoundaryFallback {...args} />+ </div>+ </div>+ ),+};diff --git a/products/desktop/packages/ui/src/primitives/ErrorBoundary.tsx b/products/desktop/packages/ui/src/primitives/ErrorBoundary.tsxindex 27e07726792d..d433a1610f0b 100644--- a/products/desktop/packages/ui/src/primitives/ErrorBoundary.tsx+++ b/products/desktop/packages/ui/src/primitives/ErrorBoundary.tsx@@ -1,5 +1,4 @@-import { Warning } from "@phosphor-icons/react";-import { Box, Button, Callout, Flex, Text } from "@radix-ui/themes";+import { ErrorBoundaryFallback } from "@posthog/ui/primitives/ErrorBoundaryFallback";import { Component, type ErrorInfo, type ReactNode } from "react";export interface ErrorBoundaryProps {@@ -29,11 +28,16 @@ export interface ErrorBoundaryProps {interface State {error: Error | null;+ componentStack: string | null;lastResetKey: unknown;}export class ErrorBoundary extends Component<ErrorBoundaryProps, State> {- state: State = { error: null, lastResetKey: this.props.resetKey };+ state: State = {+ error: null,+ componentStack: null,+ lastResetKey: this.props.resetKey,+ };static getDerivedStateFromError(error: Error): Partial<State> {return { error };@@ -44,48 +48,35 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, State> {state: State,): Partial<State> | null {if (props.resetKey === state.lastResetKey) return null;- return { error: null, lastResetKey: props.resetKey };+ return { error: null, componentStack: null, lastResetKey: props.resetKey };}componentDidCatch(error: Error, errorInfo: ErrorInfo) {const suppressed = this.props.shouldSuppress?.(error) ?? false;+ this.setState({ componentStack: errorInfo.componentStack ?? null });this.props.onError?.(error, {componentStack: errorInfo.componentStack,suppressed,});}- handleRetry = () => {- this.setState({ error: null });+ handleRefresh = () => {+ window.location.reload();};render() {- const { error } = this.state;+ const { error, componentStack } = this.state;if (!error) return this.props.children;if (this.props.shouldSuppress?.(error)) return null;if (this.props.fallback) return this.props.fallback;return (- <Box p="4">- <Callout.Root color="red" size="2">- <Callout.Icon>- <Warning weight="fill" />- </Callout.Icon>- <Callout.Text>- <Flex direction="column" gap="2">- <Text className="font-medium">Something went wrong</Text>- <Text className="text-[13px] text-gray-11">- {error.message || "An unexpected error occurred"}- </Text>- <Flex gap="2" mt="2">- <Button size="1" variant="soft" onClick={this.handleRetry}>- Try again- </Button>- </Flex>- </Flex>- </Callout.Text>- </Callout.Root>- </Box>+ <ErrorBoundaryFallback+ error={error}+ componentStack={componentStack}+ boundaryName={this.props.name}+ onRefresh={this.handleRefresh}+ />);}}diff --git a/products/desktop/packages/ui/src/primitives/ErrorBoundaryFallback.tsx b/products/desktop/packages/ui/src/primitives/ErrorBoundaryFallback.tsxnew file mode 100644index 000000000000..bfe40865ec23--- /dev/null+++ b/products/desktop/packages/ui/src/primitives/ErrorBoundaryFallback.tsx@@ -0,0 +1,134 @@+import { ArrowClockwise, Check, Copy } from "@phosphor-icons/react";+import {+ Button,+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+ Heading,+ Text,+} from "@posthog/quill";+import { hoggiePng } from "@posthog/shared/hoggies";+import {+ buildErrorReport,+ summarizeError,+} from "@posthog/ui/primitives/errorReport";+import { useEffect, useRef, useState } from "react";++/** How long the copy button confirms before it returns to its resting label. */+const COPIED_MS = 2000;++export interface ErrorBoundaryFallbackProps {+ error: Error;+ componentStack?: string | null;+ /** The `name` of the boundary that caught the error, included in the copied report. */+ boundaryName?: string;+ onRefresh: () => void;+}++/**+ * The screen an `ErrorBoundary` shows in place of a crashed subtree. Pure:+ * everything it renders comes from props, so the story and the boundary share+ * one implementation.+ */+export function ErrorBoundaryFallback({+ error,+ componentStack,+ boundaryName,+ onRefresh,+}: ErrorBoundaryFallbackProps) {+ const [copied, setCopied] = useState(false);+ const [detailsOpen, setDetailsOpen] = useState(false);+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ useEffect(+ () => () => (timer.current ? clearTimeout(timer.current) : undefined),+ [],+ );++ const report = buildErrorReport({+ error,+ componentStack,+ boundaryName,+ timestamp: new Date(),+ userAgent:+ typeof navigator !== "undefined" ? navigator.userAgent : undefined,+ });++ async function copyReport() {+ try {+ await navigator.clipboard.writeText(report);+ setCopied(true);+ if (timer.current) clearTimeout(timer.current);+ timer.current = setTimeout(() => setCopied(false), COPIED_MS);+ } catch {+ // Clipboard access can be denied, so the details panel stays selectable as the fallback.+ }+ }++ const summary = summarizeError(error);++ return (+ <div+ role="alert"+ className="@container flex h-full min-h-64 w-full flex-1 justify-center overflow-y-auto p-6"+ >+ <div className="my-auto flex w-full max-w-md flex-col items-center gap-6 text-center">+ <img+ src={hoggiePng("shocked")}+ alt=""+ className="pointer-events-none @max-[420px]:w-28 w-36 select-none"+ />+ <div className="flex w-full flex-col items-center gap-2">+ <Heading size="lg">Something went wrong</Heading>+ <Text size="sm" variant="muted" className="text-balance">+ PostHog hit an error it could not recover from. Refresh the app to+ try again. If it keeps happening, copy the error details and send+ them to us.+ </Text>+ <code+ title={summary}+ className="mt-1 max-w-full truncate rounded-md border border-border bg-muted px-2 py-1 font-mono text-muted-foreground text-xs"+ >+ {summary}+ </code>+ </div>+ <div className="flex flex-wrap items-center justify-center gap-2">+ <Button+ type="button"+ variant="primary"+ data-attr="error-boundary-refresh"+ onClick={onRefresh}+ >+ <ArrowClockwise />+ Refresh app+ </Button>+ <Button+ type="button"+ variant="outline"+ data-attr="error-boundary-copy"+ onClick={copyReport}+ >+ {copied ? <Check className="text-success-foreground" /> : <Copy />}+ {copied ? "Copied" : "Copy error details"}+ </Button>+ </div>+ <Collapsible+ open={detailsOpen}+ onOpenChange={setDetailsOpen}+ className="flex w-full flex-col items-center gap-2"+ >+ <CollapsibleTrigger+ data-attr="error-boundary-details"+ className="w-auto text-muted-foreground"+ >+ {detailsOpen ? "Hide technical details" : "Show technical details"}+ </CollapsibleTrigger>+ <CollapsibleContent className="w-full">+ <pre className="max-h-56 select-text overflow-auto whitespace-pre-wrap break-words rounded-md border border-border bg-muted p-3 text-left font-mono text-[11px] text-muted-foreground leading-relaxed">+ {report}+ </pre>+ </CollapsibleContent>+ </Collapsible>+ </div>+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/primitives/errorReport.ts b/products/desktop/packages/ui/src/primitives/errorReport.tsnew file mode 100644index 000000000000..c95f535d7ac9--- /dev/null+++ b/products/desktop/packages/ui/src/primitives/errorReport.ts@@ -0,0 +1,43 @@+export interface ErrorReportInput {+ error: Error;+ componentStack?: string | null;+ /** The `name` of the boundary that caught the error, when it has one. */+ boundaryName?: string;+ timestamp: Date;+ userAgent?: string;+}++/** One-line summary shown on the fallback screen: `TypeError: foo is not a function`. */+export function summarizeError(error: Error): string {+ const name = error.name || "Error";+ return error.message ? `${name}: ${error.message}` : name;+}++/**+ * The plain-text report the user copies and pastes into a bug report. Header+ * lines first so a reader can place it before scrolling the stack.+ */+export function buildErrorReport({+ error,+ componentStack,+ boundaryName,+ timestamp,+ userAgent,+}: ErrorReportInput): string {+ const header = [+ "PostHog Desktop error report",+ boundaryName ? `Boundary: ${boundaryName}` : null,+ `Time: ${timestamp.toISOString()}`,+ userAgent ? `User agent: ${userAgent}` : null,+ ].filter((line): line is string => line !== null);++ const sections = [+ header.join("\n"),+ error.stack || summarizeError(error),+ componentStack?.trim()+ ? `Component stack:\n${componentStack.trim()}`+ : null,+ ].filter((section): section is string => section !== null);++ return sections.join("\n\n");+}diff --git a/products/desktop/packages/ui/src/shell/ErrorBoundary.test.tsx b/products/desktop/packages/ui/src/shell/ErrorBoundary.test.tsxindex 7cfa9de438ba..199752d0a0c3 100644--- a/products/desktop/packages/ui/src/shell/ErrorBoundary.test.tsx+++ b/products/desktop/packages/ui/src/shell/ErrorBoundary.test.tsx@@ -2,7 +2,6 @@ import {isNotAuthenticatedError,NotAuthenticatedError,} from "@posthog/shared";-import { Theme } from "@radix-ui/themes";import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import type { ReactNode } from "react";@@ -38,15 +37,13 @@ function Boundary(props: {fallback?: ReactNode;}) {return (- <Theme>- <ErrorBoundary- resetKey={props.resetKey}- shouldSuppress={props.shouldSuppress}- fallback={props.fallback}- >- {props.children}- </ErrorBoundary>- </Theme>+ <ErrorBoundary+ resetKey={props.resetKey}+ shouldSuppress={props.shouldSuppress}+ fallback={props.fallback}+ >+ {props.children}+ </ErrorBoundary>);}@@ -55,6 +52,7 @@ beforeEach(() => {});afterEach(() => {+ vi.unstubAllGlobals();vi.restoreAllMocks();vi.mocked(captureException).mockClear();});@@ -69,15 +67,45 @@ describe("ErrorBoundary", () => {expect(screen.getByText("ok")).toBeInTheDocument();});- it("renders the default fallback UI on error and reports telemetry", () => {+ it("hides the stack until requested and reports telemetry", async () => {+ const user = userEvent.setup();+ const error = new Error("boom");+ error.stack = "Error: boom\n at Thrower (test.tsx:1:1)";render(<Boundary>- <Thrower error={new Error("boom")} />+ <Thrower error={error} /></Boundary>,);expect(screen.getByText("Something went wrong")).toBeInTheDocument();- expect(screen.getByText("boom")).toBeInTheDocument();+ expect(screen.getByText("Error: boom")).toBeInTheDocument();+ expect(screen.queryByText(/at Thrower/)).not.toBeInTheDocument();expect(captureException).toHaveBeenCalledTimes(1);++ await user.click(+ screen.getByRole("button", { name: /show technical details/i }),+ );+ expect(screen.getByText(/at Thrower/)).toBeInTheDocument();+ });++ it("copies a report with the boundary name, stack and component stack", async () => {+ const user = userEvent.setup();+ const error = new Error("boom");+ error.stack = "Error: boom\n at Thrower (test.tsx:1:1)";+ render(+ <ErrorBoundary name="SessionView">+ <Thrower error={error} />+ </ErrorBoundary>,+ );++ await user.click(+ screen.getByRole("button", { name: /copy error details/i }),+ );++ const report = await navigator.clipboard.readText();+ expect(report).toContain("Boundary: SessionView");+ expect(report).toContain("at Thrower (test.tsx:1:1)");+ expect(report).toMatch(/Component stack:\n\s*at Thrower/);+ expect(screen.getByRole("button", { name: /copied/i })).toBeInTheDocument();});it("renders custom fallback when provided", () => {@@ -127,22 +155,19 @@ describe("ErrorBoundary", () => {expect(screen.getByText("ok")).toBeInTheDocument();});- it("recovers via retry button", async () => {+ it("refreshes the app from the error screen", async () => {const user = userEvent.setup();- const { rerender } = render(+ const reload = vi.fn();+ vi.stubGlobal("location", { reload });++ render(<Boundary><Thrower error={new Error("boom")} /></Boundary>,);- expect(screen.getByText("Something went wrong")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: /^refresh app$/i }));- rerender(- <Boundary>- <Thrower error={null} />- </Boundary>,- );- await user.click(screen.getByRole("button", { name: /try again/i }));- expect(screen.getByText("ok")).toBeInTheDocument();+ expect(reload).toHaveBeenCalledTimes(1);});});