diff --git a/gui/app/public/i18n/en/translation.ftl b/gui/app/public/i18n/en/translation.ftl index b026d716b..074ea718f 100644 --- a/gui/app/public/i18n/en/translation.ftl +++ b/gui/app/public/i18n/en/translation.ftl @@ -10,6 +10,9 @@ websocket-connection_lost = The server crashed! websocket-connection_lost-desc = It looks like the SlimeVR server crashed. Check the logs and restart the program. websocket-timedout = Could not connect to the server websocket-timedout-desc = It looks like the SlimeVR server crashed or timed out. Check the logs and restart the program. +websocket-report-question = Help us fix this by sending an error report. +websocket-report-send = Send report +websocket-report-sent = Report sent. Thank you! websocket-error-close = Exit SlimeVR websocket-error-logs = Open the logs Folder diff --git a/gui/app/src/components/onboarding/pages/ConnectionLost.tsx b/gui/app/src/components/onboarding/pages/ConnectionLost.tsx index 0bca3234e..7a3a862fe 100644 --- a/gui/app/src/components/onboarding/pages/ConnectionLost.tsx +++ b/gui/app/src/components/onboarding/pages/ConnectionLost.tsx @@ -5,9 +5,35 @@ import { EmptyLayout } from '@/components/EmptyLayout'; import { useConfig } from '@/hooks/config'; import { useElectron } from '@/hooks/electron'; import { useWebsocketAPI } from '@/hooks/websocket-api'; +import { useCrashReport } from '@/hooks/error-reporting'; +import { CrashReportKind } from '@slimevr/gui-shared'; import { error } from '@/utils/logging'; import { Localized } from '@fluent/react'; +function CrashReportBanner({ kind }: { kind: CrashReportKind }) { + const { available, sent, send } = useCrashReport(kind); + + if (!available) return null; + + return ( +
+
+ +
+ {!sent && ( +
+ ); +} + function Error({ title, desc }: { title: string; desc: string }) { const electron = useElectron(); const { saveConfig } = useConfig(); @@ -30,7 +56,7 @@ function Error({ title, desc }: { title: string; desc: string }) { return ( <> -
+
@@ -62,28 +88,38 @@ export function ConnectionLost() { return ( -
-
- {isLoading && ( - <> - -
- - - -
- - )} - {isCrashed && ( - - )} - {isTimedOut && ( - - )} +
+
+
+ {isLoading && ( + <> + +
+ + + +
+ + )} + {isCrashed && ( + + )} + {isTimedOut && ( + + )} +
+ {(isCrashed || isTimedOut) && ( +
+ +
+ )}
); diff --git a/gui/app/src/components/providers/ConfigContext.tsx b/gui/app/src/components/providers/ConfigContext.tsx index e5c329fd0..6b22d0b7f 100644 --- a/gui/app/src/components/providers/ConfigContext.tsx +++ b/gui/app/src/components/providers/ConfigContext.tsx @@ -1,17 +1,5 @@ import { ReactNode } from 'react'; import { ConfigContextC, loadConfig, useConfigProvider } from '@/hooks/config'; -import { initSentry } from '@/utils/sentry'; -import { getDefaultStore } from 'jotai'; -import { ErrorReportingConsent } from 'solarxr-protocol'; -import { serverErrorReportingAtom } from '@/hooks/error-reporting'; - -const isSteam = window.electronAPI ? await window.electronAPI.isSteam() : false; -initSentry( - isSteam, - () => - getDefaultStore().get(serverErrorReportingAtom)?.consent ?? - ErrorReportingConsent.UNDECIDED -); const config = await loadConfig(); diff --git a/gui/app/src/components/settings/pages/BehaviorSettings.tsx b/gui/app/src/components/settings/pages/BehaviorSettings.tsx index 6f04f7efa..144754325 100644 --- a/gui/app/src/components/settings/pages/BehaviorSettings.tsx +++ b/gui/app/src/components/settings/pages/BehaviorSettings.tsx @@ -255,9 +255,9 @@ export function BehaviorSettings() { variant="toggle" name="errorReporting" id="behavior-error-reporting" - disabled={errorReporting.consent === null} + disabled={errorReporting.setting === null} checked={ - errorReporting.consent === ErrorReportingConsent.ALLOWED + errorReporting.setting === ErrorReportingConsent.ALLOWED } onChange={(event) => errorReporting.answer( diff --git a/gui/app/src/hooks/error-reporting.ts b/gui/app/src/hooks/error-reporting.ts index ec85d142e..2323321a4 100644 --- a/gui/app/src/hooks/error-reporting.ts +++ b/gui/app/src/hooks/error-reporting.ts @@ -1,4 +1,4 @@ -import { useEffect } from 'react'; +import { useEffect, useState } from 'react'; import { atom, useAtom, useAtomValue } from 'jotai'; import { ChangeErrorReportingSettingsRequestT, @@ -7,27 +7,28 @@ import { ErrorReportingSettingsResponseT, RpcMessage, } from 'solarxr-protocol'; -import { ErrorReportingState } from '@slimevr/gui-shared'; +import { CrashReportKind, ErrorReportingState } from '@slimevr/gui-shared'; import { useWebsocketAPI } from './websocket-api'; -import { applyErrorReporting, applyErrorReportingConsent } from '@/utils/sentry'; +import { applyErrorReporting } from '@/utils/sentry'; export type ErrorReportingAnswer = | ErrorReportingConsent.ALLOWED | ErrorReportingConsent.DENIED; -interface PendingAnswer { - consent: ErrorReportingAnswer; - /** Only used if the server has no answer yet */ - offline: boolean; -} - +/** What the server said */ export const serverErrorReportingAtom = atom(null); -const pendingAnswerAtom = atom(null); +/** What the user chose, until the server confirms it */ +const pendingAnswerAtom = atom(null); + +export const sessionConsentAtom = atom( + (get) => get(serverErrorReportingAtom)?.consent ?? ErrorReportingConsent.UNDECIDED +); export function useProvideErrorReporting() { const { useRPCPacket, sendRPCPacket, isConnected } = useWebsocketAPI(); const [server, setServer] = useAtom(serverErrorReportingAtom); const [pending, setPending] = useAtom(pendingAnswerAtom); + const consent = useAtomValue(sessionConsentAtom); useEffect(() => { if (!isConnected) return; @@ -48,45 +49,52 @@ export function useProvideErrorReporting() { ); useEffect(() => { - if (!isConnected || !server || !pending) return; - if (server.consent === pending.consent) { - setPending(null); - } else if (!pending.offline || server.consent === ErrorReportingConsent.UNDECIDED) { - sendRPCPacket( - RpcMessage.ChangeErrorReportingSettingsRequest, - new ChangeErrorReportingSettingsRequestT(pending.consent) - ); - } else { - // Offline answer, the earlier answer wins + if (!isConnected || !server || pending === null) return; + if (server.consent === pending) { setPending(null); + return; } + sendRPCPacket( + RpcMessage.ChangeErrorReportingSettingsRequest, + new ChangeErrorReportingSettingsRequestT(pending) + ); }, [isConnected, server, pending]); useEffect(() => { - if (server) applyErrorReporting(server); - }, [server]); - - const consent = server?.consent; - useEffect(() => { - if (consent !== undefined) applyErrorReportingConsent(consent); - }, [consent]); + const identity = server + ? { userId: server.userId, sessionId: server.sessionId } + : null; + applyErrorReporting(consent, identity); + }, [consent, server?.userId, server?.sessionId]); } export function useErrorReporting() { - const { isConnected, isFirstConnection, timedOut } = useWebsocketAPI(); + const { isConnected } = useWebsocketAPI(); const server = useAtomValue(serverErrorReportingAtom); const [pending, setPending] = useAtom(pendingAnswerAtom); - const unanswered = - pending === null && - (server === null || server.consent === ErrorReportingConsent.UNDECIDED); - // The server can't ask when it crashed or never started - const serverUnreachable = !isConnected && (!isFirstConnection || timedOut); - return { - consent: pending?.consent ?? server?.consent ?? null, - needsAnswer: unanswered && (isConnected ? server !== null : serverUnreachable), - answer: (consent: ErrorReportingAnswer) => - setPending({ consent, offline: !isConnected }), + setting: pending ?? server?.consent ?? null, + needsAnswer: + isConnected && + server?.consent === ErrorReportingConsent.UNDECIDED && + pending === null, + answer: (consent: ErrorReportingAnswer) => setPending(consent), + }; +} + +export function useCrashReport(kind: CrashReportKind) { + const consent = useAtomValue(sessionConsentAtom); + const [sent, setSent] = useState(false); + // Only Electron main has the server crash data + const isElectron = !!window.electronAPI; + const alreadyReported = consent === ErrorReportingConsent.ALLOWED; + + return { + available: isElectron && !alreadyReported, + sent, + send: async () => { + if (await window.electronAPI.sendCrashReport(kind)) setSent(true); + }, }; } diff --git a/gui/app/src/index.tsx b/gui/app/src/index.tsx index 311ba4f39..17d9f8fb0 100644 --- a/gui/app/src/index.tsx +++ b/gui/app/src/index.tsx @@ -1,3 +1,4 @@ +import './utils/sentry-init'; import '@fontsource/poppins/500.css'; import '@fontsource/poppins/700.css'; import '@fontsource/jetbrains-mono/500.css'; diff --git a/gui/app/src/utils/sentry-init.ts b/gui/app/src/utils/sentry-init.ts new file mode 100644 index 000000000..f582ba84a --- /dev/null +++ b/gui/app/src/utils/sentry-init.ts @@ -0,0 +1,6 @@ +import { getDefaultStore } from 'jotai'; +import { sessionConsentAtom } from '@/hooks/error-reporting'; +import { initSentry } from './sentry'; + +const isSteam = window.electronAPI ? await window.electronAPI.isSteam() : false; +initSentry(isSteam, () => getDefaultStore().get(sessionConsentAtom)); diff --git a/gui/app/src/utils/sentry.ts b/gui/app/src/utils/sentry.ts index a8d4dba55..7482e553d 100644 --- a/gui/app/src/utils/sentry.ts +++ b/gui/app/src/utils/sentry.ts @@ -8,7 +8,6 @@ import { useNavigationType, } from 'react-router-dom'; import { ErrorReportingConsent } from 'solarxr-protocol'; -import { ErrorReportingState } from '@slimevr/gui-shared'; const OFFLINE_DB_NAME = 'sentry-offline'; const OFFLINE_STORE_NAME = 'queue'; @@ -49,7 +48,6 @@ export function initSentry(isSteam: boolean, getConsent: () => ErrorReportingCon if (sessionId) log.attributes = { ...log.attributes, ['session_id']: sessionId }; return log; }, - // The offline queue caches everything until the user answered transport: (options) => Sentry.makeBrowserOfflineTransport(Sentry.makeFetchTransport)({ ...options, @@ -73,6 +71,24 @@ export function initSentry(isSteam: boolean, getConsent: () => ErrorReportingCon log('Initialized the Sentry client, reports are held until consent'); } +export interface ReportingIdentity { + userId: string; + sessionId: string; +} + +let appliedConsent = ErrorReportingConsent.UNDECIDED; + +function applyGate(consent: ErrorReportingConsent) { + log(`Error reporting consent: ${ErrorReportingConsent[consent]}`); + if (consent === ErrorReportingConsent.ALLOWED) { + startReplay(); + Sentry.getClient()?.getTransport()?.flush(); + } else { + Sentry.getReplay()?.stop(); + if (consent === ErrorReportingConsent.DENIED) clearOfflineQueue(); + } +} + function clearOfflineQueue() { const request = indexedDB.open(OFFLINE_DB_NAME); request.onupgradeneeded = () => request.transaction?.abort(); @@ -103,30 +119,30 @@ function startReplay() { ); } -export function applyErrorReporting(server: ErrorReportingState) { - window.electronAPI?.setErrorReporting(server); - - if (!isEnabled) return; - Sentry.setUser({ id: server.userId }); - Sentry.setTag('session_id', server.sessionId); +function applyIdentity(identity: ReportingIdentity) { + Sentry.setUser({ id: identity.userId }); + Sentry.setTag('session_id', identity.sessionId); if (!Sentry.getIsolationScope().getSession()) { - Sentry.startSession({ ignoreDuration: true, user: { id: server.userId } }); + Sentry.startSession({ ignoreDuration: true, user: { id: identity.userId } }); Sentry.captureSession(); } } -/** Call when the consent changes */ -export function applyErrorReportingConsent(consent: ErrorReportingConsent) { - if (!isEnabled) return; - log(`Error reporting consent: ${ErrorReportingConsent[consent]}`); +export function applyErrorReporting( + consent: ErrorReportingConsent, + identity: ReportingIdentity | null +) { + window.electronAPI?.setErrorReporting({ + consent, + userId: identity?.userId ?? '', + sessionId: identity?.sessionId ?? '', + }); - if (consent === ErrorReportingConsent.ALLOWED) { - startReplay(); - // No timeout: sends what the offline queue held - Sentry.getClient()?.getTransport()?.flush(); - } else { - Sentry.getReplay()?.stop(); - if (consent === ErrorReportingConsent.DENIED) clearOfflineQueue(); + if (!isEnabled) return; + if (identity) applyIdentity(identity); + if (consent !== appliedConsent) { + appliedConsent = consent; + applyGate(consent); } } diff --git a/gui/electron/main/index.ts b/gui/electron/main/index.ts index b6192322e..405b097a7 100644 --- a/gui/electron/main/index.ts +++ b/gui/electron/main/index.ts @@ -42,7 +42,10 @@ import { captureJavaNotFound, captureServerExit, captureServerLaunchError, + flushErrorReports, initSentry, + sendCrashReport, + trackServerOutput, } from './sentry'; type Stores = Awaited>; @@ -217,6 +220,8 @@ handleIpc(IPC_CHANNELS.SET_ERROR_REPORTING, (e, state) => { applyErrorReporting(state); }); +handleIpc(IPC_CHANNELS.SEND_CRASH_REPORT, (e, kind) => sendCrashReport(kind)); + const defaultWindowState: { width: number; height: number; @@ -513,6 +518,7 @@ const spawnServer = async () => { outputTail.push(...message.split('\n').filter((line) => line.length > 0)); outputTail.splice(0, Math.max(0, outputTail.length - SERVER_OUTPUT_TAIL_LINES)); }; + trackServerOutput(() => outputTail.join('\n')); serverProcess.stdout?.on('data', (message) => { keepOutput(message.toString()); @@ -615,6 +621,7 @@ app.whenReady().then(async () => { await stores.cache.save(); discordPresence.destroy(); await saveWindowState(); + await flushErrorReports(); await closeLogger(); app.exit(0); }); diff --git a/gui/electron/main/sentry.ts b/gui/electron/main/sentry.ts index cd77a94a7..7e488f894 100644 --- a/gui/electron/main/sentry.ts +++ b/gui/electron/main/sentry.ts @@ -9,23 +9,34 @@ import { app } from 'electron'; import { join } from 'node:path'; import { mkdir, readdir, readFile, rm, unlink, writeFile } from 'node:fs/promises'; import { randomUUID } from 'node:crypto'; -import { ErrorReportingState } from '@slimevr/gui-shared'; +import { CrashReportKind, ErrorReportingState } from '@slimevr/gui-shared'; import { ErrorReportingConsent } from 'solarxr-protocol'; import { getGuiDataFolder } from './paths'; import { logger, setLogForwarder } from './logger'; const HELD_LIMIT = 500; const SERVER_ROUTE_TAG = 'route'; +const USER_REQUESTED_TAG = 'user_requested'; type OfflineTransportOptions = Parameters< ReturnType >[0]; +function isUserRequested(envelope: Envelope) { + return envelope[1].some( + ([header, payload]) => + header.type === 'event' && + (payload as { tags?: Record })?.tags?.[USER_REQUESTED_TAG] === + 'true' + ); +} + /** Caches everything on disk until the user answered */ function createConsentGate() { const folder = join(getGuiDataFolder(), 'sentry-held'); let consent = ErrorReportingConsent.UNDECIDED; let inner: Transport | null = null; + let sending: Promise = Promise.resolve(); async function hold(envelope: Envelope) { await mkdir(folder, { recursive: true }); @@ -59,7 +70,7 @@ function createConsentGate() { inner = transport; return { send: async (envelope) => { - if (consent === ErrorReportingConsent.ALLOWED) + if (consent === ErrorReportingConsent.ALLOWED || isUserRequested(envelope)) return transport.send(envelope); if (consent === ErrorReportingConsent.UNDECIDED) await hold(envelope); return {}; @@ -71,13 +82,14 @@ function createConsentGate() { if (consent === next) return; consent = next; if (next === ErrorReportingConsent.ALLOWED && inner) { - sendHeld(inner).catch((e) => + sending = sendHeld(inner).catch((e) => logger.warn({ err: e }, 'Failed to send held error reports') ); } else if (next === ErrorReportingConsent.DENIED) { rm(folder, { recursive: true, force: true }).catch(() => undefined); } }, + settled: () => sending, }; } @@ -131,22 +143,62 @@ export function initSentry(isSteam: boolean) { export function applyErrorReporting(state: ErrorReportingState) { consentGate.apply(state.consent); if (!Sentry.isInitialized()) return; - Sentry.setUser({ id: state.userId }); - Sentry.setTag('session_id', state.sessionId); + // Empty until the server answered + if (state.userId) Sentry.setUser({ id: state.userId }); + if (state.sessionId) Sentry.setTag('session_id', state.sessionId); +} + +export async function flushErrorReports() { + await consentGate.settled(); + if (Sentry.isInitialized()) await Sentry.flush(2000); } const serverScope = { tags: { [SERVER_ROUTE_TAG]: 'server' } }; +interface ServerFailure { + eventId: string; + code: number | null; + signal: string | null; + outputTail: string; +} + +let lastServerFailure: ServerFailure | null = null; +let serverOutputTail = () => ''; + +/** Lets a user requested report include the live server output */ +export function trackServerOutput(getOutputTail: () => string) { + serverOutputTail = getOutputTail; +} + export function captureServerExit( code: number | null, signal: string | null, outputTail: string ) { - Sentry.captureMessage('server_exit_nonzero', { + const eventId = Sentry.captureMessage('server_exit_nonzero', { ...serverScope, level: 'error', extra: { code, signal, outputTail }, }); + lastServerFailure = { eventId, code, signal, outputTail }; +} + +export function sendCrashReport(kind: CrashReportKind) { + if (!Sentry.isInitialized()) return false; + const failure = lastServerFailure; + Sentry.withScope((scope) => { + scope.setTag(USER_REQUESTED_TAG, 'true'); + Sentry.captureEvent({ + event_id: failure?.eventId, + message: failure ? 'server_exit_nonzero' : `server_${kind}`, + level: 'error', + tags: serverScope.tags, + extra: failure + ? { code: failure.code, signal: failure.signal, outputTail: failure.outputTail } + : { outputTail: serverOutputTail() }, + }); + }); + return true; } export function captureServerLaunchError(err: Error) { diff --git a/gui/electron/preload/index.ts b/gui/electron/preload/index.ts index 99be88ec3..8eb7dd0f6 100644 --- a/gui/electron/preload/index.ts +++ b/gui/electron/preload/index.ts @@ -58,4 +58,5 @@ contextBridge.exposeInMainWorld('electronAPI', { ipcRenderer.invoke(IPC_CHANNELS.SET_KEYBIND_RECORDING, recording), setErrorReporting: (state) => ipcRenderer.invoke(IPC_CHANNELS.SET_ERROR_REPORTING, state), + sendCrashReport: (kind) => ipcRenderer.invoke(IPC_CHANNELS.SEND_CRASH_REPORT, kind), } satisfies IElectronAPI); diff --git a/gui/shared/src/interface.ts b/gui/shared/src/interface.ts index 9b0389272..d67bf5c46 100644 --- a/gui/shared/src/interface.ts +++ b/gui/shared/src/interface.ts @@ -39,6 +39,9 @@ export type DiscordPresence = | { enable: false } | { enable: true; activity: string; iconText: string | undefined }; +/** Which crash screen the user sent a report from */ +export type CrashReportKind = 'timeout' | 'connection_lost'; + export interface ErrorReportingState { consent: ErrorReportingConsent; userId: string; @@ -70,6 +73,7 @@ export interface IElectronAPI { isSteam: () => Promise; setKeybindRecording: (recording: boolean) => void; setErrorReporting: (state: ErrorReportingState) => void; + sendCrashReport: (kind: CrashReportKind) => Promise; } declare global { diff --git a/gui/shared/src/ipc.ts b/gui/shared/src/ipc.ts index 511fd99f3..4e78a085b 100644 --- a/gui/shared/src/ipc.ts +++ b/gui/shared/src/ipc.ts @@ -5,6 +5,7 @@ import { SaveDialogReturnValue, } from 'electron'; import { + CrashReportKind, DiscordPresence, ErrorReportingState, GHGet, @@ -30,6 +31,7 @@ export const IPC_CHANNELS = { IS_STEAM: 'is-steam', SET_KEYBIND_RECORDING: 'set-keybind-recording', SET_ERROR_REPORTING: 'set-error-reporting', + SEND_CRASH_REPORT: 'send-crash-report', } as const; export interface IpcInvokeMap { @@ -61,4 +63,5 @@ export interface IpcInvokeMap { [IPC_CHANNELS.IS_STEAM]: () => boolean; [IPC_CHANNELS.SET_KEYBIND_RECORDING]: (recording: boolean) => void; [IPC_CHANNELS.SET_ERROR_REPORTING]: (state: ErrorReportingState) => void; + [IPC_CHANNELS.SEND_CRASH_REPORT]: (kind: CrashReportKind) => boolean; }