diff --git a/.env.example b/.env.example index 9b84897d..9803958f 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,6 @@ +# Sentry +VITE_SENTRY_DSN="https://********************************@*****************.example.com/****************" + # GitHub OAuth Configuration VITE_GITHUB_OAUTH_CLIENT_ID="********************" VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************" diff --git a/package-lock.json b/package-lock.json index f00fdf46..453e7c18 100644 --- a/package-lock.json +++ b/package-lock.json @@ -46,6 +46,7 @@ "@radix-ui/react-toggle": "^1.1.0", "@radix-ui/react-toggle-group": "^1.1.0", "@radix-ui/react-tooltip": "^1.1.4", + "@sentry/react": "^10.22.0", "@std/encoding": "npm:@jsr/std__encoding@^1.0.10", "@tanstack/react-query": "^5.56.2", "@unhead/addons": "^2.0.10", @@ -4807,6 +4808,98 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@sentry-internal/browser-utils": { + "version": "10.22.0", + "resolved": "https://registry.npmjs.org/@sentry-internal/browser-utils/-/browser-utils-10.22.0.tgz", + "integrity": "sha512-BpJoLZEyJr7ORzkCrIjxRTnFWwO1mJNICVh3B9g5d9245niGT4OJvRozmLz89WgJkZFHWu84ls6Xfq5b/3tGFQ==", + "license": "MIT", + "dependencies": { + "@sentry/core": "10.22.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@sentry-internal/feedback": { + "version": "10.22.0", + "resolved": "https://registry.npmjs.org/@sentry-internal/feedback/-/feedback-10.22.0.tgz", + "integrity": "sha512-zXySOin/gGHPV+yKaHqjN9YZ7psEJwzLn8PzCLeo+4REzF1eQwbYZIgOxJFD32z8s3nZiABSWFM/n1CvVfMEsQ==", + "license": "MIT", + "dependencies": { + "@sentry/core": "10.22.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@sentry-internal/replay": { + "version": "10.22.0", + "resolved": "https://registry.npmjs.org/@sentry-internal/replay/-/replay-10.22.0.tgz", + "integrity": "sha512-JNE4kHAQSG4/V+J+Zog3vKBWgOe9H33ol/MEU1RuLM/4I+uLf4mTetwnS9ilpnnW/Z/gQYfA+R3CiMrZtqTivw==", + "license": "MIT", + "dependencies": { + "@sentry-internal/browser-utils": "10.22.0", + "@sentry/core": "10.22.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@sentry-internal/replay-canvas": { + "version": "10.22.0", + "resolved": "https://registry.npmjs.org/@sentry-internal/replay-canvas/-/replay-canvas-10.22.0.tgz", + "integrity": "sha512-DE4JNUskJg+O+wFq42W5gAa/99aD5k7TfGOwABxvnzFv8vkKA7pqXwPbFFPzypdKIkln+df7RmbnDwQRNg6/lA==", + "license": "MIT", + "dependencies": { + "@sentry-internal/replay": "10.22.0", + "@sentry/core": "10.22.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@sentry/browser": { + "version": "10.22.0", + "resolved": "https://registry.npmjs.org/@sentry/browser/-/browser-10.22.0.tgz", + "integrity": "sha512-wD2XqN+yeBpQFfdPo6+wlKDMyyuDctVGzZWE4qTPntICKQuwMdAfeq5Ma89ad0Dw+bzG9UijGeyuJQlswF87Mw==", + "license": "MIT", + "dependencies": { + "@sentry-internal/browser-utils": "10.22.0", + "@sentry-internal/feedback": "10.22.0", + "@sentry-internal/replay": "10.22.0", + "@sentry-internal/replay-canvas": "10.22.0", + "@sentry/core": "10.22.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@sentry/core": { + "version": "10.22.0", + "resolved": "https://registry.npmjs.org/@sentry/core/-/core-10.22.0.tgz", + "integrity": "sha512-V1oeHbrOKzxadsCmgtPku3v3Emo/Bpb3VSuKmlLrQefiHX98MWtjJ3XDGfduzD5/dCdh0r/OOLwjcmrO/PZ2aw==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@sentry/react": { + "version": "10.22.0", + "resolved": "https://registry.npmjs.org/@sentry/react/-/react-10.22.0.tgz", + "integrity": "sha512-XByOjtW30LMNibmCPJF5LNYFmETNOUmWByECADox8GYV4BEX18WGXl4K1fpPDTSk+y4vUCHbltHa4GkyTRwG8Q==", + "license": "MIT", + "dependencies": { + "@sentry/browser": "10.22.0", + "@sentry/core": "10.22.0", + "hoist-non-react-statics": "^3.3.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "react": "^16.14.0 || 17.x || 18.x || 19.x" + } + }, "node_modules/@shikijs/core": { "version": "3.12.2", "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.12.2.tgz", @@ -8959,6 +9052,21 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hoist-non-react-statics": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz", + "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==", + "license": "BSD-3-Clause", + "dependencies": { + "react-is": "^16.7.0" + } + }, + "node_modules/hoist-non-react-statics/node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "license": "MIT" + }, "node_modules/hookable": { "version": "5.5.3", "resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz", diff --git a/package.json b/package.json index b3f09dc2..ffa71029 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,7 @@ "@radix-ui/react-toggle": "^1.1.0", "@radix-ui/react-toggle-group": "^1.1.0", "@radix-ui/react-tooltip": "^1.1.4", + "@sentry/react": "^10.22.0", "@std/encoding": "npm:@jsr/std__encoding@^1.0.10", "@tanstack/react-query": "^5.56.2", "@unhead/addons": "^2.0.10", diff --git a/src/App.tsx b/src/App.tsx index 8c6a1ebe..b6740b43 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -13,6 +13,7 @@ import { NostrLoginProvider } from '@nostrify/react/login'; import { AppProvider } from '@/components/AppProvider'; import { AppConfig } from '@/contexts/AppContext'; import { useAppContext } from '@/hooks/useAppContext'; +import { SentryProvider } from '@/components/SentryProvider'; import { AISettingsProvider } from '@/components/AISettingsProvider'; import { GitSettingsProvider } from '@/components/GitSettingsProvider'; import { DeploySettingsProvider } from '@/components/DeploySettingsProvider'; @@ -99,6 +100,8 @@ const defaultConfig: AppConfig = { fsPathProjects: electronPaths.fsPathProjects, fsPathConfig: electronPaths.fsPathConfig, fsPathTmp: electronPaths.fsPathTmp, + sentryDsn: import.meta.env.VITE_SENTRY_DSN || "", + sentryEnabled: false, }; const presetRelays = [ @@ -134,32 +137,34 @@ export function App() { - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/components/AppProvider.tsx b/src/components/AppProvider.tsx index 275bdb8e..3acce193 100644 --- a/src/components/AppProvider.tsx +++ b/src/components/AppProvider.tsx @@ -30,6 +30,8 @@ const AppConfigSchema = z.object({ fsPathProjects: z.string().min(1), fsPathConfig: z.string().min(1), fsPathTmp: z.string().min(1), + sentryDsn: z.string(), + sentryEnabled: z.boolean(), }) satisfies z.ZodType; export function AppProvider(props: AppProviderProps) { diff --git a/src/components/SentryProvider.test.tsx b/src/components/SentryProvider.test.tsx new file mode 100644 index 00000000..c81b055c --- /dev/null +++ b/src/components/SentryProvider.test.tsx @@ -0,0 +1,153 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, waitFor } from '@testing-library/react'; +import { SentryProvider } from './SentryProvider'; +import { AppContext } from '@/contexts/AppContext'; +import * as sentryModule from '@/lib/sentry'; + +// Mock the sentry module +vi.mock('@/lib/sentry', () => ({ + initializeSentry: vi.fn(() => Promise.resolve()), + disableSentry: vi.fn(() => Promise.resolve()), + isSentryInitialized: vi.fn(() => false), +})); + +describe('SentryProvider', () => { + const mockUpdateConfig = vi.fn(); + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('initializes Sentry when both DSN and sentryEnabled are true', async () => { + const config = { + sentryDsn: 'https://test@sentry.io/123', + sentryEnabled: true, + theme: 'light' as const, + relayUrl: 'wss://relay.test', + projectTemplate: 'https://test.git', + esmUrl: 'https://esm.test', + corsProxy: 'https://proxy.test/{href}', + faviconUrl: 'https://favicon.test/{href}', + previewDomain: 'test.dev', + showcaseEnabled: false, + showcaseModerator: '', + ngitServers: [], + fsPathProjects: '/projects', + fsPathConfig: '/config', + fsPathTmp: '/tmp', + }; + + render( + + + Test + + + ); + + await waitFor(() => { + expect(sentryModule.initializeSentry).toHaveBeenCalledWith('https://test@sentry.io/123'); + }); + }); + + it('does not initialize Sentry when DSN is empty', async () => { + const config = { + sentryDsn: '', + sentryEnabled: true, + theme: 'light' as const, + relayUrl: 'wss://relay.test', + projectTemplate: 'https://test.git', + esmUrl: 'https://esm.test', + corsProxy: 'https://proxy.test/{href}', + faviconUrl: 'https://favicon.test/{href}', + previewDomain: 'test.dev', + showcaseEnabled: false, + showcaseModerator: '', + ngitServers: [], + fsPathProjects: '/projects', + fsPathConfig: '/config', + fsPathTmp: '/tmp', + }; + + render( + + + Test + + + ); + + // Wait a bit to ensure no initialization happens + await new Promise(resolve => setTimeout(resolve, 100)); + + expect(sentryModule.initializeSentry).not.toHaveBeenCalled(); + }); + + it('does not initialize Sentry when sentryEnabled is false', async () => { + const config = { + sentryDsn: 'https://test@sentry.io/123', + sentryEnabled: false, + theme: 'light' as const, + relayUrl: 'wss://relay.test', + projectTemplate: 'https://test.git', + esmUrl: 'https://esm.test', + corsProxy: 'https://proxy.test/{href}', + faviconUrl: 'https://favicon.test/{href}', + previewDomain: 'test.dev', + showcaseEnabled: false, + showcaseModerator: '', + ngitServers: [], + fsPathProjects: '/projects', + fsPathConfig: '/config', + fsPathTmp: '/tmp', + }; + + render( + + + Test + + + ); + + // Wait a bit to ensure no initialization happens + await new Promise(resolve => setTimeout(resolve, 100)); + + expect(sentryModule.initializeSentry).not.toHaveBeenCalled(); + }); + + it('disables Sentry when it was initialized but conditions change', async () => { + // Mock that Sentry is initialized + vi.mocked(sentryModule.isSentryInitialized).mockReturnValue(true); + + const config = { + sentryDsn: '', + sentryEnabled: false, + theme: 'light' as const, + relayUrl: 'wss://relay.test', + projectTemplate: 'https://test.git', + esmUrl: 'https://esm.test', + corsProxy: 'https://proxy.test/{href}', + faviconUrl: 'https://favicon.test/{href}', + previewDomain: 'test.dev', + showcaseEnabled: false, + showcaseModerator: '', + ngitServers: [], + fsPathProjects: '/projects', + fsPathConfig: '/config', + fsPathTmp: '/tmp', + }; + + render( + + + Test + + + ); + + await waitFor(() => { + expect(sentryModule.disableSentry).toHaveBeenCalled(); + }); + }); +}); diff --git a/src/components/SentryProvider.tsx b/src/components/SentryProvider.tsx new file mode 100644 index 00000000..16b895d0 --- /dev/null +++ b/src/components/SentryProvider.tsx @@ -0,0 +1,25 @@ +import { ReactNode, useEffect } from 'react'; +import { useAppContext } from '@/hooks/useAppContext'; +import { initializeSentry, disableSentry, isSentryInitialized } from '@/lib/sentry'; + +interface SentryProviderProps { + children: ReactNode; +} + +export function SentryProvider({ children }: SentryProviderProps) { + const { config } = useAppContext(); + + useEffect(() => { + const shouldEnableSentry = config.sentryDsn && config.sentryEnabled; + + if (shouldEnableSentry && !isSentryInitialized()) { + // Initialize Sentry + initializeSentry(config.sentryDsn).catch(console.error); + } else if (!shouldEnableSentry && isSentryInitialized()) { + // Disable Sentry + disableSentry().catch(console.error); + } + }, [config.sentryDsn, config.sentryEnabled]); + + return <>{children}>; +} diff --git a/src/contexts/AppContext.ts b/src/contexts/AppContext.ts index d2031044..d1ac8228 100644 --- a/src/contexts/AppContext.ts +++ b/src/contexts/AppContext.ts @@ -31,6 +31,10 @@ export interface AppConfig { fsPathConfig: string; /** VFS path for temporary files directory */ fsPathTmp: string; + /** Sentry DSN for error reporting (empty string = disabled) */ + sentryDsn: string; + /** Whether the user has enabled Sentry error reporting */ + sentryEnabled: boolean; } export interface AppContextType { diff --git a/src/hooks/useAIProjectId.test.ts b/src/hooks/useAIProjectId.test.ts index 5001992b..3b3f25b7 100644 --- a/src/hooks/useAIProjectId.test.ts +++ b/src/hooks/useAIProjectId.test.ts @@ -53,6 +53,8 @@ describe('useAIProjectId', () => { fsPathProjects: '/projects', fsPathConfig: '/config', fsPathTmp: '/tmp', + sentryDsn: '', + sentryEnabled: false, }, updateConfig: vi.fn(), }); diff --git a/src/hooks/useGit.test.ts b/src/hooks/useGit.test.ts index 5de6a24b..e23deaec 100644 --- a/src/hooks/useGit.test.ts +++ b/src/hooks/useGit.test.ts @@ -45,6 +45,8 @@ function createWrapper(corsProxy: string) { fsPathProjects: '/projects', fsPathConfig: '/config', fsPathTmp: '/tmp', + sentryDsn: '', + sentryEnabled: false, }; return createElement( diff --git a/src/lib/sentry.ts b/src/lib/sentry.ts new file mode 100644 index 00000000..79091f73 --- /dev/null +++ b/src/lib/sentry.ts @@ -0,0 +1,99 @@ +import type * as SentryTypes from '@sentry/react'; + +let sentryInstance: typeof SentryTypes | null = null; +let isInitialized = false; +let isEnabled = false; + +/** + * Dynamically imports and initializes Sentry + * @param dsn - Sentry DSN + * @returns Promise that resolves when Sentry is initialized + */ +export async function initializeSentry(dsn: string): Promise { + // Don't initialize if DSN is empty + if (!dsn) { + console.log('Sentry DSN is empty, skipping initialization'); + return; + } + + // If Sentry was already initialized once, just re-enable it + if (isInitialized && sentryInstance) { + console.log('Sentry already initialized, re-enabling'); + const client = sentryInstance.getClient(); + if (client) { + client.getOptions().enabled = true; + } + isEnabled = true; + return; + } + + try { + // Dynamic import to avoid loading Sentry unless needed + const Sentry = await import('@sentry/react'); + sentryInstance = Sentry; + + // Initialize Sentry + Sentry.init({ + dsn, + integrations: [ + Sentry.browserTracingIntegration(), + Sentry.replayIntegration({ + maskAllText: true, + blockAllMedia: true, + }), + ], + // Performance Monitoring + tracesSampleRate: 0.1, // Capture 10% of transactions for performance monitoring + // Session Replay + replaysSessionSampleRate: 0.1, // Sample 10% of sessions + replaysOnErrorSampleRate: 1.0, // Sample 100% of sessions with errors + // Environment + environment: import.meta.env.MODE, + // Release + release: import.meta.env.VITE_APP_VERSION || 'development', + }); + + isInitialized = true; + isEnabled = true; + console.log('Sentry initialized successfully'); + } catch (error) { + console.error('Failed to initialize Sentry:', error); + throw error; + } +} + +/** + * Disables Sentry by setting enabled to false + */ +export async function disableSentry(): Promise { + if (!isInitialized || !sentryInstance || !isEnabled) { + return; + } + + try { + const client = sentryInstance.getClient(); + if (client) { + // Just disable the client instead of closing it + // This allows re-enabling without re-initializing + client.getOptions().enabled = false; + } + isEnabled = false; + console.log('Sentry disabled successfully'); + } catch (error) { + console.error('Failed to disable Sentry:', error); + } +} + +/** + * Checks if Sentry is currently initialized and enabled + */ +export function isSentryInitialized(): boolean { + return isInitialized && isEnabled; +} + +/** + * Gets the Sentry instance (if initialized) + */ +export function getSentryInstance(): typeof SentryTypes | null { + return sentryInstance; +} diff --git a/src/locales/en.json b/src/locales/en.json index 8f628bb8..75eb8caa 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -55,6 +55,10 @@ "configDirectoryDescription": "Filesystem path where configuration files are stored", "temporaryDirectory": "Temporary Directory", "temporaryDirectoryDescription": "Filesystem path for temporary files", + "sentryDsn": "Sentry DSN", + "sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.", + "shareErrorReports": "Share error reports", + "shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.", "english": "English", "portuguese": "Portuguese", "chinese": "Chinese", diff --git a/src/pages/Preferences.tsx b/src/pages/Preferences.tsx index ac62a581..4057d591 100644 --- a/src/pages/Preferences.tsx +++ b/src/pages/Preferences.tsx @@ -3,15 +3,17 @@ import { useTranslation } from 'react-i18next'; import { Button } from "@/components/ui/button"; import { ThemePicker } from "@/components/ThemePicker"; import { LanguagePicker } from "@/components/LanguagePicker"; - +import { Switch } from "@/components/ui/switch"; import { Label } from "@/components/ui/label"; import { useIsMobile } from "@/hooks/useIsMobile"; import { useNavigate } from "react-router-dom"; +import { useAppContext } from "@/hooks/useAppContext"; export function Preferences() { const { t } = useTranslation(); const isMobile = useIsMobile(); const navigate = useNavigate(); + const { config, updateConfig } = useAppContext(); return ( @@ -70,6 +72,29 @@ export function Preferences() { {t('languageDescription')} + + + + + + {t('shareErrorReports')} + + + { + updateConfig((current) => ({ + ...current, + sentryEnabled: checked, + })); + }} + /> + + + {t('shareErrorReportsDescription')} + + ); diff --git a/src/pages/SystemSettings.tsx b/src/pages/SystemSettings.tsx index d65be79d..75f8f076 100644 --- a/src/pages/SystemSettings.tsx +++ b/src/pages/SystemSettings.tsx @@ -29,6 +29,7 @@ export function SystemSettings() { const [fsPathProjectsInput, setFsPathProjectsInput] = useState(config.fsPathProjects); const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig); const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp); + const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn); // Service Worker state const [swState, setSwState] = useState(''); @@ -464,6 +465,36 @@ export function SystemSettings() { + {/* Sentry DSN Configuration */} + + + + {t('sentryDsn')} + + + + { + const value = e.target.value; + setSentryDsnInput(value); + updateConfig((current) => ({ + ...current, + sentryDsn: value, + })); + }} + /> + + {t('sentryDsnDescription')} + + + + + + {/* Filesystem Paths Configuration */} diff --git a/src/test/TestApp.tsx b/src/test/TestApp.tsx index d9d195d6..ae134a43 100644 --- a/src/test/TestApp.tsx +++ b/src/test/TestApp.tsx @@ -42,6 +42,8 @@ export function TestApp({ children }: TestAppProps) { fsPathProjects: '/projects', fsPathConfig: '/config', fsPathTmp: '/tmp', + sentryDsn: '', + sentryEnabled: false, }; // Initialize LightningFS for testing diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index b337d67a..26ed71da 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -1,11 +1,2 @@ /// -/// - -interface ImportMetaEnv { - readonly VITE_GITHUB_OAUTH_CLIENT_ID?: string; - readonly VITE_GITHUB_OAUTH_CLIENT_SECRET?: string; -} - -interface ImportMeta { - readonly env: ImportMetaEnv; -} +/// \ No newline at end of file
+ {t('shareErrorReportsDescription')} +
+ {t('sentryDsnDescription')} +