Fix sentry issue when no server

This commit is contained in:
loucass003 committed 2026-10-15 18:07:33 +02:00
1 parent 0140b0970d
commit 75caf21de5
13 files changed
+225 -100

No files matched your search

+3
View File
@@ -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
@@ -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 (
<div className="flex flex-col xs:flex-row items-center gap-3 xs:gap-4 w-full max-w-2xl bg-background-70 rounded-lg px-4 py-3 min-h-[64px]">
<div className="flex-grow text-center xs:text-left">
<Typography
id={sent ? 'websocket-report-sent' : 'websocket-report-question'}
/>
</div>
{!sent && (
<Button
variant="secondary"
className="flex-shrink-0"
onClick={send}
id="websocket-report-send"
/>
)}
</div>
);
}
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 (
<>
<LoaderIcon slimeState={SlimeState.SAD} size={200} />
<div>
<div className="flex flex-col items-center text-center">
<Localized id={title}>
<Typography variant="main-title" />
</Localized>
@@ -62,28 +88,38 @@ export function ConnectionLost() {
return (
<EmptyLayout>
<div className="flex w-full h-full justify-center items-center p-4">
<div className="flex flex-col items-center gap-4 -mt-12">
{isLoading && (
<>
<LoaderIcon slimeState={SlimeState.JUMPY} size={200} />
<div>
<Localized id="websocket-connecting">
<Typography variant="main-title" />
</Localized>
</div>
</>
)}
{isCrashed && (
<Error
title="websocket-connection_lost"
desc="websocket-connection_lost-desc"
/>
)}
{isTimedOut && (
<Error title="websocket-timedout" desc="websocket-timedout-desc" />
)}
<div className="flex flex-col w-full h-full p-4">
<div className="flex flex-grow justify-center items-center">
<div className="flex flex-col items-center gap-4 -mt-12">
{isLoading && (
<>
<LoaderIcon slimeState={SlimeState.JUMPY} size={200} />
<div>
<Localized id="websocket-connecting">
<Typography variant="main-title" />
</Localized>
</div>
</>
)}
{isCrashed && (
<Error
title="websocket-connection_lost"
desc="websocket-connection_lost-desc"
/>
)}
{isTimedOut && (
<Error
title="websocket-timedout"
desc="websocket-timedout-desc"
/>
)}
</div>
</div>
{(isCrashed || isTimedOut) && (
<div className="flex justify-center">
<CrashReportBanner kind={isTimedOut ? 'timeout' : 'connection_lost'} />
</div>
)}
</div>
</EmptyLayout>
);
@@ -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();
@@ -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(
+46 -38
View File
@@ -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<ErrorReportingState | null>(null);
const pendingAnswerAtom = atom<PendingAnswer | null>(null);
/** What the user chose, until the server confirms it */
const pendingAnswerAtom = atom<ErrorReportingAnswer | null>(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);
},
};
}
+1
View File
@@ -1,3 +1,4 @@
import './utils/sentry-init';
import '@fontsource/poppins/500.css';
import '@fontsource/poppins/700.css';
import '@fontsource/jetbrains-mono/500.css';
+6
View File
@@ -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));
+36 -20
View File
@@ -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);
}
}
+7
View File
@@ -42,7 +42,10 @@ import {
captureJavaNotFound,
captureServerExit,
captureServerLaunchError,
flushErrorReports,
initSentry,
sendCrashReport,
trackServerOutput,
} from './sentry';
type Stores = Awaited<ReturnType<typeof initStores>>;
@@ -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);
});
+58 -6
View File
@@ -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<typeof Sentry.makeElectronOfflineTransport>
>[0];
function isUserRequested(envelope: Envelope) {
return envelope[1].some(
([header, payload]) =>
header.type === 'event' &&
(payload as { tags?: Record<string, unknown> })?.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<void> = 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) {
+1
View File
@@ -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);
+4
View File
@@ -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<boolean>;
setKeybindRecording: (recording: boolean) => void;
setErrorReporting: (state: ErrorReportingState) => void;
sendCrashReport: (kind: CrashReportKind) => Promise<boolean>;
}
declare global {
+3
View File
@@ -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;
}