A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.
TypeScript amazon-primeelectronepic-games-launcherepic-games-storeepic-storegaminggoggog-galaxyheroic-games-launcherlinuxplay-gamesprotonsteamwine
[Feat] Add a proper error screen with copy log buttons (#6130)
Flávio Fearn13615cab8835
diff --git a/public/locales/en/translation.json b/public/locales/en/translation.jsonindex 60d547647..4a9f85a95 100644--- a/public/locales/en/translation.json+++ b/public/locales/en/translation.json@@ -582,7 +582,32 @@"offline-notification-title": "offline"},"error": {- "recovery": "Refreshing the library usually fixes it. Clearing the cache or resetting Heroic are the next steps if it does not."+ "back-to-library": "Back to library",+ "boundary": {+ "subtitle": "Heroic couldn't finish loading this screen. Reloading usually fixes it.",+ "title": "Something went wrong"+ },+ "copy-failed": "Could not copy. Try again, or open the log folder.",+ "copy-report": "Copy error report",+ "download-report": "Download error report",+ "more-actions": "More actions",+ "open-log-folder": "Open log folder",+ "page": {+ "subtitle": "The rest of Heroic is still working. Go back to your library, or try this page again.",+ "title": "This page couldn't load"+ },+ "preparing-report": "Preparing…",+ "recovery": "Refreshing the library usually fixes it. Clearing the cache or resetting Heroic are the next steps if it does not.",+ "reload": "Reload Heroic",+ "report-copied": "Error report copied. Paste it into your issue on GitHub.",+ "report-copied-no-log": "Error report copied, without the Heroic log (none was found).",+ "report-download-failed": "Could not download the report. Try again.",+ "report-downloaded": "Error report downloaded. Attach it to your issue on GitHub.",+ "report-issue": "Report on GitHub",+ "retry-page": "Try this page again",+ "show-full-message": "Show full message",+ "technical-details": "Technical details",+ "version-caption": "Heroic {{version}}"},"externalLink": {"dontAskAgain": "Don't ask again",diff --git a/src/frontend/App.tsx b/src/frontend/App.tsxindex fd633dffd..bd99c31e8 100644--- a/src/frontend/App.tsx+++ b/src/frontend/App.tsx@@ -24,6 +24,9 @@ import StoreStatusWarning from './components/UI/StoreStatusWarning'import { SettingsModalWrapper } from './screens/Settings/components/SettingsModal'import AnalyticsDialog from './screens/Settings/components/AnalyticsDialog'import ConsoleComboListener from './screens/ConsoleMode/components/ConsoleComboListener'+import AppErrorBoundary, {+ PageErrorBoundary+} from './components/UI/AppErrorBoundary'function Root() {const {@@ -146,66 +149,74 @@ const router = createHashRouter([{path: '/',element: <Root />,+ errorElement: <AppErrorBoundary />,children: [{- index: true,- lazy: makeLazyFunc(import('./screens/Library'))- },- {- path: 'login',- lazy: makeLazyFunc(import('./screens/Login'))- },- {- path: 'store/:store',- lazy: makeLazyFunc(import('./screens/WebView'))- },- {- path: 'wiki',- lazy: makeLazyFunc(import('./screens/WebView'))- },- {- path: 'gamepage/:runner/:appName',- lazy: makeLazyFunc(import('./screens/Game/GamePage'))- },- {- path: 'store-page',- lazy: makeLazyFunc(import('./screens/WebView'))- },- {- path: 'discounts',- lazy: makeLazyFunc(import('./screens/Discounts'))- },- {- path: 'loginweb/:runner',- lazy: makeLazyFunc(import('./screens/WebView'))- },- {- path: 'settings/:type',- lazy: makeLazyFunc(import('./screens/Settings'))- },- {- path: 'wine-manager',- lazy: makeLazyFunc(import('./screens/WineManager'))- },- {- path: 'download-manager',- lazy: makeLazyFunc(import('./screens/DownloadManager'))- },- {- path: 'accessibility',- lazy: makeLazyFunc(import('./screens/Accessibility'))- },- {- path: 'support',- lazy: makeLazyFunc(import('./screens/Support'))- },- {- path: 'console',- lazy: makeLazyFunc(import('./screens/ConsoleMode'))- },- {- path: '*',- element: <Navigate replace to="/" />+ // Pathless layout route: keeps ShellError for shell failures while+ // page errors render inside main.content and leave the shell usable.+ errorElement: <PageErrorBoundary />,+ children: [+ {+ index: true,+ lazy: makeLazyFunc(import('./screens/Library'))+ },+ {+ path: 'login',+ lazy: makeLazyFunc(import('./screens/Login'))+ },+ {+ path: 'store/:store',+ lazy: makeLazyFunc(import('./screens/WebView'))+ },+ {+ path: 'wiki',+ lazy: makeLazyFunc(import('./screens/WebView'))+ },+ {+ path: 'gamepage/:runner/:appName',+ lazy: makeLazyFunc(import('./screens/Game/GamePage'))+ },+ {+ path: 'store-page',+ lazy: makeLazyFunc(import('./screens/WebView'))+ },+ {+ path: 'discounts',+ lazy: makeLazyFunc(import('./screens/Discounts'))+ },+ {+ path: 'loginweb/:runner',+ lazy: makeLazyFunc(import('./screens/WebView'))+ },+ {+ path: 'settings/:type',+ lazy: makeLazyFunc(import('./screens/Settings'))+ },+ {+ path: 'wine-manager',+ lazy: makeLazyFunc(import('./screens/WineManager'))+ },+ {+ path: 'download-manager',+ lazy: makeLazyFunc(import('./screens/DownloadManager'))+ },+ {+ path: 'accessibility',+ lazy: makeLazyFunc(import('./screens/Accessibility'))+ },+ {+ path: 'support',+ lazy: makeLazyFunc(import('./screens/Support'))+ },+ {+ path: 'console',+ lazy: makeLazyFunc(import('./screens/ConsoleMode'))+ },+ {+ path: '*',+ element: <Navigate replace to="/" />+ }+ ]}]}diff --git a/src/frontend/components/UI/AppErrorBoundary/__tests__/isLogTooLarge.test.ts b/src/frontend/components/UI/AppErrorBoundary/__tests__/isLogTooLarge.test.tsnew file mode 100644index 000000000..3ab67a89a--- /dev/null+++ b/src/frontend/components/UI/AppErrorBoundary/__tests__/isLogTooLarge.test.ts@@ -0,0 +1,24 @@+import { isLogTooLarge } from '../logReport'++const makeLines = (count: number) =>+ Array.from({ length: count }, (_, index) => `line ${index}`).join('\n')++describe('isLogTooLarge', () => {+ it('switches to download after 500 lines', () => {+ expect(isLogTooLarge(makeLines(499))).toBe(false)+ expect(isLogTooLarge(makeLines(500))).toBe(false)+ expect(isLogTooLarge(makeLines(501))).toBe(true)+ expect(isLogTooLarge(`${makeLines(500)}\n`)).toBe(false)+ expect(isLogTooLarge(`${makeLines(501)}\n`)).toBe(true)+ })++ it('switches to download above one million characters', () => {+ expect(isLogTooLarge('a'.repeat(999_999))).toBe(false)+ expect(isLogTooLarge('a'.repeat(1_000_000))).toBe(false)+ expect(isLogTooLarge('a'.repeat(1_000_001))).toBe(true)+ })++ it('keeps an empty log in copy mode', () => {+ expect(isLogTooLarge('')).toBe(false)+ })+})diff --git a/src/frontend/components/UI/AppErrorBoundary/index.css b/src/frontend/components/UI/AppErrorBoundary/index.cssnew file mode 100644index 000000000..96c0c5d45--- /dev/null+++ b/src/frontend/components/UI/AppErrorBoundary/index.css@@ -0,0 +1,342 @@+.AppError {+ display: flex;+ flex-direction: column;+ color: var(--text-default);+ text-align: start;+}++/* Page variant lives inside main.content: fill it, but never the viewport. */+.AppError--page {+ flex: 1;+ min-height: 100%;+ padding: var(--space-xl-fixed);+ overflow-y: auto;+ container-type: inline-size;+}++/* Shell variant is the whole window: the app shell could not render. */+.AppError--shell {+ height: 100vh;+ min-height: 100vh;+ padding: var(--space-xl-fixed);+ overflow-y: auto;+ background: var(--gradient-body-background, var(--body-background));+ container-type: inline-size;+}++.AppError__panel {+ display: flex;+ flex-direction: column;+ gap: var(--space-lg-fixed);+ margin-block: auto;+ margin-inline: auto;+ height: fit-content;+}++.AppError--page .AppError__panel {+ width: min(100%, 44rem);+}++.AppError--shell .AppError__panel {+ width: min(100%, 56rem);+}++.AppError__header {+ display: flex;+ align-items: flex-start;+ gap: var(--space-md-fixed);+}++.AppError__icon {+ display: flex;+ flex: 0 0 auto;+ align-items: center;+ justify-content: center;+ padding: var(--space-sm-fixed);+ border-radius: var(--radius-sm);+ color: var(--danger);+ background: color-mix(in oklab, var(--danger) 14%, transparent);+}++.AppError__heading {+ display: flex;+ flex-direction: column;+ min-width: 0;+}++.AppError__title {+ margin: 0;+ font-size: var(--title-lg);+}++.AppError__title:focus {+ outline: none;+}++.AppError__subtitle {+ margin: var(--space-xs-fixed) 0 0;+ color: var(--text-secondary);+ font-size: var(--body-md);+ line-height: var(--leading-normal);+}++.AppError__error {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: var(--space-xs-fixed);+ min-width: 0;+}++.AppError__error .Badge {+ max-width: 100%;+}++.AppError__message {+ display: -webkit-box;+ margin: 0;+ overflow: hidden;+ font-family: monospace;+ font-size: var(--body-md);+ line-height: var(--leading-normal);+ overflow-wrap: anywhere;+ white-space: pre-wrap;+ user-select: text;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;+}++.AppError__message.is-expanded {+ display: block;+ overflow: visible;+ -webkit-line-clamp: unset;+}++.AppError__show-full {+ padding: 0;+ border: none;+ background: none;+ color: var(--accent);+ cursor: pointer;+ font: inherit;+ font-size: var(--body-sm);+ text-decoration: underline;+}++.AppError__show-full:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++.AppError__caption {+ margin: 0;+ color: var(--text-secondary);+ font-size: var(--body-sm);+}++.AppError__details {+ padding: var(--space-sm-fixed) var(--space-md-fixed);+ border: 1px solid color-mix(in oklab, var(--text-default) 16%, transparent);+ border-radius: var(--radius-sm);+ background: color-mix(in oklab, var(--text-default) 4%, transparent);+}++.AppError__details summary {+ cursor: pointer;+ font-size: var(--body-sm);+ font-weight: var(--semibold);+}++.AppError__stack {+ max-height: 18rem;+ margin: var(--space-sm-fixed) 0 0;+ overflow: auto;+ font-family: monospace;+ font-size: var(--body-sm);+ line-height: var(--leading-normal);+ overflow-wrap: anywhere;+ white-space: pre-wrap;+ user-select: text;+}++.AppError__actions {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-xs-fixed);+}++.AppError__actions .Button {+ max-width: 100%;+}++.AppError__actions .Button[aria-disabled='true'] {+ opacity: 0.65;+ cursor: progress;+}++.AppError__actions .Button__label {+ white-space: normal;+ overflow-wrap: anywhere;+}++.AppError__menu {+ position: relative;+ margin-inline-start: auto;+}++.AppError__menuTrigger {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 2.75rem;+ height: 2.75rem;+ padding: 0;+ border: 1px solid transparent;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-default);+ cursor: pointer;+}++.AppError__menuTrigger:hover:not(:disabled) {+ background: color-mix(in oklab, var(--text-default) 8%, transparent);+}++.AppError__menuTrigger:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.AppError__menuTrigger:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++.AppError__menuPanel {+ position: absolute;+ inset-block-start: calc(100% + var(--space-2xs-fixed));+ inset-inline-end: 0;+ z-index: 20;+ display: flex;+ flex-direction: column;+ min-width: 13rem;+ padding: var(--space-2xs-fixed);+ border: 1px solid+ var(--divider, color-mix(in oklab, var(--text-default) 16%, transparent));+ border-radius: var(--radius-sm);+ background: var(--panel-background, var(--modal-background));+ box-shadow: var(--shadow-lg, 0 10px 30px rgba(0, 0, 0, 0.35));+}++.AppError__menuItem {+ display: flex;+ align-items: center;+ gap: var(--space-xs-fixed);+ width: 100%;+ padding: var(--space-xs-fixed) var(--space-sm-fixed);+ border: none;+ border-radius: var(--radius-xs);+ background: none;+ color: var(--text-default);+ cursor: pointer;+ font: inherit;+ text-align: start;+ white-space: nowrap;+}++.AppError__menuItem:hover,+.AppError__menuItem:focus-visible {+ background: color-mix(in oklab, var(--text-default) 10%, transparent);+ outline: none;+}++.AppError__menuItem.is-separated {+ margin-block-start: var(--space-2xs-fixed);+ border-block-start: 1px solid+ var(--divider, color-mix(in oklab, var(--text-default) 16%, transparent));+ border-start-start-radius: 0;+ border-start-end-radius: 0;+}++.AppError__feedback {+ min-height: 1.4em;+}++.AppError__feedback-message {+ margin: 0;+ font-size: var(--body-sm);+}++.AppError__feedback-message.is-success {+ color: var(--success);+}++.AppError__feedback-message.is-error {+ color: var(--danger);+}++body.high-contrast .AppError__icon {+ background: transparent;+ border: 1px solid var(--danger);+}++/* Narrow content area: stack the header and let actions wrap cleanly. */+@container (max-width: 38rem) {+ .AppError--page .AppError__header {+ flex-direction: column;+ }++ .AppError--page .AppError__icon svg {+ width: 18px;+ height: 18px;+ }++ .AppError--page .AppError__actions {+ flex-direction: column;+ align-items: stretch;+ }++ .AppError--page .AppError__actions .Button {+ width: 100%;+ }++ .AppError--page .AppError__menu {+ align-self: flex-end;+ margin-inline-start: 0;+ }+}++@media (max-width: 640px) {+ .AppError {+ padding: var(--space-md-fixed);+ }++ .AppError__header {+ flex-direction: column;+ }++ .AppError__icon svg {+ width: 18px;+ height: 18px;+ }++ .AppError__actions {+ flex-direction: column;+ align-items: stretch;+ }++ .AppError__actions .Button {+ width: 100%;+ }++ .AppError__menu {+ align-self: flex-end;+ margin-inline-start: 0;+ }+}++/* Directional icons point the other way in RTL. */+.isRTL .AppError__mirror {+ transform: scaleX(-1);+}diff --git a/src/frontend/components/UI/AppErrorBoundary/index.stories.tsx b/src/frontend/components/UI/AppErrorBoundary/index.stories.tsxnew file mode 100644index 000000000..219a54089--- /dev/null+++ b/src/frontend/components/UI/AppErrorBoundary/index.stories.tsx@@ -0,0 +1,87 @@+import { expect, userEvent } from 'storybook/test'+import type { Meta, StoryObj } from '@storybook/react-vite'++import { AppErrorScreen } from '.'++const sampleError = new TypeError(+ "Cannot read properties of undefined (reading 'toUpperCase')"+)+sampleError.stack = [+ "TypeError: Cannot read properties of undefined (reading 'toUpperCase')",+ ' at Library/index.tsx:71:20',+ ' at Array.sort (<anonymous>)'+].join('\n')++const meta = {+ title: 'Feedback/AppErrorBoundary',+ component: AppErrorScreen,+ args: {+ variant: 'shell',+ error: sampleError,+ route: '/gamepage/legendary/TestGame',+ onReload: () => undefined+ },+ parameters: {+ layout: 'fullscreen',+ docs: {+ description: {+ component:+ 'Shared crash screen. The shell variant takes over the window; the page variant replaces only the page content and keeps the sidebar usable.'+ }+ }+ }+} satisfies Meta<typeof AppErrorScreen>++export default meta++type Story = StoryObj<typeof meta>++export const Shell: Story = {+ play: async ({ canvas }) => {+ await expect(+ canvas.getByRole('heading', { name: /Something went wrong/i })+ ).toBeInTheDocument()+ await expect(+ canvas.getByRole('button', { name: /Reload Heroic/i })+ ).toBeInTheDocument()+ await expect(+ canvas.getByRole('button', { name: /Copy error report/i })+ ).toBeInTheDocument()+ await expect(+ canvas.queryByRole('button', { name: /Back to library/i })+ ).not.toBeInTheDocument()+ }+}++export const Page: Story = {+ args: {+ variant: 'page',+ onBackToLibrary: () => undefined,+ onRetry: () => undefined,+ onReload: undefined+ },+ play: async ({ canvas }) => {+ await expect(+ canvas.getByRole('heading', { name: /This page couldn't load/i })+ ).toBeInTheDocument()+ await expect(+ canvas.getByRole('button', { name: /Back to library/i })+ ).toBeInTheDocument()+ await expect(+ canvas.getByRole('button', { name: /Copy error report/i })+ ).toBeInTheDocument()+ await expect(+ canvas.queryByRole('button', { name: /Reload Heroic/i })+ ).not.toBeInTheDocument()++ const trigger = canvas.getByRole('button', { name: /More actions/i })+ await expect(trigger).toHaveAttribute('aria-haspopup', 'menu')+ await userEvent.click(trigger)+ await expect(+ await canvas.findByRole('menuitem', { name: /Try this page again/i })+ ).toBeInTheDocument()+ await expect(+ canvas.queryByRole('menuitem', { name: /Reload/i })+ ).not.toBeInTheDocument()+ }+}diff --git a/src/frontend/components/UI/AppErrorBoundary/index.tsx b/src/frontend/components/UI/AppErrorBoundary/index.tsxnew file mode 100644index 000000000..1ed1b8bb5--- /dev/null+++ b/src/frontend/components/UI/AppErrorBoundary/index.tsx@@ -0,0 +1,732 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import {+ isRouteErrorResponse,+ useLocation,+ useNavigate,+ useRouteError+} from 'react-router-dom'+import classNames from 'classnames'+import {+ ArrowLeft,+ Copy,+ Download,+ EllipsisVertical,+ ExternalLink,+ FolderOpen,+ RefreshCw,+ RotateCcw,+ TriangleAlert+} from 'lucide-react'++import Badge from '../Badge'+import Button from '../Button'+import Icon from '../Icon'+import Panel from '../Panel'+import { isLogTooLarge } from './logReport'+import './index.css'++const GITHUB_NEW_ISSUE_URL =+ 'https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher/issues/new?template=bug_report.yaml'++type ErrorVariant = 'page' | 'shell'++type ErrorInfo = {+ name: string+ message: string+ stack: string+}++type Feedback = {+ tone: 'success' | 'error'+ message: string+}++type MenuAction = {+ id: string+ label: string+ icon: typeof FolderOpen+ onSelect: () => void+ separated?: boolean+}++function safeStringify(value: unknown): string {+ if (value == null) return ''+ if (typeof value === 'string') return value+ if (typeof value === 'number' || typeof value === 'boolean') {+ return String(value)+ }+ try {+ return JSON.stringify(value, null, 2)+ } catch {+ // Circular or otherwise unserializable values+ return Object.prototype.toString.call(value)+ }+}++function normalizeError(error: unknown): ErrorInfo {+ if (isRouteErrorResponse(error)) {+ return {+ name: `HTTP ${error.status}`,+ message: safeStringify(error.data) || error.statusText || 'Unknown error',+ stack: ''+ }+ }++ if (error instanceof Error) {+ return {+ name: error.name || 'Error',+ message: error.message || safeStringify(error) || 'Unknown error',+ stack: error.stack ?? ''+ }+ }++ return {+ name: 'Error',+ message: safeStringify(error) || 'Unknown error',+ stack: ''+ }+}++async function writeToClipboard(text: string) {+ try {+ if (navigator.clipboard?.writeText) {+ await navigator.clipboard.writeText(text)+ return+ }+ } catch {+ // Fall through to the Electron clipboard, which does not need a+ // permission prompt and works even when the document is not focused.+ }++ const electronClipboard = window.api?.clipboardWriteText as+ | ((value: string) => void | Promise<void>)+ | undefined++ if (!electronClipboard) {+ throw new Error('Clipboard is unavailable')+ }++ await Promise.resolve(electronClipboard(text))+}++async function readHeroicLog(): Promise<string> {+ try {+ return (await window.api?.getLogContent?.({})) ?? ''+ } catch {+ return ''+ }+}++async function readSystemInfo(): Promise<string> {+ try {+ const info = await window.api?.systemInfo?.get?.(false)+ return info ? JSON.stringify(info, null, 2) : ''+ } catch {+ return ''+ }+}++function reportFileName(date = new Date()): string {+ const pad = (value: number) => String(value).padStart(2, '0')++ return `heroic-error-report-${date.getFullYear()}${pad(+ date.getMonth() + 1+ )}${pad(date.getDate())}-${pad(date.getHours())}${pad(+ date.getMinutes()+ )}${pad(date.getSeconds())}.txt`+}++function downloadTextFile(text: string, filename: string) {+ const blob = new Blob([text], { type: 'text/plain;charset=utf-8' })+ const url = URL.createObjectURL(blob)+ const anchor = document.createElement('a')++ anchor.href = url+ anchor.download = filename+ anchor.style.display = 'none'+ document.body.append(anchor)++ try {+ anchor.click()+ } finally {+ anchor.remove()+ setTimeout(() => URL.revokeObjectURL(url), 0)+ }+}++interface AppErrorScreenProps {+ variant: ErrorVariant+ error: unknown+ route?: string+ onBackToLibrary?: () => void+ onRetry?: () => void+ onReload?: () => void+}++/**+ * Shared crash screen. `page` renders inside the app shell and replaces the+ * page content only; `shell` renders full screen when the shell itself could+ * not load.+ */+// Used by the Storybook stories, which ts-prune does not scan.+// ts-prune-ignore-next+export function AppErrorScreen({+ variant,+ error,+ route,+ onBackToLibrary,+ onRetry,+ onReload+}: AppErrorScreenProps) {+ const { t } = useTranslation()+ const isPage = variant === 'page'++ const titleRef = useRef<HTMLHeadingElement>(null)+ const messageRef = useRef<HTMLParagraphElement>(null)+ const menuRef = useRef<HTMLDivElement>(null)+ const menuTriggerRef = useRef<HTMLButtonElement>(null)++ const [heroicVersion, setHeroicVersion] = useState('')+ const [versionSettled, setVersionSettled] = useState(false)+ const [busy, setBusy] = useState(false)+ const [feedback, setFeedback] = useState<Feedback | null>(null)+ const [menuOpen, setMenuOpen] = useState(false)+ const [messageExpanded, setMessageExpanded] = useState(false)+ const [messageOverflows, setMessageOverflows] = useState(false)++ const [occurredAt] = useState(() => new Date().toISOString())+ const [reportMode, setReportMode] = useState<'copy' | 'download'>('copy')++ const errorInfo = useMemo(() => normalizeError(error), [error])++ const logRef = useRef<string | null>(null)+ const logRequestRef = useRef<Promise<string> | null>(null)++ const loadLog = useCallback(() => {+ if (logRef.current !== null) return Promise.resolve(logRef.current)++ if (!logRequestRef.current) {+ logRequestRef.current = readHeroicLog().then((log) => {+ logRef.current = log+ return log+ })+ }++ return logRequestRef.current+ }, [])++ useEffect(() => {+ let cancelled = false++ void loadLog().then((log) => {+ if (!cancelled) {+ setReportMode(isLogTooLarge(log) ? 'download' : 'copy')+ }+ })++ return () => {+ cancelled = true+ }+ }, [loadLog])++ useEffect(() => {+ titleRef.current?.focus()+ }, [])++ useEffect(() => {+ let cancelled = false++ Promise.resolve(window.api?.getHeroicVersion?.())+ .then((version) => {+ if (!cancelled && typeof version === 'string') {+ setHeroicVersion(version)+ }+ })+ .catch(() => {+ // The version is a nice-to-have, never block the screen on it+ })+ .finally(() => {+ if (!cancelled) setVersionSettled(true)+ })++ return () => {+ cancelled = true+ }+ }, [])++ useEffect(() => {+ const element = messageRef.current+ if (!element || messageExpanded) return++ const measure = () => {+ setMessageOverflows(element.scrollHeight > element.clientHeight + 1)+ }++ measure()+ const observer = new ResizeObserver(measure)+ observer.observe(element)++ return () => observer.disconnect()+ }, [errorInfo.message, messageExpanded])++ useEffect(() => {+ if (!menuOpen) return++ const handlePointerDown = (event: MouseEvent) => {+ if (!menuRef.current?.contains(event.target as Node)) {+ setMenuOpen(false)+ }+ }++ document.addEventListener('mousedown', handlePointerDown)+ return () => document.removeEventListener('mousedown', handlePointerDown)+ }, [menuOpen])++ // Make sure the crash also ends up in the log, even if the user never+ // copies anything before closing Heroic. The version arrives asynchronously,+ // so guard against logging once per version update.+ const hasLoggedCrash = useRef(false)+ useEffect(() => {+ if (!versionSettled || hasLoggedCrash.current) return+ hasLoggedCrash.current = true++ try {+ window.api?.logError?.(+ [+ 'Unexpected application error',+ `Route: ${route || 'unknown'}`,+ `Heroic version: ${heroicVersion || 'unknown'}`,+ `${errorInfo.name}: ${errorInfo.message}`,+ errorInfo.stack+ ]+ .filter(Boolean)+ .join('\n')+ )+ } catch {+ // The error boundary must never throw while reporting an error+ }+ }, [route, heroicVersion, errorInfo, versionSettled])++ const platform = useMemo(+ () =>+ typeof navigator === 'undefined'+ ? 'unknown'+ : `${navigator.platform || 'unknown'} — ${navigator.userAgent}`,+ []+ )++ const technicalDetails = useMemo(+ () =>+ [+ `Time: ${occurredAt}`,+ `Route: ${route || 'unknown'}`,+ `Heroic version: ${heroicVersion || 'unknown'}`,+ `Platform: ${platform}`,+ '',+ `${errorInfo.name}: ${errorInfo.message}`,+ errorInfo.stack ? `\nStack trace:\n${errorInfo.stack}` : ''+ ].join('\n'),+ [+ occurredAt,+ route,+ heroicVersion,+ platform,+ errorInfo.name,+ errorInfo.message,+ errorInfo.stack+ ]+ )++ const buildReport = useCallback(+ (log: string, systemInfo: string) =>+ [+ '=== Heroic Games Launcher error report ===',+ '',+ technicalDetails,+ '',+ '=== System information ===',+ systemInfo || '(unavailable)',+ '',+ '=== Heroic log ===',+ log.trim() || '(no log file found)'+ ].join('\n'),+ [technicalDetails]+ )++ const handleCopyReport = async () => {+ setBusy(true)+ setFeedback(null)++ try {+ const [log, systemInfo] = await Promise.all([loadLog(), readSystemInfo()])+ const report = buildReport(log, systemInfo)++ await writeToClipboard(report)+ setFeedback({+ tone: 'success',+ message: log.trim()+ ? t(+ 'error.report-copied',+ 'Error report copied. Paste it into your issue on GitHub.'+ )+ : t(+ 'error.report-copied-no-log',+ 'Error report copied, without the Heroic log (none was found).'+ )+ })+ } catch {+ setFeedback({+ tone: 'error',+ message: t(+ 'error.copy-failed',+ 'Could not copy. Try again, or open the log folder.'+ )+ })+ } finally {+ setBusy(false)+ }+ }++ const handleDownloadReport = async () => {+ setBusy(true)+ setFeedback(null)++ try {+ const [log, systemInfo] = await Promise.all([loadLog(), readSystemInfo()])++ downloadTextFile(buildReport(log, systemInfo), reportFileName())+ setFeedback({+ tone: 'success',+ message: t(+ 'error.report-downloaded',+ 'Error report downloaded. Attach it to your issue on GitHub.'+ )+ })+ } catch {+ setFeedback({+ tone: 'error',+ message: t(+ 'error.report-download-failed',+ 'Could not download the report. Try again.'+ )+ })+ } finally {+ setBusy(false)+ }+ }++ const handleOpenLogFolder = () => {+ try {+ window.api?.showLogFileInFolder?.({})+ } catch {+ // Nothing sensible to do if the folder cannot be opened+ }+ }++ const handleOpenIssue = () => {+ try {+ window.api?.openExternalUrl?.(GITHUB_NEW_ISSUE_URL)+ } catch {+ // Ignore+ }+ }++ const closeMenu = useCallback((returnFocus = true) => {+ setMenuOpen(false)+ if (returnFocus) {+ menuTriggerRef.current?.focus()+ }+ }, [])++ const handleMenuKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {+ const items = Array.from(+ menuRef.current?.querySelectorAll<HTMLButtonElement>(+ '[role="menuitem"]:not([disabled])'+ ) ?? []+ )+ const current = items.indexOf(document.activeElement as HTMLButtonElement)++ if (event.key === 'Escape') {+ event.preventDefault()+ closeMenu()+ return+ }++ if (!items.length) return++ let next = -1+ if (event.key === 'ArrowDown') next = (current + 1) % items.length+ if (event.key === 'ArrowUp')+ next = (current - 1 + items.length) % items.length+ if (event.key === 'Home') next = 0+ if (event.key === 'End') next = items.length - 1++ if (next >= 0) {+ event.preventDefault()+ items[next].focus()+ }+ }++ const handleMenuToggle = () => {+ if (menuOpen) {+ closeMenu()+ return+ }++ setMenuOpen(true)+ // Move focus to the first action once the menu is mounted+ requestAnimationFrame(() => {+ menuRef.current+ ?.querySelector<HTMLButtonElement>('[role="menuitem"]')+ ?.focus()+ })+ }++ const menuActions: MenuAction[] = [+ ...(isPage && onRetry+ ? [+ {+ id: 'retry',+ label: t('error.retry-page', 'Try this page again'),+ icon: RotateCcw,+ onSelect: onRetry+ }+ ]+ : []),+ {+ id: 'open-log-folder',+ label: t('error.open-log-folder', 'Open log folder'),+ icon: FolderOpen,+ onSelect: handleOpenLogFolder+ },+ {+ id: 'download-report',+ label: t('error.download-report', 'Download error report'),+ icon: Download,+ onSelect: handleDownloadReport+ },+ {+ id: 'report-issue',+ label: t('error.report-issue', 'Report on GitHub'),+ icon: ExternalLink,+ onSelect: handleOpenIssue,+ separated: true+ }+ ]++ return (+ <div+ className={classNames('AppError', `AppError--${variant}`)}+ data-variant={variant}+ >+ <Panel className="AppError__panel" padding="lg" tone="solid">+ <header className="AppError__header">+ <span className="AppError__icon" aria-hidden="true">+ <Icon glyph={TriangleAlert} size="lg" />+ </span>+ <div className="AppError__heading">+ <h1 className="AppError__title" ref={titleRef} tabIndex={-1}>+ {isPage+ ? t('error.page.title', "This page couldn't load")+ : t('error.boundary.title', 'Something went wrong')}+ </h1>+ <p className="AppError__subtitle">+ {isPage+ ? t(+ 'error.page.subtitle',+ 'The rest of Heroic is still working. Go back to your library, or try this page again.'+ )+ : t(+ 'error.boundary.subtitle',+ "Heroic couldn't finish loading this screen. Reloading usually fixes it."+ )}+ </p>+ </div>+ </header>++ <div className="AppError__error">+ <Badge variant="error">{errorInfo.name}</Badge>+ <p+ className={classNames('AppError__message', {+ 'is-expanded': messageExpanded+ })}+ ref={messageRef}+ >+ {errorInfo.message}+ </p>+ {messageOverflows && !messageExpanded && (+ <button+ type="button"+ className="AppError__show-full"+ onClick={() => setMessageExpanded(true)}+ >+ {t('error.show-full-message', 'Show full message')}+ </button>+ )}+ </div>++ {isPage && heroicVersion && (+ <p className="AppError__caption">+ {t('error.version-caption', 'Heroic {{version}}', {+ version: heroicVersion+ })}+ </p>+ )}++ <details className="AppError__details">+ <summary>{t('error.technical-details', 'Technical details')}</summary>+ <pre className="AppError__stack">{technicalDetails}</pre>+ </details>++ <div className="AppError__actions">+ {isPage ? (+ <Button+ icon={+ <Icon+ glyph={ArrowLeft}+ size="sm"+ className="AppError__mirror"+ />+ }+ onClick={onBackToLibrary}+ >+ {t('error.back-to-library', 'Back to library')}+ </Button>+ ) : (+ <Button+ icon={<Icon glyph={RefreshCw} size="sm" />}+ onClick={onReload}+ >+ {t('error.reload', 'Reload Heroic')}+ </Button>+ )}++ <Button+ variant="secondary"+ icon={+ <Icon+ glyph={reportMode === 'download' ? Download : Copy}+ size="sm"+ />+ }+ onClick={() => {+ if (!busy) {+ void (reportMode === 'download'+ ? handleDownloadReport()+ : handleCopyReport())+ }+ }}+ aria-disabled={busy}+ >+ {busy+ ? t('error.preparing-report', 'Preparing…')+ : reportMode === 'download'+ ? t('error.download-report', 'Download error report')+ : t('error.copy-report', 'Copy error report')}+ </Button>++ <div+ className="AppError__menu"+ ref={menuRef}+ onBlur={(event) => {+ if (+ !menuRef.current?.contains(event.relatedTarget as Node | null)+ ) {+ setMenuOpen(false)+ }+ }}+ >+ <button+ type="button"+ ref={menuTriggerRef}+ className="AppError__menuTrigger"+ aria-label={t('error.more-actions', 'More actions')}+ aria-haspopup="menu"+ aria-expanded={menuOpen}+ onClick={handleMenuToggle}+ onKeyDown={(event) => {+ if (event.key === 'Escape') closeMenu()+ }}+ >+ <Icon glyph={EllipsisVertical} size="lg" />+ </button>++ {menuOpen && (+ <div+ className="AppError__menuPanel"+ role="menu"+ aria-label={t('error.more-actions', 'More actions')}+ onKeyDown={handleMenuKeyDown}+ >+ {menuActions.map((action) => (+ <button+ key={action.id}+ type="button"+ role="menuitem"+ className={classNames('AppError__menuItem', {+ 'is-separated': action.separated+ })}+ onClick={() => {+ // Retry navigates away; every other action leaves the+ // page in place, so keep the keyboard user on the trigger.+ closeMenu(action.id !== 'retry')+ action.onSelect()+ }}+ >+ <Icon glyph={action.icon} size="sm" />+ <span>{action.label}</span>+ </button>+ ))}+ </div>+ )}+ </div>+ </div>++ <div className="AppError__feedback" aria-live="polite">+ {feedback && (+ <p className={`AppError__feedback-message is-${feedback.tone}`}>+ {feedback.message}+ </p>+ )}+ </div>+ </Panel>+ </div>+ )+}++/** Full-screen boundary for errors thrown by the app shell itself. */+export default function AppErrorBoundary() {+ const error = useRouteError()+ const location = useLocation()++ const route = `${location.pathname}${location.search}${location.hash}`++ return (+ <AppErrorScreen+ variant="shell"+ error={error}+ route={route}+ onReload={() => window.location.reload()}+ />+ )+}++/** Boundary for the pathless route that wraps the pages inside the shell. */+export function PageErrorBoundary() {+ const error = useRouteError()+ const location = useLocation()+ const navigate = useNavigate()++ const route = `${location.pathname}${location.search}${location.hash}`++ return (+ <AppErrorScreen+ variant="page"+ error={error}+ route={route}+ onBackToLibrary={() => navigate('/')}+ onRetry={() => navigate(route, { replace: true })}+ />+ )+}diff --git a/src/frontend/components/UI/AppErrorBoundary/logReport.ts b/src/frontend/components/UI/AppErrorBoundary/logReport.tsnew file mode 100644index 000000000..71ae8e06b--- /dev/null+++ b/src/frontend/components/UI/AppErrorBoundary/logReport.ts@@ -0,0 +1,15 @@+const MAX_LOG_LINES = 500+const MAX_LOG_CHARACTERS = 1_000_000++/**+ * Reports are pasted into GitHub issues, so long logs should be downloaded+ * instead of copied to the clipboard.+ */+export function isLogTooLarge(log: string): boolean {+ if (log.length > MAX_LOG_CHARACTERS) return true++ const lines = log.split(/\r?\n/)+ if (lines.at(-1) === '') lines.pop()++ return lines.length > MAX_LOG_LINES+}