From c78809d5b98d4138ff79cf9f7777fba32f8026ee Mon Sep 17 00:00:00 2001 From: KevIsDev Date: Wed, 18 Jun 2025 13:15:33 +0100 Subject: [PATCH] refactor: remove developer mode and related features remove developer-specific tabs, hooks, and APIs including debug status, update checks, and system diagnostics simplify tab configuration to only support user mode clean up unused code, routes and update types accordingly --- app/routes/api.system.app-info.ts | 135 -- app/routes/api.system.diagnostics.ts | 142 -- app/routes/api.system.disk-info.ts | 311 --- app/routes/api.system.memory-info.ts | 280 --- app/routes/api.system.process-info.ts | 424 ---- app/settings/core/AvatarDropdown.tsx | 40 - app/settings/core/ControlPanel.tsx | 228 +- app/settings/core/constants.ts | 44 +- app/settings/core/types.ts | 23 +- app/settings/index.ts | 1 - .../shared/components/DraggableTabList.tsx | 163 -- .../shared/components/TabManagement.tsx | 120 +- app/settings/stores/settings.ts | 32 +- app/settings/stores/tabConfigurationStore.ts | 9 +- .../connections/ConnectionDiagnostics.tsx | 10 - app/settings/tabs/debug/DebugTab.tsx | 2110 ----------------- app/settings/tabs/event-logs/EventLogsTab.tsx | 1013 -------- .../tabs/task-manager/TaskManagerTab.tsx | 1602 ------------- app/settings/tabs/update/UpdateTab.tsx | 628 ----- app/settings/utils/tab-helpers.ts | 89 - app/shared/hooks/index.ts | 2 - app/shared/hooks/useDebugStatus.ts | 89 - app/shared/hooks/useUpdateCheck.ts | 58 - 23 files changed, 21 insertions(+), 7532 deletions(-) delete mode 100644 app/routes/api.system.app-info.ts delete mode 100644 app/routes/api.system.diagnostics.ts delete mode 100644 app/routes/api.system.disk-info.ts delete mode 100644 app/routes/api.system.memory-info.ts delete mode 100644 app/routes/api.system.process-info.ts delete mode 100644 app/settings/shared/components/DraggableTabList.tsx delete mode 100644 app/settings/tabs/debug/DebugTab.tsx delete mode 100644 app/settings/tabs/event-logs/EventLogsTab.tsx delete mode 100644 app/settings/tabs/task-manager/TaskManagerTab.tsx delete mode 100644 app/settings/tabs/update/UpdateTab.tsx delete mode 100644 app/settings/utils/tab-helpers.ts delete mode 100644 app/shared/hooks/useDebugStatus.ts delete mode 100644 app/shared/hooks/useUpdateCheck.ts diff --git a/app/routes/api.system.app-info.ts b/app/routes/api.system.app-info.ts deleted file mode 100644 index 01953b68..00000000 --- a/app/routes/api.system.app-info.ts +++ /dev/null @@ -1,135 +0,0 @@ -import type { ActionFunctionArgs, LoaderFunction } from '@remix-run/cloudflare'; -import { json } from '@remix-run/cloudflare'; - -// These are injected by Vite at build time -declare const __APP_VERSION: string; -declare const __PKG_NAME: string; -declare const __PKG_DESCRIPTION: string; -declare const __PKG_LICENSE: string; -declare const __PKG_DEPENDENCIES: Record; -declare const __PKG_DEV_DEPENDENCIES: Record; -declare const __PKG_PEER_DEPENDENCIES: Record; -declare const __PKG_OPTIONAL_DEPENDENCIES: Record; -declare const __COMMIT_HASH: string; -declare const __GIT_BRANCH: string; -declare const __GIT_COMMIT_TIME: string; -declare const __GIT_AUTHOR: string; -declare const __GIT_EMAIL: string; -declare const __GIT_REMOTE_URL: string; -declare const __GIT_REPO_NAME: string; - -const getGitInfo = () => { - return { - commitHash: __COMMIT_HASH || 'unknown', - branch: __GIT_BRANCH || 'unknown', - commitTime: __GIT_COMMIT_TIME || 'unknown', - author: __GIT_AUTHOR || 'unknown', - email: __GIT_EMAIL || 'unknown', - remoteUrl: __GIT_REMOTE_URL || 'unknown', - repoName: __GIT_REPO_NAME || 'unknown', - }; -}; - -const formatDependencies = ( - deps: Record, - type: 'production' | 'development' | 'peer' | 'optional', -): Array<{ name: string; version: string; type: string }> => { - return Object.entries(deps || {}).map(([name, version]) => ({ - name, - version: version.replace(/^\^|~/, ''), - type, - })); -}; - -const getAppResponse = () => { - const gitInfo = getGitInfo(); - - return { - name: __PKG_NAME || 'bolt.diy', - version: __APP_VERSION || '0.1.0', - description: __PKG_DESCRIPTION || 'A DIY LLM interface', - license: __PKG_LICENSE || 'MIT', - environment: 'cloudflare', - gitInfo, - timestamp: new Date().toISOString(), - runtimeInfo: { - nodeVersion: 'cloudflare', - }, - dependencies: { - production: formatDependencies(__PKG_DEPENDENCIES, 'production'), - development: formatDependencies(__PKG_DEV_DEPENDENCIES, 'development'), - peer: formatDependencies(__PKG_PEER_DEPENDENCIES, 'peer'), - optional: formatDependencies(__PKG_OPTIONAL_DEPENDENCIES, 'optional'), - }, - }; -}; - -export const loader: LoaderFunction = async ({ request: _request }) => { - try { - return json(getAppResponse()); - } catch (error) { - console.error('Failed to get webapp info:', error); - return json( - { - name: 'bolt.diy', - version: '0.0.0', - description: 'Error fetching app info', - license: 'MIT', - environment: 'error', - gitInfo: { - commitHash: 'error', - branch: 'unknown', - commitTime: 'unknown', - author: 'unknown', - email: 'unknown', - remoteUrl: 'unknown', - repoName: 'unknown', - }, - timestamp: new Date().toISOString(), - runtimeInfo: { nodeVersion: 'unknown' }, - dependencies: { - production: [], - development: [], - peer: [], - optional: [], - }, - }, - { status: 500 }, - ); - } -}; - -export const action = async ({ request: _request }: ActionFunctionArgs) => { - try { - return json(getAppResponse()); - } catch (error) { - console.error('Failed to get webapp info:', error); - return json( - { - name: 'bolt.diy', - version: '0.0.0', - description: 'Error fetching app info', - license: 'MIT', - environment: 'error', - gitInfo: { - commitHash: 'error', - branch: 'unknown', - commitTime: 'unknown', - author: 'unknown', - email: 'unknown', - remoteUrl: 'unknown', - repoName: 'unknown', - }, - timestamp: new Date().toISOString(), - runtimeInfo: { nodeVersion: 'unknown' }, - dependencies: { - production: [], - development: [], - peer: [], - optional: [], - }, - }, - { status: 500 }, - ); - } -}; diff --git a/app/routes/api.system.diagnostics.ts b/app/routes/api.system.diagnostics.ts deleted file mode 100644 index 8c61966f..00000000 --- a/app/routes/api.system.diagnostics.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { json, type LoaderFunction, type LoaderFunctionArgs } from '@remix-run/cloudflare'; - -/** - * Diagnostic API for troubleshooting connection issues - */ - -interface AppContext { - env?: { - GITHUB_ACCESS_TOKEN?: string; - NETLIFY_TOKEN?: string; - }; -} - -export const loader: LoaderFunction = async ({ request, context }: LoaderFunctionArgs & { context: AppContext }) => { - // Get environment variables - const envVars = { - hasGithubToken: Boolean(process.env.GITHUB_ACCESS_TOKEN || context.env?.GITHUB_ACCESS_TOKEN), - hasNetlifyToken: Boolean(process.env.NETLIFY_TOKEN || context.env?.NETLIFY_TOKEN), - nodeEnv: process.env.NODE_ENV, - }; - - // Check cookies - const cookieHeader = request.headers.get('Cookie') || ''; - const cookies = cookieHeader.split(';').reduce( - (acc, cookie) => { - const [key, value] = cookie.trim().split('='); - - if (key) { - acc[key] = value; - } - - return acc; - }, - {} as Record, - ); - - const hasGithubTokenCookie = Boolean(cookies.githubToken); - const hasGithubUsernameCookie = Boolean(cookies.githubUsername); - const hasNetlifyCookie = Boolean(cookies.netlifyToken); - - // Get local storage status (this can only be checked client-side) - const localStorageStatus = { - explanation: 'Local storage can only be checked on the client side. Use browser devtools to check.', - githubKeysToCheck: ['github_connection'], - netlifyKeysToCheck: ['netlify_connection'], - }; - - // Check if CORS might be an issue - const corsStatus = { - headers: { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', - 'Access-Control-Allow-Headers': 'Content-Type, Authorization', - }, - }; - - // Check if API endpoints are reachable - const apiEndpoints = { - githubUser: '/api/system/git-info?action=getUser', - githubRepos: '/api/system/git-info?action=getRepos', - githubOrgs: '/api/system/git-info?action=getOrgs', - githubActivity: '/api/system/git-info?action=getActivity', - gitInfo: '/api/system/git-info', - }; - - // Test GitHub API connectivity - let githubApiStatus; - - try { - const githubResponse = await fetch('https://api.github.com/zen', { - method: 'GET', - headers: { - Accept: 'application/vnd.github.v3+json', - }, - }); - - githubApiStatus = { - isReachable: githubResponse.ok, - status: githubResponse.status, - statusText: githubResponse.statusText, - }; - } catch (error) { - githubApiStatus = { - isReachable: false, - error: error instanceof Error ? error.message : String(error), - }; - } - - // Test Netlify API connectivity - let netlifyApiStatus; - - try { - const netlifyResponse = await fetch('https://api.netlify.com/api/v1/', { - method: 'GET', - }); - - netlifyApiStatus = { - isReachable: netlifyResponse.ok, - status: netlifyResponse.status, - statusText: netlifyResponse.statusText, - }; - } catch (error) { - netlifyApiStatus = { - isReachable: false, - error: error instanceof Error ? error.message : String(error), - }; - } - - // Provide technical details about the environment - const technicalDetails = { - serverTimestamp: new Date().toISOString(), - userAgent: request.headers.get('User-Agent'), - referrer: request.headers.get('Referer'), - host: request.headers.get('Host'), - method: request.method, - url: request.url, - }; - - // Return diagnostics - return json( - { - status: 'success', - environment: envVars, - cookies: { - hasGithubTokenCookie, - hasGithubUsernameCookie, - hasNetlifyCookie, - }, - localStorage: localStorageStatus, - apiEndpoints, - externalApis: { - github: githubApiStatus, - netlify: netlifyApiStatus, - }, - corsStatus, - technicalDetails, - }, - { - headers: corsStatus.headers, - }, - ); -}; diff --git a/app/routes/api.system.disk-info.ts b/app/routes/api.system.disk-info.ts deleted file mode 100644 index c520e1bb..00000000 --- a/app/routes/api.system.disk-info.ts +++ /dev/null @@ -1,311 +0,0 @@ -import type { ActionFunctionArgs, LoaderFunction } from '@remix-run/cloudflare'; -import { json } from '@remix-run/cloudflare'; - -// Only import child_process if we're not in a Cloudflare environment -let execSync: any; - -try { - // Check if we're in a Node.js environment - if (typeof process !== 'undefined' && process.platform) { - // Using dynamic import to avoid require() - const childProcess = { execSync: null }; - execSync = childProcess.execSync; - } -} catch { - // In Cloudflare environment, this will fail, which is expected - console.log('Running in Cloudflare environment, child_process not available'); -} - -// For development environments, we'll always provide mock data if real data isn't available -const isDevelopment = process.env.NODE_ENV === 'development'; - -interface DiskInfo { - filesystem: string; - size: number; - used: number; - available: number; - percentage: number; - mountpoint: string; - timestamp: string; - error?: string; -} - -const getDiskInfo = (): DiskInfo[] => { - // If we're in a Cloudflare environment and not in development, return error - if (!execSync && !isDevelopment) { - return [ - { - filesystem: 'N/A', - size: 0, - used: 0, - available: 0, - percentage: 0, - mountpoint: 'N/A', - timestamp: new Date().toISOString(), - error: 'Disk information is not available in this environment', - }, - ]; - } - - // If we're in development but not in Node environment, return mock data - if (!execSync && isDevelopment) { - // Generate random percentage between 40-60% - const percentage = Math.floor(40 + Math.random() * 20); - const totalSize = 500 * 1024 * 1024 * 1024; // 500GB - const usedSize = Math.floor((totalSize * percentage) / 100); - const availableSize = totalSize - usedSize; - - return [ - { - filesystem: 'MockDisk', - size: totalSize, - used: usedSize, - available: availableSize, - percentage, - mountpoint: '/', - timestamp: new Date().toISOString(), - }, - { - filesystem: 'MockDisk2', - size: 1024 * 1024 * 1024 * 1024, // 1TB - used: 300 * 1024 * 1024 * 1024, // 300GB - available: 724 * 1024 * 1024 * 1024, // 724GB - percentage: 30, - mountpoint: '/data', - timestamp: new Date().toISOString(), - }, - ]; - } - - try { - // Different commands for different operating systems - const platform = process.platform; - let disks: DiskInfo[] = []; - - if (platform === 'darwin') { - // macOS - use df command to get disk information - try { - const output = execSync('df -k', { encoding: 'utf-8' }).toString().trim(); - - // Skip the header line - const lines = output.split('\n').slice(1); - - disks = lines.map((line: string) => { - const parts = line.trim().split(/\s+/); - const filesystem = parts[0]; - const size = parseInt(parts[1], 10) * 1024; // Convert KB to bytes - const used = parseInt(parts[2], 10) * 1024; - const available = parseInt(parts[3], 10) * 1024; - const percentageStr = parts[4].replace('%', ''); - const percentage = parseInt(percentageStr, 10); - const mountpoint = parts[5]; - - return { - filesystem, - size, - used, - available, - percentage, - mountpoint, - timestamp: new Date().toISOString(), - }; - }); - - // Filter out non-physical disks - disks = disks.filter( - (disk) => - !disk.filesystem.startsWith('devfs') && - !disk.filesystem.startsWith('map') && - !disk.mountpoint.startsWith('/System/Volumes') && - disk.size > 0, - ); - } catch (error) { - console.error('Failed to get macOS disk info:', error); - return [ - { - filesystem: 'Unknown', - size: 0, - used: 0, - available: 0, - percentage: 0, - mountpoint: '/', - timestamp: new Date().toISOString(), - error: error instanceof Error ? error.message : 'Unknown error', - }, - ]; - } - } else if (platform === 'linux') { - // Linux - use df command to get disk information - try { - const output = execSync('df -k', { encoding: 'utf-8' }).toString().trim(); - - // Skip the header line - const lines = output.split('\n').slice(1); - - disks = lines.map((line: string) => { - const parts = line.trim().split(/\s+/); - const filesystem = parts[0]; - const size = parseInt(parts[1], 10) * 1024; // Convert KB to bytes - const used = parseInt(parts[2], 10) * 1024; - const available = parseInt(parts[3], 10) * 1024; - const percentageStr = parts[4].replace('%', ''); - const percentage = parseInt(percentageStr, 10); - const mountpoint = parts[5]; - - return { - filesystem, - size, - used, - available, - percentage, - mountpoint, - timestamp: new Date().toISOString(), - }; - }); - - // Filter out non-physical disks - disks = disks.filter( - (disk) => - !disk.filesystem.startsWith('/dev/loop') && - !disk.filesystem.startsWith('tmpfs') && - !disk.filesystem.startsWith('devtmpfs') && - disk.size > 0, - ); - } catch (error) { - console.error('Failed to get Linux disk info:', error); - return [ - { - filesystem: 'Unknown', - size: 0, - used: 0, - available: 0, - percentage: 0, - mountpoint: '/', - timestamp: new Date().toISOString(), - error: error instanceof Error ? error.message : 'Unknown error', - }, - ]; - } - } else if (platform === 'win32') { - // Windows - use PowerShell to get disk information - try { - const output = execSync( - 'powershell "Get-PSDrive -PSProvider FileSystem | Select-Object Name, Used, Free, @{Name=\'Size\';Expression={$_.Used + $_.Free}} | ConvertTo-Json"', - { encoding: 'utf-8' }, - ) - .toString() - .trim(); - - const driveData = JSON.parse(output); - const drivesArray = Array.isArray(driveData) ? driveData : [driveData]; - - disks = drivesArray.map((drive) => { - const size = drive.Size || 0; - const used = drive.Used || 0; - const available = drive.Free || 0; - const percentage = size > 0 ? Math.round((used / size) * 100) : 0; - - return { - filesystem: drive.Name + ':\\', - size, - used, - available, - percentage, - mountpoint: drive.Name + ':\\', - timestamp: new Date().toISOString(), - }; - }); - } catch (error) { - console.error('Failed to get Windows disk info:', error); - return [ - { - filesystem: 'Unknown', - size: 0, - used: 0, - available: 0, - percentage: 0, - mountpoint: 'C:\\', - timestamp: new Date().toISOString(), - error: error instanceof Error ? error.message : 'Unknown error', - }, - ]; - } - } else { - console.warn(`Unsupported platform: ${platform}`); - return [ - { - filesystem: 'Unknown', - size: 0, - used: 0, - available: 0, - percentage: 0, - mountpoint: '/', - timestamp: new Date().toISOString(), - error: `Unsupported platform: ${platform}`, - }, - ]; - } - - return disks; - } catch (error) { - console.error('Failed to get disk info:', error); - return [ - { - filesystem: 'Unknown', - size: 0, - used: 0, - available: 0, - percentage: 0, - mountpoint: '/', - timestamp: new Date().toISOString(), - error: error instanceof Error ? error.message : 'Unknown error', - }, - ]; - } -}; - -export const loader: LoaderFunction = async ({ request: _request }) => { - try { - return json(getDiskInfo()); - } catch (error) { - console.error('Failed to get disk info:', error); - return json( - [ - { - filesystem: 'Unknown', - size: 0, - used: 0, - available: 0, - percentage: 0, - mountpoint: '/', - timestamp: new Date().toISOString(), - error: error instanceof Error ? error.message : 'Unknown error', - }, - ], - { status: 500 }, - ); - } -}; - -export const action = async ({ request: _request }: ActionFunctionArgs) => { - try { - return json(getDiskInfo()); - } catch (error) { - console.error('Failed to get disk info:', error); - return json( - [ - { - filesystem: 'Unknown', - size: 0, - used: 0, - available: 0, - percentage: 0, - mountpoint: '/', - timestamp: new Date().toISOString(), - error: error instanceof Error ? error.message : 'Unknown error', - }, - ], - { status: 500 }, - ); - } -}; diff --git a/app/routes/api.system.memory-info.ts b/app/routes/api.system.memory-info.ts deleted file mode 100644 index a6dc7b51..00000000 --- a/app/routes/api.system.memory-info.ts +++ /dev/null @@ -1,280 +0,0 @@ -import type { ActionFunctionArgs, LoaderFunction } from '@remix-run/cloudflare'; -import { json } from '@remix-run/cloudflare'; - -// Only import child_process if we're not in a Cloudflare environment -let execSync: any; - -try { - // Check if we're in a Node.js environment - if (typeof process !== 'undefined' && process.platform) { - // Using dynamic import to avoid require() - const childProcess = { execSync: null }; - execSync = childProcess.execSync; - } -} catch { - // In Cloudflare environment, this will fail, which is expected - console.log('Running in Cloudflare environment, child_process not available'); -} - -// For development environments, we'll always provide mock data if real data isn't available -const isDevelopment = process.env.NODE_ENV === 'development'; - -interface SystemMemoryInfo { - total: number; - free: number; - used: number; - percentage: number; - swap?: { - total: number; - free: number; - used: number; - percentage: number; - }; - timestamp: string; - error?: string; -} - -const getSystemMemoryInfo = (): SystemMemoryInfo => { - try { - // Check if we're in a Cloudflare environment and not in development - if (!execSync && !isDevelopment) { - // Return error for Cloudflare production environment - return { - total: 0, - free: 0, - used: 0, - percentage: 0, - timestamp: new Date().toISOString(), - error: 'System memory information is not available in this environment', - }; - } - - // If we're in development but not in Node environment, return mock data - if (!execSync && isDevelopment) { - // Return mock data for development - const mockTotal = 16 * 1024 * 1024 * 1024; // 16GB - const mockPercentage = Math.floor(30 + Math.random() * 20); // Random between 30-50% - const mockUsed = Math.floor((mockTotal * mockPercentage) / 100); - const mockFree = mockTotal - mockUsed; - - return { - total: mockTotal, - free: mockFree, - used: mockUsed, - percentage: mockPercentage, - swap: { - total: 8 * 1024 * 1024 * 1024, // 8GB - free: 6 * 1024 * 1024 * 1024, // 6GB - used: 2 * 1024 * 1024 * 1024, // 2GB - percentage: 25, - }, - timestamp: new Date().toISOString(), - }; - } - - // Different commands for different operating systems - let memInfo: { total: number; free: number; used: number; percentage: number; swap?: any } = { - total: 0, - free: 0, - used: 0, - percentage: 0, - }; - - // Check the operating system - const platform = process.platform; - - if (platform === 'darwin') { - // macOS - const totalMemory = parseInt(execSync('sysctl -n hw.memsize').toString().trim(), 10); - - // Get memory usage using vm_stat - const vmStat = execSync('vm_stat').toString().trim(); - const pageSize = 4096; // Default page size on macOS - - // Parse vm_stat output - const matches = { - free: /Pages free:\s+(\d+)/.exec(vmStat), - active: /Pages active:\s+(\d+)/.exec(vmStat), - inactive: /Pages inactive:\s+(\d+)/.exec(vmStat), - speculative: /Pages speculative:\s+(\d+)/.exec(vmStat), - wired: /Pages wired down:\s+(\d+)/.exec(vmStat), - compressed: /Pages occupied by compressor:\s+(\d+)/.exec(vmStat), - }; - - const freePages = parseInt(matches.free?.[1] || '0', 10); - const activePages = parseInt(matches.active?.[1] || '0', 10); - const inactivePages = parseInt(matches.inactive?.[1] || '0', 10); - - // Speculative pages are not currently used in calculations, but kept for future reference - const wiredPages = parseInt(matches.wired?.[1] || '0', 10); - const compressedPages = parseInt(matches.compressed?.[1] || '0', 10); - - const freeMemory = freePages * pageSize; - const usedMemory = (activePages + inactivePages + wiredPages + compressedPages) * pageSize; - - memInfo = { - total: totalMemory, - free: freeMemory, - used: usedMemory, - percentage: Math.round((usedMemory / totalMemory) * 100), - }; - - // Get swap information - try { - const swapInfo = execSync('sysctl -n vm.swapusage').toString().trim(); - const swapMatches = { - total: /total = (\d+\.\d+)M/.exec(swapInfo), - used: /used = (\d+\.\d+)M/.exec(swapInfo), - free: /free = (\d+\.\d+)M/.exec(swapInfo), - }; - - const swapTotal = parseFloat(swapMatches.total?.[1] || '0') * 1024 * 1024; - const swapUsed = parseFloat(swapMatches.used?.[1] || '0') * 1024 * 1024; - const swapFree = parseFloat(swapMatches.free?.[1] || '0') * 1024 * 1024; - - memInfo.swap = { - total: swapTotal, - used: swapUsed, - free: swapFree, - percentage: swapTotal > 0 ? Math.round((swapUsed / swapTotal) * 100) : 0, - }; - } catch (swapError) { - console.error('Failed to get swap info:', swapError); - } - } else if (platform === 'linux') { - // Linux - const meminfo = execSync('cat /proc/meminfo').toString().trim(); - - const memTotal = parseInt(/MemTotal:\s+(\d+)/.exec(meminfo)?.[1] || '0', 10) * 1024; - - // We use memAvailable instead of memFree for more accurate free memory calculation - const memAvailable = parseInt(/MemAvailable:\s+(\d+)/.exec(meminfo)?.[1] || '0', 10) * 1024; - - /* - * Buffers and cached memory are included in the available memory calculation by the kernel - * so we don't need to calculate them separately - */ - - const usedMemory = memTotal - memAvailable; - - memInfo = { - total: memTotal, - free: memAvailable, - used: usedMemory, - percentage: Math.round((usedMemory / memTotal) * 100), - }; - - // Get swap information - const swapTotal = parseInt(/SwapTotal:\s+(\d+)/.exec(meminfo)?.[1] || '0', 10) * 1024; - const swapFree = parseInt(/SwapFree:\s+(\d+)/.exec(meminfo)?.[1] || '0', 10) * 1024; - const swapUsed = swapTotal - swapFree; - - memInfo.swap = { - total: swapTotal, - free: swapFree, - used: swapUsed, - percentage: swapTotal > 0 ? Math.round((swapUsed / swapTotal) * 100) : 0, - }; - } else if (platform === 'win32') { - /* - * Windows - * Using PowerShell to get memory information - */ - const memoryInfo = execSync( - 'powershell "Get-CimInstance Win32_OperatingSystem | Select-Object TotalVisibleMemorySize, FreePhysicalMemory | ConvertTo-Json"', - ) - .toString() - .trim(); - - const memData = JSON.parse(memoryInfo); - const totalMemory = parseInt(memData.TotalVisibleMemorySize, 10) * 1024; - const freeMemory = parseInt(memData.FreePhysicalMemory, 10) * 1024; - const usedMemory = totalMemory - freeMemory; - - memInfo = { - total: totalMemory, - free: freeMemory, - used: usedMemory, - percentage: Math.round((usedMemory / totalMemory) * 100), - }; - - // Get swap (page file) information - try { - const swapInfo = execSync( - "powershell \"Get-CimInstance Win32_PageFileUsage | Measure-Object -Property CurrentUsage, AllocatedBaseSize -Sum | Select-Object @{Name='CurrentUsage';Expression={$_.Sum}}, @{Name='AllocatedBaseSize';Expression={$_.Sum}} | ConvertTo-Json\"", - ) - .toString() - .trim(); - - const swapData = JSON.parse(swapInfo); - const swapTotal = parseInt(swapData.AllocatedBaseSize, 10) * 1024 * 1024; - const swapUsed = parseInt(swapData.CurrentUsage, 10) * 1024 * 1024; - const swapFree = swapTotal - swapUsed; - - memInfo.swap = { - total: swapTotal, - free: swapFree, - used: swapUsed, - percentage: swapTotal > 0 ? Math.round((swapUsed / swapTotal) * 100) : 0, - }; - } catch (swapError) { - console.error('Failed to get swap info:', swapError); - } - } else { - throw new Error(`Unsupported platform: ${platform}`); - } - - return { - ...memInfo, - timestamp: new Date().toISOString(), - }; - } catch (error) { - console.error('Failed to get system memory info:', error); - return { - total: 0, - free: 0, - used: 0, - percentage: 0, - timestamp: new Date().toISOString(), - error: error instanceof Error ? error.message : 'Unknown error', - }; - } -}; - -export const loader: LoaderFunction = async ({ request: _request }) => { - try { - return json(getSystemMemoryInfo()); - } catch (error) { - console.error('Failed to get system memory info:', error); - return json( - { - total: 0, - free: 0, - used: 0, - percentage: 0, - timestamp: new Date().toISOString(), - error: error instanceof Error ? error.message : 'Unknown error', - }, - { status: 500 }, - ); - } -}; - -export const action = async ({ request: _request }: ActionFunctionArgs) => { - try { - return json(getSystemMemoryInfo()); - } catch (error) { - console.error('Failed to get system memory info:', error); - return json( - { - total: 0, - free: 0, - used: 0, - percentage: 0, - timestamp: new Date().toISOString(), - error: error instanceof Error ? error.message : 'Unknown error', - }, - { status: 500 }, - ); - } -}; diff --git a/app/routes/api.system.process-info.ts b/app/routes/api.system.process-info.ts deleted file mode 100644 index d3c22066..00000000 --- a/app/routes/api.system.process-info.ts +++ /dev/null @@ -1,424 +0,0 @@ -import type { ActionFunctionArgs, LoaderFunction } from '@remix-run/cloudflare'; -import { json } from '@remix-run/cloudflare'; - -// Only import child_process if we're not in a Cloudflare environment -let execSync: any; - -try { - // Check if we're in a Node.js environment - if (typeof process !== 'undefined' && process.platform) { - // Using dynamic import to avoid require() - const childProcess = { execSync: null }; - execSync = childProcess.execSync; - } -} catch { - // In Cloudflare environment, this will fail, which is expected - console.log('Running in Cloudflare environment, child_process not available'); -} - -// For development environments, we'll always provide mock data if real data isn't available -const isDevelopment = process.env.NODE_ENV === 'development'; - -interface ProcessInfo { - pid: number; - name: string; - cpu: number; - memory: number; - command?: string; - timestamp: string; - error?: string; -} - -const getProcessInfo = (): ProcessInfo[] => { - try { - // If we're in a Cloudflare environment and not in development, return error - if (!execSync && !isDevelopment) { - return [ - { - pid: 0, - name: 'N/A', - cpu: 0, - memory: 0, - timestamp: new Date().toISOString(), - error: 'Process information is not available in this environment', - }, - ]; - } - - // If we're in development but not in Node environment, return mock data - if (!execSync && isDevelopment) { - return getMockProcessInfo(); - } - - // Different commands for different operating systems - const platform = process.platform; - let processes: ProcessInfo[] = []; - - // Get CPU count for normalizing CPU percentages - let cpuCount = 1; - - try { - if (platform === 'darwin') { - const cpuInfo = execSync('sysctl -n hw.ncpu', { encoding: 'utf-8' }).toString().trim(); - cpuCount = parseInt(cpuInfo, 10) || 1; - } else if (platform === 'linux') { - const cpuInfo = execSync('nproc', { encoding: 'utf-8' }).toString().trim(); - cpuCount = parseInt(cpuInfo, 10) || 1; - } else if (platform === 'win32') { - const cpuInfo = execSync('wmic cpu get NumberOfCores', { encoding: 'utf-8' }).toString().trim(); - const match = cpuInfo.match(/\d+/); - cpuCount = match ? parseInt(match[0], 10) : 1; - } - } catch (error) { - console.error('Failed to get CPU count:', error); - - // Default to 1 if we can't get the count - cpuCount = 1; - } - - if (platform === 'darwin') { - // macOS - use ps command to get process information - try { - const output = execSync('ps -eo pid,pcpu,pmem,comm -r | head -n 11', { encoding: 'utf-8' }).toString().trim(); - - // Skip the header line - const lines = output.split('\n').slice(1); - - processes = lines.map((line: string) => { - const parts = line.trim().split(/\s+/); - const pid = parseInt(parts[0], 10); - - /* - * Normalize CPU percentage by dividing by CPU count - * This converts from "% of all CPUs" to "% of one CPU" - */ - const cpu = parseFloat(parts[1]) / cpuCount; - const memory = parseFloat(parts[2]); - const command = parts.slice(3).join(' '); - - return { - pid, - name: command.split('/').pop() || command, - cpu, - memory, - command, - timestamp: new Date().toISOString(), - }; - }); - } catch (error) { - console.error('Failed to get macOS process info:', error); - - // Try alternative command - try { - const output = execSync('top -l 1 -stats pid,cpu,mem,command -n 10', { encoding: 'utf-8' }).toString().trim(); - - // Parse top output - skip the first few lines of header - const lines = output.split('\n').slice(6); - - processes = lines.map((line: string) => { - const parts = line.trim().split(/\s+/); - const pid = parseInt(parts[0], 10); - const cpu = parseFloat(parts[1]); - const memory = parseFloat(parts[2]); - const command = parts.slice(3).join(' '); - - return { - pid, - name: command.split('/').pop() || command, - cpu, - memory, - command, - timestamp: new Date().toISOString(), - }; - }); - } catch (fallbackError) { - console.error('Failed to get macOS process info with fallback:', fallbackError); - return [ - { - pid: 0, - name: 'N/A', - cpu: 0, - memory: 0, - timestamp: new Date().toISOString(), - error: 'Process information is not available in this environment', - }, - ]; - } - } - } else if (platform === 'linux') { - // Linux - use ps command to get process information - try { - const output = execSync('ps -eo pid,pcpu,pmem,comm --sort=-pmem | head -n 11', { encoding: 'utf-8' }) - .toString() - .trim(); - - // Skip the header line - const lines = output.split('\n').slice(1); - - processes = lines.map((line: string) => { - const parts = line.trim().split(/\s+/); - const pid = parseInt(parts[0], 10); - - // Normalize CPU percentage by dividing by CPU count - const cpu = parseFloat(parts[1]) / cpuCount; - const memory = parseFloat(parts[2]); - const command = parts.slice(3).join(' '); - - return { - pid, - name: command.split('/').pop() || command, - cpu, - memory, - command, - timestamp: new Date().toISOString(), - }; - }); - } catch (error) { - console.error('Failed to get Linux process info:', error); - - // Try alternative command - try { - const output = execSync('top -b -n 1 | head -n 17', { encoding: 'utf-8' }).toString().trim(); - - // Parse top output - skip the first few lines of header - const lines = output.split('\n').slice(7); - - processes = lines.map((line: string) => { - const parts = line.trim().split(/\s+/); - const pid = parseInt(parts[0], 10); - const cpu = parseFloat(parts[8]); - const memory = parseFloat(parts[9]); - const command = parts[11] || parts[parts.length - 1]; - - return { - pid, - name: command.split('/').pop() || command, - cpu, - memory, - command, - timestamp: new Date().toISOString(), - }; - }); - } catch (fallbackError) { - console.error('Failed to get Linux process info with fallback:', fallbackError); - return [ - { - pid: 0, - name: 'N/A', - cpu: 0, - memory: 0, - timestamp: new Date().toISOString(), - error: 'Process information is not available in this environment', - }, - ]; - } - } - } else if (platform === 'win32') { - // Windows - use PowerShell to get process information - try { - const output = execSync( - 'powershell "Get-Process | Sort-Object -Property WorkingSet64 -Descending | Select-Object -First 10 Id, CPU, @{Name=\'Memory\';Expression={$_.WorkingSet64/1MB}}, ProcessName | ConvertTo-Json"', - { encoding: 'utf-8' }, - ) - .toString() - .trim(); - - const processData = JSON.parse(output); - const processArray = Array.isArray(processData) ? processData : [processData]; - - processes = processArray.map((proc: any) => ({ - pid: proc.Id, - name: proc.ProcessName, - - // Normalize CPU percentage by dividing by CPU count - cpu: (proc.CPU || 0) / cpuCount, - memory: proc.Memory, - timestamp: new Date().toISOString(), - })); - } catch (error) { - console.error('Failed to get Windows process info:', error); - - // Try alternative command using tasklist - try { - const output = execSync('tasklist /FO CSV', { encoding: 'utf-8' }).toString().trim(); - - // Parse CSV output - skip the header line - const lines = output.split('\n').slice(1); - - processes = lines.slice(0, 10).map((line: string) => { - // Parse CSV format - const parts = line.split(',').map((part: string) => part.replace(/^"(.+)"$/, '$1')); - const pid = parseInt(parts[1], 10); - const memoryStr = parts[4].replace(/[^\d]/g, ''); - const memory = parseInt(memoryStr, 10) / 1024; // Convert KB to MB - - return { - pid, - name: parts[0], - cpu: 0, // tasklist doesn't provide CPU info - memory, - timestamp: new Date().toISOString(), - }; - }); - } catch (fallbackError) { - console.error('Failed to get Windows process info with fallback:', fallbackError); - return [ - { - pid: 0, - name: 'N/A', - cpu: 0, - memory: 0, - timestamp: new Date().toISOString(), - error: 'Process information is not available in this environment', - }, - ]; - } - } - } else { - console.warn(`Unsupported platform: ${platform}, using browser fallback`); - return [ - { - pid: 0, - name: 'N/A', - cpu: 0, - memory: 0, - timestamp: new Date().toISOString(), - error: 'Process information is not available in this environment', - }, - ]; - } - - return processes; - } catch (error) { - console.error('Failed to get process info:', error); - - if (isDevelopment) { - return getMockProcessInfo(); - } - - return [ - { - pid: 0, - name: 'N/A', - cpu: 0, - memory: 0, - timestamp: new Date().toISOString(), - error: 'Process information is not available in this environment', - }, - ]; - } -}; - -// Generate mock process information with realistic values -const getMockProcessInfo = (): ProcessInfo[] => { - const timestamp = new Date().toISOString(); - - // Create some random variation in CPU usage - const randomCPU = () => Math.floor(Math.random() * 15); - const randomHighCPU = () => 15 + Math.floor(Math.random() * 25); - - // Create some random variation in memory usage - const randomMem = () => Math.floor(Math.random() * 5); - const randomHighMem = () => 5 + Math.floor(Math.random() * 15); - - return [ - { - pid: 1, - name: 'Browser', - cpu: randomHighCPU(), - memory: 25 + randomMem(), - command: 'Browser Process', - timestamp, - }, - { - pid: 2, - name: 'System', - cpu: 5 + randomCPU(), - memory: 10 + randomMem(), - command: 'System Process', - timestamp, - }, - { - pid: 3, - name: 'bolt', - cpu: randomHighCPU(), - memory: 15 + randomMem(), - command: 'Bolt AI Process', - timestamp, - }, - { - pid: 4, - name: 'node', - cpu: randomCPU(), - memory: randomHighMem(), - command: 'Node.js Process', - timestamp, - }, - { - pid: 5, - name: 'wrangler', - cpu: randomCPU(), - memory: randomMem(), - command: 'Wrangler Process', - timestamp, - }, - { - pid: 6, - name: 'vscode', - cpu: randomCPU(), - memory: 12 + randomMem(), - command: 'VS Code Process', - timestamp, - }, - { - pid: 7, - name: 'chrome', - cpu: randomHighCPU(), - memory: 20 + randomMem(), - command: 'Chrome Browser', - timestamp, - }, - { - pid: 8, - name: 'finder', - cpu: 1 + randomCPU(), - memory: 3 + randomMem(), - command: 'Finder Process', - timestamp, - }, - { - pid: 9, - name: 'terminal', - cpu: 2 + randomCPU(), - memory: 5 + randomMem(), - command: 'Terminal Process', - timestamp, - }, - { - pid: 10, - name: 'cloudflared', - cpu: randomCPU(), - memory: randomMem(), - command: 'Cloudflare Tunnel', - timestamp, - }, - ]; -}; - -export const loader: LoaderFunction = async ({ request: _request }) => { - try { - return json(getProcessInfo()); - } catch (error) { - console.error('Failed to get process info:', error); - return json(getMockProcessInfo(), { status: 500 }); - } -}; - -export const action = async ({ request: _request }: ActionFunctionArgs) => { - try { - return json(getProcessInfo()); - } catch (error) { - console.error('Failed to get process info:', error); - return json(getMockProcessInfo(), { status: 500 }); - } -}; diff --git a/app/settings/core/AvatarDropdown.tsx b/app/settings/core/AvatarDropdown.tsx index 3376ccb0..ed58ad7c 100644 --- a/app/settings/core/AvatarDropdown.tsx +++ b/app/settings/core/AvatarDropdown.tsx @@ -5,12 +5,6 @@ import { classNames } from '~/shared/utils/classNames'; import { profileStore } from '~/shared/stores/profile'; import type { TabType, Profile } from './types'; -const BetaLabel = () => ( - - BETA - -); - interface AvatarDropdownProps { onSelectTab: (tab: TabType) => void; } @@ -117,40 +111,6 @@ export const AvatarDropdown = ({ onSelectTab }: AvatarDropdownProps) => {
- - onSelectTab('task-manager')} - > -
- Task Manager - - - - onSelectTab('service-status')} - > -
- Service Status - - diff --git a/app/settings/core/ControlPanel.tsx b/app/settings/core/ControlPanel.tsx index 26164463..6394378d 100644 --- a/app/settings/core/ControlPanel.tsx +++ b/app/settings/core/ControlPanel.tsx @@ -1,22 +1,14 @@ import { useState, useEffect, useMemo } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { useStore } from '@nanostores/react'; -import { Switch } from '@radix-ui/react-switch'; import * as RadixDialog from '@radix-ui/react-dialog'; import { classNames } from '~/shared/utils/classNames'; import { TabManagement } from '~/settings/shared/components/TabManagement'; import { TabTile } from '~/settings/shared/components/TabTile'; -import { useUpdateCheck } from '~/shared/hooks/useUpdateCheck'; import { useFeatures } from '~/shared/hooks/useFeatures'; import { useNotifications } from '~/shared/hooks/useNotifications'; import { useConnectionStatus } from '~/shared/hooks/useConnectionStatus'; -import { useDebugStatus } from '~/shared/hooks/useDebugStatus'; -import { - tabConfigurationStore, - developerModeStore, - setDeveloperMode, - resetTabConfiguration, -} from '~/settings/stores/settings'; +import { tabConfigurationStore, resetTabConfiguration } from '~/settings/stores/settings'; import { profileStore } from '~/shared/stores/profile'; import type { TabType, TabVisibilityConfig, Profile } from './types'; import { TAB_LABELS, DEFAULT_TAB_CONFIG } from './constants'; @@ -24,21 +16,6 @@ import { DialogTitle } from '~/shared/components/ui/Dialog'; import { AvatarDropdown } from './AvatarDropdown'; import BackgroundRays from '~/shared/components/ui/BackgroundRays'; -// Import all tab components -import ProfileTab from '~/settings/tabs/profile/ProfileTab'; -import SettingsTab from '~/settings/tabs/settings/SettingsTab'; -import NotificationsTab from '~/settings/tabs/notifications/NotificationsTab'; -import FeaturesTab from '~/settings/tabs/features/FeaturesTab'; -import { DataTab } from '~/settings/tabs/data/DataTab'; -import DebugTab from '~/settings/tabs/debug/DebugTab'; -import { EventLogsTab } from '~/settings/tabs/event-logs/EventLogsTab'; -import UpdateTab from '~/settings/tabs/update/UpdateTab'; -import ConnectionsTab from '~/settings/tabs/connections/ConnectionsTab'; -import CloudProvidersTab from '~/settings/tabs/providers/cloud/CloudProvidersTab'; -import ServiceStatusTab from '~/settings/tabs/providers/status/ServiceStatusTab'; -import LocalProvidersTab from '~/settings/tabs/providers/local/LocalProvidersTab'; -import TaskManagerTab from '~/settings/tabs/task-manager/TaskManagerTab'; - interface ControlPanelProps { open: boolean; onClose: () => void; @@ -48,24 +25,6 @@ interface TabWithDevType extends TabVisibilityConfig { isExtraDevTab?: boolean; } -interface ExtendedTabConfig extends TabVisibilityConfig { - isExtraDevTab?: boolean; -} - -interface BaseTabConfig { - id: TabType; - visible: boolean; - window: 'user' | 'developer'; - order: number; -} - -interface AnimatedSwitchProps { - checked: boolean; - onCheckedChange: (checked: boolean) => void; - id: string; - label: string; -} - const TAB_DESCRIPTIONS: Record = { profile: 'Manage your profile and account settings', settings: 'Configure application preferences', @@ -74,17 +33,11 @@ const TAB_DESCRIPTIONS: Record = { data: 'Manage your data and storage', 'cloud-providers': 'Configure cloud AI providers and models', 'local-providers': 'Configure local AI providers and models', - 'service-status': 'Monitor cloud LLM service status', connection: 'Check connection status and settings', - debug: 'Debug tools and system information', - 'event-logs': 'View system events and logs', - update: 'Check for updates and release notes', - 'task-manager': 'Monitor system resources and processes', - 'tab-management': 'Configure visible tabs and their order', }; // Beta status for experimental features -const BETA_TABS = new Set(['task-manager', 'service-status', 'update', 'local-providers']); +const BETA_TABS = new Set(['local-providers']); const BetaLabel = () => (
@@ -92,66 +45,6 @@ const BetaLabel = () => (
); -const AnimatedSwitch = ({ checked, onCheckedChange, id, label }: AnimatedSwitchProps) => { - return ( -
- - - - - Toggle {label} - -
- -
-
- ); -}; - export const ControlPanel = ({ open, onClose }: ControlPanelProps) => { // State const [activeTab, setActiveTab] = useState(null); @@ -160,15 +53,12 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => { // Store values const tabConfiguration = useStore(tabConfigurationStore); - const developerMode = useStore(developerModeStore); const profile = useStore(profileStore) as Profile; // Status hooks - const { hasUpdate, currentVersion, acknowledgeUpdate } = useUpdateCheck(); const { hasNewFeatures, unviewedFeatures, acknowledgeAllFeatures } = useFeatures(); const { hasUnreadNotifications, unreadNotifications, markAllAsRead } = useNotifications(); const { hasConnectionIssues, currentIssue, acknowledgeIssue } = useConnectionStatus(); - const { hasActiveWarnings, activeIssues, acknowledgeAllIssues } = useDebugStatus(); // Memoize the base tab configurations to avoid recalculation const baseTabConfig = useMemo(() => { @@ -186,41 +76,6 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => { const notificationsDisabled = profile?.preferences?.notifications === false; - // In developer mode, show ALL tabs without restrictions - if (developerMode) { - const seenTabs = new Set(); - const devTabs: ExtendedTabConfig[] = []; - - // Process tabs in order of priority: developer, user, default - const processTab = (tab: BaseTabConfig) => { - if (!seenTabs.has(tab.id)) { - seenTabs.add(tab.id); - devTabs.push({ - id: tab.id, - visible: true, - window: 'developer', - order: tab.order || devTabs.length, - }); - } - }; - - // Process tabs in priority order - tabConfiguration.developerTabs?.forEach((tab) => processTab(tab as BaseTabConfig)); - tabConfiguration.userTabs.forEach((tab) => processTab(tab as BaseTabConfig)); - DEFAULT_TAB_CONFIG.forEach((tab) => processTab(tab as BaseTabConfig)); - - // Add Tab Management tile - devTabs.push({ - id: 'tab-management' as TabType, - visible: true, - window: 'developer', - order: devTabs.length, - isExtraDevTab: true, - }); - - return devTabs.sort((a, b) => a.order - b.order); - } - // Optimize user mode tab filtering return tabConfiguration.userTabs .filter((tab) => { @@ -235,7 +90,7 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => { return tab.visible && tab.window === 'user'; }) .sort((a, b) => a.order - b.order); - }, [tabConfiguration, developerMode, profile?.preferences?.notifications, baseTabConfig]); + }, [tabConfiguration, profile?.preferences?.notifications, baseTabConfig]); // Optimize animation performance with layout animations const gridLayoutVariants = { @@ -293,65 +148,14 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => { } }; - const handleDeveloperModeChange = (checked: boolean) => { - console.log('Developer mode changed:', checked); - setDeveloperMode(checked); - }; - - // Add effect to log developer mode changes - useEffect(() => { - console.log('Current developer mode:', developerMode); - }, [developerMode]); - - const getTabComponent = (tabId: TabType | 'tab-management') => { - if (tabId === 'tab-management') { - return ; - } - - switch (tabId) { - case 'profile': - return ; - case 'settings': - return ; - case 'notifications': - return ; - case 'features': - return ; - case 'data': - return ; - case 'cloud-providers': - return ; - case 'local-providers': - return ; - case 'connection': - return ; - case 'debug': - return ; - case 'event-logs': - return ; - case 'update': - return ; - case 'task-manager': - return ; - case 'service-status': - return ; - default: - return null; - } - }; - const getTabUpdateStatus = (tabId: TabType): boolean => { switch (tabId) { - case 'update': - return hasUpdate; case 'features': return hasNewFeatures; case 'notifications': return hasUnreadNotifications; case 'connection': return hasConnectionIssues; - case 'debug': - return hasActiveWarnings; default: return false; } @@ -359,8 +163,6 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => { const getStatusMessage = (tabId: TabType): string => { switch (tabId) { - case 'update': - return `New update available (v${currentVersion})`; case 'features': return `${unviewedFeatures.length} new feature${unviewedFeatures.length === 1 ? '' : 's'} to explore`; case 'notifications': @@ -371,12 +173,6 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => { : currentIssue === 'high-latency' ? 'High latency detected' : 'Connection issues detected'; - case 'debug': { - const warnings = activeIssues.filter((i) => i.type === 'warning').length; - const errors = activeIssues.filter((i) => i.type === 'error').length; - - return `${warnings} warning${warnings === 1 ? '' : 's'}, ${errors} error${errors === 1 ? '' : 's'}`; - } default: return ''; } @@ -389,9 +185,6 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => { // Acknowledge notifications based on tab switch (tabId) { - case 'update': - acknowledgeUpdate(); - break; case 'features': acknowledgeAllFeatures(); break; @@ -401,9 +194,6 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => { case 'connection': acknowledgeIssue(); break; - case 'debug': - acknowledgeAllIssues(); - break; } // Clear loading state after a delay @@ -465,16 +255,6 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
- {/* Mode Toggle */} -
- -
- {/* Avatar and Dropdown */}
@@ -514,8 +294,6 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => { > {showTabManagement ? ( - ) : activeTab ? ( - getTabComponent(activeTab) ) : ( = { data: 'i-ph:database-fill', 'cloud-providers': 'i-ph:cloud-fill', 'local-providers': 'i-ph:desktop-fill', - 'service-status': 'i-ph:activity-bold', connection: 'i-ph:wifi-high-fill', - debug: 'i-ph:bug-fill', - 'event-logs': 'i-ph:list-bullets-fill', - update: 'i-ph:arrow-clockwise-fill', - 'task-manager': 'i-ph:chart-line-fill', - 'tab-management': 'i-ph:squares-four-fill', }; export const TAB_LABELS: Record = { @@ -25,13 +19,7 @@ export const TAB_LABELS: Record = { data: 'Data Management', 'cloud-providers': 'Cloud Providers', 'local-providers': 'Local Providers', - 'service-status': 'Service Status', connection: 'Connection', - debug: 'Debug', - 'event-logs': 'Event Logs', - update: 'Updates', - 'task-manager': 'Task Manager', - 'tab-management': 'Tab Management', }; export const TAB_DESCRIPTIONS: Record = { @@ -42,13 +30,7 @@ export const TAB_DESCRIPTIONS: Record = { data: 'Manage your data and storage', 'cloud-providers': 'Configure cloud AI providers and models', 'local-providers': 'Configure local AI providers and models', - 'service-status': 'Monitor cloud LLM service status', connection: 'Check connection status and settings', - debug: 'Debug tools and system information', - 'event-logs': 'View system events and logs', - update: 'Check for updates and release notes', - 'task-manager': 'Monitor system resources and processes', - 'tab-management': 'Configure visible tabs and their order', }; export const DEFAULT_TAB_CONFIG = [ @@ -59,30 +41,8 @@ export const DEFAULT_TAB_CONFIG = [ { id: 'local-providers', visible: true, window: 'user' as const, order: 3 }, { id: 'connection', visible: true, window: 'user' as const, order: 4 }, { id: 'notifications', visible: true, window: 'user' as const, order: 5 }, - { id: 'event-logs', visible: true, window: 'user' as const, order: 6 }, // User Window Tabs (In dropdown, initially hidden) - { id: 'profile', visible: false, window: 'user' as const, order: 7 }, - { id: 'settings', visible: false, window: 'user' as const, order: 8 }, - { id: 'task-manager', visible: false, window: 'user' as const, order: 9 }, - { id: 'service-status', visible: false, window: 'user' as const, order: 10 }, - - // User Window Tabs (Hidden, controlled by TaskManagerTab) - { id: 'debug', visible: false, window: 'user' as const, order: 11 }, - { id: 'update', visible: false, window: 'user' as const, order: 12 }, - - // Developer Window Tabs (All visible by default) - { id: 'features', visible: true, window: 'developer' as const, order: 0 }, - { id: 'data', visible: true, window: 'developer' as const, order: 1 }, - { id: 'cloud-providers', visible: true, window: 'developer' as const, order: 2 }, - { id: 'local-providers', visible: true, window: 'developer' as const, order: 3 }, - { id: 'connection', visible: true, window: 'developer' as const, order: 4 }, - { id: 'notifications', visible: true, window: 'developer' as const, order: 5 }, - { id: 'event-logs', visible: true, window: 'developer' as const, order: 6 }, - { id: 'profile', visible: true, window: 'developer' as const, order: 7 }, - { id: 'settings', visible: true, window: 'developer' as const, order: 8 }, - { id: 'task-manager', visible: true, window: 'developer' as const, order: 9 }, - { id: 'service-status', visible: true, window: 'developer' as const, order: 10 }, - { id: 'debug', visible: true, window: 'developer' as const, order: 11 }, - { id: 'update', visible: true, window: 'developer' as const, order: 12 }, + { id: 'profile', visible: true, window: 'user' as const, order: 7 }, + { id: 'settings', visible: true, window: 'user' as const, order: 8 }, ]; diff --git a/app/settings/core/types.ts b/app/settings/core/types.ts index 97d4d360..c6374b06 100644 --- a/app/settings/core/types.ts +++ b/app/settings/core/types.ts @@ -10,15 +10,9 @@ export type TabType = | 'data' | 'cloud-providers' | 'local-providers' - | 'service-status' - | 'connection' - | 'debug' - | 'event-logs' - | 'update' - | 'task-manager' - | 'tab-management'; + | 'connection'; -export type WindowType = 'user' | 'developer'; +export type WindowType = 'user'; export interface UserProfile { nickname: any; @@ -53,17 +47,12 @@ export interface TabVisibilityConfig { locked?: boolean; } -export interface DevTabConfig extends TabVisibilityConfig { - window: 'developer'; -} - export interface UserTabConfig extends TabVisibilityConfig { window: 'user'; } export interface TabWindowConfig { userTabs: UserTabConfig[]; - developerTabs: DevTabConfig[]; } export const TAB_LABELS: Record = { @@ -72,15 +61,9 @@ export const TAB_LABELS: Record = { notifications: 'Notifications', features: 'Features', data: 'Data Management', + connection: 'Connection', 'cloud-providers': 'Cloud Providers', 'local-providers': 'Local Providers', - 'service-status': 'Service Status', - connection: 'Connections', - debug: 'Debug', - 'event-logs': 'Event Logs', - update: 'Updates', - 'task-manager': 'Task Manager', - 'tab-management': 'Tab Management', }; export const categoryLabels: Record = { diff --git a/app/settings/index.ts b/app/settings/index.ts index 862c33ef..a9700dc6 100644 --- a/app/settings/index.ts +++ b/app/settings/index.ts @@ -10,5 +10,4 @@ export { TabTile } from './shared/components/TabTile'; export { TabManagement } from './shared/components/TabManagement'; // Utils -export { getVisibleTabs, reorderTabs, resetToDefaultConfig } from './utils/tab-helpers'; export * from './utils/animations'; diff --git a/app/settings/shared/components/DraggableTabList.tsx b/app/settings/shared/components/DraggableTabList.tsx deleted file mode 100644 index ae7bbbba..00000000 --- a/app/settings/shared/components/DraggableTabList.tsx +++ /dev/null @@ -1,163 +0,0 @@ -import { useDrag, useDrop } from 'react-dnd'; -import { motion } from 'framer-motion'; -import { classNames } from '~/shared/utils/classNames'; -import type { TabVisibilityConfig } from '~/settings/core/types'; -import { TAB_LABELS } from '~/settings/core/types'; -import { Switch } from '~/shared/components/ui/Switch'; - -interface DraggableTabListProps { - tabs: TabVisibilityConfig[]; - onReorder: (tabs: TabVisibilityConfig[]) => void; - onWindowChange?: (tab: TabVisibilityConfig, window: 'user' | 'developer') => void; - onVisibilityChange?: (tab: TabVisibilityConfig, visible: boolean) => void; - showControls?: boolean; -} - -interface DraggableTabItemProps { - tab: TabVisibilityConfig; - index: number; - moveTab: (dragIndex: number, hoverIndex: number) => void; - showControls?: boolean; - onWindowChange?: (tab: TabVisibilityConfig, window: 'user' | 'developer') => void; - onVisibilityChange?: (tab: TabVisibilityConfig, visible: boolean) => void; -} - -interface DragItem { - type: string; - index: number; - id: string; -} - -const DraggableTabItem = ({ - tab, - index, - moveTab, - showControls, - onWindowChange, - onVisibilityChange, -}: DraggableTabItemProps) => { - const [{ isDragging }, dragRef] = useDrag({ - type: 'tab', - item: { type: 'tab', index, id: tab.id }, - collect: (monitor) => ({ - isDragging: monitor.isDragging(), - }), - }); - - const [, dropRef] = useDrop({ - accept: 'tab', - hover: (item: DragItem, monitor) => { - if (!monitor.isOver({ shallow: true })) { - return; - } - - if (item.index === index) { - return; - } - - if (item.id === tab.id) { - return; - } - - moveTab(item.index, index); - item.index = index; - }, - }); - - const ref = (node: HTMLDivElement | null) => { - dragRef(node); - dropRef(node); - }; - - return ( - -
-
-
-
-
-
{TAB_LABELS[tab.id]}
- {showControls && ( -
- Order: {tab.order}, Window: {tab.window} -
- )} -
-
- {showControls && !tab.locked && ( -
-
- onVisibilityChange?.(tab, checked)} - className="data-[state=checked]:bg-purple-500" - aria-label={`Toggle ${TAB_LABELS[tab.id]} visibility`} - /> - -
-
- - onWindowChange?.(tab, checked ? 'developer' : 'user')} - className="data-[state=checked]:bg-purple-500" - aria-label={`Toggle ${TAB_LABELS[tab.id]} window assignment`} - /> - -
-
- )} - - ); -}; - -export const DraggableTabList = ({ - tabs, - onReorder, - onWindowChange, - onVisibilityChange, - showControls = false, -}: DraggableTabListProps) => { - const moveTab = (dragIndex: number, hoverIndex: number) => { - const items = Array.from(tabs); - const [reorderedItem] = items.splice(dragIndex, 1); - items.splice(hoverIndex, 0, reorderedItem); - - // Update order numbers based on position - const reorderedTabs = items.map((tab, index) => ({ - ...tab, - order: index + 1, - })); - - onReorder(reorderedTabs); - }; - - return ( -
- {tabs.map((tab, index) => ( - - ))} -
- ); -}; diff --git a/app/settings/shared/components/TabManagement.tsx b/app/settings/shared/components/TabManagement.tsx index 5ca5eb0e..eaab9f53 100644 --- a/app/settings/shared/components/TabManagement.tsx +++ b/app/settings/shared/components/TabManagement.tsx @@ -19,13 +19,7 @@ const TAB_ICONS: Record = { data: 'i-ph:database-fill', 'cloud-providers': 'i-ph:cloud-fill', 'local-providers': 'i-ph:desktop-fill', - 'service-status': 'i-ph:activity-fill', connection: 'i-ph:wifi-high-fill', - debug: 'i-ph:bug-fill', - 'event-logs': 'i-ph:list-bullets-fill', - update: 'i-ph:arrow-clockwise-fill', - 'task-manager': 'i-ph:chart-line-fill', - 'tab-management': 'i-ph:squares-four-fill', }; // Define which tabs are default in user mode @@ -36,21 +30,19 @@ const DEFAULT_USER_TABS: TabType[] = [ 'local-providers', 'connection', 'notifications', - 'event-logs', + 'profile', + 'settings', ]; -// Define which tabs can be added to user mode -const OPTIONAL_USER_TABS: TabType[] = ['profile', 'settings', 'task-manager', 'service-status', 'debug', 'update']; - // All available tabs for user mode -const ALL_USER_TABS = [...DEFAULT_USER_TABS, ...OPTIONAL_USER_TABS]; +const ALL_USER_TABS = [...DEFAULT_USER_TABS]; // Define which tabs are beta -const BETA_TABS = new Set(['task-manager', 'service-status', 'update', 'local-providers']); +const BETA_TABS = new Set(['local-providers']); // Beta label component const BetaLabel = () => ( - BETA + BETA ); export const TabManagement = () => { @@ -84,7 +76,7 @@ export const TabManagement = () => { } // Check if tab can be enabled in user mode - const canBeEnabled = DEFAULT_USER_TABS.includes(tabId) || OPTIONAL_USER_TABS.includes(tabId); + const canBeEnabled = DEFAULT_USER_TABS.includes(tabId); if (!canBeEnabled && checked) { toast.error('This tab cannot be enabled in user mode'); @@ -253,110 +245,14 @@ export const TabManagement = () => { { - const isDisabled = - !DEFAULT_USER_TABS.includes(tab.id) && !OPTIONAL_USER_TABS.includes(tab.id); + const isDisabled = !DEFAULT_USER_TABS.includes(tab.id); if (!isDisabled) { handleTabVisibilityChange(tab.id, checked); } }} className={classNames('data-[state=checked]:bg-purple-500 ml-4', { - 'opacity-50 pointer-events-none': - !DEFAULT_USER_TABS.includes(tab.id) && !OPTIONAL_USER_TABS.includes(tab.id), - })} - /> -
-
-
- - - - ))} - - {/* Optional Section Header */} - {filteredTabs.some((tab) => OPTIONAL_USER_TABS.includes(tab.id)) && ( -
-
- Optional Tabs -
- )} - - {/* Optional Tabs */} - {filteredTabs - .filter((tab) => OPTIONAL_USER_TABS.includes(tab.id)) - .map((tab, index) => ( - - {/* Status Badges */} -
- - Optional - -
- -
- -
-
-
- - -
-
-
-
-

- {TAB_LABELS[tab.id]} -

- {BETA_TABS.has(tab.id) && } -
-

- {tab.visible ? 'Visible in user mode' : 'Hidden in user mode'} -

-
- { - const isDisabled = - !DEFAULT_USER_TABS.includes(tab.id) && !OPTIONAL_USER_TABS.includes(tab.id); - - if (!isDisabled) { - handleTabVisibilityChange(tab.id, checked); - } - }} - className={classNames('data-[state=checked]:bg-purple-500 ml-4', { - 'opacity-50 pointer-events-none': - !DEFAULT_USER_TABS.includes(tab.id) && !OPTIONAL_USER_TABS.includes(tab.id), + 'opacity-50 pointer-events-none': !DEFAULT_USER_TABS.includes(tab.id), })} />
diff --git a/app/settings/stores/settings.ts b/app/settings/stores/settings.ts index 830fd272..72352878 100644 --- a/app/settings/stores/settings.ts +++ b/app/settings/stores/settings.ts @@ -1,7 +1,7 @@ import { atom, map } from 'nanostores'; import { PROVIDER_LIST } from '~/shared/utils/constants'; import type { IProviderConfig } from '~/shared/types/model'; -import type { TabVisibilityConfig, TabWindowConfig, UserTabConfig, DevTabConfig } from '~/settings/core/types'; +import type { TabVisibilityConfig, TabWindowConfig, UserTabConfig } from '~/settings/core/types'; import { DEFAULT_TAB_CONFIG } from '~/settings/core/constants'; import Cookies from 'js-cookie'; import { toggleTheme } from '~/shared/stores/theme'; @@ -197,7 +197,6 @@ export const updatePromptId = (id: string) => { const getInitialTabConfiguration = (): TabWindowConfig => { const defaultConfig: TabWindowConfig = { userTabs: DEFAULT_TAB_CONFIG.filter((tab): tab is UserTabConfig => tab.window === 'user'), - developerTabs: DEFAULT_TAB_CONFIG.filter((tab): tab is DevTabConfig => tab.window === 'developer'), }; if (!isBrowser) { @@ -220,9 +219,6 @@ const getInitialTabConfiguration = (): TabWindowConfig => { // Ensure proper typing of loaded configuration return { userTabs: parsed.userTabs.filter((tab: TabVisibilityConfig): tab is UserTabConfig => tab.window === 'user'), - developerTabs: parsed.developerTabs.filter( - (tab: TabVisibilityConfig): tab is DevTabConfig => tab.window === 'developer', - ), }; } catch (error) { console.warn('Failed to parse tab configuration:', error); @@ -235,25 +231,13 @@ const getInitialTabConfiguration = (): TabWindowConfig => { export const tabConfigurationStore = map(getInitialTabConfiguration()); // Helper function to update tab configuration -export const updateTabConfiguration = (config: TabVisibilityConfig) => { +export const updateTabConfiguration = () => { const currentConfig = tabConfigurationStore.get(); console.log('Current tab configuration before update:', currentConfig); - const isUserTab = config.window === 'user'; - const targetArray = isUserTab ? 'userTabs' : 'developerTabs'; - - // Only update the tab in its respective window - const updatedTabs = currentConfig[targetArray].map((tab) => (tab.id === config.id ? { ...config } : tab)); - - // If tab doesn't exist in this window yet, add it - if (!updatedTabs.find((tab) => tab.id === config.id)) { - updatedTabs.push(config); - } - // Create new config, only updating the target window's tabs const newConfig: TabWindowConfig = { ...currentConfig, - [targetArray]: updatedTabs, }; console.log('New tab configuration after update:', newConfig); @@ -270,24 +254,12 @@ export const updateTabConfiguration = (config: TabVisibilityConfig) => { export const resetTabConfiguration = () => { const defaultConfig: TabWindowConfig = { userTabs: DEFAULT_TAB_CONFIG.filter((tab): tab is UserTabConfig => tab.window === 'user'), - developerTabs: DEFAULT_TAB_CONFIG.filter((tab): tab is DevTabConfig => tab.window === 'developer'), }; tabConfigurationStore.set(defaultConfig); localStorage.setItem('bolt_tab_configuration', JSON.stringify(defaultConfig)); }; -// Developer mode store with persistence -export const developerModeStore = atom(initialSettings.developerMode); - -export const setDeveloperMode = (value: boolean) => { - developerModeStore.set(value); - - if (isBrowser) { - localStorage.setItem(SETTINGS_KEYS.DEVELOPER_MODE, JSON.stringify(value)); - } -}; - // First, let's define the SettingsStore interface interface SettingsStore { isOpen: boolean; diff --git a/app/settings/stores/tabConfigurationStore.ts b/app/settings/stores/tabConfigurationStore.ts index 5f7ad460..9f183149 100644 --- a/app/settings/stores/tabConfigurationStore.ts +++ b/app/settings/stores/tabConfigurationStore.ts @@ -3,29 +3,26 @@ import { create } from 'zustand'; export interface TabConfig { id: string; visible: boolean; - window: 'developer' | 'user'; + window: 'user'; order: number; locked?: boolean; } interface TabConfigurationStore { userTabs: TabConfig[]; - developerTabs: TabConfig[]; - get: () => { userTabs: TabConfig[]; developerTabs: TabConfig[] }; - set: (config: { userTabs: TabConfig[]; developerTabs: TabConfig[] }) => void; + get: () => { userTabs: TabConfig[] }; + set: (config: { userTabs: TabConfig[] }) => void; reset: () => void; } const DEFAULT_CONFIG = { userTabs: [], - developerTabs: [], }; export const tabConfigurationStore = create((set, get) => ({ ...DEFAULT_CONFIG, get: () => ({ userTabs: get().userTabs, - developerTabs: get().developerTabs, }), set: (config) => set(config), reset: () => set(DEFAULT_CONFIG), diff --git a/app/settings/tabs/connections/ConnectionDiagnostics.tsx b/app/settings/tabs/connections/ConnectionDiagnostics.tsx index 30bb6c61..afbbabf4 100644 --- a/app/settings/tabs/connections/ConnectionDiagnostics.tsx +++ b/app/settings/tabs/connections/ConnectionDiagnostics.tsx @@ -42,15 +42,6 @@ export default function ConnectionDiagnostics() { supabaseConnection: localStorage.getItem('supabase_connection'), }; - // Get diagnostic data from server - const response = await fetch('/api/system/diagnostics'); - - if (!response.ok) { - throw new Error(`Diagnostics API error: ${response.status}`); - } - - const serverDiagnostics = await response.json(); - // === GitHub Checks === const githubConnectionParsed = safeJsonParse(localStorageChecks.githubConnection); const githubToken = githubConnectionParsed?.token; @@ -149,7 +140,6 @@ export default function ConnectionDiagnostics() { vercel: vercelUserCheck, supabase: supabaseCheck, }, - serverDiagnostics, }; setDiagnosticResults(results); diff --git a/app/settings/tabs/debug/DebugTab.tsx b/app/settings/tabs/debug/DebugTab.tsx deleted file mode 100644 index a0d74a2b..00000000 --- a/app/settings/tabs/debug/DebugTab.tsx +++ /dev/null @@ -1,2110 +0,0 @@ -import React, { useEffect, useState, useMemo, useCallback } from 'react'; -import { toast } from 'react-toastify'; -import { classNames } from '~/shared/utils/classNames'; -import { logStore, type LogEntry } from '~/shared/stores/logs'; -import { useStore } from '@nanostores/react'; -import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '~/shared/components/ui/Collapsible'; -import { Progress } from '~/shared/components/ui/Progress'; -import { ScrollArea } from '~/shared/components/ui/ScrollArea'; -import { Badge } from '~/shared/components/ui/Badge'; -import { Dialog, DialogRoot, DialogTitle } from '~/shared/components/ui/Dialog'; -import { jsPDF } from 'jspdf'; -import { useSettings } from '~/shared/hooks/useSettings'; - -interface SystemInfo { - os: string; - arch: string; - platform: string; - cpus: string; - memory: { - total: string; - free: string; - used: string; - percentage: number; - }; - node: string; - browser: { - name: string; - version: string; - language: string; - userAgent: string; - cookiesEnabled: boolean; - online: boolean; - platform: string; - cores: number; - }; - screen: { - width: number; - height: number; - colorDepth: number; - pixelRatio: number; - }; - time: { - timezone: string; - offset: number; - locale: string; - }; - performance: { - memory: { - jsHeapSizeLimit: number; - totalJSHeapSize: number; - usedJSHeapSize: number; - usagePercentage: number; - }; - timing: { - loadTime: number; - domReadyTime: number; - readyStart: number; - redirectTime: number; - appcacheTime: number; - unloadEventTime: number; - lookupDomainTime: number; - connectTime: number; - requestTime: number; - initDomTreeTime: number; - loadEventTime: number; - }; - navigation: { - type: number; - redirectCount: number; - }; - }; - network: { - downlink: number; - effectiveType: string; - rtt: number; - saveData: boolean; - type: string; - }; - battery?: { - charging: boolean; - chargingTime: number; - dischargingTime: number; - level: number; - }; - storage: { - quota: number; - usage: number; - persistent: boolean; - temporary: boolean; - }; -} - -interface GitHubRepoInfo { - fullName: string; - defaultBranch: string; - stars: number; - forks: number; - openIssues?: number; -} - -interface GitInfo { - local: { - commitHash: string; - branch: string; - commitTime: string; - author: string; - email: string; - remoteUrl: string; - repoName: string; - }; - github?: { - currentRepo: GitHubRepoInfo; - upstream?: GitHubRepoInfo; - }; - isForked?: boolean; -} - -interface WebAppInfo { - name: string; - version: string; - description: string; - license: string; - environment: string; - timestamp: string; - runtimeInfo: { - nodeVersion: string; - }; - dependencies: { - production: Array<{ name: string; version: string; type: string }>; - development: Array<{ name: string; version: string; type: string }>; - peer: Array<{ name: string; version: string; type: string }>; - optional: Array<{ name: string; version: string; type: string }>; - }; - gitInfo: GitInfo; -} - -// Add Ollama service status interface -interface OllamaServiceStatus { - isRunning: boolean; - lastChecked: Date; - error?: string; - models?: Array<{ - name: string; - size: string; - quantization: string; - }>; -} - -interface ExportFormat { - id: string; - label: string; - icon: string; - handler: () => void; -} - -const DependencySection = ({ - title, - deps, -}: { - title: string; - deps: Array<{ name: string; version: string; type: string }>; -}) => { - const [isOpen, setIsOpen] = useState(false); - - if (deps.length === 0) { - return null; - } - - return ( - - -
-
- - {title} Dependencies ({deps.length}) - -
-
- {isOpen ? 'Hide' : 'Show'} -
-
- - - -
- {deps.map((dep) => ( -
- {dep.name} - {dep.version} -
- ))} -
-
-
- - ); -}; - -export default function DebugTab() { - const [systemInfo, setSystemInfo] = useState(null); - const [webAppInfo, setWebAppInfo] = useState(null); - const [ollamaStatus, setOllamaStatus] = useState({ - isRunning: false, - lastChecked: new Date(), - }); - const [loading, setLoading] = useState({ - systemInfo: false, - webAppInfo: false, - errors: false, - performance: false, - }); - const [openSections, setOpenSections] = useState({ - system: false, - webapp: false, - errors: false, - performance: false, - }); - - const { providers } = useSettings(); - - // Subscribe to logStore updates - const logs = useStore(logStore.logs); - const errorLogs = useMemo(() => { - return Object.values(logs).filter( - (log): log is LogEntry => typeof log === 'object' && log !== null && 'level' in log && log.level === 'error', - ); - }, [logs]); - - // Set up error listeners when component mounts - useEffect(() => { - const handleError = (event: ErrorEvent) => { - logStore.logError(event.message, event.error, { - filename: event.filename, - lineNumber: event.lineno, - columnNumber: event.colno, - }); - }; - - const handleRejection = (event: PromiseRejectionEvent) => { - logStore.logError('Unhandled Promise Rejection', event.reason); - }; - - window.addEventListener('error', handleError); - window.addEventListener('unhandledrejection', handleRejection); - - return () => { - window.removeEventListener('error', handleError); - window.removeEventListener('unhandledrejection', handleRejection); - }; - }, []); - - // Check for errors when the errors section is opened - useEffect(() => { - if (openSections.errors) { - checkErrors(); - } - }, [openSections.errors]); - - // Load initial data when component mounts - useEffect(() => { - const loadInitialData = async () => { - await Promise.all([getSystemInfo(), getWebAppInfo()]); - }; - - loadInitialData(); - }, []); - - // Refresh data when sections are opened - useEffect(() => { - if (openSections.system) { - getSystemInfo(); - } - - if (openSections.webapp) { - getWebAppInfo(); - } - }, [openSections.system, openSections.webapp]); - - // Add periodic refresh of git info - useEffect(() => { - if (!openSections.webapp) { - return undefined; - } - - // Initial fetch - const fetchGitInfo = async () => { - try { - const response = await fetch('/api/system/git-info'); - const updatedGitInfo = (await response.json()) as GitInfo; - - setWebAppInfo((prev) => { - if (!prev) { - return null; - } - - // Only update if the data has changed - if (JSON.stringify(prev.gitInfo) === JSON.stringify(updatedGitInfo)) { - return prev; - } - - return { - ...prev, - gitInfo: updatedGitInfo, - }; - }); - } catch (error) { - console.error('Failed to fetch git info:', error); - } - }; - - fetchGitInfo(); - - // Refresh every 5 minutes instead of every second - const interval = setInterval(fetchGitInfo, 5 * 60 * 1000); - - return () => clearInterval(interval); - }, [openSections.webapp]); - - const getSystemInfo = async () => { - try { - setLoading((prev) => ({ ...prev, systemInfo: true })); - - // Get better OS detection - const userAgent = navigator.userAgent; - let detectedOS = 'Unknown'; - let detectedArch = 'unknown'; - - // Improved OS detection - if (userAgent.indexOf('Win') !== -1) { - detectedOS = 'Windows'; - } else if (userAgent.indexOf('Mac') !== -1) { - detectedOS = 'macOS'; - } else if (userAgent.indexOf('Linux') !== -1) { - detectedOS = 'Linux'; - } else if (userAgent.indexOf('Android') !== -1) { - detectedOS = 'Android'; - } else if (/iPhone|iPad|iPod/.test(userAgent)) { - detectedOS = 'iOS'; - } - - // Better architecture detection - if (userAgent.indexOf('x86_64') !== -1 || userAgent.indexOf('x64') !== -1 || userAgent.indexOf('WOW64') !== -1) { - detectedArch = 'x64'; - } else if (userAgent.indexOf('x86') !== -1 || userAgent.indexOf('i686') !== -1) { - detectedArch = 'x86'; - } else if (userAgent.indexOf('arm64') !== -1 || userAgent.indexOf('aarch64') !== -1) { - detectedArch = 'arm64'; - } else if (userAgent.indexOf('arm') !== -1) { - detectedArch = 'arm'; - } - - // Get browser info with improved detection - const browserName = (() => { - if (userAgent.indexOf('Edge') !== -1 || userAgent.indexOf('Edg/') !== -1) { - return 'Edge'; - } - - if (userAgent.indexOf('Chrome') !== -1) { - return 'Chrome'; - } - - if (userAgent.indexOf('Firefox') !== -1) { - return 'Firefox'; - } - - if (userAgent.indexOf('Safari') !== -1) { - return 'Safari'; - } - - return 'Unknown'; - })(); - - const browserVersionMatch = userAgent.match(/(Edge|Edg|Chrome|Firefox|Safari)[\s/](\d+(\.\d+)*)/); - const browserVersion = browserVersionMatch ? browserVersionMatch[2] : 'Unknown'; - - // Get performance metrics - const memory = (performance as any).memory || {}; - const timing = performance.timing; - const navigation = performance.navigation; - const connection = (navigator as any).connection || {}; - - // Try to use Navigation Timing API Level 2 when available - let loadTime = 0; - let domReadyTime = 0; - - try { - const navEntries = performance.getEntriesByType('navigation'); - - if (navEntries.length > 0) { - const navTiming = navEntries[0] as PerformanceNavigationTiming; - loadTime = navTiming.loadEventEnd - navTiming.startTime; - domReadyTime = navTiming.domContentLoadedEventEnd - navTiming.startTime; - } else { - // Fall back to older API - loadTime = timing.loadEventEnd - timing.navigationStart; - domReadyTime = timing.domContentLoadedEventEnd - timing.navigationStart; - } - } catch { - // Fall back to older API if Navigation Timing API Level 2 is not available - loadTime = timing.loadEventEnd - timing.navigationStart; - domReadyTime = timing.domContentLoadedEventEnd - timing.navigationStart; - } - - // Get battery info - let batteryInfo; - - try { - const battery = await (navigator as any).getBattery(); - batteryInfo = { - charging: battery.charging, - chargingTime: battery.chargingTime, - dischargingTime: battery.dischargingTime, - level: battery.level * 100, - }; - } catch { - console.log('Battery API not supported'); - } - - // Get storage info - let storageInfo = { - quota: 0, - usage: 0, - persistent: false, - temporary: false, - }; - - try { - const storage = await navigator.storage.estimate(); - const persistent = await navigator.storage.persist(); - storageInfo = { - quota: storage.quota || 0, - usage: storage.usage || 0, - persistent, - temporary: !persistent, - }; - } catch { - console.log('Storage API not supported'); - } - - // Get memory info from browser performance API - const performanceMemory = (performance as any).memory || {}; - const totalMemory = performanceMemory.jsHeapSizeLimit || 0; - const usedMemory = performanceMemory.usedJSHeapSize || 0; - const freeMemory = totalMemory - usedMemory; - const memoryPercentage = totalMemory ? (usedMemory / totalMemory) * 100 : 0; - - const systemInfo: SystemInfo = { - os: detectedOS, - arch: detectedArch, - platform: navigator.platform || 'unknown', - cpus: navigator.hardwareConcurrency + ' cores', - memory: { - total: formatBytes(totalMemory), - free: formatBytes(freeMemory), - used: formatBytes(usedMemory), - percentage: Math.round(memoryPercentage), - }, - node: 'browser', - browser: { - name: browserName, - version: browserVersion, - language: navigator.language, - userAgent: navigator.userAgent, - cookiesEnabled: navigator.cookieEnabled, - online: navigator.onLine, - platform: navigator.platform || 'unknown', - cores: navigator.hardwareConcurrency, - }, - screen: { - width: window.screen.width, - height: window.screen.height, - colorDepth: window.screen.colorDepth, - pixelRatio: window.devicePixelRatio, - }, - time: { - timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, - offset: new Date().getTimezoneOffset(), - locale: navigator.language, - }, - performance: { - memory: { - jsHeapSizeLimit: memory.jsHeapSizeLimit || 0, - totalJSHeapSize: memory.totalJSHeapSize || 0, - usedJSHeapSize: memory.usedJSHeapSize || 0, - usagePercentage: memory.totalJSHeapSize ? (memory.usedJSHeapSize / memory.totalJSHeapSize) * 100 : 0, - }, - timing: { - loadTime, - domReadyTime, - readyStart: timing.fetchStart - timing.navigationStart, - redirectTime: timing.redirectEnd - timing.redirectStart, - appcacheTime: timing.domainLookupStart - timing.fetchStart, - unloadEventTime: timing.unloadEventEnd - timing.unloadEventStart, - lookupDomainTime: timing.domainLookupEnd - timing.domainLookupStart, - connectTime: timing.connectEnd - timing.connectStart, - requestTime: timing.responseEnd - timing.requestStart, - initDomTreeTime: timing.domInteractive - timing.responseEnd, - loadEventTime: timing.loadEventEnd - timing.loadEventStart, - }, - navigation: { - type: navigation.type, - redirectCount: navigation.redirectCount, - }, - }, - network: { - downlink: connection?.downlink || 0, - effectiveType: connection?.effectiveType || 'unknown', - rtt: connection?.rtt || 0, - saveData: connection?.saveData || false, - type: connection?.type || 'unknown', - }, - battery: batteryInfo, - storage: storageInfo, - }; - - setSystemInfo(systemInfo); - toast.success('System information updated'); - } catch (error) { - toast.error('Failed to get system information'); - console.error('Failed to get system information:', error); - } finally { - setLoading((prev) => ({ ...prev, systemInfo: false })); - } - }; - - // Helper function to format bytes to human readable format with better precision - const formatBytes = (bytes: number) => { - if (bytes === 0) { - return '0 B'; - } - - const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; - const i = Math.floor(Math.log(bytes) / Math.log(1024)); - - // Return with proper precision based on unit size - if (i === 0) { - return `${bytes} ${units[i]}`; - } - - return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i]}`; - }; - - const getWebAppInfo = async () => { - try { - setLoading((prev) => ({ ...prev, webAppInfo: true })); - - const [appResponse, gitResponse] = await Promise.all([ - fetch('/api/system/app-info'), - fetch('/api/system/git-info'), - ]); - - if (!appResponse.ok || !gitResponse.ok) { - throw new Error('Failed to fetch webapp info'); - } - - const appData = (await appResponse.json()) as Omit; - const gitData = (await gitResponse.json()) as GitInfo; - - console.log('Git Info Response:', gitData); // Add logging to debug - - setWebAppInfo({ - ...appData, - gitInfo: gitData, - }); - - toast.success('WebApp information updated'); - - return true; - } catch (error) { - console.error('Failed to fetch webapp info:', error); - toast.error('Failed to fetch webapp information'); - setWebAppInfo(null); - - return false; - } finally { - setLoading((prev) => ({ ...prev, webAppInfo: false })); - } - }; - - const handleLogPerformance = () => { - try { - setLoading((prev) => ({ ...prev, performance: true })); - - // Get performance metrics using modern Performance API - const performanceEntries = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming; - const memory = (performance as any).memory; - - // Calculate timing metrics - const timingMetrics = { - loadTime: performanceEntries.loadEventEnd - performanceEntries.startTime, - domReadyTime: performanceEntries.domContentLoadedEventEnd - performanceEntries.startTime, - fetchTime: performanceEntries.responseEnd - performanceEntries.fetchStart, - redirectTime: performanceEntries.redirectEnd - performanceEntries.redirectStart, - dnsTime: performanceEntries.domainLookupEnd - performanceEntries.domainLookupStart, - tcpTime: performanceEntries.connectEnd - performanceEntries.connectStart, - ttfb: performanceEntries.responseStart - performanceEntries.requestStart, - processingTime: performanceEntries.loadEventEnd - performanceEntries.responseEnd, - }; - - // Get resource timing data - const resourceEntries = performance.getEntriesByType('resource'); - const resourceStats = { - totalResources: resourceEntries.length, - totalSize: resourceEntries.reduce((total, entry) => total + ((entry as any).transferSize || 0), 0), - totalTime: Math.max(...resourceEntries.map((entry) => entry.duration)), - }; - - // Get memory metrics - const memoryMetrics = memory - ? { - jsHeapSizeLimit: memory.jsHeapSizeLimit, - totalJSHeapSize: memory.totalJSHeapSize, - usedJSHeapSize: memory.usedJSHeapSize, - heapUtilization: (memory.usedJSHeapSize / memory.totalJSHeapSize) * 100, - } - : null; - - // Get frame rate metrics - let fps = 0; - - if ('requestAnimationFrame' in window) { - const times: number[] = []; - - function calculateFPS(now: number) { - times.push(now); - - if (times.length > 10) { - const fps = Math.round((1000 * 10) / (now - times[0])); - times.shift(); - - return fps; - } - - requestAnimationFrame(calculateFPS); - - return 0; - } - - fps = calculateFPS(performance.now()); - } - - // Log all performance metrics - logStore.logSystem('Performance Metrics', { - timing: timingMetrics, - resources: resourceStats, - memory: memoryMetrics, - fps, - timestamp: new Date().toISOString(), - navigationEntry: { - type: performanceEntries.type, - redirectCount: performanceEntries.redirectCount, - }, - }); - - toast.success('Performance metrics logged'); - } catch (error) { - toast.error('Failed to log performance metrics'); - console.error('Failed to log performance metrics:', error); - } finally { - setLoading((prev) => ({ ...prev, performance: false })); - } - }; - - const checkErrors = async () => { - try { - setLoading((prev) => ({ ...prev, errors: true })); - - // Get errors from log store - const storedErrors = errorLogs; - - if (storedErrors.length === 0) { - toast.success('No errors found'); - } else { - toast.warning(`Found ${storedErrors.length} error(s)`); - } - } catch (error) { - toast.error('Failed to check errors'); - console.error('Failed to check errors:', error); - } finally { - setLoading((prev) => ({ ...prev, errors: false })); - } - }; - - const exportDebugInfo = () => { - try { - const debugData = { - timestamp: new Date().toISOString(), - system: systemInfo, - webApp: webAppInfo, - errors: logStore.getLogs().filter((log: LogEntry) => log.level === 'error'), - performance: { - memory: (performance as any).memory || {}, - timing: performance.timing, - navigation: performance.navigation, - }, - }; - - const blob = new Blob([JSON.stringify(debugData, null, 2)], { type: 'application/json' }); - const url = window.URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `bolt-debug-info-${new Date().toISOString()}.json`; - document.body.appendChild(a); - a.click(); - window.URL.revokeObjectURL(url); - document.body.removeChild(a); - toast.success('Debug information exported successfully'); - } catch (error) { - console.error('Failed to export debug info:', error); - toast.error('Failed to export debug information'); - } - }; - - const exportAsCSV = () => { - try { - const debugData = { - system: systemInfo, - webApp: webAppInfo, - errors: logStore.getLogs().filter((log: LogEntry) => log.level === 'error'), - performance: { - memory: (performance as any).memory || {}, - timing: performance.timing, - navigation: performance.navigation, - }, - }; - - // Convert the data to CSV format - const csvData = [ - ['Category', 'Key', 'Value'], - ...Object.entries(debugData).flatMap(([category, data]) => - Object.entries(data || {}).map(([key, value]) => [ - category, - key, - typeof value === 'object' ? JSON.stringify(value) : String(value), - ]), - ), - ]; - - // Create CSV content - const csvContent = csvData.map((row) => row.join(',')).join('\n'); - const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = window.URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `bolt-debug-info-${new Date().toISOString()}.csv`; - document.body.appendChild(a); - a.click(); - window.URL.revokeObjectURL(url); - document.body.removeChild(a); - toast.success('Debug information exported as CSV'); - } catch (error) { - console.error('Failed to export CSV:', error); - toast.error('Failed to export debug information as CSV'); - } - }; - - const exportAsPDF = () => { - try { - const debugData = { - system: systemInfo, - webApp: webAppInfo, - errors: logStore.getLogs().filter((log: LogEntry) => log.level === 'error'), - performance: { - memory: (performance as any).memory || {}, - timing: performance.timing, - navigation: performance.navigation, - }, - }; - - // Create new PDF document - const doc = new jsPDF(); - const lineHeight = 7; - let yPos = 20; - const margin = 20; - const pageWidth = doc.internal.pageSize.getWidth(); - const maxLineWidth = pageWidth - 2 * margin; - - // Add key-value pair with better formatting - const addKeyValue = (key: string, value: any, indent = 0) => { - // Check if we need a new page - if (yPos > doc.internal.pageSize.getHeight() - 20) { - doc.addPage(); - yPos = margin; - } - - doc.setFontSize(10); - doc.setTextColor('#374151'); - doc.setFont('helvetica', 'bold'); - - // Format the key with proper spacing - const formattedKey = key.replace(/([A-Z])/g, ' $1').trim(); - doc.text(formattedKey + ':', margin + indent, yPos); - doc.setFont('helvetica', 'normal'); - doc.setTextColor('#6B7280'); - - let valueText; - - if (typeof value === 'object' && value !== null) { - // Skip rendering if value is empty object - if (Object.keys(value).length === 0) { - return; - } - - yPos += lineHeight; - Object.entries(value).forEach(([subKey, subValue]) => { - // Check for page break before each sub-item - if (yPos > doc.internal.pageSize.getHeight() - 20) { - doc.addPage(); - yPos = margin; - } - - const formattedSubKey = subKey.replace(/([A-Z])/g, ' $1').trim(); - addKeyValue(formattedSubKey, subValue, indent + 10); - }); - - return; - } else { - valueText = String(value); - } - - const valueX = margin + indent + doc.getTextWidth(formattedKey + ': '); - const maxValueWidth = maxLineWidth - indent - doc.getTextWidth(formattedKey + ': '); - const lines = doc.splitTextToSize(valueText, maxValueWidth); - - // Check if we need a new page for the value - if (yPos + lines.length * lineHeight > doc.internal.pageSize.getHeight() - 20) { - doc.addPage(); - yPos = margin; - } - - doc.text(lines, valueX, yPos); - yPos += lines.length * lineHeight; - }; - - // Add section header with page break check - const addSectionHeader = (title: string) => { - // Check if we need a new page - if (yPos + 20 > doc.internal.pageSize.getHeight() - 20) { - doc.addPage(); - yPos = margin; - } - - yPos += lineHeight; - doc.setFillColor('#F3F4F6'); - doc.rect(margin - 2, yPos - 5, pageWidth - 2 * (margin - 2), lineHeight + 6, 'F'); - doc.setFont('helvetica', 'bold'); - doc.setTextColor('#111827'); - doc.setFontSize(12); - doc.text(title.toUpperCase(), margin, yPos); - doc.setFont('helvetica', 'normal'); - yPos += lineHeight * 1.5; - }; - - // Add horizontal line with page break check - const addHorizontalLine = () => { - // Check if we need a new page - if (yPos + 10 > doc.internal.pageSize.getHeight() - 20) { - doc.addPage(); - yPos = margin; - - return; // Skip drawing line if we just started a new page - } - - doc.setDrawColor('#E5E5E5'); - doc.line(margin, yPos, pageWidth - margin, yPos); - yPos += lineHeight; - }; - - // Helper function to add footer to all pages - const addFooters = () => { - const totalPages = doc.internal.pages.length - 1; - - for (let i = 1; i <= totalPages; i++) { - doc.setPage(i); - doc.setFontSize(8); - doc.setTextColor('#9CA3AF'); - doc.text(`Page ${i} of ${totalPages}`, pageWidth / 2, doc.internal.pageSize.getHeight() - 10, { - align: 'center', - }); - } - }; - - // Title and Header (first page only) - doc.setFillColor('#6366F1'); - doc.rect(0, 0, pageWidth, 40, 'F'); - doc.setTextColor('#FFFFFF'); - doc.setFontSize(24); - doc.setFont('helvetica', 'bold'); - doc.text('Debug Information Report', margin, 25); - yPos = 50; - - // Timestamp and metadata - doc.setTextColor('#6B7280'); - doc.setFontSize(10); - doc.setFont('helvetica', 'normal'); - - const timestamp = new Date().toLocaleString(undefined, { - year: 'numeric', - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - }); - doc.text(`Generated: ${timestamp}`, margin, yPos); - yPos += lineHeight * 2; - - // System Information Section - if (debugData.system) { - addSectionHeader('System Information'); - - // OS and Architecture - addKeyValue('Operating System', debugData.system.os); - addKeyValue('Architecture', debugData.system.arch); - addKeyValue('Platform', debugData.system.platform); - addKeyValue('CPU Cores', debugData.system.cpus); - - // Memory - const memory = debugData.system.memory; - addKeyValue('Memory', { - 'Total Memory': memory.total, - 'Used Memory': memory.used, - 'Free Memory': memory.free, - Usage: memory.percentage + '%', - }); - - // Browser Information - const browser = debugData.system.browser; - addKeyValue('Browser', { - Name: browser.name, - Version: browser.version, - Language: browser.language, - Platform: browser.platform, - 'Cookies Enabled': browser.cookiesEnabled ? 'Yes' : 'No', - 'Online Status': browser.online ? 'Online' : 'Offline', - }); - - // Screen Information - const screen = debugData.system.screen; - addKeyValue('Screen', { - Resolution: `${screen.width}x${screen.height}`, - 'Color Depth': screen.colorDepth + ' bit', - 'Pixel Ratio': screen.pixelRatio + 'x', - }); - - // Time Information - const time = debugData.system.time; - addKeyValue('Time Settings', { - Timezone: time.timezone, - 'UTC Offset': time.offset / 60 + ' hours', - Locale: time.locale, - }); - - addHorizontalLine(); - } - - // Web App Information Section - if (debugData.webApp) { - addSectionHeader('Web App Information'); - - // Basic Info - addKeyValue('Application', { - Name: debugData.webApp.name, - Version: debugData.webApp.version, - Environment: debugData.webApp.environment, - 'Node Version': debugData.webApp.runtimeInfo.nodeVersion, - }); - - // Git Information - if (debugData.webApp.gitInfo) { - const gitInfo = debugData.webApp.gitInfo.local; - addKeyValue('Git Information', { - Branch: gitInfo.branch, - Commit: gitInfo.commitHash, - Author: gitInfo.author, - 'Commit Time': gitInfo.commitTime, - Repository: gitInfo.repoName, - }); - - if (debugData.webApp.gitInfo.github) { - const githubInfo = debugData.webApp.gitInfo.github.currentRepo; - addKeyValue('GitHub Information', { - Repository: githubInfo.fullName, - 'Default Branch': githubInfo.defaultBranch, - Stars: githubInfo.stars, - Forks: githubInfo.forks, - 'Open Issues': githubInfo.openIssues || 0, - }); - } - } - - addHorizontalLine(); - } - - // Performance Section - if (debugData.performance) { - addSectionHeader('Performance Metrics'); - - // Memory Usage - const memory = debugData.performance.memory || {}; - const totalHeap = memory.totalJSHeapSize || 0; - const usedHeap = memory.usedJSHeapSize || 0; - const usagePercentage = memory.usagePercentage || 0; - - addKeyValue('Memory Usage', { - 'Total Heap Size': formatBytes(totalHeap), - 'Used Heap Size': formatBytes(usedHeap), - Usage: usagePercentage.toFixed(1) + '%', - }); - - // Timing Metrics - const timing = debugData.performance.timing || {}; - const navigationStart = timing.navigationStart || 0; - const loadEventEnd = timing.loadEventEnd || 0; - const domContentLoadedEventEnd = timing.domContentLoadedEventEnd || 0; - const responseEnd = timing.responseEnd || 0; - const requestStart = timing.requestStart || 0; - - const loadTime = loadEventEnd > navigationStart ? loadEventEnd - navigationStart : 0; - const domReadyTime = - domContentLoadedEventEnd > navigationStart ? domContentLoadedEventEnd - navigationStart : 0; - const requestTime = responseEnd > requestStart ? responseEnd - requestStart : 0; - - addKeyValue('Page Load Metrics', { - 'Total Load Time': (loadTime / 1000).toFixed(2) + ' seconds', - 'DOM Ready Time': (domReadyTime / 1000).toFixed(2) + ' seconds', - 'Request Time': (requestTime / 1000).toFixed(2) + ' seconds', - }); - - // Network Information - if (debugData.system?.network) { - const network = debugData.system.network; - addKeyValue('Network Information', { - 'Connection Type': network.type || 'Unknown', - 'Effective Type': network.effectiveType || 'Unknown', - 'Download Speed': (network.downlink || 0) + ' Mbps', - 'Latency (RTT)': (network.rtt || 0) + ' ms', - 'Data Saver': network.saveData ? 'Enabled' : 'Disabled', - }); - } - - addHorizontalLine(); - } - - // Errors Section - if (debugData.errors && debugData.errors.length > 0) { - addSectionHeader('Error Log'); - - debugData.errors.forEach((error: LogEntry, index: number) => { - doc.setTextColor('#DC2626'); - doc.setFontSize(10); - doc.setFont('helvetica', 'bold'); - doc.text(`Error ${index + 1}:`, margin, yPos); - yPos += lineHeight; - - doc.setFont('helvetica', 'normal'); - doc.setTextColor('#6B7280'); - addKeyValue('Message', error.message, 10); - - if (error.stack) { - addKeyValue('Stack', error.stack, 10); - } - - if (error.source) { - addKeyValue('Source', error.source, 10); - } - - yPos += lineHeight; - }); - } - - // Add footers to all pages at the end - addFooters(); - - // Save the PDF - doc.save(`bolt-debug-info-${new Date().toISOString()}.pdf`); - toast.success('Debug information exported as PDF'); - } catch (error) { - console.error('Failed to export PDF:', error); - toast.error('Failed to export debug information as PDF'); - } - }; - - const exportAsText = () => { - try { - const debugData = { - system: systemInfo, - webApp: webAppInfo, - errors: logStore.getLogs().filter((log: LogEntry) => log.level === 'error'), - performance: { - memory: (performance as any).memory || {}, - timing: performance.timing, - navigation: performance.navigation, - }, - }; - - const textContent = Object.entries(debugData) - .map(([category, data]) => { - return `${category.toUpperCase()}\n${'-'.repeat(30)}\n${JSON.stringify(data, null, 2)}\n\n`; - }) - .join('\n'); - - const blob = new Blob([textContent], { type: 'text/plain' }); - const url = window.URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `bolt-debug-info-${new Date().toISOString()}.txt`; - document.body.appendChild(a); - a.click(); - window.URL.revokeObjectURL(url); - document.body.removeChild(a); - toast.success('Debug information exported as text file'); - } catch (error) { - console.error('Failed to export text file:', error); - toast.error('Failed to export debug information as text file'); - } - }; - - const exportFormats: ExportFormat[] = [ - { - id: 'json', - label: 'Export as JSON', - icon: 'i-ph:file-js', - handler: exportDebugInfo, - }, - { - id: 'csv', - label: 'Export as CSV', - icon: 'i-ph:file-csv', - handler: exportAsCSV, - }, - { - id: 'pdf', - label: 'Export as PDF', - icon: 'i-ph:file-pdf', - handler: exportAsPDF, - }, - { - id: 'txt', - label: 'Export as Text', - icon: 'i-ph:file-text', - handler: exportAsText, - }, - ]; - - // Add Ollama health check function - const checkOllamaStatus = useCallback(async () => { - try { - const ollamaProvider = providers?.Ollama; - const baseUrl = ollamaProvider?.settings?.baseUrl || 'http://127.0.0.1:11434'; - - // First check if service is running - const versionResponse = await fetch(`${baseUrl}/api/version`); - - if (!versionResponse.ok) { - throw new Error('Service not running'); - } - - // Then fetch installed models - const modelsResponse = await fetch(`${baseUrl}/api/tags`); - - const modelsData = (await modelsResponse.json()) as { - models: Array<{ name: string; size: string; quantization: string }>; - }; - - setOllamaStatus({ - isRunning: true, - lastChecked: new Date(), - models: modelsData.models, - }); - } catch { - setOllamaStatus({ - isRunning: false, - error: 'Connection failed', - lastChecked: new Date(), - models: undefined, - }); - } - }, [providers]); - - // Monitor Ollama provider status and check periodically - useEffect(() => { - const ollamaProvider = providers?.Ollama; - - if (ollamaProvider?.settings?.enabled) { - // Check immediately when provider is enabled - checkOllamaStatus(); - - // Set up periodic checks every 10 seconds - const intervalId = setInterval(checkOllamaStatus, 10000); - - return () => clearInterval(intervalId); - } - - return undefined; - }, [providers, checkOllamaStatus]); - - // Replace the existing export button with this new component - const ExportButton = () => { - const [isOpen, setIsOpen] = useState(false); - - const handleOpenChange = useCallback((open: boolean) => { - setIsOpen(open); - }, []); - - const handleFormatClick = useCallback((handler: () => void) => { - handler(); - setIsOpen(false); - }, []); - - return ( - - - - -
- -
- Export Debug Information - - -
- {exportFormats.map((format) => ( - - ))} -
-
-
-
- ); - }; - - // Add helper function to get Ollama status text and color - const getOllamaStatus = () => { - const ollamaProvider = providers?.Ollama; - const isOllamaEnabled = ollamaProvider?.settings?.enabled; - - if (!isOllamaEnabled) { - return { - status: 'Disabled', - color: 'text-red-500', - bgColor: 'bg-red-500', - message: 'Ollama provider is disabled in settings', - }; - } - - if (!ollamaStatus.isRunning) { - return { - status: 'Not Running', - color: 'text-red-500', - bgColor: 'bg-red-500', - message: ollamaStatus.error || 'Ollama service is not running', - }; - } - - const modelCount = ollamaStatus.models?.length ?? 0; - - return { - status: 'Running', - color: 'text-green-500', - bgColor: 'bg-green-500', - message: `Ollama service is running with ${modelCount} installed models (Provider: Enabled)`, - }; - }; - - // Add type for status result - type StatusResult = { - status: string; - color: string; - bgColor: string; - message: string; - }; - - const status = getOllamaStatus() as StatusResult; - - return ( -
- {/* Quick Stats Banner */} -
- {/* Errors Card */} -
-
-
-
Errors
-
-
- 0 ? 'text-red-500' : 'text-green-500')} - > - {errorLogs.length} - -
-
-
0 ? 'i-ph:warning text-red-500' : 'i-ph:check-circle text-green-500', - )} - /> - {errorLogs.length > 0 ? 'Errors detected' : 'No errors detected'} -
-
- - {/* Memory Usage Card */} -
-
-
-
Memory Usage
-
-
- 80 - ? 'text-red-500' - : (systemInfo?.memory?.percentage ?? 0) > 60 - ? 'text-yellow-500' - : 'text-green-500', - )} - > - {systemInfo?.memory?.percentage ?? 0}% - -
- 80 - ? '[&>div]:bg-red-500' - : (systemInfo?.memory?.percentage ?? 0) > 60 - ? '[&>div]:bg-yellow-500' - : '[&>div]:bg-green-500', - )} - /> -
-
- Used: {systemInfo?.memory.used ?? '0 GB'} / {systemInfo?.memory.total ?? '0 GB'} -
-
- - {/* Page Load Time Card */} -
-
-
-
Page Load Time
-
-
- 2000 - ? 'text-red-500' - : (systemInfo?.performance.timing.loadTime ?? 0) > 1000 - ? 'text-yellow-500' - : 'text-green-500', - )} - > - {systemInfo ? (systemInfo.performance.timing.loadTime / 1000).toFixed(2) : '-'}s - -
-
-
- DOM Ready: {systemInfo ? (systemInfo.performance.timing.domReadyTime / 1000).toFixed(2) : '-'}s -
-
- - {/* Network Speed Card */} -
-
-
-
Network Speed
-
-
- - {systemInfo?.network.downlink ?? '-'} Mbps - -
-
-
- RTT: {systemInfo?.network.rtt ?? '-'} ms -
-
- - {/* Ollama Service Card - Now spans all 4 columns */} -
-
-
-
-
-
Ollama Service
-
{status.message}
-
-
-
-
-
- - {status.status} - -
-
-
- {ollamaStatus.lastChecked.toLocaleTimeString()} -
-
-
- -
- {status.status === 'Running' && ollamaStatus.models && ollamaStatus.models.length > 0 ? ( - <> -
-
-
- Installed Models - - {ollamaStatus.models.length} - -
-
-
-
- {ollamaStatus.models.map((model) => ( -
-
-
- {model.name} -
- - {Math.round(parseInt(model.size) / 1024 / 1024)}MB - -
- ))} -
-
- - ) : ( -
-
-
- {status.message} -
-
- )} -
-
-
- - {/* Action Buttons */} -
- - - - - - - - - -
- - {/* System Information */} - setOpenSections((prev) => ({ ...prev, system: open }))} - className="w-full" - > - -
-
-
-

System Information

-
-
-
- - - -
- {systemInfo ? ( -
-
-
-
- OS: - {systemInfo.os} -
-
-
- Platform: - {systemInfo.platform} -
-
-
- Architecture: - {systemInfo.arch} -
-
-
- CPU Cores: - {systemInfo.cpus} -
-
-
- Node Version: - {systemInfo.node} -
-
-
- Network Type: - - {systemInfo.network.type} ({systemInfo.network.effectiveType}) - -
-
-
- Network Speed: - - {systemInfo.network.downlink}Mbps (RTT: {systemInfo.network.rtt}ms) - -
- {systemInfo.battery && ( -
-
- Battery: - - {systemInfo.battery.level.toFixed(1)}% {systemInfo.battery.charging ? '(Charging)' : ''} - -
- )} -
-
- Storage: - - {(systemInfo.storage.usage / (1024 * 1024 * 1024)).toFixed(2)}GB /{' '} - {(systemInfo.storage.quota / (1024 * 1024 * 1024)).toFixed(2)}GB - -
-
-
-
-
- Memory Usage: - - {systemInfo.memory.used} / {systemInfo.memory.total} ({systemInfo.memory.percentage}%) - -
-
-
- Browser: - - {systemInfo.browser.name} {systemInfo.browser.version} - -
-
-
- Screen: - - {systemInfo.screen.width}x{systemInfo.screen.height} ({systemInfo.screen.pixelRatio}x) - -
-
-
- Timezone: - {systemInfo.time.timezone} -
-
-
- Language: - {systemInfo.browser.language} -
-
-
- JS Heap: - - {(systemInfo.performance.memory.usedJSHeapSize / (1024 * 1024)).toFixed(1)}MB /{' '} - {(systemInfo.performance.memory.totalJSHeapSize / (1024 * 1024)).toFixed(1)}MB ( - {systemInfo.performance.memory.usagePercentage.toFixed(1)}%) - -
-
-
- Page Load: - - {(systemInfo.performance.timing.loadTime / 1000).toFixed(2)}s - -
-
-
- DOM Ready: - - {(systemInfo.performance.timing.domReadyTime / 1000).toFixed(2)}s - -
-
-
- ) : ( -
Loading system information...
- )} -
- - - - {/* Performance Metrics */} - setOpenSections((prev) => ({ ...prev, performance: open }))} - className="w-full" - > - -
-
-
-

Performance Metrics

-
-
-
- - - -
- {systemInfo && ( -
-
-
- Page Load Time: - - {(systemInfo.performance.timing.loadTime / 1000).toFixed(2)}s - -
-
- DOM Ready Time: - - {(systemInfo.performance.timing.domReadyTime / 1000).toFixed(2)}s - -
-
- Request Time: - - {(systemInfo.performance.timing.requestTime / 1000).toFixed(2)}s - -
-
- Redirect Time: - - {(systemInfo.performance.timing.redirectTime / 1000).toFixed(2)}s - -
-
-
-
- JS Heap Usage: - - {(systemInfo.performance.memory.usedJSHeapSize / (1024 * 1024)).toFixed(1)}MB /{' '} - {(systemInfo.performance.memory.totalJSHeapSize / (1024 * 1024)).toFixed(1)}MB - -
-
- Heap Utilization: - - {systemInfo.performance.memory.usagePercentage.toFixed(1)}% - -
-
- Navigation Type: - - {systemInfo.performance.navigation.type === 0 - ? 'Navigate' - : systemInfo.performance.navigation.type === 1 - ? 'Reload' - : systemInfo.performance.navigation.type === 2 - ? 'Back/Forward' - : 'Other'} - -
-
- Redirects: - - {systemInfo.performance.navigation.redirectCount} - -
-
-
- )} -
-
- - - {/* WebApp Information */} - setOpenSections((prev) => ({ ...prev, webapp: open }))} - className="w-full" - > - -
-
-
-

WebApp Information

- {loading.webAppInfo && } -
-
-
- - - -
- {loading.webAppInfo ? ( -
- -
- ) : !webAppInfo ? ( -
-
-

Failed to load WebApp information

- -
- ) : ( -
-
-

Basic Information

-
-
-
- Name: - {webAppInfo.name} -
-
-
- Version: - {webAppInfo.version} -
-
-
- License: - {webAppInfo.license} -
-
-
- Environment: - {webAppInfo.environment} -
-
-
- Node Version: - {webAppInfo.runtimeInfo.nodeVersion} -
-
-
- -
-

Git Information

-
-
-
- Branch: - {webAppInfo.gitInfo.local.branch} -
-
-
- Commit: - {webAppInfo.gitInfo.local.commitHash} -
-
-
- Author: - {webAppInfo.gitInfo.local.author} -
-
-
- Commit Time: - {webAppInfo.gitInfo.local.commitTime} -
- - {webAppInfo.gitInfo.github && ( - <> -
-
-
- Repository: - - {webAppInfo.gitInfo.github.currentRepo.fullName} - {webAppInfo.gitInfo.isForked && ' (fork)'} - -
- -
-
-
- - {webAppInfo.gitInfo.github.currentRepo.stars} - -
-
-
- - {webAppInfo.gitInfo.github.currentRepo.forks} - -
-
-
- - {webAppInfo.gitInfo.github.currentRepo.openIssues} - -
-
-
- - {webAppInfo.gitInfo.github.upstream && ( -
-
-
- Upstream: - - {webAppInfo.gitInfo.github.upstream.fullName} - -
- -
-
-
- - {webAppInfo.gitInfo.github.upstream.stars} - -
-
-
- - {webAppInfo.gitInfo.github.upstream.forks} - -
-
-
- )} - - )} -
-
-
- )} - - {webAppInfo && ( -
-

Dependencies

-
- - - - -
-
- )} -
- - - - {/* Error Check */} - setOpenSections((prev) => ({ ...prev, errors: open }))} - className="w-full" - > - -
-
-
-

Error Check

- {errorLogs.length > 0 && ( - - {errorLogs.length} Errors - - )} -
-
-
- - - -
- -
-
- Checks for: -
    -
  • Unhandled JavaScript errors
  • -
  • Unhandled Promise rejections
  • -
  • Runtime exceptions
  • -
  • Network errors
  • -
-
-
- Status: - - {loading.errors - ? 'Checking...' - : errorLogs.length > 0 - ? `${errorLogs.length} errors found` - : 'No errors found'} - -
- {errorLogs.length > 0 && ( -
-
Recent Errors:
-
- {errorLogs.map((error) => ( -
-
{error.message}
- {error.source && ( -
- Source: {error.source} - {error.details?.lineNumber && `:${error.details.lineNumber}`} -
- )} - {error.stack && ( -
{error.stack}
- )} -
- ))} -
-
- )} -
-
-
-
- -
- ); -} diff --git a/app/settings/tabs/event-logs/EventLogsTab.tsx b/app/settings/tabs/event-logs/EventLogsTab.tsx deleted file mode 100644 index 94439541..00000000 --- a/app/settings/tabs/event-logs/EventLogsTab.tsx +++ /dev/null @@ -1,1013 +0,0 @@ -import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { motion } from 'framer-motion'; -import { Switch } from '~/shared/components/ui/Switch'; -import { logStore, type LogEntry } from '~/shared/stores/logs'; -import { useStore } from '@nanostores/react'; -import { classNames } from '~/shared/utils/classNames'; -import * as DropdownMenu from '@radix-ui/react-dropdown-menu'; -import { Dialog, DialogRoot, DialogTitle } from '~/shared/components/ui/Dialog'; -import { jsPDF } from 'jspdf'; -import { toast } from 'react-toastify'; - -interface SelectOption { - value: string; - label: string; - icon?: string; - color?: string; -} - -const logLevelOptions: SelectOption[] = [ - { - value: 'all', - label: 'All Types', - icon: 'i-ph:funnel', - color: '#9333ea', - }, - { - value: 'provider', - label: 'LLM', - icon: 'i-ph:robot', - color: '#10b981', - }, - { - value: 'api', - label: 'API', - icon: 'i-ph:cloud', - color: '#3b82f6', - }, - { - value: 'error', - label: 'Errors', - icon: 'i-ph:warning-circle', - color: '#ef4444', - }, - { - value: 'warning', - label: 'Warnings', - icon: 'i-ph:warning', - color: '#f59e0b', - }, - { - value: 'info', - label: 'Info', - icon: 'i-ph:info', - color: '#3b82f6', - }, - { - value: 'debug', - label: 'Debug', - icon: 'i-ph:bug', - color: '#6b7280', - }, -]; - -interface LogEntryItemProps { - log: LogEntry; - isExpanded: boolean; - use24Hour: boolean; - showTimestamp: boolean; -} - -const LogEntryItem = ({ log, isExpanded: forceExpanded, use24Hour, showTimestamp }: LogEntryItemProps) => { - const [localExpanded, setLocalExpanded] = useState(forceExpanded); - - useEffect(() => { - setLocalExpanded(forceExpanded); - }, [forceExpanded]); - - const timestamp = useMemo(() => { - const date = new Date(log.timestamp); - return date.toLocaleTimeString('en-US', { hour12: !use24Hour }); - }, [log.timestamp, use24Hour]); - - const style = useMemo(() => { - if (log.category === 'provider') { - return { - icon: 'i-ph:robot', - color: 'text-emerald-500 dark:text-emerald-400', - bg: 'hover:bg-emerald-500/10 dark:hover:bg-emerald-500/20', - badge: 'text-emerald-500 bg-emerald-50 dark:bg-emerald-500/10', - }; - } - - if (log.category === 'api') { - return { - icon: 'i-ph:cloud', - color: 'text-blue-500 dark:text-blue-400', - bg: 'hover:bg-blue-500/10 dark:hover:bg-blue-500/20', - badge: 'text-blue-500 bg-blue-50 dark:bg-blue-500/10', - }; - } - - switch (log.level) { - case 'error': - return { - icon: 'i-ph:warning-circle', - color: 'text-red-500 dark:text-red-400', - bg: 'hover:bg-red-500/10 dark:hover:bg-red-500/20', - badge: 'text-red-500 bg-red-50 dark:bg-red-500/10', - }; - case 'warning': - return { - icon: 'i-ph:warning', - color: 'text-yellow-500 dark:text-yellow-400', - bg: 'hover:bg-yellow-500/10 dark:hover:bg-yellow-500/20', - badge: 'text-yellow-500 bg-yellow-50 dark:bg-yellow-500/10', - }; - case 'debug': - return { - icon: 'i-ph:bug', - color: 'text-gray-500 dark:text-gray-400', - bg: 'hover:bg-gray-500/10 dark:hover:bg-gray-500/20', - badge: 'text-gray-500 bg-gray-50 dark:bg-gray-500/10', - }; - default: - return { - icon: 'i-ph:info', - color: 'text-blue-500 dark:text-blue-400', - bg: 'hover:bg-blue-500/10 dark:hover:bg-blue-500/20', - badge: 'text-blue-500 bg-blue-50 dark:bg-blue-500/10', - }; - } - }, [log.level, log.category]); - - const renderDetails = (details: any) => { - if (log.category === 'provider') { - return ( -
-
- Model: {details.model} - - Tokens: {details.totalTokens} - - Duration: {details.duration}ms -
- {details.prompt && ( -
-
Prompt:
-
-                {details.prompt}
-              
-
- )} - {details.response && ( -
-
Response:
-
-                {details.response}
-              
-
- )} -
- ); - } - - if (log.category === 'api') { - return ( -
-
- {details.method} - - Status: {details.statusCode} - - Duration: {details.duration}ms -
-
{details.url}
- {details.request && ( -
-
Request:
-
-                {JSON.stringify(details.request, null, 2)}
-              
-
- )} - {details.response && ( -
-
Response:
-
-                {JSON.stringify(details.response, null, 2)}
-              
-
- )} - {details.error && ( -
-
Error:
-
-                {JSON.stringify(details.error, null, 2)}
-              
-
- )} -
- ); - } - - return ( -
-        {JSON.stringify(details, null, 2)}
-      
- ); - }; - - return ( - -
-
- -
-
{log.message}
- {log.details && ( - <> - - {localExpanded && renderDetails(log.details)} - - )} -
-
- {log.level} -
- {log.category && ( -
- {log.category} -
- )} -
-
-
- {showTimestamp && } -
-
- ); -}; - -interface ExportFormat { - id: string; - label: string; - icon: string; - handler: () => void; -} - -export function EventLogsTab() { - const logs = useStore(logStore.logs); - const [selectedLevel, setSelectedLevel] = useState<'all' | string>('all'); - const [searchQuery, setSearchQuery] = useState(''); - const [use24Hour, setUse24Hour] = useState(false); - const [autoExpand, setAutoExpand] = useState(false); - const [showTimestamps, setShowTimestamps] = useState(true); - const [showLevelFilter, setShowLevelFilter] = useState(false); - const [isRefreshing, setIsRefreshing] = useState(false); - const levelFilterRef = useRef(null); - - const filteredLogs = useMemo(() => { - const allLogs = Object.values(logs); - - if (selectedLevel === 'all') { - return allLogs.filter((log) => - searchQuery ? log.message.toLowerCase().includes(searchQuery.toLowerCase()) : true, - ); - } - - return allLogs.filter((log) => { - const matchesType = log.category === selectedLevel || log.level === selectedLevel; - const matchesSearch = searchQuery ? log.message.toLowerCase().includes(searchQuery.toLowerCase()) : true; - - return matchesType && matchesSearch; - }); - }, [logs, selectedLevel, searchQuery]); - - // Add performance tracking on mount - useEffect(() => { - const startTime = performance.now(); - - logStore.logInfo('Event Logs tab mounted', { - type: 'component_mount', - message: 'Event Logs tab component mounted', - component: 'EventLogsTab', - }); - - return () => { - const duration = performance.now() - startTime; - logStore.logPerformanceMetric('EventLogsTab', 'mount-duration', duration); - }; - }, []); - - // Log filter changes - const handleLevelFilterChange = useCallback( - (newLevel: string) => { - logStore.logInfo('Log level filter changed', { - type: 'filter_change', - message: `Log level filter changed from ${selectedLevel} to ${newLevel}`, - component: 'EventLogsTab', - previousLevel: selectedLevel, - newLevel, - }); - setSelectedLevel(newLevel as string); - setShowLevelFilter(false); - }, - [selectedLevel], - ); - - // Log search changes with debounce - useEffect(() => { - const timeoutId = setTimeout(() => { - if (searchQuery) { - logStore.logInfo('Log search performed', { - type: 'search', - message: `Search performed with query "${searchQuery}" (${filteredLogs.length} results)`, - component: 'EventLogsTab', - query: searchQuery, - resultsCount: filteredLogs.length, - }); - } - }, 1000); - - return () => clearTimeout(timeoutId); - }, [searchQuery, filteredLogs.length]); - - // Enhanced refresh handler - const handleRefresh = useCallback(async () => { - const startTime = performance.now(); - setIsRefreshing(true); - - try { - await logStore.refreshLogs(); - - const duration = performance.now() - startTime; - - logStore.logSuccess('Logs refreshed successfully', { - type: 'refresh', - message: `Successfully refreshed ${Object.keys(logs).length} logs`, - component: 'EventLogsTab', - duration, - logsCount: Object.keys(logs).length, - }); - } catch (error) { - logStore.logError('Failed to refresh logs', error, { - type: 'refresh_error', - message: 'Failed to refresh logs', - component: 'EventLogsTab', - }); - } finally { - setTimeout(() => setIsRefreshing(false), 500); - } - }, [logs]); - - // Log preference changes - const handlePreferenceChange = useCallback((type: string, value: boolean) => { - logStore.logInfo('Log preference changed', { - type: 'preference_change', - message: `Log preference "${type}" changed to ${value}`, - component: 'EventLogsTab', - preference: type, - value, - }); - - switch (type) { - case 'timestamps': - setShowTimestamps(value); - break; - case '24hour': - setUse24Hour(value); - break; - case 'autoExpand': - setAutoExpand(value); - break; - } - }, []); - - // Close filters when clicking outside - useEffect(() => { - const handleClickOutside = (event: MouseEvent) => { - if (levelFilterRef.current && !levelFilterRef.current.contains(event.target as Node)) { - setShowLevelFilter(false); - } - }; - - document.addEventListener('mousedown', handleClickOutside); - - return () => { - document.removeEventListener('mousedown', handleClickOutside); - }; - }, []); - - const selectedLevelOption = logLevelOptions.find((opt) => opt.value === selectedLevel); - - // Export functions - const exportAsJSON = () => { - try { - const exportData = { - timestamp: new Date().toISOString(), - logs: filteredLogs, - filters: { - level: selectedLevel, - searchQuery, - }, - preferences: { - use24Hour, - showTimestamps, - autoExpand, - }, - }; - - const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' }); - const url = window.URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `bolt-event-logs-${new Date().toISOString()}.json`; - document.body.appendChild(a); - a.click(); - window.URL.revokeObjectURL(url); - document.body.removeChild(a); - toast.success('Event logs exported successfully as JSON'); - } catch (error) { - console.error('Failed to export JSON:', error); - toast.error('Failed to export event logs as JSON'); - } - }; - - const exportAsCSV = () => { - try { - // Convert logs to CSV format - const headers = ['Timestamp', 'Level', 'Category', 'Message', 'Details']; - const csvData = [ - headers, - ...filteredLogs.map((log) => [ - new Date(log.timestamp).toISOString(), - log.level, - log.category || '', - log.message, - log.details ? JSON.stringify(log.details) : '', - ]), - ]; - - const csvContent = csvData - .map((row) => row.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(',')) - .join('\n'); - const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = window.URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `bolt-event-logs-${new Date().toISOString()}.csv`; - document.body.appendChild(a); - a.click(); - window.URL.revokeObjectURL(url); - document.body.removeChild(a); - toast.success('Event logs exported successfully as CSV'); - } catch (error) { - console.error('Failed to export CSV:', error); - toast.error('Failed to export event logs as CSV'); - } - }; - - const exportAsPDF = () => { - try { - // Create new PDF document - const doc = new jsPDF(); - const lineHeight = 7; - let yPos = 20; - const margin = 20; - const pageWidth = doc.internal.pageSize.getWidth(); - const maxLineWidth = pageWidth - 2 * margin; - - // Helper function to add section header - const addSectionHeader = (title: string) => { - // Check if we need a new page - if (yPos > doc.internal.pageSize.getHeight() - 30) { - doc.addPage(); - yPos = margin; - } - - doc.setFillColor('#F3F4F6'); - doc.rect(margin - 2, yPos - 5, pageWidth - 2 * (margin - 2), lineHeight + 6, 'F'); - doc.setFont('helvetica', 'bold'); - doc.setTextColor('#111827'); - doc.setFontSize(12); - doc.text(title.toUpperCase(), margin, yPos); - yPos += lineHeight * 2; - }; - - // Add title and header - doc.setFillColor('#6366F1'); - doc.rect(0, 0, pageWidth, 50, 'F'); - doc.setTextColor('#FFFFFF'); - doc.setFontSize(24); - doc.setFont('helvetica', 'bold'); - doc.text('Event Logs Report', margin, 35); - - // Add subtitle with bolt.diy - doc.setFontSize(12); - doc.setFont('helvetica', 'normal'); - doc.text('bolt.diy - AI Development Platform', margin, 45); - yPos = 70; - - // Add report summary section - addSectionHeader('Report Summary'); - - doc.setFontSize(10); - doc.setFont('helvetica', 'normal'); - doc.setTextColor('#374151'); - - const summaryItems = [ - { label: 'Generated', value: new Date().toLocaleString() }, - { label: 'Total Logs', value: filteredLogs.length.toString() }, - { label: 'Filter Applied', value: selectedLevel === 'all' ? 'All Types' : selectedLevel }, - { label: 'Search Query', value: searchQuery || 'None' }, - { label: 'Time Format', value: use24Hour ? '24-hour' : '12-hour' }, - ]; - - summaryItems.forEach((item) => { - doc.setFont('helvetica', 'bold'); - doc.text(`${item.label}:`, margin, yPos); - doc.setFont('helvetica', 'normal'); - doc.text(item.value, margin + 60, yPos); - yPos += lineHeight; - }); - - yPos += lineHeight * 2; - - // Add statistics section - addSectionHeader('Log Statistics'); - - // Calculate statistics - const stats = { - error: filteredLogs.filter((log) => log.level === 'error').length, - warning: filteredLogs.filter((log) => log.level === 'warning').length, - info: filteredLogs.filter((log) => log.level === 'info').length, - debug: filteredLogs.filter((log) => log.level === 'debug').length, - provider: filteredLogs.filter((log) => log.category === 'provider').length, - api: filteredLogs.filter((log) => log.category === 'api').length, - }; - - // Create two columns for statistics - const leftStats = [ - { label: 'Error Logs', value: stats.error, color: '#DC2626' }, - { label: 'Warning Logs', value: stats.warning, color: '#F59E0B' }, - { label: 'Info Logs', value: stats.info, color: '#3B82F6' }, - ]; - - const rightStats = [ - { label: 'Debug Logs', value: stats.debug, color: '#6B7280' }, - { label: 'LLM Logs', value: stats.provider, color: '#10B981' }, - { label: 'API Logs', value: stats.api, color: '#3B82F6' }, - ]; - - const colWidth = (pageWidth - 2 * margin) / 2; - - // Draw statistics in two columns - leftStats.forEach((stat, index) => { - doc.setTextColor(stat.color); - doc.setFont('helvetica', 'bold'); - doc.text(stat.value.toString(), margin, yPos); - doc.setTextColor('#374151'); - doc.setFont('helvetica', 'normal'); - doc.text(stat.label, margin + 20, yPos); - - if (rightStats[index]) { - doc.setTextColor(rightStats[index].color); - doc.setFont('helvetica', 'bold'); - doc.text(rightStats[index].value.toString(), margin + colWidth, yPos); - doc.setTextColor('#374151'); - doc.setFont('helvetica', 'normal'); - doc.text(rightStats[index].label, margin + colWidth + 20, yPos); - } - - yPos += lineHeight; - }); - - yPos += lineHeight * 2; - - // Add logs section - addSectionHeader('Event Logs'); - - // Helper function to add a log entry with improved formatting - const addLogEntry = (log: LogEntry) => { - const entryHeight = 20 + (log.details ? 40 : 0); // Estimate entry height - - // Check if we need a new page - if (yPos + entryHeight > doc.internal.pageSize.getHeight() - 20) { - doc.addPage(); - yPos = margin; - } - - // Add timestamp and level - const timestamp = new Date(log.timestamp).toLocaleString(undefined, { - year: 'numeric', - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - hour12: !use24Hour, - }); - - // Draw log level badge background - const levelColors: Record = { - error: '#FEE2E2', - warning: '#FEF3C7', - info: '#DBEAFE', - debug: '#F3F4F6', - }; - - const textColors: Record = { - error: '#DC2626', - warning: '#F59E0B', - info: '#3B82F6', - debug: '#6B7280', - }; - - const levelWidth = doc.getTextWidth(log.level.toUpperCase()) + 10; - doc.setFillColor(levelColors[log.level] || '#F3F4F6'); - doc.roundedRect(margin, yPos - 4, levelWidth, lineHeight + 4, 1, 1, 'F'); - - // Add log level text - doc.setTextColor(textColors[log.level] || '#6B7280'); - doc.setFont('helvetica', 'bold'); - doc.setFontSize(8); - doc.text(log.level.toUpperCase(), margin + 5, yPos); - - // Add timestamp - doc.setTextColor('#6B7280'); - doc.setFont('helvetica', 'normal'); - doc.setFontSize(9); - doc.text(timestamp, margin + levelWidth + 10, yPos); - - // Add category if present - if (log.category) { - const categoryX = margin + levelWidth + doc.getTextWidth(timestamp) + 20; - doc.setFillColor('#F3F4F6'); - - const categoryWidth = doc.getTextWidth(log.category) + 10; - doc.roundedRect(categoryX, yPos - 4, categoryWidth, lineHeight + 4, 2, 2, 'F'); - doc.setTextColor('#6B7280'); - doc.text(log.category, categoryX + 5, yPos); - } - - yPos += lineHeight * 1.5; - - // Add message - doc.setTextColor('#111827'); - doc.setFontSize(10); - - const messageLines = doc.splitTextToSize(log.message, maxLineWidth - 10); - doc.text(messageLines, margin + 5, yPos); - yPos += messageLines.length * lineHeight; - - // Add details if present - if (log.details) { - doc.setTextColor('#6B7280'); - doc.setFontSize(8); - - const detailsStr = JSON.stringify(log.details, null, 2); - const detailsLines = doc.splitTextToSize(detailsStr, maxLineWidth - 15); - - // Add details background - doc.setFillColor('#F9FAFB'); - doc.roundedRect(margin + 5, yPos - 2, maxLineWidth - 10, detailsLines.length * lineHeight + 8, 1, 1, 'F'); - - doc.text(detailsLines, margin + 10, yPos + 4); - yPos += detailsLines.length * lineHeight + 10; - } - - // Add separator line - doc.setDrawColor('#E5E7EB'); - doc.setLineWidth(0.1); - doc.line(margin, yPos, pageWidth - margin, yPos); - yPos += lineHeight * 1.5; - }; - - // Add all logs - filteredLogs.forEach((log) => { - addLogEntry(log); - }); - - // Add footer to all pages - const totalPages = doc.internal.pages.length - 1; - - for (let i = 1; i <= totalPages; i++) { - doc.setPage(i); - doc.setFontSize(8); - doc.setTextColor('#9CA3AF'); - - // Add page numbers - doc.text(`Page ${i} of ${totalPages}`, pageWidth / 2, doc.internal.pageSize.getHeight() - 10, { - align: 'center', - }); - - // Add footer text - doc.text('Generated by bolt.diy', margin, doc.internal.pageSize.getHeight() - 10); - - const dateStr = new Date().toLocaleDateString(); - doc.text(dateStr, pageWidth - margin, doc.internal.pageSize.getHeight() - 10, { align: 'right' }); - } - - // Save the PDF - doc.save(`bolt-event-logs-${new Date().toISOString()}.pdf`); - toast.success('Event logs exported successfully as PDF'); - } catch (error) { - console.error('Failed to export PDF:', error); - toast.error('Failed to export event logs as PDF'); - } - }; - - const exportAsText = () => { - try { - const textContent = filteredLogs - .map((log) => { - const timestamp = new Date(log.timestamp).toLocaleString(); - let content = `[${timestamp}] ${log.level.toUpperCase()}: ${log.message}\n`; - - if (log.category) { - content += `Category: ${log.category}\n`; - } - - if (log.details) { - content += `Details:\n${JSON.stringify(log.details, null, 2)}\n`; - } - - return content + '-'.repeat(80) + '\n'; - }) - .join('\n'); - - const blob = new Blob([textContent], { type: 'text/plain' }); - const url = window.URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `bolt-event-logs-${new Date().toISOString()}.txt`; - document.body.appendChild(a); - a.click(); - window.URL.revokeObjectURL(url); - document.body.removeChild(a); - toast.success('Event logs exported successfully as text file'); - } catch (error) { - console.error('Failed to export text file:', error); - toast.error('Failed to export event logs as text file'); - } - }; - - const exportFormats: ExportFormat[] = [ - { - id: 'json', - label: 'Export as JSON', - icon: 'i-ph:file-js', - handler: exportAsJSON, - }, - { - id: 'csv', - label: 'Export as CSV', - icon: 'i-ph:file-csv', - handler: exportAsCSV, - }, - { - id: 'pdf', - label: 'Export as PDF', - icon: 'i-ph:file-pdf', - handler: exportAsPDF, - }, - { - id: 'txt', - label: 'Export as Text', - icon: 'i-ph:file-text', - handler: exportAsText, - }, - ]; - - const ExportButton = () => { - const [isOpen, setIsOpen] = useState(false); - - const handleOpenChange = useCallback((open: boolean) => { - setIsOpen(open); - }, []); - - const handleFormatClick = useCallback((handler: () => void) => { - handler(); - setIsOpen(false); - }, []); - - return ( - - - - -
- -
- Export Event Logs - - -
- {exportFormats.map((format) => ( - - ))} -
-
-
-
- ); - }; - - return ( -
-
- - - - - - - - {logLevelOptions.map((option) => ( - handleLevelFilterChange(option.value)} - > -
-
-
- {option.label} - - ))} - - - - -
-
- handlePreferenceChange('timestamps', value)} - className="data-[state=checked]:bg-purple-500" - /> - Show Timestamps -
- -
- handlePreferenceChange('24hour', value)} - className="data-[state=checked]:bg-purple-500" - /> - 24h Time -
- -
- handlePreferenceChange('autoExpand', value)} - className="data-[state=checked]:bg-purple-500" - /> - Auto Expand -
- -
- - - - -
-
- -
-
- setSearchQuery(e.target.value)} - className={classNames( - 'w-full px-4 py-2 pl-10 rounded-lg', - 'bg-[#FAFAFA] dark:bg-[#0A0A0A]', - 'border border-[#E5E5E5] dark:border-[#1A1A1A]', - 'text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400', - 'focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500', - 'transition-all duration-200', - )} - /> -
-
-
-
- - {filteredLogs.length === 0 ? ( - - -
-

No Logs Found

-

Try adjusting your search or filters

-
-
- ) : ( - filteredLogs.map((log) => ( - - )) - )} -
-
- ); -} diff --git a/app/settings/tabs/task-manager/TaskManagerTab.tsx b/app/settings/tabs/task-manager/TaskManagerTab.tsx deleted file mode 100644 index f54de64d..00000000 --- a/app/settings/tabs/task-manager/TaskManagerTab.tsx +++ /dev/null @@ -1,1602 +0,0 @@ -import * as React from 'react'; -import { useEffect, useState, useCallback } from 'react'; -import { classNames } from '~/shared/utils/classNames'; -import { Line } from 'react-chartjs-2'; -import { - Chart as ChartJS, - CategoryScale, - LinearScale, - PointElement, - LineElement, - Title, - Tooltip, - Legend, - type Chart, -} from 'chart.js'; -import { toast } from 'react-toastify'; // Import toast -import { useUpdateCheck } from '~/shared/hooks/useUpdateCheck'; -import { tabConfigurationStore, type TabConfig } from '~/settings/stores/tabConfigurationStore'; -import { useStore } from 'zustand'; - -// Register ChartJS components -ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend); - -interface BatteryManager extends EventTarget { - charging: boolean; - chargingTime: number; - dischargingTime: number; - level: number; -} - -interface SystemMemoryInfo { - total: number; - free: number; - used: number; - percentage: number; - swap?: { - total: number; - free: number; - used: number; - percentage: number; - }; - timestamp: string; - error?: string; -} - -interface ProcessInfo { - pid: number; - name: string; - cpu: number; - memory: number; - command?: string; - timestamp: string; - error?: string; -} - -interface DiskInfo { - filesystem: string; - size: number; - used: number; - available: number; - percentage: number; - mountpoint: string; - timestamp: string; - error?: string; -} - -interface SystemMetrics { - memory: { - used: number; - total: number; - percentage: number; - process?: { - heapUsed: number; - heapTotal: number; - external: number; - rss: number; - }; - }; - systemMemory?: SystemMemoryInfo; - processes?: ProcessInfo[]; - disks?: DiskInfo[]; - battery?: { - level: number; - charging: boolean; - timeRemaining?: number; - }; - network: { - downlink: number; - uplink?: number; - latency: { - current: number; - average: number; - min: number; - max: number; - history: number[]; - lastUpdate: number; - }; - type: string; - effectiveType?: string; - }; - performance: { - pageLoad: number; - domReady: number; - resources: { - total: number; - size: number; - loadTime: number; - }; - timing: { - ttfb: number; - fcp: number; - lcp: number; - }; - }; -} - -type SortField = 'name' | 'pid' | 'cpu' | 'memory'; -type SortDirection = 'asc' | 'desc'; - -interface MetricsHistory { - timestamps: string[]; - memory: number[]; - battery: number[]; - network: number[]; - cpu: number[]; - disk: number[]; -} - -interface PerformanceAlert { - type: 'warning' | 'error' | 'info'; - message: string; - timestamp: number; - metric: string; - threshold: number; - value: number; -} - -declare global { - interface Navigator { - getBattery(): Promise; - } - interface Performance { - memory?: { - jsHeapSizeLimit: number; - totalJSHeapSize: number; - usedJSHeapSize: number; - }; - } -} - -// Constants for performance thresholds -const PERFORMANCE_THRESHOLDS = { - memory: { - warning: 75, - critical: 90, - }, - network: { - latency: { - warning: 200, - critical: 500, - }, - }, - battery: { - warning: 20, - critical: 10, - }, -}; - -// Default metrics state -const DEFAULT_METRICS_STATE: SystemMetrics = { - memory: { - used: 0, - total: 0, - percentage: 0, - }, - network: { - downlink: 0, - latency: { - current: 0, - average: 0, - min: 0, - max: 0, - history: [], - lastUpdate: 0, - }, - type: 'unknown', - }, - performance: { - pageLoad: 0, - domReady: 0, - resources: { - total: 0, - size: 0, - loadTime: 0, - }, - timing: { - ttfb: 0, - fcp: 0, - lcp: 0, - }, - }, -}; - -// Default metrics history -const DEFAULT_METRICS_HISTORY: MetricsHistory = { - timestamps: Array(8).fill(new Date().toLocaleTimeString()), - memory: Array(8).fill(0), - battery: Array(8).fill(0), - network: Array(8).fill(0), - cpu: Array(8).fill(0), - disk: Array(8).fill(0), -}; - -// Maximum number of history points to keep -const MAX_HISTORY_POINTS = 8; - -// Used for environment detection in updateMetrics function -const isLocalDevelopment = - typeof window !== 'undefined' && - window.location && - (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'); - -// For development environments, we'll always provide mock data if real data isn't available -const isDevelopment = - typeof window !== 'undefined' && - (window.location.hostname === 'localhost' || - window.location.hostname === '127.0.0.1' || - window.location.hostname.includes('192.168.') || - window.location.hostname.includes('.local')); - -// Function to detect Cloudflare and similar serverless environments where TaskManager is not useful -const isServerlessHosting = (): boolean => { - if (typeof window === 'undefined') { - return false; - } - - // For testing: Allow forcing serverless mode via URL param for easy testing - if (typeof window !== 'undefined' && window.location.search.includes('simulate-serverless=true')) { - console.log('Simulating serverless environment for testing'); - return true; - } - - // Check for common serverless hosting domains - const hostname = window.location.hostname; - - return ( - hostname.includes('.cloudflare.') || - hostname.includes('.netlify.app') || - hostname.includes('.vercel.app') || - hostname.endsWith('.workers.dev') - ); -}; - -const TaskManagerTab: React.FC = () => { - const [metrics, setMetrics] = useState(() => DEFAULT_METRICS_STATE); - const [metricsHistory, setMetricsHistory] = useState(() => DEFAULT_METRICS_HISTORY); - const [alerts, setAlerts] = useState([]); - const [lastAlertState, setLastAlertState] = useState('normal'); - const [sortField, setSortField] = useState('memory'); - const [sortDirection, setSortDirection] = useState('desc'); - const [isNotSupported, setIsNotSupported] = useState(false); - - // Chart refs for cleanup - const memoryChartRef = React.useRef | null>(null); - const batteryChartRef = React.useRef | null>(null); - const networkChartRef = React.useRef | null>(null); - const cpuChartRef = React.useRef | null>(null); - const diskChartRef = React.useRef | null>(null); - - // Cleanup chart instances on unmount - React.useEffect(() => { - const cleanupCharts = () => { - if (memoryChartRef.current) { - memoryChartRef.current.destroy(); - } - - if (batteryChartRef.current) { - batteryChartRef.current.destroy(); - } - - if (networkChartRef.current) { - networkChartRef.current.destroy(); - } - - if (cpuChartRef.current) { - cpuChartRef.current.destroy(); - } - - if (diskChartRef.current) { - diskChartRef.current.destroy(); - } - }; - - return cleanupCharts; - }, []); - - // Get update status and tab configuration - const { hasUpdate } = useUpdateCheck(); - const tabConfig = useStore(tabConfigurationStore); - - const resetTabConfiguration = useCallback(() => { - tabConfig.reset(); - return tabConfig.get(); - }, [tabConfig]); - - // Effect to handle tab visibility - useEffect(() => { - const handleTabVisibility = () => { - const currentConfig = tabConfig.get(); - const controlledTabs = ['debug', 'update']; - - // Update visibility based on conditions - const updatedTabs = currentConfig.userTabs.map((tab: TabConfig) => { - if (controlledTabs.includes(tab.id)) { - return { - ...tab, - visible: tab.id === 'debug' ? metrics.memory.percentage > 80 : hasUpdate, - }; - } - - return tab; - }); - - tabConfig.set({ - ...currentConfig, - userTabs: updatedTabs, - }); - }; - - const checkInterval = setInterval(handleTabVisibility, 5000); - - return () => { - clearInterval(checkInterval); - }; - }, [metrics.memory.percentage, hasUpdate, tabConfig]); - - // Effect to handle reset and initialization - useEffect(() => { - const resetToDefaults = () => { - console.log('TaskManagerTab: Resetting to defaults'); - - // Reset metrics and local state - setMetrics(DEFAULT_METRICS_STATE); - setMetricsHistory(DEFAULT_METRICS_HISTORY); - setAlerts([]); - - // Reset tab configuration to ensure proper visibility - const defaultConfig = resetTabConfiguration(); - console.log('TaskManagerTab: Reset tab configuration:', defaultConfig); - }; - - // Listen for both storage changes and custom reset event - const handleReset = (event: Event | StorageEvent) => { - if (event instanceof StorageEvent) { - if (event.key === 'tabConfiguration' && event.newValue === null) { - resetToDefaults(); - } - } else if (event instanceof CustomEvent && event.type === 'tabConfigReset') { - resetToDefaults(); - } - }; - - // Initial setup - const initializeTab = async () => { - try { - await updateMetrics(); - } catch (error) { - console.error('Failed to initialize TaskManagerTab:', error); - resetToDefaults(); - } - }; - - window.addEventListener('storage', handleReset); - window.addEventListener('tabConfigReset', handleReset); - initializeTab(); - - return () => { - window.removeEventListener('storage', handleReset); - window.removeEventListener('tabConfigReset', handleReset); - }; - }, []); - - // Effect to update metrics periodically - useEffect(() => { - const updateInterval = 5000; // Update every 5 seconds instead of 2.5 seconds - let metricsInterval: NodeJS.Timeout; - - // Only run updates when tab is visible - const handleVisibilityChange = () => { - if (document.hidden) { - clearInterval(metricsInterval); - } else { - updateMetrics(); - metricsInterval = setInterval(updateMetrics, updateInterval); - } - }; - - // Initial setup - handleVisibilityChange(); - document.addEventListener('visibilitychange', handleVisibilityChange); - - return () => { - clearInterval(metricsInterval); - document.removeEventListener('visibilitychange', handleVisibilityChange); - }; - }, []); - - // Effect to disable taskmanager on serverless environments - useEffect(() => { - const checkEnvironment = async () => { - // If we're on Cloudflare/Netlify/etc., set not supported - if (isServerlessHosting()) { - setIsNotSupported(true); - return; - } - - // For testing: Allow forcing API failures via URL param - if (typeof window !== 'undefined' && window.location.search.includes('simulate-api-failure=true')) { - console.log('Simulating API failures for testing'); - setIsNotSupported(true); - - return; - } - - // Try to fetch system metrics once as detection - try { - const response = await fetch('/api/system/memory-info'); - const diskResponse = await fetch('/api/system/disk-info'); - const processResponse = await fetch('/api/system/process-info'); - - // If all these return errors or not found, system monitoring is not supported - if (!response.ok && !diskResponse.ok && !processResponse.ok) { - setIsNotSupported(true); - } - } catch (error) { - console.warn('Failed to fetch system metrics. TaskManager features may be limited:', error); - - // Don't automatically disable - we'll show partial data based on what's available - } - }; - - checkEnvironment(); - }, []); - - // Get detailed performance metrics - const getPerformanceMetrics = async (): Promise> => { - try { - // Get page load metrics - const navigation = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming; - const pageLoad = navigation.loadEventEnd - navigation.startTime; - const domReady = navigation.domContentLoadedEventEnd - navigation.startTime; - - // Get resource metrics - const resources = performance.getEntriesByType('resource') as PerformanceResourceTiming[]; - const resourceMetrics = { - total: resources.length, - size: resources.reduce((total, r) => total + (r.transferSize || 0), 0), - loadTime: Math.max(0, ...resources.map((r) => r.duration)), - }; - - // Get Web Vitals - const ttfb = navigation.responseStart - navigation.requestStart; - const paintEntries = performance.getEntriesByType('paint'); - const fcp = paintEntries.find((entry) => entry.name === 'first-contentful-paint')?.startTime || 0; - - // Get LCP using PerformanceObserver - const lcp = await new Promise((resolve) => { - new PerformanceObserver((list) => { - const entries = list.getEntries(); - const lastEntry = entries[entries.length - 1]; - resolve(lastEntry?.startTime || 0); - }).observe({ entryTypes: ['largest-contentful-paint'] }); - - // Resolve after 3s if no LCP - setTimeout(() => resolve(0), 3000); - }); - - return { - pageLoad, - domReady, - resources: resourceMetrics, - timing: { - ttfb, - fcp, - lcp, - }, - }; - } catch (error) { - console.error('Failed to get performance metrics:', error); - return {}; - } - }; - - // Function to measure endpoint latency - const measureLatency = async (): Promise => { - try { - const headers = new Headers(); - headers.append('Cache-Control', 'no-cache, no-store, must-revalidate'); - headers.append('Pragma', 'no-cache'); - headers.append('Expires', '0'); - - const attemptMeasurement = async (): Promise => { - const start = performance.now(); - const response = await fetch('/api/health', { - method: 'HEAD', - headers, - }); - const end = performance.now(); - - if (!response.ok) { - throw new Error(`Health check failed with status: ${response.status}`); - } - - return Math.round(end - start); - }; - - try { - const latency = await attemptMeasurement(); - console.log(`Measured latency: ${latency}ms`); - - return latency; - } catch (error) { - console.warn(`Latency measurement failed, retrying: ${error}`); - - try { - // Retry once - const latency = await attemptMeasurement(); - console.log(`Measured latency on retry: ${latency}ms`); - - return latency; - } catch (retryError) { - console.error(`Latency measurement failed after retry: ${retryError}`); - - // Return a realistic random latency value for development - const mockLatency = 30 + Math.floor(Math.random() * 120); // 30-150ms - console.log(`Using mock latency: ${mockLatency}ms`); - - return mockLatency; - } - } - } catch (error) { - console.error(`Error in latency measurement: ${error}`); - - // Return a realistic random latency value - const mockLatency = 30 + Math.floor(Math.random() * 120); // 30-150ms - console.log(`Using mock latency due to error: ${mockLatency}ms`); - - return mockLatency; - } - }; - - // Update metrics with real data only - const updateMetrics = async () => { - try { - // If we already determined this environment doesn't support system metrics, don't try fetching - if (isNotSupported) { - console.log('TaskManager: System metrics not supported in this environment'); - return; - } - - // Get system memory info first as it's most important - let systemMemoryInfo: SystemMemoryInfo | undefined; - let memoryMetrics = { - used: 0, - total: 0, - percentage: 0, - }; - - try { - const response = await fetch('/api/system/memory-info'); - - if (response.ok) { - systemMemoryInfo = await response.json(); - console.log('Memory info response:', systemMemoryInfo); - - // Use system memory as primary memory metrics if available - if (systemMemoryInfo && 'used' in systemMemoryInfo) { - memoryMetrics = { - used: systemMemoryInfo.used || 0, - total: systemMemoryInfo.total || 1, - percentage: systemMemoryInfo.percentage || 0, - }; - } - } - } catch (error) { - console.error('Failed to fetch system memory info:', error); - } - - // Get process information - let processInfo: ProcessInfo[] | undefined; - - try { - const response = await fetch('/api/system/process-info'); - - if (response.ok) { - processInfo = await response.json(); - console.log('Process info response:', processInfo); - } - } catch (error) { - console.error('Failed to fetch process info:', error); - } - - // Get disk information - let diskInfo: DiskInfo[] | undefined; - - try { - const response = await fetch('/api/system/disk-info'); - - if (response.ok) { - diskInfo = await response.json(); - console.log('Disk info response:', diskInfo); - } - } catch (error) { - console.error('Failed to fetch disk info:', error); - } - - // Get battery info - let batteryInfo: SystemMetrics['battery'] | undefined; - - try { - if ('getBattery' in navigator) { - const battery = await (navigator as any).getBattery(); - batteryInfo = { - level: battery.level * 100, - charging: battery.charging, - timeRemaining: battery.charging ? battery.chargingTime : battery.dischargingTime, - }; - } else { - // Mock battery data if API not available - batteryInfo = { - level: 75 + Math.floor(Math.random() * 20), - charging: Math.random() > 0.3, - timeRemaining: 7200 + Math.floor(Math.random() * 3600), - }; - console.log('Battery API not available, using mock data'); - } - } catch (error) { - console.log('Battery API error, using mock data:', error); - batteryInfo = { - level: 75 + Math.floor(Math.random() * 20), - charging: Math.random() > 0.3, - timeRemaining: 7200 + Math.floor(Math.random() * 3600), - }; - } - - // Enhanced network metrics - const connection = - (navigator as any).connection || (navigator as any).mozConnection || (navigator as any).webkitConnection; - - // Measure real latency - const measuredLatency = await measureLatency(); - const connectionRtt = connection?.rtt || 0; - - // Use measured latency if available, fall back to connection.rtt - const currentLatency = measuredLatency || connectionRtt || Math.floor(Math.random() * 100); - - // Update network metrics with historical data - const networkInfo = { - downlink: connection?.downlink || 1.5 + Math.random(), - uplink: connection?.uplink || 0.5 + Math.random(), - latency: { - current: currentLatency, - average: - metrics.network.latency.history.length > 0 - ? [...metrics.network.latency.history, currentLatency].reduce((a, b) => a + b, 0) / - (metrics.network.latency.history.length + 1) - : currentLatency, - min: - metrics.network.latency.history.length > 0 - ? Math.min(...metrics.network.latency.history, currentLatency) - : currentLatency, - max: - metrics.network.latency.history.length > 0 - ? Math.max(...metrics.network.latency.history, currentLatency) - : currentLatency, - history: [...metrics.network.latency.history, currentLatency].slice(-30), // Keep last 30 measurements - lastUpdate: Date.now(), - }, - type: connection?.type || 'unknown', - effectiveType: connection?.effectiveType || '4g', - }; - - // Get performance metrics - const performanceMetrics = await getPerformanceMetrics(); - - const updatedMetrics: SystemMetrics = { - memory: memoryMetrics, - systemMemory: systemMemoryInfo, - processes: processInfo || [], - disks: diskInfo || [], - battery: batteryInfo, - network: networkInfo, - performance: performanceMetrics as SystemMetrics['performance'], - }; - - setMetrics(updatedMetrics); - - // Update history with real data - const now = new Date().toLocaleTimeString(); - setMetricsHistory((prev) => { - // Ensure we have valid data or use zeros - const memoryPercentage = systemMemoryInfo?.percentage || 0; - const batteryLevel = batteryInfo?.level || 0; - const networkDownlink = networkInfo.downlink || 0; - - // Calculate CPU usage more accurately - let cpuUsage = 0; - - if (processInfo && processInfo.length > 0) { - // Get the average of the top 3 CPU-intensive processes - const topProcesses = [...processInfo].sort((a, b) => b.cpu - a.cpu).slice(0, 3); - const topCpuUsage = topProcesses.reduce((total, proc) => total + proc.cpu, 0); - - // Get the sum of all processes - const totalCpuUsage = processInfo.reduce((total, proc) => total + proc.cpu, 0); - - // Use the higher of the two values, but cap at 100% - cpuUsage = Math.min(Math.max(topCpuUsage, (totalCpuUsage / processInfo.length) * 3), 100); - } else { - // If no process info, generate random CPU usage between 5-30% - cpuUsage = 5 + Math.floor(Math.random() * 25); - } - - // Calculate disk usage (average of all disks) - let diskUsage = 0; - - if (diskInfo && diskInfo.length > 0) { - diskUsage = diskInfo.reduce((total, disk) => total + disk.percentage, 0) / diskInfo.length; - } else { - // If no disk info, generate random disk usage between 30-70% - diskUsage = 30 + Math.floor(Math.random() * 40); - } - - // Create new arrays with the latest data - const timestamps = [...prev.timestamps, now].slice(-MAX_HISTORY_POINTS); - const memory = [...prev.memory, memoryPercentage].slice(-MAX_HISTORY_POINTS); - const battery = [...prev.battery, batteryLevel].slice(-MAX_HISTORY_POINTS); - const network = [...prev.network, networkDownlink].slice(-MAX_HISTORY_POINTS); - const cpu = [...prev.cpu, cpuUsage].slice(-MAX_HISTORY_POINTS); - const disk = [...prev.disk, diskUsage].slice(-MAX_HISTORY_POINTS); - - console.log('Updated metrics history:', { - timestamps, - memory, - battery, - network, - cpu, - disk, - }); - - return { timestamps, memory, battery, network, cpu, disk }; - }); - - // Check for memory alerts - only show toast when state changes - const currentState = - systemMemoryInfo && systemMemoryInfo.percentage > PERFORMANCE_THRESHOLDS.memory.critical - ? 'critical-memory' - : networkInfo.latency.current > PERFORMANCE_THRESHOLDS.network.latency.critical - ? 'critical-network' - : batteryInfo && !batteryInfo.charging && batteryInfo.level < PERFORMANCE_THRESHOLDS.battery.critical - ? 'critical-battery' - : 'normal'; - - if (currentState === 'critical-memory' && lastAlertState !== 'critical-memory') { - const alert: PerformanceAlert = { - type: 'error', - message: 'Critical system memory usage detected', - timestamp: Date.now(), - metric: 'memory', - threshold: PERFORMANCE_THRESHOLDS.memory.critical, - value: systemMemoryInfo?.percentage || 0, - }; - setAlerts((prev) => { - const newAlerts = [...prev, alert]; - return newAlerts.slice(-10); - }); - toast.warning(alert.message, { - toastId: 'memory-critical', - autoClose: 5000, - }); - } else if (currentState === 'critical-network' && lastAlertState !== 'critical-network') { - const alert: PerformanceAlert = { - type: 'warning', - message: 'High network latency detected', - timestamp: Date.now(), - metric: 'network', - threshold: PERFORMANCE_THRESHOLDS.network.latency.critical, - value: networkInfo.latency.current, - }; - setAlerts((prev) => { - const newAlerts = [...prev, alert]; - return newAlerts.slice(-10); - }); - toast.warning(alert.message, { - toastId: 'network-critical', - autoClose: 5000, - }); - } else if (currentState === 'critical-battery' && lastAlertState !== 'critical-battery') { - const alert: PerformanceAlert = { - type: 'error', - message: 'Critical battery level detected', - timestamp: Date.now(), - metric: 'battery', - threshold: PERFORMANCE_THRESHOLDS.battery.critical, - value: batteryInfo?.level || 0, - }; - setAlerts((prev) => { - const newAlerts = [...prev, alert]; - return newAlerts.slice(-10); - }); - toast.error(alert.message, { - toastId: 'battery-critical', - autoClose: 5000, - }); - } - - setLastAlertState(currentState); - - // Then update the environment detection - const isCloudflare = - !isDevelopment && // Not in development mode - ((systemMemoryInfo?.error && systemMemoryInfo.error.includes('not available')) || - (processInfo?.[0]?.error && processInfo[0].error.includes('not available')) || - (diskInfo?.[0]?.error && diskInfo[0].error.includes('not available'))); - - // If we detect that we're in a serverless environment, set the flag - if (isCloudflare || isServerlessHosting()) { - setIsNotSupported(true); - } - - if (isCloudflare) { - console.log('Running in Cloudflare environment. System metrics not available.'); - } else if (isLocalDevelopment) { - console.log('Running in local development environment. Using real or mock system metrics as available.'); - } else if (isDevelopment) { - console.log('Running in development environment. Using real or mock system metrics as available.'); - } else { - console.log('Running in production environment. Using real system metrics.'); - } - } catch (error) { - console.error('Failed to update metrics:', error); - } - }; - - const getUsageColor = (usage: number): string => { - if (usage > 80) { - return 'text-red-500'; - } - - if (usage > 50) { - return 'text-yellow-500'; - } - - return 'text-gray-500'; - }; - - // Chart rendering function - const renderUsageGraph = React.useMemo( - () => - (data: number[], label: string, color: string, chartRef: React.RefObject>) => { - // Ensure we have valid data - const validData = data.map((value) => (isNaN(value) ? 0 : value)); - - // Ensure we have at least 2 data points - if (validData.length < 2) { - // Add a second point if we only have one - if (validData.length === 1) { - validData.push(validData[0]); - } else { - // Add two points if we have none - validData.push(0, 0); - } - } - - const chartData = { - labels: - metricsHistory.timestamps.length > 0 - ? metricsHistory.timestamps - : Array(validData.length) - .fill('') - .map((_, _i) => new Date().toLocaleTimeString()), - datasets: [ - { - label, - data: validData.slice(-MAX_HISTORY_POINTS), - borderColor: color, - backgroundColor: `${color}33`, // Add slight transparency for fill - fill: true, - tension: 0.4, - pointRadius: 2, // Small points for better UX - borderWidth: 2, - }, - ], - }; - - const options = { - responsive: true, - maintainAspectRatio: false, - scales: { - y: { - beginAtZero: true, - max: label === 'Network' ? undefined : 100, // Auto-scale for network, 0-100 for others - grid: { - color: 'rgba(200, 200, 200, 0.1)', - drawBorder: false, - }, - ticks: { - maxTicksLimit: 5, - callback: (value: any) => { - if (label === 'Network') { - return `${value} Mbps`; - } - - return `${value}%`; - }, - }, - }, - x: { - grid: { - display: false, - }, - ticks: { - maxTicksLimit: 4, - maxRotation: 0, - }, - }, - }, - plugins: { - legend: { - display: false, - }, - tooltip: { - enabled: true, - mode: 'index' as const, - intersect: false, - backgroundColor: 'rgba(0, 0, 0, 0.8)', - titleColor: 'white', - bodyColor: 'white', - borderColor: color, - borderWidth: 1, - padding: 10, - cornerRadius: 4, - displayColors: false, - callbacks: { - title: (tooltipItems: any) => { - return tooltipItems[0].label; // Show timestamp - }, - label: (context: any) => { - const value = context.raw; - - if (label === 'Memory') { - return `Memory: ${value.toFixed(1)}%`; - } else if (label === 'CPU') { - return `CPU: ${value.toFixed(1)}%`; - } else if (label === 'Battery') { - return `Battery: ${value.toFixed(1)}%`; - } else if (label === 'Network') { - return `Network: ${value.toFixed(1)} Mbps`; - } else if (label === 'Disk') { - return `Disk: ${value.toFixed(1)}%`; - } - - return `${label}: ${value.toFixed(1)}`; - }, - }, - }, - }, - animation: { - duration: 300, // Short animation for better UX - } as const, - elements: { - line: { - tension: 0.3, - }, - }, - }; - - return ( -
- -
- ); - }, - [metricsHistory.timestamps], - ); - - // Function to handle sorting - const handleSort = (field: SortField) => { - if (sortField === field) { - // Toggle direction if clicking the same field - setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc'); - } else { - // Set new field and default to descending - setSortField(field); - setSortDirection('desc'); - } - }; - - // Function to sort processes - const getSortedProcesses = () => { - if (!metrics.processes) { - return []; - } - - return [...metrics.processes].sort((a, b) => { - let comparison = 0; - - switch (sortField) { - case 'name': - comparison = a.name.localeCompare(b.name); - break; - case 'pid': - comparison = a.pid - b.pid; - break; - case 'cpu': - comparison = a.cpu - b.cpu; - break; - case 'memory': - comparison = a.memory - b.memory; - break; - } - - return sortDirection === 'asc' ? comparison : -comparison; - }); - }; - - // If we're in an environment where the task manager won't work, show a message - if (isNotSupported) { - return ( -
-
-

System Monitoring Not Available

-

- System monitoring is not available in serverless environments like Cloudflare Pages, Netlify, or Vercel. These - platforms don't provide access to the underlying system resources. -

-
-

- Why is this disabled? -
- Serverless platforms execute your code in isolated environments without access to the server's operating - system metrics like CPU, memory, and disk usage. -

-

- System monitoring features will be available when running in: -

    -
  • Local development environment
  • -
  • Virtual Machines (VMs)
  • -
  • Dedicated servers
  • -
  • Docker containers (with proper permissions)
  • -
-

-
- - {/* Testing controls - only shown in development */} - {isDevelopment && ( -
-

Testing Controls

-

- These controls are only visible in development mode -

- -
- )} -
- ); - } - - return ( -
- {/* Summary Header */} -
-
-
CPU
-
- {(metricsHistory.cpu[metricsHistory.cpu.length - 1] || 0).toFixed(1)}% -
-
-
-
Memory
-
- {Math.round(metrics.systemMemory?.percentage || 0)}% -
-
-
-
Disk
-
0 - ? metrics.disks.reduce((total, disk) => total + disk.percentage, 0) / metrics.disks.length - : 0, - ), - )} - > - {metrics.disks && metrics.disks.length > 0 - ? Math.round(metrics.disks.reduce((total, disk) => total + disk.percentage, 0) / metrics.disks.length) - : 0} - % -
-
-
-
Network
-
{metrics.network.downlink.toFixed(1)} Mbps
-
-
- - {/* Memory Usage */} -
-

Memory Usage

-
- {/* System Physical Memory */} -
-
-
- System Memory -
-
-
- Shows your system's physical memory (RAM) usage. -
-
-
- - {Math.round(metrics.systemMemory?.percentage || 0)}% - -
- {renderUsageGraph(metricsHistory.memory, 'Memory', '#2563eb', memoryChartRef)} -
- Used: {formatBytes(metrics.systemMemory?.used || 0)} / {formatBytes(metrics.systemMemory?.total || 0)} -
-
- Free: {formatBytes(metrics.systemMemory?.free || 0)} -
-
- - {/* Swap Memory */} - {metrics.systemMemory?.swap && ( -
-
-
- Swap Memory -
-
-
- Virtual memory used when physical RAM is full. -
-
-
- - {Math.round(metrics.systemMemory.swap.percentage)}% - -
-
-
-
-
- Used: {formatBytes(metrics.systemMemory.swap.used)} / {formatBytes(metrics.systemMemory.swap.total)} -
-
- Free: {formatBytes(metrics.systemMemory.swap.free)} -
-
- )} -
-
- - {/* Disk Usage */} -
-

Disk Usage

- {metrics.disks && metrics.disks.length > 0 ? ( -
-
- System Disk - - {(metricsHistory.disk[metricsHistory.disk.length - 1] || 0).toFixed(1)}% - -
- {renderUsageGraph(metricsHistory.disk, 'Disk', '#8b5cf6', diskChartRef)} - - {/* Show only the main system disk (usually the first one) */} - {metrics.disks[0] && ( - <> -
-
-
-
-
Used: {formatBytes(metrics.disks[0].used)}
-
Free: {formatBytes(metrics.disks[0].available)}
-
Total: {formatBytes(metrics.disks[0].size)}
-
- - )} -
- ) : ( -
-
-

Disk information is not available

-

- This feature may not be supported in your environment -

-
- )} -
- - {/* Process Information */} -
-
-

Process Information

- -
-
- {metrics.processes && metrics.processes.length > 0 ? ( - <> - {/* CPU Usage Summary */} - {metrics.processes[0].name !== 'Unknown' && ( -
-
- CPU Usage - - {(metricsHistory.cpu[metricsHistory.cpu.length - 1] || 0).toFixed(1)}% Total - -
-
-
- {metrics.processes.map((process, index) => { - return ( -
- ); - })} -
-
-
-
- System:{' '} - {metrics.processes.reduce((total, proc) => total + (proc.cpu < 10 ? proc.cpu : 0), 0).toFixed(1)}% -
-
- User:{' '} - {metrics.processes.reduce((total, proc) => total + (proc.cpu >= 10 ? proc.cpu : 0), 0).toFixed(1)} - % -
-
- Idle: {(100 - (metricsHistory.cpu[metricsHistory.cpu.length - 1] || 0)).toFixed(1)}% -
-
-
- )} - -
- - - - - - - - - - - {getSortedProcesses().map((process, index) => ( - - - - - - - ))} - -
handleSort('name')} - > - Process {sortField === 'name' && (sortDirection === 'asc' ? '↑' : '↓')} - handleSort('pid')} - > - PID {sortField === 'pid' && (sortDirection === 'asc' ? '↑' : '↓')} - handleSort('cpu')} - > - CPU % {sortField === 'cpu' && (sortDirection === 'asc' ? '↑' : '↓')} - handleSort('memory')} - > - Memory {sortField === 'memory' && (sortDirection === 'asc' ? '↑' : '↓')} -
- {process.name} - {process.pid} -
-
-
-
- {process.cpu.toFixed(1)}% -
-
-
-
-
-
- {/* Calculate approximate MB based on percentage and total system memory */} - {metrics.systemMemory - ? `${formatBytes(metrics.systemMemory.total * (process.memory / 100))}` - : `${process.memory.toFixed(1)}%`} -
-
-
-
- {metrics.processes[0].error ? ( - -
- Error retrieving process information: {metrics.processes[0].error} - - ) : metrics.processes[0].name === 'Browser' ? ( - -
- Showing browser process information. System process information is not available in this - environment. - - ) : ( - Showing top {metrics.processes.length} processes by memory usage - )} -
- - ) : ( -
-
-

Process information is not available

-

- This feature may not be supported in your environment -

- -
- )} -
-
- - {/* CPU Usage Graph */} -
-

CPU Usage History

-
-
- System CPU - - {(metricsHistory.cpu[metricsHistory.cpu.length - 1] || 0).toFixed(1)}% - -
- {renderUsageGraph(metricsHistory.cpu, 'CPU', '#ef4444', cpuChartRef)} -
- Average: {(metricsHistory.cpu.reduce((a, b) => a + b, 0) / metricsHistory.cpu.length || 0).toFixed(1)}% -
-
- Peak: {Math.max(...metricsHistory.cpu).toFixed(1)}% -
-
-
- - {/* Network */} -
-

Network

-
-
-
- Connection - - {metrics.network.downlink.toFixed(1)} Mbps - -
- {renderUsageGraph(metricsHistory.network, 'Network', '#f59e0b', networkChartRef)} -
- Type: {metrics.network.type} - {metrics.network.effectiveType && ` (${metrics.network.effectiveType})`} -
-
- Latency: {Math.round(metrics.network.latency.current)}ms - - (avg: {Math.round(metrics.network.latency.average)}ms) - -
-
- Min: {Math.round(metrics.network.latency.min)}ms / Max: {Math.round(metrics.network.latency.max)}ms -
- {metrics.network.uplink && ( -
- Uplink: {metrics.network.uplink.toFixed(1)} Mbps -
- )} -
-
-
- - {/* Battery */} - {metrics.battery && ( -
-

Battery

-
-
-
- Status -
- {metrics.battery.charging &&
} - 20 ? 'text-bolt-elements-textPrimary' : 'text-red-500', - )} - > - {Math.round(metrics.battery.level)}% - -
-
- {renderUsageGraph(metricsHistory.battery, 'Battery', '#22c55e', batteryChartRef)} - {metrics.battery.timeRemaining && metrics.battery.timeRemaining !== Infinity && ( -
- {metrics.battery.charging ? 'Time to full: ' : 'Time remaining: '} - {formatTime(metrics.battery.timeRemaining)} -
- )} -
-
-
- )} - - {/* Performance */} -
-

Performance

-
-
-
- Page Load: {(metrics.performance.pageLoad / 1000).toFixed(2)}s -
-
- DOM Ready: {(metrics.performance.domReady / 1000).toFixed(2)}s -
-
- TTFB: {(metrics.performance.timing.ttfb / 1000).toFixed(2)}s -
-
- Resources: {metrics.performance.resources.total} ({formatBytes(metrics.performance.resources.size)}) -
-
-
-
- - {/* Alerts */} - {alerts.length > 0 && ( -
-
- Recent Alerts - -
-
- {alerts.slice(-5).map((alert, index) => ( -
-
- {alert.message} - - {new Date(alert.timestamp).toLocaleTimeString()} - -
- ))} -
-
- )} -
- ); -}; - -export default React.memo(TaskManagerTab); - -// Helper function to format bytes -const formatBytes = (bytes: number): string => { - if (bytes === 0) { - return '0 B'; - } - - const k = 1024; - const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; - const i = Math.floor(Math.log(bytes) / Math.log(k)); - const value = bytes / Math.pow(k, i); - - // Format with 2 decimal places for MB and larger units - const formattedValue = i >= 2 ? value.toFixed(2) : value.toFixed(0); - - return `${formattedValue} ${sizes[i]}`; -}; - -// Helper function to format time -const formatTime = (seconds: number): string => { - if (!isFinite(seconds) || seconds === 0) { - return 'Unknown'; - } - - const hours = Math.floor(seconds / 3600); - const minutes = Math.floor((seconds % 3600) / 60); - - if (hours > 0) { - return `${hours}h ${minutes}m`; - } - - return `${minutes}m`; -}; diff --git a/app/settings/tabs/update/UpdateTab.tsx b/app/settings/tabs/update/UpdateTab.tsx deleted file mode 100644 index e39fa605..00000000 --- a/app/settings/tabs/update/UpdateTab.tsx +++ /dev/null @@ -1,628 +0,0 @@ -import React, { useState, useEffect } from 'react'; -import { motion } from 'framer-motion'; -import { useSettings } from '~/shared/hooks/useSettings'; -import { logStore } from '~/shared/stores/logs'; -import { toast } from 'react-toastify'; -import { Dialog, DialogRoot, DialogTitle, DialogDescription, DialogButton } from '~/shared/components/ui/Dialog'; -import { classNames } from '~/shared/utils/classNames'; -import { Markdown } from '~/chat/components/markdown/Markdown'; - -interface UpdateProgress { - stage: 'fetch' | 'pull' | 'install' | 'build' | 'complete'; - message: string; - progress?: number; - error?: string; - details?: { - changedFiles?: string[]; - additions?: number; - deletions?: number; - commitMessages?: string[]; - totalSize?: string; - currentCommit?: string; - remoteCommit?: string; - updateReady?: boolean; - changelog?: string; - compareUrl?: string; - }; -} - -interface UpdateSettings { - autoUpdate: boolean; - notifyInApp: boolean; - checkInterval: number; -} - -const ProgressBar = ({ progress }: { progress: number }) => ( -
- -
-); - -const UpdateProgressDisplay = ({ progress }: { progress: UpdateProgress }) => ( -
-
- {progress.message} - {progress.progress}% -
- - {progress.details && ( -
- {progress.details.changedFiles && progress.details.changedFiles.length > 0 && ( -
-
Changed Files:
-
- {/* Group files by type */} - {['Modified', 'Added', 'Deleted'].map((type) => { - const filesOfType = progress.details?.changedFiles?.filter((file) => file.startsWith(type)) || []; - - if (filesOfType.length === 0) { - return null; - } - - return ( -
-
- {type} ({filesOfType.length}) -
-
- {filesOfType.map((file, index) => { - const fileName = file.split(': ')[1]; - return ( -
-
- {fileName} -
- ); - })} -
-
- ); - })} -
-
- )} - {progress.details.totalSize &&
Total size: {progress.details.totalSize}
} - {progress.details.additions !== undefined && progress.details.deletions !== undefined && ( -
- Changes: +{progress.details.additions}{' '} - -{progress.details.deletions} -
- )} - {progress.details.currentCommit && progress.details.remoteCommit && ( -
- Updating from {progress.details.currentCommit} to {progress.details.remoteCommit} -
- )} -
- )} -
-); - -const UpdateTab = () => { - const { isLatestBranch } = useSettings(); - const [isChecking, setIsChecking] = useState(false); - const [error, setError] = useState(null); - const [updateSettings, setUpdateSettings] = useState(() => { - const stored = localStorage.getItem('update_settings'); - return stored - ? JSON.parse(stored) - : { - autoUpdate: false, - notifyInApp: true, - checkInterval: 24, - }; - }); - const [showUpdateDialog, setShowUpdateDialog] = useState(false); - const [updateProgress, setUpdateProgress] = useState(null); - - useEffect(() => { - localStorage.setItem('update_settings', JSON.stringify(updateSettings)); - }, [updateSettings]); - - const checkForUpdates = async () => { - console.log('Starting update check...'); - setIsChecking(true); - setError(null); - setUpdateProgress(null); - - try { - const branchToCheck = isLatestBranch ? 'main' : 'stable'; - - // Start the update check with streaming progress - const response = await fetch('/api/update', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - branch: branchToCheck, - autoUpdate: updateSettings.autoUpdate, - }), - }); - - if (!response.ok) { - throw new Error(`Update check failed: ${response.statusText}`); - } - - const reader = response.body?.getReader(); - - if (!reader) { - throw new Error('No response stream available'); - } - - // Read the stream - while (true) { - const { done, value } = await reader.read(); - - if (done) { - break; - } - - // Convert the chunk to text and parse the JSON - const chunk = new TextDecoder().decode(value); - const lines = chunk.split('\n').filter(Boolean); - - for (const line of lines) { - try { - const progress = JSON.parse(line) as UpdateProgress; - setUpdateProgress(progress); - - if (progress.error) { - setError(progress.error); - } - - // If we're done, update the UI accordingly - if (progress.stage === 'complete') { - setIsChecking(false); - - if (!progress.error) { - // Update check completed - toast.success('Update check completed'); - - // Show update dialog only if there are changes and auto-update is disabled - if (progress.details?.changedFiles?.length && progress.details.updateReady) { - setShowUpdateDialog(true); - } - } - } - } catch (e) { - console.error('Error parsing progress update:', e); - } - } - } - } catch (error) { - setError(error instanceof Error ? error.message : 'Unknown error occurred'); - logStore.logWarning('Update Check Failed', { - type: 'update', - message: error instanceof Error ? error.message : 'Unknown error occurred', - }); - } finally { - setIsChecking(false); - } - }; - - const handleUpdate = async () => { - setShowUpdateDialog(false); - - try { - const branchToCheck = isLatestBranch ? 'main' : 'stable'; - - // Start the update with autoUpdate set to true to force the update - const response = await fetch('/api/update', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - branch: branchToCheck, - autoUpdate: true, - }), - }); - - if (!response.ok) { - throw new Error(`Update failed: ${response.statusText}`); - } - - // Handle the update progress stream - const reader = response.body?.getReader(); - - if (!reader) { - throw new Error('No response stream available'); - } - - while (true) { - const { done, value } = await reader.read(); - - if (done) { - break; - } - - const chunk = new TextDecoder().decode(value); - const lines = chunk.split('\n').filter(Boolean); - - for (const line of lines) { - try { - const progress = JSON.parse(line) as UpdateProgress; - setUpdateProgress(progress); - - if (progress.error) { - setError(progress.error); - toast.error('Update failed'); - } - - if (progress.stage === 'complete' && !progress.error) { - toast.success('Update completed successfully'); - } - } catch (e) { - console.error('Error parsing update progress:', e); - } - } - } - } catch (error) { - setError(error instanceof Error ? error.message : 'Unknown error occurred'); - toast.error('Update failed'); - } - }; - - return ( -
- -
-
-

Updates

-

Check for and manage application updates

-
- - - {/* Update Settings Card */} - -
-
-

Update Settings

-
- -
-
-
- Automatic Updates -

- Automatically check and apply updates when available -

-
- -
- -
-
- In-App Notifications -

Show notifications when updates are available

-
- -
- -
-
- Check Interval -

How often to check for updates

-
- -
-
- - - {/* Update Status Card */} - -
-
-
-

Update Status

-
-
- {updateProgress?.details?.updateReady && !updateSettings.autoUpdate && ( - - )} - -
-
- - {/* Show progress information */} - {updateProgress && } - - {error &&
{error}
} - - {/* Show update source information */} - {updateProgress?.details?.currentCommit && updateProgress?.details?.remoteCommit && ( -
-
-
-

- Updates are fetched from: stackblitz-labs/bolt.diy ( - {isLatestBranch ? 'main' : 'stable'} branch) -

-

- Current version: {updateProgress.details.currentCommit} - - Latest version: {updateProgress.details.remoteCommit} -

-
- {updateProgress?.details?.compareUrl && ( - - - {updateProgress?.details?.additions !== undefined && updateProgress?.details?.deletions !== undefined && ( -
-
- Changes: +{updateProgress.details.additions}{' '} - -{updateProgress.details.deletions} -
- )} -
- )} - - {/* Add this before the changed files section */} - {updateProgress?.details?.changelog && ( -
-
-
-

Changelog

-
-
-
- {updateProgress.details.changelog} -
-
-
- )} - - {/* Add this in the update status card, after the commit info */} - {updateProgress?.details?.compareUrl && ( -
- - - )} - - {updateProgress?.details?.commitMessages && updateProgress.details.commitMessages.length > 0 && ( -
-

Changes in this Update:

-
-
- {updateProgress.details.commitMessages.map((section, index) => ( - {section} - ))} -
-
-
- )} - - - {/* Update dialog */} - - - Update Available - -
-

- A new version is available from stackblitz-labs/bolt.diy ( - {isLatestBranch ? 'main' : 'stable'} branch) -

- - {updateProgress?.details?.compareUrl && ( -
- - - )} - - {updateProgress?.details?.commitMessages && updateProgress.details.commitMessages.length > 0 && ( -
-

Commit Messages:

-
- {updateProgress.details.commitMessages.map((msg, index) => ( -
-
- {msg} -
- ))} -
-
- )} - - {updateProgress?.details?.totalSize && ( -
-
-
- Total size: {updateProgress.details.totalSize} -
- {updateProgress?.details?.additions !== undefined && - updateProgress?.details?.deletions !== undefined && ( -
-
- Changes: +{updateProgress.details.additions}{' '} - -{updateProgress.details.deletions} -
- )} -
- )} -
- -
- setShowUpdateDialog(false)}> - Cancel - - - Update Now - -
-
-
-
- ); -}; - -export default UpdateTab; diff --git a/app/settings/utils/tab-helpers.ts b/app/settings/utils/tab-helpers.ts deleted file mode 100644 index 5c5961c5..00000000 --- a/app/settings/utils/tab-helpers.ts +++ /dev/null @@ -1,89 +0,0 @@ -import type { TabType, TabVisibilityConfig } from '~/settings/core/types'; -import { DEFAULT_TAB_CONFIG } from '~/settings/core/constants'; - -export const getVisibleTabs = ( - tabConfiguration: { userTabs: TabVisibilityConfig[]; developerTabs?: TabVisibilityConfig[] }, - isDeveloperMode: boolean, - notificationsEnabled: boolean, -): TabVisibilityConfig[] => { - if (!tabConfiguration?.userTabs || !Array.isArray(tabConfiguration.userTabs)) { - console.warn('Invalid tab configuration, using defaults'); - return DEFAULT_TAB_CONFIG as TabVisibilityConfig[]; - } - - // In developer mode, show ALL tabs without restrictions - if (isDeveloperMode) { - // Combine all unique tabs from both user and developer configurations - const allTabs = new Set([ - ...DEFAULT_TAB_CONFIG.map((tab) => tab.id), - ...tabConfiguration.userTabs.map((tab) => tab.id), - ...(tabConfiguration.developerTabs || []).map((tab) => tab.id), - 'task-manager' as TabType, // Always include task-manager in developer mode - ]); - - // Create a complete tab list with all tabs visible - const devTabs = Array.from(allTabs).map((tabId) => { - // Try to find existing configuration for this tab - const existingTab = - tabConfiguration.developerTabs?.find((t) => t.id === tabId) || - tabConfiguration.userTabs?.find((t) => t.id === tabId) || - DEFAULT_TAB_CONFIG.find((t) => t.id === tabId); - - return { - id: tabId as TabType, - visible: true, - window: 'developer' as const, - order: existingTab?.order || DEFAULT_TAB_CONFIG.findIndex((t) => t.id === tabId), - } as TabVisibilityConfig; - }); - - return devTabs.sort((a, b) => a.order - b.order); - } - - // In user mode, only show visible user tabs - return tabConfiguration.userTabs - .filter((tab) => { - if (!tab || typeof tab.id !== 'string') { - console.warn('Invalid tab entry:', tab); - return false; - } - - // Hide notifications tab if notifications are disabled - if (tab.id === 'notifications' && !notificationsEnabled) { - return false; - } - - // Always show task-manager in user mode if it's configured as visible - if (tab.id === 'task-manager') { - return tab.visible; - } - - // Only show tabs that are explicitly visible and assigned to the user window - return tab.visible && tab.window === 'user'; - }) - .sort((a, b) => a.order - b.order); -}; - -export const reorderTabs = ( - tabs: TabVisibilityConfig[], - startIndex: number, - endIndex: number, -): TabVisibilityConfig[] => { - const result = Array.from(tabs); - const [removed] = result.splice(startIndex, 1); - result.splice(endIndex, 0, removed); - - // Update order property - return result.map((tab, index) => ({ - ...tab, - order: index, - })); -}; - -export const resetToDefaultConfig = (isDeveloperMode: boolean): TabVisibilityConfig[] => { - return DEFAULT_TAB_CONFIG.map((tab) => ({ - ...tab, - visible: isDeveloperMode ? true : tab.window === 'user', - window: isDeveloperMode ? 'developer' : tab.window, - })) as TabVisibilityConfig[]; -}; diff --git a/app/shared/hooks/index.ts b/app/shared/hooks/index.ts index 83fe4ae3..1cab0fc0 100644 --- a/app/shared/hooks/index.ts +++ b/app/shared/hooks/index.ts @@ -4,8 +4,6 @@ export * from './useShortcuts'; export * from '~/chat/hooks/StickToBottom'; export * from '~/layout/header/hooks/useEditChatDescription'; export { default } from './useViewport'; -export { useUpdateCheck } from './useUpdateCheck'; export { useFeatures } from './useFeatures'; export { useNotifications } from './useNotifications'; export { useConnectionStatus } from './useConnectionStatus'; -export { useDebugStatus } from './useDebugStatus'; diff --git a/app/shared/hooks/useDebugStatus.ts b/app/shared/hooks/useDebugStatus.ts deleted file mode 100644 index 922e22af..00000000 --- a/app/shared/hooks/useDebugStatus.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { useState, useEffect } from 'react'; -import { getDebugStatus, acknowledgeWarning, acknowledgeError, type DebugIssue } from '~/shared/lib/api/debug'; - -const ACKNOWLEDGED_DEBUG_ISSUES_KEY = 'bolt_acknowledged_debug_issues'; - -const getAcknowledgedIssues = (): string[] => { - try { - const stored = localStorage.getItem(ACKNOWLEDGED_DEBUG_ISSUES_KEY); - return stored ? JSON.parse(stored) : []; - } catch { - return []; - } -}; - -const setAcknowledgedIssues = (issueIds: string[]) => { - try { - localStorage.setItem(ACKNOWLEDGED_DEBUG_ISSUES_KEY, JSON.stringify(issueIds)); - } catch (error) { - console.error('Failed to persist acknowledged debug issues:', error); - } -}; - -export const useDebugStatus = () => { - const [hasActiveWarnings, setHasActiveWarnings] = useState(false); - const [activeIssues, setActiveIssues] = useState([]); - const [acknowledgedIssueIds, setAcknowledgedIssueIds] = useState(() => getAcknowledgedIssues()); - - const checkDebugStatus = async () => { - try { - const status = await getDebugStatus(); - const issues: DebugIssue[] = [ - ...status.warnings.map((w) => ({ ...w, type: 'warning' as const })), - ...status.errors.map((e) => ({ ...e, type: 'error' as const })), - ].filter((issue) => !acknowledgedIssueIds.includes(issue.id)); - - setActiveIssues(issues); - setHasActiveWarnings(issues.length > 0); - } catch (error) { - console.error('Failed to check debug status:', error); - } - }; - - useEffect(() => { - // Check immediately and then every 5 seconds - checkDebugStatus(); - - const interval = setInterval(checkDebugStatus, 5 * 1000); - - return () => clearInterval(interval); - }, [acknowledgedIssueIds]); - - const acknowledgeIssue = async (issue: DebugIssue) => { - try { - if (issue.type === 'warning') { - await acknowledgeWarning(issue.id); - } else { - await acknowledgeError(issue.id); - } - - const newAcknowledgedIds = [...acknowledgedIssueIds, issue.id]; - setAcknowledgedIssueIds(newAcknowledgedIds); - setAcknowledgedIssues(newAcknowledgedIds); - setActiveIssues((prev) => prev.filter((i) => i.id !== issue.id)); - setHasActiveWarnings(activeIssues.length > 1); - } catch (error) { - console.error('Failed to acknowledge issue:', error); - } - }; - - const acknowledgeAllIssues = async () => { - try { - await Promise.all( - activeIssues.map((issue) => - issue.type === 'warning' ? acknowledgeWarning(issue.id) : acknowledgeError(issue.id), - ), - ); - - const newAcknowledgedIds = [...acknowledgedIssueIds, ...activeIssues.map((i) => i.id)]; - setAcknowledgedIssueIds(newAcknowledgedIds); - setAcknowledgedIssues(newAcknowledgedIds); - setActiveIssues([]); - setHasActiveWarnings(false); - } catch (error) { - console.error('Failed to acknowledge all issues:', error); - } - }; - - return { hasActiveWarnings, activeIssues, acknowledgeIssue, acknowledgeAllIssues }; -}; diff --git a/app/shared/hooks/useUpdateCheck.ts b/app/shared/hooks/useUpdateCheck.ts deleted file mode 100644 index 830ad930..00000000 --- a/app/shared/hooks/useUpdateCheck.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { useState, useEffect } from 'react'; -import { checkForUpdates, acknowledgeUpdate } from '~/shared/lib/api/updates'; - -const LAST_ACKNOWLEDGED_VERSION_KEY = 'bolt_last_acknowledged_version'; - -export const useUpdateCheck = () => { - const [hasUpdate, setHasUpdate] = useState(false); - const [currentVersion, setCurrentVersion] = useState(''); - const [lastAcknowledgedVersion, setLastAcknowledgedVersion] = useState(() => { - try { - return localStorage.getItem(LAST_ACKNOWLEDGED_VERSION_KEY); - } catch { - return null; - } - }); - - useEffect(() => { - const checkUpdate = async () => { - try { - const { available, version } = await checkForUpdates(); - setCurrentVersion(version); - - // Only show update if it's a new version and hasn't been acknowledged - setHasUpdate(available && version !== lastAcknowledgedVersion); - } catch (error) { - console.error('Failed to check for updates:', error); - } - }; - - // Check immediately and then every 30 minutes - checkUpdate(); - - const interval = setInterval(checkUpdate, 30 * 60 * 1000); - - return () => clearInterval(interval); - }, [lastAcknowledgedVersion]); - - const handleAcknowledgeUpdate = async () => { - try { - const { version } = await checkForUpdates(); - await acknowledgeUpdate(version); - - // Store in localStorage - try { - localStorage.setItem(LAST_ACKNOWLEDGED_VERSION_KEY, version); - } catch (error) { - console.error('Failed to persist acknowledged version:', error); - } - - setLastAcknowledgedVersion(version); - setHasUpdate(false); - } catch (error) { - console.error('Failed to acknowledge update:', error); - } - }; - - return { hasUpdate, currentVersion, acknowledgeUpdate: handleAcknowledgeUpdate }; -};