Compare commits
1 Commits
main
...
revert-133
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67702202af |
157
.cursorrules
Normal file
157
.cursorrules
Normal file
@@ -0,0 +1,157 @@
|
||||
# Project Overview
|
||||
|
||||
bolt.diy (previously oTToDev) is an open-source AI-powered full-stack web development platform that allows users to choose different LLM providers for coding assistance. The project supports multiple AI providers including OpenAI, Anthropic, Ollama, OpenRouter, Gemini, LMStudio, Mistral, xAI, HuggingFace, DeepSeek, and Groq.
|
||||
|
||||
# Personality
|
||||
|
||||
- Professional and technically precise
|
||||
- Focus on best practices and clean code
|
||||
- Provide clear explanations for code changes
|
||||
- Maintain consistent code style with the existing codebase
|
||||
|
||||
# Techstack
|
||||
|
||||
- Framework: Remix
|
||||
- Runtime: Node.js (>=18.18.0)
|
||||
- Package Manager: pnpm
|
||||
- UI: React with TypeScript
|
||||
- Styling: UnoCSS
|
||||
- Development Environment: Vite
|
||||
- Testing: Vitest
|
||||
- Deployment: Cloudflare Pages
|
||||
- Containerization: Docker
|
||||
- Code Quality: ESLint, Prettier, TypeScript
|
||||
|
||||
# our .env file
|
||||
|
||||
- Follow .env.example for required environment variables
|
||||
- Keep API keys and sensitive data in .env.local
|
||||
- Never commit .env files (they are gitignored)
|
||||
|
||||
# Error Fixing Process
|
||||
|
||||
1. Identify the root cause through error messages and logs
|
||||
2. Check relevant components and dependencies
|
||||
3. Verify type safety and TypeScript compliance
|
||||
4. Test changes locally before committing
|
||||
5. Follow existing error handling patterns
|
||||
|
||||
# Our Codebase
|
||||
|
||||
- Main application code in /app directory
|
||||
- Components follow a modular structure
|
||||
- Server-side code in app/lib/.server
|
||||
- Client-side utilities in app/lib/
|
||||
- Type definitions in types/ directory
|
||||
- Documentation in docs/ directory
|
||||
|
||||
# Current File Structure
|
||||
|
||||
- /app - Main application code
|
||||
- /docs - Documentation
|
||||
- /functions - Serverless functions
|
||||
- /public - Static assets
|
||||
- /scripts - Build and utility scripts
|
||||
- /types - TypeScript definitions
|
||||
- /icons - SVG icons and assets
|
||||
|
||||
# github upload process
|
||||
|
||||
1. Follow conventional commit messages
|
||||
2. Run linting and tests before committing
|
||||
3. Create feature branches for new work
|
||||
4. Submit PRs with clear descriptions
|
||||
5. Ensure CI/CD checks pass
|
||||
|
||||
# Important
|
||||
|
||||
- Keep dependencies updated
|
||||
- Follow TypeScript strict mode
|
||||
- Maintain backward compatibility
|
||||
- Document API changes
|
||||
- Test cross-browser compatibility
|
||||
|
||||
# comments
|
||||
|
||||
- Use JSDoc for function documentation
|
||||
- Keep comments clear and concise
|
||||
- Document complex logic and business rules
|
||||
- Update comments when changing code
|
||||
- Remove redundant comments
|
||||
- Always write comments that are relevant to the code they describe
|
||||
- Ensure comments explain the "why" not just the "what"
|
||||
|
||||
# code review
|
||||
|
||||
- Check for type safety
|
||||
- Verify error handling
|
||||
- Ensure code follows project patterns
|
||||
- Look for performance implications
|
||||
- Validate accessibility standards
|
||||
|
||||
# code writing
|
||||
|
||||
- Follow TypeScript best practices
|
||||
- Use functional components for React
|
||||
- Implement proper error boundaries
|
||||
- Write testable code
|
||||
- Follow the DRY principle
|
||||
|
||||
# code refactoring
|
||||
|
||||
- Maintain backward compatibility
|
||||
- Update tests alongside changes
|
||||
- Document breaking changes
|
||||
- Follow the project's type system
|
||||
- Keep components modular and reusable
|
||||
|
||||
# Development Process
|
||||
|
||||
- Write 3 reasoning paragraphs before implementing solutions
|
||||
- Analyze the problem space thoroughly before jumping to conclusions
|
||||
- Consider all edge cases and potential impacts
|
||||
- Process tasks with a Senior Developer mindset
|
||||
- Continue working until the solution is complete and verified
|
||||
- Remember and consider the full commit/change history when working
|
||||
|
||||
# Code Quality Guidelines
|
||||
|
||||
- Fewer lines of code is better, but not at the expense of readability
|
||||
- Preserve existing comments and documentation
|
||||
- Add meaningful comments explaining complex logic or business rules
|
||||
- Follow the principle of "Clean Code, Clear Intent"
|
||||
- Balance between conciseness and maintainability
|
||||
- Think twice, code once - avoid premature optimization
|
||||
- Never add comments just for the sake of commenting - ensure they add value
|
||||
|
||||
# Problem Solving Approach
|
||||
|
||||
1. Understand the context fully before making changes
|
||||
2. Document your reasoning and assumptions
|
||||
3. Consider alternative approaches and their trade-offs
|
||||
4. Validate your solution against existing patterns
|
||||
5. Test thoroughly before considering work complete
|
||||
6. Review impact on related components
|
||||
|
||||
# UI GUIDELINES
|
||||
|
||||
- Use consistent colors and typography
|
||||
- Ensure UI is responsive and accessible
|
||||
- Provide clear feedback for user actions
|
||||
- Use meaningful icons and labels
|
||||
- Keep UI clean and organized
|
||||
- Use consistent spacing and alignment
|
||||
- Use consistent naming conventions for components and variables
|
||||
- Use consistent file and folder structure
|
||||
- Use consistent naming conventions for components and variables
|
||||
- Use consistent file and folder structure
|
||||
|
||||
# Style Guide
|
||||
|
||||
- Use consistent naming conventions for components and variables
|
||||
- Use consistent file and folder structure
|
||||
- Respect the Light/Dark mode
|
||||
- Don't use white background for dark mode
|
||||
- Don't use white text on white background for dark mode
|
||||
- Match the style of the existing codebase
|
||||
- Use consistent naming conventions for components and variables
|
||||
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"ignoreMatches": [
|
||||
"@types/*",
|
||||
"eslint-*",
|
||||
"prettier*",
|
||||
"husky",
|
||||
"rimraf",
|
||||
"vitest",
|
||||
"vite",
|
||||
"typescript",
|
||||
"wrangler",
|
||||
"electron*"
|
||||
],
|
||||
"ignoreDirs": [
|
||||
"dist",
|
||||
"build",
|
||||
"node_modules",
|
||||
".git"
|
||||
],
|
||||
"skipMissing": false,
|
||||
"ignorePatterns": [
|
||||
"*.d.ts",
|
||||
"*.test.ts",
|
||||
"*.test.tsx",
|
||||
"*.spec.ts",
|
||||
"*.spec.tsx"
|
||||
]
|
||||
}
|
||||
281
.env.example
281
.env.example
@@ -1,221 +1,106 @@
|
||||
# ======================================
|
||||
# Environment Variables for Bolt.diy
|
||||
# ======================================
|
||||
# Copy this file to .env.local and fill in your API keys
|
||||
# See README.md for setup instructions
|
||||
# Rename this file to .env once you have filled in the below environment variables!
|
||||
|
||||
# ======================================
|
||||
# AI PROVIDER API KEYS
|
||||
# ======================================
|
||||
# Get your GROQ API Key here -
|
||||
# https://console.groq.com/keys
|
||||
# You only need this environment variable set if you want to use Groq models
|
||||
GROQ_API_KEY=
|
||||
|
||||
# Anthropic Claude
|
||||
# Get your API key from: https://console.anthropic.com/
|
||||
ANTHROPIC_API_KEY=your_anthropic_api_key_here
|
||||
# Get your HuggingFace API Key here -
|
||||
# https://huggingface.co/settings/tokens
|
||||
# You only need this environment variable set if you want to use HuggingFace models
|
||||
HuggingFace_API_KEY=
|
||||
|
||||
# Cerebras (High-performance inference)
|
||||
# Get your API key from: https://cloud.cerebras.ai/settings
|
||||
CEREBRAS_API_KEY=your_cerebras_api_key_here
|
||||
|
||||
# Fireworks AI (Fast inference with FireAttention engine)
|
||||
# Get your API key from: https://fireworks.ai/api-keys
|
||||
FIREWORKS_API_KEY=your_fireworks_api_key_here
|
||||
# Get your Open AI API Key by following these instructions -
|
||||
# https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key
|
||||
# You only need this environment variable set if you want to use GPT models
|
||||
OPENAI_API_KEY=
|
||||
|
||||
# OpenAI GPT models
|
||||
# Get your API key from: https://platform.openai.com/api-keys
|
||||
OPENAI_API_KEY=your_openai_api_key_here
|
||||
# Get your Anthropic API Key in your account settings -
|
||||
# https://console.anthropic.com/settings/keys
|
||||
# You only need this environment variable set if you want to use Claude models
|
||||
ANTHROPIC_API_KEY=
|
||||
|
||||
# GitHub Models (OpenAI models hosted by GitHub)
|
||||
# Get your Personal Access Token from: https://github.com/settings/tokens
|
||||
# - Select "Fine-grained tokens"
|
||||
# - Set repository access to "All repositories"
|
||||
# - Enable "GitHub Models" permission
|
||||
GITHUB_API_KEY=github_pat_your_personal_access_token_here
|
||||
# Get your OpenRouter API Key in your account settings -
|
||||
# https://openrouter.ai/settings/keys
|
||||
# You only need this environment variable set if you want to use OpenRouter models
|
||||
OPEN_ROUTER_API_KEY=
|
||||
|
||||
# Perplexity AI (Search-augmented models)
|
||||
# Get your API key from: https://www.perplexity.ai/settings/api
|
||||
PERPLEXITY_API_KEY=your_perplexity_api_key_here
|
||||
# Get your Google Generative AI API Key by following these instructions -
|
||||
# https://console.cloud.google.com/apis/credentials
|
||||
# You only need this environment variable set if you want to use Google Generative AI models
|
||||
GOOGLE_GENERATIVE_AI_API_KEY=
|
||||
|
||||
# DeepSeek
|
||||
# Get your API key from: https://platform.deepseek.com/api_keys
|
||||
DEEPSEEK_API_KEY=your_deepseek_api_key_here
|
||||
# You only need this environment variable set if you want to use oLLAMA models
|
||||
# DONT USE http://localhost:11434 due to IPV6 issues
|
||||
# USE EXAMPLE http://127.0.0.1:11434
|
||||
OLLAMA_API_BASE_URL=
|
||||
|
||||
# Google Gemini
|
||||
# Get your API key from: https://makersuite.google.com/app/apikey
|
||||
GOOGLE_GENERATIVE_AI_API_KEY=your_google_gemini_api_key_here
|
||||
# You only need this environment variable set if you want to use OpenAI Like models
|
||||
OPENAI_LIKE_API_BASE_URL=
|
||||
|
||||
# Cohere
|
||||
# Get your API key from: https://dashboard.cohere.ai/api-keys
|
||||
COHERE_API_KEY=your_cohere_api_key_here
|
||||
# You only need this environment variable set if you want to use Together AI models
|
||||
TOGETHER_API_BASE_URL=
|
||||
|
||||
# Groq (Fast inference)
|
||||
# Get your API key from: https://console.groq.com/keys
|
||||
GROQ_API_KEY=your_groq_api_key_here
|
||||
# You only need this environment variable set if you want to use DeepSeek models through their API
|
||||
DEEPSEEK_API_KEY=
|
||||
|
||||
# Mistral
|
||||
# Get your API key from: https://console.mistral.ai/api-keys/
|
||||
MISTRAL_API_KEY=your_mistral_api_key_here
|
||||
# Get your OpenAI Like API Key
|
||||
OPENAI_LIKE_API_KEY=
|
||||
|
||||
# Together AI
|
||||
# Get your API key from: https://api.together.xyz/settings/api-keys
|
||||
TOGETHER_API_KEY=your_together_api_key_here
|
||||
# Get your Together API Key
|
||||
TOGETHER_API_KEY=
|
||||
|
||||
# X.AI (Elon Musk's company)
|
||||
# Get your API key from: https://console.x.ai/
|
||||
XAI_API_KEY=your_xai_api_key_here
|
||||
# You only need this environment variable set if you want to use Hyperbolic models
|
||||
#Get your Hyperbolics API Key at https://app.hyperbolic.xyz/settings
|
||||
#baseURL="https://api.hyperbolic.xyz/v1/chat/completions"
|
||||
HYPERBOLIC_API_KEY=
|
||||
HYPERBOLIC_API_BASE_URL=
|
||||
|
||||
# Moonshot AI (Kimi models)
|
||||
# Get your API key from: https://platform.moonshot.ai/console/api-keys
|
||||
MOONSHOT_API_KEY=your_moonshot_api_key_here
|
||||
# Get your Mistral API Key by following these instructions -
|
||||
# https://console.mistral.ai/api-keys/
|
||||
# You only need this environment variable set if you want to use Mistral models
|
||||
MISTRAL_API_KEY=
|
||||
|
||||
# Z.AI (GLM models with JWT authentication)
|
||||
# Get your API key from: https://open.bigmodel.cn/usercenter/apikeys
|
||||
ZAI_API_KEY=your_zai_api_key_here
|
||||
# Get the Cohere Api key by following these instructions -
|
||||
# https://dashboard.cohere.com/api-keys
|
||||
# You only need this environment variable set if you want to use Cohere models
|
||||
COHERE_API_KEY=
|
||||
|
||||
# Hugging Face
|
||||
# Get your API key from: https://huggingface.co/settings/tokens
|
||||
HuggingFace_API_KEY=your_huggingface_api_key_here
|
||||
# Get LMStudio Base URL from LM Studio Developer Console
|
||||
# Make sure to enable CORS
|
||||
# DONT USE http://localhost:1234 due to IPV6 issues
|
||||
# Example: http://127.0.0.1:1234
|
||||
LMSTUDIO_API_BASE_URL=
|
||||
|
||||
# Hyperbolic
|
||||
# Get your API key from: https://app.hyperbolic.xyz/settings
|
||||
HYPERBOLIC_API_KEY=your_hyperbolic_api_key_here
|
||||
# Get your xAI API key
|
||||
# https://x.ai/api
|
||||
# You only need this environment variable set if you want to use xAI models
|
||||
XAI_API_KEY=
|
||||
|
||||
# OpenRouter (Meta routing for multiple providers)
|
||||
# Get your API key from: https://openrouter.ai/keys
|
||||
OPEN_ROUTER_API_KEY=your_openrouter_api_key_here
|
||||
# Get your Perplexity API Key here -
|
||||
# https://www.perplexity.ai/settings/api
|
||||
# You only need this environment variable set if you want to use Perplexity models
|
||||
PERPLEXITY_API_KEY=
|
||||
|
||||
# ======================================
|
||||
# CUSTOM PROVIDER BASE URLS (Optional)
|
||||
# ======================================
|
||||
# Get your AWS configuration
|
||||
# https://console.aws.amazon.com/iam/home
|
||||
# The JSON should include the following keys:
|
||||
# - region: The AWS region where Bedrock is available.
|
||||
# - accessKeyId: Your AWS access key ID.
|
||||
# - secretAccessKey: Your AWS secret access key.
|
||||
# - sessionToken (optional): Temporary session token if using an IAM role or temporary credentials.
|
||||
# Example JSON:
|
||||
# {"region": "us-east-1", "accessKeyId": "yourAccessKeyId", "secretAccessKey": "yourSecretAccessKey", "sessionToken": "yourSessionToken"}
|
||||
AWS_BEDROCK_CONFIG=
|
||||
|
||||
# Ollama (Local models)
|
||||
# DON'T USE http://localhost:11434 due to IPv6 issues
|
||||
# USE: http://127.0.0.1:11434
|
||||
OLLAMA_API_BASE_URL=http://127.0.0.1:11434
|
||||
|
||||
# OpenAI-like API (Compatible providers)
|
||||
OPENAI_LIKE_API_BASE_URL=your_openai_like_base_url_here
|
||||
OPENAI_LIKE_API_KEY=your_openai_like_api_key_here
|
||||
|
||||
# Together AI Base URL
|
||||
TOGETHER_API_BASE_URL=your_together_base_url_here
|
||||
|
||||
# Hyperbolic Base URL
|
||||
HYPERBOLIC_API_BASE_URL=https://api.hyperbolic.xyz/v1/chat/completions
|
||||
|
||||
# LMStudio (Local models)
|
||||
# Make sure to enable CORS in LMStudio
|
||||
# DON'T USE http://localhost:1234 due to IPv6 issues
|
||||
# USE: http://127.0.0.1:1234
|
||||
LMSTUDIO_API_BASE_URL=http://127.0.0.1:1234
|
||||
|
||||
# ======================================
|
||||
# CLOUD SERVICES CONFIGURATION
|
||||
# ======================================
|
||||
|
||||
# AWS Bedrock Configuration (JSON format)
|
||||
# Get your credentials from: https://console.aws.amazon.com/iam/home
|
||||
# Example: {"region": "us-east-1", "accessKeyId": "yourAccessKeyId", "secretAccessKey": "yourSecretAccessKey"}
|
||||
AWS_BEDROCK_CONFIG=your_aws_bedrock_config_json_here
|
||||
|
||||
# ======================================
|
||||
# GITHUB INTEGRATION
|
||||
# ======================================
|
||||
|
||||
# GitHub Personal Access Token
|
||||
# Get from: https://github.com/settings/tokens
|
||||
# Used for importing/cloning repositories and accessing private repos
|
||||
VITE_GITHUB_ACCESS_TOKEN=your_github_personal_access_token_here
|
||||
|
||||
# GitHub Token Type ('classic' or 'fine-grained')
|
||||
VITE_GITHUB_TOKEN_TYPE=classic
|
||||
|
||||
# ======================================
|
||||
# GITLAB INTEGRATION
|
||||
# ======================================
|
||||
|
||||
# GitLab Personal Access Token
|
||||
# Get your GitLab Personal Access Token here:
|
||||
# https://gitlab.com/-/profile/personal_access_tokens
|
||||
#
|
||||
# This token is used for:
|
||||
# 1. Importing/cloning GitLab repositories
|
||||
# 2. Accessing private projects
|
||||
# 3. Creating/updating branches
|
||||
# 4. Creating/updating commits and pushing code
|
||||
# 5. Creating new GitLab projects via the API
|
||||
#
|
||||
# Make sure your token has the following scopes:
|
||||
# - api (for full API access including project creation and commits)
|
||||
# - read_repository (to clone/import repositories)
|
||||
# - write_repository (to push commits and update branches)
|
||||
VITE_GITLAB_ACCESS_TOKEN=your_gitlab_personal_access_token_here
|
||||
|
||||
# Set the GitLab instance URL (e.g., https://gitlab.com or your self-hosted domain)
|
||||
VITE_GITLAB_URL=https://gitlab.com
|
||||
|
||||
# GitLab token type should be 'personal-access-token'
|
||||
VITE_GITLAB_TOKEN_TYPE=personal-access-token
|
||||
|
||||
# ======================================
|
||||
# VERCEL INTEGRATION
|
||||
# ======================================
|
||||
|
||||
# Vercel Access Token
|
||||
# Get your access token from: https://vercel.com/account/tokens
|
||||
# This token is used for:
|
||||
# 1. Deploying projects to Vercel
|
||||
# 2. Managing Vercel projects and deployments
|
||||
# 3. Accessing project analytics and logs
|
||||
VITE_VERCEL_ACCESS_TOKEN=your_vercel_access_token_here
|
||||
|
||||
# ======================================
|
||||
# NETLIFY INTEGRATION
|
||||
# ======================================
|
||||
|
||||
# Netlify Access Token
|
||||
# Get your access token from: https://app.netlify.com/user/applications
|
||||
# This token is used for:
|
||||
# 1. Deploying sites to Netlify
|
||||
# 2. Managing Netlify sites and deployments
|
||||
# 3. Accessing build logs and analytics
|
||||
VITE_NETLIFY_ACCESS_TOKEN=your_netlify_access_token_here
|
||||
|
||||
# ======================================
|
||||
# SUPABASE INTEGRATION
|
||||
# ======================================
|
||||
|
||||
# Supabase Project Configuration
|
||||
# Get your project details from: https://supabase.com/dashboard
|
||||
# Select your project → Settings → API
|
||||
VITE_SUPABASE_URL=your_supabase_project_url_here
|
||||
VITE_SUPABASE_ANON_KEY=your_supabase_anon_key_here
|
||||
|
||||
# Supabase Access Token (for management operations)
|
||||
# Generate from: https://supabase.com/dashboard/account/tokens
|
||||
VITE_SUPABASE_ACCESS_TOKEN=your_supabase_access_token_here
|
||||
|
||||
# ======================================
|
||||
# DEVELOPMENT SETTINGS
|
||||
# ======================================
|
||||
|
||||
# Development Mode
|
||||
NODE_ENV=development
|
||||
|
||||
# Application Port (optional, defaults to 5173 for development)
|
||||
PORT=5173
|
||||
|
||||
# Logging Level (debug, info, warn, error)
|
||||
# Include this environment variable if you want more logging for debugging locally
|
||||
VITE_LOG_LEVEL=debug
|
||||
|
||||
# Default Context Window Size (for local models)
|
||||
DEFAULT_NUM_CTX=32768
|
||||
|
||||
# ======================================
|
||||
# SETUP INSTRUCTIONS
|
||||
# ======================================
|
||||
# 1. Copy this file to .env.local: cp .env.example .env.local
|
||||
# 2. Fill in the API keys for the services you want to use
|
||||
# 3. All service integration keys use VITE_ prefix for auto-connection
|
||||
# 4. Restart your development server: pnpm run dev
|
||||
# 5. Services will auto-connect on startup if tokens are provided
|
||||
# 6. Go to Settings > Service tabs to manage connections manually if needed
|
||||
# Example Context Values for qwen2.5-coder:32b
|
||||
#
|
||||
# DEFAULT_NUM_CTX=32768 # Consumes 36GB of VRAM
|
||||
# DEFAULT_NUM_CTX=24576 # Consumes 32GB of VRAM
|
||||
# DEFAULT_NUM_CTX=12288 # Consumes 26GB of VRAM
|
||||
# DEFAULT_NUM_CTX=6144 # Consumes 24GB of VRAM
|
||||
DEFAULT_NUM_CTX=
|
||||
|
||||
142
.env.production
142
.env.production
@@ -1,142 +0,0 @@
|
||||
# Rename this file to .env once you have filled in the below environment variables!
|
||||
|
||||
# Get your GROQ API Key here -
|
||||
# https://console.groq.com/keys
|
||||
# You only need this environment variable set if you want to use Groq models
|
||||
GROQ_API_KEY=
|
||||
|
||||
# Get your HuggingFace API Key here -
|
||||
# https://huggingface.co/settings/tokens
|
||||
# You only need this environment variable set if you want to use HuggingFace models
|
||||
HuggingFace_API_KEY=
|
||||
|
||||
# Get your Open AI API Key by following these instructions -
|
||||
# https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key
|
||||
# You only need this environment variable set if you want to use GPT models
|
||||
OPENAI_API_KEY=
|
||||
|
||||
# Get your Anthropic API Key in your account settings -
|
||||
# https://console.anthropic.com/settings/keys
|
||||
# You only need this environment variable set if you want to use Claude models
|
||||
ANTHROPIC_API_KEY=
|
||||
|
||||
# Get your OpenRouter API Key in your account settings -
|
||||
# https://openrouter.ai/settings/keys
|
||||
# You only need this environment variable set if you want to use OpenRouter models
|
||||
OPEN_ROUTER_API_KEY=
|
||||
|
||||
# Get your Google Generative AI API Key by following these instructions -
|
||||
# https://console.cloud.google.com/apis/credentials
|
||||
# You only need this environment variable set if you want to use Google Generative AI models
|
||||
GOOGLE_GENERATIVE_AI_API_KEY=
|
||||
|
||||
# You only need this environment variable set if you want to use oLLAMA models
|
||||
# DONT USE http://localhost:11434 due to IPV6 issues
|
||||
# USE EXAMPLE http://127.0.0.1:11434
|
||||
OLLAMA_API_BASE_URL=
|
||||
|
||||
# You only need this environment variable set if you want to use OpenAI Like models
|
||||
OPENAI_LIKE_API_BASE_URL=
|
||||
|
||||
# You only need this environment variable set if you want to use Together AI models
|
||||
TOGETHER_API_BASE_URL=
|
||||
|
||||
# You only need this environment variable set if you want to use DeepSeek models through their API
|
||||
DEEPSEEK_API_KEY=
|
||||
|
||||
# Get your OpenAI Like API Key
|
||||
OPENAI_LIKE_API_KEY=
|
||||
|
||||
# Get your Together API Key
|
||||
TOGETHER_API_KEY=
|
||||
|
||||
# You only need this environment variable set if you want to use Hyperbolic models
|
||||
HYPERBOLIC_API_KEY=
|
||||
HYPERBOLIC_API_BASE_URL=
|
||||
|
||||
# Get your Mistral API Key by following these instructions -
|
||||
# https://console.mistral.ai/api-keys/
|
||||
# You only need this environment variable set if you want to use Mistral models
|
||||
MISTRAL_API_KEY=
|
||||
|
||||
# Get the Cohere Api key by following these instructions -
|
||||
# https://dashboard.cohere.com/api-keys
|
||||
# You only need this environment variable set if you want to use Cohere models
|
||||
COHERE_API_KEY=
|
||||
|
||||
# Get LMStudio Base URL from LM Studio Developer Console
|
||||
# Make sure to enable CORS
|
||||
# DONT USE http://localhost:1234 due to IPV6 issues
|
||||
# Example: http://127.0.0.1:1234
|
||||
LMSTUDIO_API_BASE_URL=
|
||||
|
||||
# Get your xAI API key
|
||||
# https://x.ai/api
|
||||
# You only need this environment variable set if you want to use xAI models
|
||||
XAI_API_KEY=
|
||||
|
||||
# Get your Perplexity API Key here -
|
||||
# https://www.perplexity.ai/settings/api
|
||||
# You only need this environment variable set if you want to use Perplexity models
|
||||
PERPLEXITY_API_KEY=
|
||||
|
||||
# Get your AWS configuration
|
||||
# https://console.aws.amazon.com/iam/home
|
||||
AWS_BEDROCK_CONFIG=
|
||||
|
||||
# Include this environment variable if you want more logging for debugging locally
|
||||
VITE_LOG_LEVEL=
|
||||
|
||||
# Get your GitHub Personal Access Token here -
|
||||
# https://github.com/settings/tokens
|
||||
# This token is used for:
|
||||
# 1. Importing/cloning GitHub repositories without rate limiting
|
||||
# 2. Accessing private repositories
|
||||
# 3. Automatic GitHub authentication (no need to manually connect in the UI)
|
||||
#
|
||||
# For classic tokens, ensure it has these scopes: repo, read:org, read:user
|
||||
# For fine-grained tokens, ensure it has Repository and Organization access
|
||||
VITE_GITHUB_ACCESS_TOKEN=
|
||||
|
||||
# Specify the type of GitHub token you're using
|
||||
# Can be 'classic' or 'fine-grained'
|
||||
# Classic tokens are recommended for broader access
|
||||
VITE_GITHUB_TOKEN_TYPE=
|
||||
|
||||
# ======================================
|
||||
# SERVICE INTEGRATIONS
|
||||
# ======================================
|
||||
|
||||
# GitLab Personal Access Token
|
||||
# Get your GitLab Personal Access Token here:
|
||||
# https://gitlab.com/-/profile/personal_access_tokens
|
||||
# Required scopes: api, read_repository, write_repository
|
||||
VITE_GITLAB_ACCESS_TOKEN=
|
||||
|
||||
# GitLab instance URL (e.g., https://gitlab.com or your self-hosted domain)
|
||||
VITE_GITLAB_URL=https://gitlab.com
|
||||
|
||||
# GitLab token type
|
||||
VITE_GITLAB_TOKEN_TYPE=personal-access-token
|
||||
|
||||
# Vercel Access Token
|
||||
# Get your access token from: https://vercel.com/account/tokens
|
||||
VITE_VERCEL_ACCESS_TOKEN=
|
||||
|
||||
# Netlify Access Token
|
||||
# Get your access token from: https://app.netlify.com/user/applications
|
||||
VITE_NETLIFY_ACCESS_TOKEN=
|
||||
|
||||
# Supabase Configuration
|
||||
# Get your project details from: https://supabase.com/dashboard
|
||||
VITE_SUPABASE_URL=
|
||||
VITE_SUPABASE_ANON_KEY=
|
||||
VITE_SUPABASE_ACCESS_TOKEN=
|
||||
|
||||
# Example Context Values for qwen2.5-coder:32b
|
||||
#
|
||||
# DEFAULT_NUM_CTX=32768 # Consumes 36GB of VRAM
|
||||
# DEFAULT_NUM_CTX=24576 # Consumes 32GB of VRAM
|
||||
# DEFAULT_NUM_CTX=12288 # Consumes 26GB of VRAM
|
||||
# DEFAULT_NUM_CTX=6144 # Consumes 24GB of VRAM
|
||||
DEFAULT_NUM_CTX=
|
||||
30
.github/CODEOWNERS
vendored
30
.github/CODEOWNERS
vendored
@@ -1,30 +0,0 @@
|
||||
# Code Owners for bolt.diy
|
||||
# These users/teams will automatically be requested for review when files are modified
|
||||
|
||||
# Global ownership - repository maintainers
|
||||
* @stackblitz-labs/bolt-maintainers
|
||||
|
||||
# GitHub workflows and CI/CD configuration - require maintainer review
|
||||
/.github/ @stackblitz-labs/bolt-maintainers
|
||||
/package.json @stackblitz-labs/bolt-maintainers
|
||||
/pnpm-lock.yaml @stackblitz-labs/bolt-maintainers
|
||||
|
||||
# Security-sensitive configurations - require maintainer review
|
||||
/.env* @stackblitz-labs/bolt-maintainers
|
||||
/wrangler.toml @stackblitz-labs/bolt-maintainers
|
||||
/Dockerfile @stackblitz-labs/bolt-maintainers
|
||||
/docker-compose.yaml @stackblitz-labs/bolt-maintainers
|
||||
|
||||
# Core application architecture - require maintainer review
|
||||
/app/lib/.server/ @stackblitz-labs/bolt-maintainers
|
||||
/app/routes/api.* @stackblitz-labs/bolt-maintainers
|
||||
|
||||
# Build and deployment configuration - require maintainer review
|
||||
/vite*.config.ts @stackblitz-labs/bolt-maintainers
|
||||
/tsconfig.json @stackblitz-labs/bolt-maintainers
|
||||
/uno.config.ts @stackblitz-labs/bolt-maintainers
|
||||
/eslint.config.mjs @stackblitz-labs/bolt-maintainers
|
||||
|
||||
# Documentation (optional review)
|
||||
/*.md
|
||||
/docs/
|
||||
4
.github/actions/setup-and-build/action.yaml
vendored
4
.github/actions/setup-and-build/action.yaml
vendored
@@ -4,11 +4,11 @@ inputs:
|
||||
pnpm-version:
|
||||
required: false
|
||||
type: string
|
||||
default: '9.14.4'
|
||||
default: '9.4.0'
|
||||
node-version:
|
||||
required: false
|
||||
type: string
|
||||
default: '20.18.0'
|
||||
default: '20.15.1'
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
|
||||
69
.github/workflows/ci.yaml
vendored
69
.github/workflows/ci.yaml
vendored
@@ -3,20 +3,13 @@ name: CI/CD
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
# Cancel in-progress runs on the same branch/PR
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -24,67 +17,11 @@ jobs:
|
||||
- name: Setup and Build
|
||||
uses: ./.github/actions/setup-and-build
|
||||
|
||||
- name: Cache TypeScript compilation
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
.tsbuildinfo
|
||||
node_modules/.cache
|
||||
key: ${{ runner.os }}-typescript-${{ hashFiles('**/tsconfig.json', 'app/**/*.ts', 'app/**/*.tsx') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-typescript-
|
||||
|
||||
- name: Run type check
|
||||
run: pnpm run typecheck
|
||||
|
||||
- name: Cache ESLint
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules/.cache/eslint
|
||||
key: ${{ runner.os }}-eslint-${{ hashFiles('.eslintrc*', 'app/**/*.ts', 'app/**/*.tsx') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-eslint-
|
||||
|
||||
- name: Run ESLint
|
||||
run: pnpm run lint
|
||||
# - name: Run ESLint
|
||||
# run: pnpm run lint
|
||||
|
||||
- name: Run tests
|
||||
run: pnpm run test
|
||||
|
||||
- name: Upload test coverage
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: coverage-report
|
||||
path: coverage/
|
||||
retention-days: 7
|
||||
|
||||
docker-validation:
|
||||
name: Docker Build Validation
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Validate Docker production build
|
||||
run: |
|
||||
echo "🐳 Testing Docker production target..."
|
||||
docker build --target bolt-ai-production . --no-cache --progress=plain
|
||||
echo "✅ Production target builds successfully"
|
||||
|
||||
- name: Validate Docker development build
|
||||
run: |
|
||||
echo "🐳 Testing Docker development target..."
|
||||
docker build --target development . --no-cache --progress=plain
|
||||
echo "✅ Development target builds successfully"
|
||||
|
||||
- name: Validate docker-compose configuration
|
||||
run: |
|
||||
echo "🐳 Validating docker-compose configuration..."
|
||||
docker compose config --quiet
|
||||
echo "✅ docker-compose configuration is valid"
|
||||
|
||||
86
.github/workflows/docker.yaml
vendored
86
.github/workflows/docker.yaml
vendored
@@ -1,67 +1,81 @@
|
||||
---
|
||||
name: Docker Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, stable]
|
||||
tags: ['v*', '*.*.*']
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- v*
|
||||
- '*'
|
||||
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
DOCKER_IMAGE: ghcr.io/${{ github.repository }}
|
||||
BUILD_TARGET: bolt-ai-production # bolt-ai-development
|
||||
|
||||
jobs:
|
||||
docker-build-publish:
|
||||
runs-on: ubuntu-latest
|
||||
# timeout-minutes: 30
|
||||
steps:
|
||||
- name: Checkout code
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set lowercase image name
|
||||
id: image
|
||||
run: echo "name=$(echo '${{ github.repository }}' | tr '[:upper:]' '[:lower:]')" >> $GITHUB_OUTPUT
|
||||
|
||||
|
||||
- id: string
|
||||
uses: ASzc/change-string-case-action@v6
|
||||
with:
|
||||
string: ${{ env.DOCKER_IMAGE }}
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: crazy-max/ghaction-docker-meta@v5
|
||||
with:
|
||||
images: ${{ steps.string.outputs.lowercase }}
|
||||
flavor: |
|
||||
latest=true
|
||||
prefix=
|
||||
suffix=
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=pep440,pattern={{version}}
|
||||
type=ref,event=tag
|
||||
type=raw,value={{sha}}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
|
||||
- name: Login to Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
username: ${{ github.actor }} # ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }} # ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Extract metadata for Docker image
|
||||
id: meta
|
||||
uses: docker/metadata-action@v4
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ steps.image.outputs.name }}
|
||||
tags: |
|
||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||
type=raw,value=stable,enable=${{ github.ref == 'refs/heads/stable' }}
|
||||
type=ref,event=tag
|
||||
type=sha,format=short
|
||||
type=raw,value=${{ github.ref_name }},enable=${{ startsWith(github.ref, 'refs/tags/') || github.ref == 'refs/heads/main' || github.ref == 'refs/heads/stable' }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
target: ${{ env.BUILD_TARGET }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
target: bolt-ai-production
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
|
||||
cache-from: type=registry,ref=${{ steps.string.outputs.lowercase }}:latest
|
||||
cache-to: type=inline
|
||||
|
||||
- name: Check manifest
|
||||
run: docker buildx imagetools inspect ${{ env.REGISTRY }}/${{ steps.image.outputs.name }}:${{ steps.meta.outputs.version }}
|
||||
run: |
|
||||
docker buildx imagetools inspect ${{ steps.string.outputs.lowercase }}:${{ steps.meta.outputs.version }}
|
||||
|
||||
- name: Dump context
|
||||
if: always()
|
||||
uses: crazy-max/ghaction-dump-context@v2
|
||||
|
||||
98
.github/workflows/electron.yml
vendored
98
.github/workflows/electron.yml
vendored
@@ -1,98 +0,0 @@
|
||||
name: Electron Build and Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Tag for the release (e.g., v1.0.0). Leave empty if not applicable.'
|
||||
required: false
|
||||
push:
|
||||
branches:
|
||||
- electron
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest] # Use unsigned macOS builds for now
|
||||
node-version: [20.18.0]
|
||||
fail-fast: false
|
||||
|
||||
steps:
|
||||
- name: Check out Git repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 9.14.4
|
||||
run_install: false
|
||||
|
||||
- name: Get pnpm store directory
|
||||
shell: bash
|
||||
run: |
|
||||
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
|
||||
|
||||
- name: Setup pnpm cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ env.STORE_PATH }}
|
||||
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pnpm-store-
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
# Install Linux dependencies
|
||||
- name: Install Linux dependencies
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y rpm
|
||||
|
||||
# Build
|
||||
- name: Build Electron app
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NODE_OPTIONS: "--max_old_space_size=4096"
|
||||
run: |
|
||||
if [ "$RUNNER_OS" == "Windows" ]; then
|
||||
pnpm run electron:build:win
|
||||
elif [ "$RUNNER_OS" == "macOS" ]; then
|
||||
pnpm run electron:build:mac
|
||||
else
|
||||
pnpm run electron:build:linux
|
||||
fi
|
||||
shell: bash
|
||||
|
||||
# Create Release
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
# Use the workflow_dispatch input tag if available, else use the Git ref name.
|
||||
tag_name: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref_name }}
|
||||
# Only branch pushes remain drafts. For workflow_dispatch and tag pushes the release is published.
|
||||
draft: ${{ github.event_name != 'workflow_dispatch' && github.ref_type == 'branch' }}
|
||||
# For tag pushes, name the release as "Release <tagname>", otherwise "Electron Release".
|
||||
name: ${{ (github.event_name == 'push' && github.ref_type == 'tag') && format('Release {0}', github.ref_name) || 'Electron Release' }}
|
||||
files: |
|
||||
dist/*.exe
|
||||
dist/*.dmg
|
||||
dist/*.deb
|
||||
dist/*.AppImage
|
||||
dist/*.zip
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
98
.github/workflows/pr-release-validation.yaml
vendored
98
.github/workflows/pr-release-validation.yaml
vendored
@@ -6,79 +6,12 @@ on:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
checks: write
|
||||
|
||||
jobs:
|
||||
quality-gates:
|
||||
name: Quality Gates
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Wait for CI checks
|
||||
uses: lewagon/wait-on-check-action@v1.3.1
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
check-name: 'Test'
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
wait-interval: 10
|
||||
|
||||
- name: Check required status checks
|
||||
uses: actions/github-script@v7
|
||||
continue-on-error: true
|
||||
with:
|
||||
script: |
|
||||
const { data: checks } = await github.rest.checks.listForRef({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
ref: context.payload.pull_request.head.sha
|
||||
});
|
||||
|
||||
const requiredChecks = ['Test', 'CodeQL Analysis'];
|
||||
const optionalChecks = ['Quality Analysis', 'Deploy Preview'];
|
||||
const failedChecks = [];
|
||||
const passedChecks = [];
|
||||
|
||||
// Check required workflows
|
||||
for (const checkName of requiredChecks) {
|
||||
const check = checks.check_runs.find(c => c.name === checkName);
|
||||
if (check && check.conclusion === 'success') {
|
||||
passedChecks.push(checkName);
|
||||
} else {
|
||||
failedChecks.push(checkName);
|
||||
}
|
||||
}
|
||||
|
||||
// Report optional checks
|
||||
for (const checkName of optionalChecks) {
|
||||
const check = checks.check_runs.find(c => c.name === checkName);
|
||||
if (check && check.conclusion === 'success') {
|
||||
passedChecks.push(`${checkName} (optional)`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ Passed checks: ${passedChecks.join(', ')}`);
|
||||
|
||||
if (failedChecks.length > 0) {
|
||||
console.log(`❌ Failed required checks: ${failedChecks.join(', ')}`);
|
||||
core.setFailed(`Required checks failed: ${failedChecks.join(', ')}`);
|
||||
} else {
|
||||
console.log(`✅ All required checks passed!`);
|
||||
}
|
||||
|
||||
validate-release:
|
||||
name: Release Validation
|
||||
runs-on: ubuntu-latest
|
||||
needs: quality-gates
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Validate PR Labels
|
||||
run: |
|
||||
@@ -96,30 +29,3 @@ jobs:
|
||||
else
|
||||
echo "This PR doesn't have the stable-release label. No release will be created."
|
||||
fi
|
||||
|
||||
- name: Check breaking changes
|
||||
if: contains(github.event.pull_request.labels.*.name, 'major')
|
||||
run: |
|
||||
echo "⚠️ This PR contains breaking changes and will trigger a major release."
|
||||
|
||||
- name: Validate changelog entry
|
||||
if: contains(github.event.pull_request.labels.*.name, 'stable-release')
|
||||
run: |
|
||||
if ! grep -q "${{ github.event.pull_request.number }}" CHANGES.md; then
|
||||
echo "❌ No changelog entry found for PR #${{ github.event.pull_request.number }}"
|
||||
echo "Please add an entry to CHANGES.md"
|
||||
exit 1
|
||||
else
|
||||
echo "✓ Changelog entry found"
|
||||
fi
|
||||
|
||||
security-review:
|
||||
name: Security Review Required
|
||||
runs-on: ubuntu-latest
|
||||
if: contains(github.event.pull_request.labels.*.name, 'security')
|
||||
|
||||
steps:
|
||||
- name: Check security label
|
||||
run: |
|
||||
echo "🔒 This PR has security implications and requires additional review"
|
||||
echo "Ensure a security team member has approved this PR before merging"
|
||||
|
||||
196
.github/workflows/preview.yaml
vendored
196
.github/workflows/preview.yaml
vendored
@@ -1,196 +0,0 @@
|
||||
name: Preview Deployment
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, closed]
|
||||
branches: [main]
|
||||
|
||||
# Cancel in-progress runs on the same PR
|
||||
concurrency:
|
||||
group: preview-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
deployments: write
|
||||
|
||||
jobs:
|
||||
deploy-preview:
|
||||
name: Deploy Preview
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.action != 'closed'
|
||||
|
||||
steps:
|
||||
- name: Check if preview deployment is configured
|
||||
id: check-secrets
|
||||
run: |
|
||||
if [[ -n "${{ secrets.CLOUDFLARE_API_TOKEN }}" && -n "${{ secrets.CLOUDFLARE_ACCOUNT_ID }}" ]]; then
|
||||
echo "configured=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "configured=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.check-secrets.outputs.configured == 'true'
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup and Build
|
||||
if: steps.check-secrets.outputs.configured == 'true'
|
||||
uses: ./.github/actions/setup-and-build
|
||||
|
||||
- name: Build for production
|
||||
if: steps.check-secrets.outputs.configured == 'true'
|
||||
run: pnpm run build
|
||||
env:
|
||||
NODE_ENV: production
|
||||
|
||||
- name: Deploy to Cloudflare Pages
|
||||
if: steps.check-secrets.outputs.configured == 'true'
|
||||
id: deploy
|
||||
uses: cloudflare/pages-action@v1
|
||||
with:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
projectName: bolt-diy-preview
|
||||
directory: build/client
|
||||
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Preview deployment not configured
|
||||
if: steps.check-secrets.outputs.configured == 'false'
|
||||
run: |
|
||||
echo "✅ Preview deployment is not configured for this repository"
|
||||
echo "To enable preview deployments, add the following secrets:"
|
||||
echo "- CLOUDFLARE_API_TOKEN"
|
||||
echo "- CLOUDFLARE_ACCOUNT_ID"
|
||||
echo "This is optional and the workflow will pass without it."
|
||||
echo "url=https://preview-not-configured.example.com" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Add preview URL comment to PR
|
||||
uses: actions/github-script@v7
|
||||
continue-on-error: true
|
||||
with:
|
||||
script: |
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
});
|
||||
|
||||
const previewComment = comments.find(comment =>
|
||||
comment.body.includes('🚀 Preview deployment')
|
||||
);
|
||||
|
||||
const isConfigured = '${{ steps.check-secrets.outputs.configured }}' === 'true';
|
||||
const deployUrl = '${{ steps.deploy.outputs.url }}' || 'https://preview-not-configured.example.com';
|
||||
|
||||
let commentBody;
|
||||
if (isConfigured) {
|
||||
commentBody = `🚀 Preview deployment is ready!
|
||||
|
||||
| Name | Link |
|
||||
|------|------|
|
||||
| Latest commit | ${{ github.sha }} |
|
||||
| Preview URL | ${deployUrl} |
|
||||
|
||||
Built with ❤️ by [bolt.diy](https://bolt.diy)
|
||||
`;
|
||||
} else {
|
||||
commentBody = `ℹ️ Preview deployment not configured
|
||||
|
||||
| Name | Info |
|
||||
|------|------|
|
||||
| Latest commit | ${{ github.sha }} |
|
||||
| Status | Preview deployment requires Cloudflare secrets |
|
||||
|
||||
To enable preview deployments, repository maintainers can add:
|
||||
- \`CLOUDFLARE_API_TOKEN\` secret
|
||||
- \`CLOUDFLARE_ACCOUNT_ID\` secret
|
||||
|
||||
Built with ❤️ by [bolt.diy](https://bolt.diy)
|
||||
`;
|
||||
}
|
||||
|
||||
if (previewComment) {
|
||||
github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: previewComment.id,
|
||||
body: commentBody
|
||||
});
|
||||
} else {
|
||||
github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
body: commentBody
|
||||
});
|
||||
}
|
||||
|
||||
- name: Run smoke tests on preview
|
||||
run: |
|
||||
if [[ "${{ steps.check-secrets.outputs.configured }}" == "true" ]]; then
|
||||
echo "Running smoke tests on preview deployment..."
|
||||
echo "Preview URL: ${{ steps.deploy.outputs.url }}"
|
||||
# Basic HTTP check instead of Playwright tests
|
||||
curl -f ${{ steps.deploy.outputs.url }} || echo "Preview environment check completed"
|
||||
else
|
||||
echo "✅ Smoke tests skipped - preview deployment not configured"
|
||||
echo "This is normal and expected when Cloudflare secrets are not available"
|
||||
fi
|
||||
|
||||
- name: Preview workflow summary
|
||||
run: |
|
||||
echo "✅ Preview deployment workflow completed successfully"
|
||||
if [[ "${{ steps.check-secrets.outputs.configured }}" == "true" ]]; then
|
||||
echo "🚀 Preview deployed to: ${{ steps.deploy.outputs.url }}"
|
||||
else
|
||||
echo "ℹ️ Preview deployment not configured (this is normal)"
|
||||
fi
|
||||
|
||||
cleanup-preview:
|
||||
name: Cleanup Preview
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.action == 'closed'
|
||||
|
||||
steps:
|
||||
- name: Delete preview environment
|
||||
uses: actions/github-script@v7
|
||||
continue-on-error: true
|
||||
with:
|
||||
script: |
|
||||
const deployments = await github.rest.repos.listDeployments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
environment: `preview-pr-${{ github.event.pull_request.number }}`,
|
||||
});
|
||||
|
||||
for (const deployment of deployments.data) {
|
||||
await github.rest.repos.createDeploymentStatus({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
deployment_id: deployment.id,
|
||||
state: 'inactive',
|
||||
});
|
||||
}
|
||||
|
||||
- name: Remove preview comment
|
||||
uses: actions/github-script@v7
|
||||
continue-on-error: true
|
||||
with:
|
||||
script: |
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
});
|
||||
|
||||
for (const comment of comments) {
|
||||
if (comment.body.includes('🚀 Preview deployment')) {
|
||||
await github.rest.issues.deleteComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: comment.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
181
.github/workflows/quality.yaml
vendored
181
.github/workflows/quality.yaml
vendored
@@ -1,181 +0,0 @@
|
||||
name: Code Quality
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
# Cancel in-progress runs on the same branch/PR
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
quality-checks:
|
||||
name: Quality Analysis
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup and Build
|
||||
uses: ./.github/actions/setup-and-build
|
||||
|
||||
- name: Check for duplicate dependencies
|
||||
run: |
|
||||
echo "Checking for duplicate dependencies..."
|
||||
pnpm dedupe --check || echo "✅ Duplicate dependency check completed"
|
||||
|
||||
- name: Check bundle size
|
||||
run: |
|
||||
pnpm run build
|
||||
echo "Bundle analysis completed (bundlesize tool requires configuration)"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Dead code elimination check
|
||||
run: |
|
||||
echo "Checking for unused imports and dead code..."
|
||||
npx unimported || echo "Unimported tool completed with warnings"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check for unused dependencies
|
||||
run: |
|
||||
echo "Checking for unused dependencies..."
|
||||
npx depcheck --config .depcheckrc.json || echo "Dependency check completed with findings"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check package.json formatting
|
||||
run: |
|
||||
echo "Checking package.json formatting..."
|
||||
npx sort-package-json package.json --check || echo "Package.json formatting check completed"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Generate complexity report
|
||||
run: |
|
||||
echo "Analyzing code complexity..."
|
||||
npx es6-plato -r -d complexity-report app/ || echo "Complexity analysis completed"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload complexity report
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: complexity-report
|
||||
path: complexity-report/
|
||||
retention-days: 7
|
||||
|
||||
accessibility-tests:
|
||||
name: Accessibility Tests
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup and Build
|
||||
uses: ./.github/actions/setup-and-build
|
||||
|
||||
- name: Start development server
|
||||
run: |
|
||||
pnpm run build
|
||||
pnpm run start &
|
||||
sleep 15
|
||||
env:
|
||||
CI: true
|
||||
|
||||
- name: Run accessibility tests with axe
|
||||
run: |
|
||||
echo "Running accessibility tests..."
|
||||
npx @axe-core/cli http://localhost:5173 --exit || echo "Accessibility tests completed with findings"
|
||||
continue-on-error: true
|
||||
|
||||
performance-audit:
|
||||
name: Performance Audit
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup and Build
|
||||
uses: ./.github/actions/setup-and-build
|
||||
|
||||
- name: Start server for Lighthouse
|
||||
run: |
|
||||
pnpm run build
|
||||
pnpm run start &
|
||||
sleep 20
|
||||
|
||||
- name: Run Lighthouse audit
|
||||
run: |
|
||||
echo "Running Lighthouse performance audit..."
|
||||
npx lighthouse http://localhost:5173 --output-path=./lighthouse-report.html --output=html --chrome-flags="--headless --no-sandbox" || echo "Lighthouse audit completed"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload Lighthouse report
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: lighthouse-report
|
||||
path: lighthouse-report.html
|
||||
retention-days: 7
|
||||
|
||||
pr-size-check:
|
||||
name: PR Size Check
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'pull_request'
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Calculate PR size
|
||||
id: pr-size
|
||||
run: |
|
||||
# Get the base branch (target branch)
|
||||
BASE_BRANCH="${{ github.event.pull_request.base.ref }}"
|
||||
|
||||
# Count additions and deletions
|
||||
ADDITIONS=$(git diff --numstat origin/$BASE_BRANCH...HEAD | awk '{sum += $1} END {print sum}')
|
||||
DELETIONS=$(git diff --numstat origin/$BASE_BRANCH...HEAD | awk '{sum += $2} END {print sum}')
|
||||
TOTAL_CHANGES=$((ADDITIONS + DELETIONS))
|
||||
|
||||
echo "additions=$ADDITIONS" >> $GITHUB_OUTPUT
|
||||
echo "deletions=$DELETIONS" >> $GITHUB_OUTPUT
|
||||
echo "total=$TOTAL_CHANGES" >> $GITHUB_OUTPUT
|
||||
|
||||
# Determine size category
|
||||
if [ $TOTAL_CHANGES -lt 50 ]; then
|
||||
echo "size=XS" >> $GITHUB_OUTPUT
|
||||
elif [ $TOTAL_CHANGES -lt 200 ]; then
|
||||
echo "size=S" >> $GITHUB_OUTPUT
|
||||
elif [ $TOTAL_CHANGES -lt 500 ]; then
|
||||
echo "size=M" >> $GITHUB_OUTPUT
|
||||
elif [ $TOTAL_CHANGES -lt 1000 ]; then
|
||||
echo "size=L" >> $GITHUB_OUTPUT
|
||||
elif [ $TOTAL_CHANGES -lt 2000 ]; then
|
||||
echo "size=XL" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "size=XXL" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: PR size summary
|
||||
run: |
|
||||
echo "✅ PR Size Analysis Complete"
|
||||
echo "📊 Changes: +${{ steps.pr-size.outputs.additions }} -${{ steps.pr-size.outputs.deletions }}"
|
||||
echo "📏 Size Category: ${{ steps.pr-size.outputs.size }}"
|
||||
echo "💡 This information helps reviewers understand the scope of changes"
|
||||
|
||||
if [ "${{ steps.pr-size.outputs.size }}" = "XXL" ]; then
|
||||
echo "ℹ️ This is a large PR - consider breaking it into smaller chunks for future PRs"
|
||||
echo "However, large PRs are acceptable for major feature additions like this one"
|
||||
fi
|
||||
121
.github/workflows/security.yaml
vendored
121
.github/workflows/security.yaml
vendored
@@ -1,121 +0,0 @@
|
||||
name: Security Analysis
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, stable]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
schedule:
|
||||
# Run weekly security scan on Sundays at 2 AM
|
||||
- cron: '0 2 * * 0'
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: read
|
||||
|
||||
jobs:
|
||||
codeql:
|
||||
name: CodeQL Analysis
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ['javascript', 'typescript']
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v3
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
queries: security-extended,security-and-quality
|
||||
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v3
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v3
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
upload: false
|
||||
output: "codeql-results"
|
||||
|
||||
- name: Upload CodeQL results as artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: codeql-results-${{ matrix.language }}
|
||||
path: codeql-results
|
||||
|
||||
dependency-scan:
|
||||
name: Dependency Vulnerability Scan
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20.18.0'
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: '9.14.4'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run npm audit
|
||||
run: pnpm audit --audit-level moderate
|
||||
continue-on-error: true
|
||||
|
||||
- name: Generate SBOM
|
||||
uses: anchore/sbom-action@v0
|
||||
with:
|
||||
path: ./
|
||||
format: spdx-json
|
||||
artifact-name: sbom.spdx.json
|
||||
|
||||
- name: Upload SBOM as artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: sbom-results
|
||||
path: |
|
||||
sbom.spdx.json
|
||||
**/sbom.spdx.json
|
||||
|
||||
secrets-scan:
|
||||
name: Secrets Detection
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Run Trivy secrets scan
|
||||
uses: aquasecurity/trivy-action@master
|
||||
with:
|
||||
scan-type: 'fs'
|
||||
scan-ref: '.'
|
||||
format: 'sarif'
|
||||
output: 'trivy-secrets-results.sarif'
|
||||
scanners: 'secret'
|
||||
|
||||
- name: Upload Trivy secrets results as artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: trivy-secrets-results
|
||||
path: trivy-secrets-results.sarif
|
||||
|
||||
247
.github/workflows/test-workflows.yaml
vendored
247
.github/workflows/test-workflows.yaml
vendored
@@ -1,247 +0,0 @@
|
||||
name: Test Workflows
|
||||
|
||||
# This workflow is for testing our new workflow changes safely
|
||||
on:
|
||||
push:
|
||||
branches: [workflow-testing, test-*]
|
||||
pull_request:
|
||||
branches: [workflow-testing]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
test_type:
|
||||
description: 'Type of test to run'
|
||||
required: true
|
||||
default: 'all'
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- ci-only
|
||||
- security-only
|
||||
- quality-only
|
||||
|
||||
jobs:
|
||||
workflow-test-info:
|
||||
name: Workflow Test Information
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Display test information
|
||||
run: |
|
||||
echo "🧪 Testing new workflow configurations"
|
||||
echo "Branch: ${{ github.ref_name }}"
|
||||
echo "Event: ${{ github.event_name }}"
|
||||
echo "Test type: ${{ github.event.inputs.test_type || 'all' }}"
|
||||
echo ""
|
||||
echo "This is a safe test environment - no changes will affect production workflows"
|
||||
|
||||
test-basic-setup:
|
||||
name: Test Basic Setup
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Test setup-and-build action
|
||||
uses: ./.github/actions/setup-and-build
|
||||
|
||||
- name: Verify Node.js version
|
||||
run: |
|
||||
echo "Node.js version: $(node --version)"
|
||||
if [[ "$(node --version)" == *"20.18.0"* ]]; then
|
||||
echo "✅ Correct Node.js version"
|
||||
else
|
||||
echo "❌ Wrong Node.js version"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Verify pnpm version
|
||||
run: |
|
||||
echo "pnpm version: $(pnpm --version)"
|
||||
if [[ "$(pnpm --version)" == *"9.14.4"* ]]; then
|
||||
echo "✅ Correct pnpm version"
|
||||
else
|
||||
echo "❌ Wrong pnpm version"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Test build process
|
||||
run: |
|
||||
echo "✅ Build completed successfully"
|
||||
|
||||
test-linting:
|
||||
name: Test Linting
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup and Build
|
||||
uses: ./.github/actions/setup-and-build
|
||||
|
||||
- name: Test ESLint
|
||||
run: |
|
||||
echo "Testing ESLint configuration..."
|
||||
pnpm run lint --max-warnings 0 || echo "ESLint found issues (expected for testing)"
|
||||
|
||||
- name: Test TypeScript
|
||||
run: |
|
||||
echo "Testing TypeScript compilation..."
|
||||
pnpm run typecheck
|
||||
|
||||
test-caching:
|
||||
name: Test Caching Strategy
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup and Build
|
||||
uses: ./.github/actions/setup-and-build
|
||||
|
||||
- name: Test TypeScript cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
.tsbuildinfo
|
||||
node_modules/.cache
|
||||
key: test-${{ runner.os }}-typescript-${{ hashFiles('**/tsconfig.json', 'app/**/*.ts', 'app/**/*.tsx') }}
|
||||
restore-keys: |
|
||||
test-${{ runner.os }}-typescript-
|
||||
|
||||
- name: Test ESLint cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules/.cache/eslint
|
||||
key: test-${{ runner.os }}-eslint-${{ hashFiles('.eslintrc*', 'app/**/*.ts', 'app/**/*.tsx') }}
|
||||
restore-keys: |
|
||||
test-${{ runner.os }}-eslint-
|
||||
|
||||
- name: Verify caching works
|
||||
run: |
|
||||
echo "✅ Caching configuration tested"
|
||||
|
||||
test-security-tools:
|
||||
name: Test Security Tools
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.inputs.test_type == 'all' || github.event.inputs.test_type == 'security-only'
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20.18.0'
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: '9.14.4'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Test dependency audit (non-blocking)
|
||||
run: |
|
||||
echo "Testing pnpm audit..."
|
||||
pnpm audit --audit-level moderate || echo "Audit found issues (this is for testing)"
|
||||
|
||||
- name: Test Trivy installation
|
||||
run: |
|
||||
echo "Testing Trivy secrets scanner..."
|
||||
docker run --rm -v ${{ github.workspace }}:/workspace aquasecurity/trivy:latest fs /workspace --exit-code 0 --no-progress --format table --scanners secret || echo "Trivy test completed"
|
||||
|
||||
test-quality-checks:
|
||||
name: Test Quality Checks
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.inputs.test_type == 'all' || github.event.inputs.test_type == 'quality-only'
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup and Build
|
||||
uses: ./.github/actions/setup-and-build
|
||||
|
||||
- name: Test bundle size analysis
|
||||
run: |
|
||||
echo "Testing bundle size analysis..."
|
||||
ls -la build/client/ || echo "Build directory structure checked"
|
||||
|
||||
- name: Test dependency checks
|
||||
run: |
|
||||
echo "Testing depcheck..."
|
||||
npx depcheck --config .depcheckrc.json || echo "Depcheck completed"
|
||||
|
||||
- name: Test package.json formatting
|
||||
run: |
|
||||
echo "Testing package.json sorting..."
|
||||
npx sort-package-json package.json --check || echo "Package.json check completed"
|
||||
|
||||
validate-docker-config:
|
||||
name: Validate Docker Configuration
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Test Docker build (without push)
|
||||
run: |
|
||||
echo "Testing Docker build configuration..."
|
||||
docker build --target bolt-ai-production . --no-cache --progress=plain
|
||||
echo "✅ Docker build test completed"
|
||||
|
||||
test-results-summary:
|
||||
name: Test Results Summary
|
||||
runs-on: ubuntu-latest
|
||||
needs: [workflow-test-info, test-basic-setup, test-linting, test-caching, test-security-tools, test-quality-checks, validate-docker-config]
|
||||
if: always()
|
||||
steps:
|
||||
- name: Check all test results
|
||||
run: |
|
||||
echo "🧪 Workflow Testing Results Summary"
|
||||
echo "=================================="
|
||||
|
||||
if [[ "${{ needs.test-basic-setup.result }}" == "success" ]]; then
|
||||
echo "✅ Basic Setup: PASSED"
|
||||
else
|
||||
echo "❌ Basic Setup: FAILED"
|
||||
fi
|
||||
|
||||
if [[ "${{ needs.test-linting.result }}" == "success" ]]; then
|
||||
echo "✅ Linting Tests: PASSED"
|
||||
else
|
||||
echo "❌ Linting Tests: FAILED"
|
||||
fi
|
||||
|
||||
if [[ "${{ needs.test-caching.result }}" == "success" ]]; then
|
||||
echo "✅ Caching Tests: PASSED"
|
||||
else
|
||||
echo "❌ Caching Tests: FAILED"
|
||||
fi
|
||||
|
||||
if [[ "${{ needs.test-security-tools.result }}" == "success" ]]; then
|
||||
echo "✅ Security Tools: PASSED"
|
||||
else
|
||||
echo "❌ Security Tools: FAILED"
|
||||
fi
|
||||
|
||||
if [[ "${{ needs.test-quality-checks.result }}" == "success" ]]; then
|
||||
echo "✅ Quality Checks: PASSED"
|
||||
else
|
||||
echo "❌ Quality Checks: FAILED"
|
||||
fi
|
||||
|
||||
if [[ "${{ needs.validate-docker-config.result }}" == "success" ]]; then
|
||||
echo "✅ Docker Config: PASSED"
|
||||
else
|
||||
echo "❌ Docker Config: FAILED"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "Next steps:"
|
||||
echo "1. Review any failures above"
|
||||
echo "2. Fix issues in workflow configurations"
|
||||
echo "3. Re-test until all checks pass"
|
||||
echo "4. Create PR to merge workflow improvements"
|
||||
8
.github/workflows/update-stable.yml
vendored
8
.github/workflows/update-stable.yml
vendored
@@ -26,12 +26,12 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20.18.0'
|
||||
node-version: '20'
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: '9.14.4'
|
||||
version: latest
|
||||
run_install: false
|
||||
|
||||
- name: Get pnpm store directory
|
||||
@@ -119,9 +119,7 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
VERSION="v${{ steps.bump_version.outputs.new_version }}"
|
||||
# Save changelog to a file
|
||||
echo "${{ steps.changelog.outputs.content }}" > release_notes.md
|
||||
gh release create "$VERSION" \
|
||||
--title "Release $VERSION" \
|
||||
--notes-file release_notes.md \
|
||||
--notes "${{ steps.changelog.outputs.content }}" \
|
||||
--target stable
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -25,7 +25,6 @@ dist-ssr
|
||||
/.history
|
||||
/.cache
|
||||
/build
|
||||
functions/build/
|
||||
.env.local
|
||||
.env
|
||||
.dev.vars
|
||||
@@ -44,5 +43,5 @@ app/commit.json
|
||||
changelogUI.md
|
||||
docs/instructions/Roadmap.md
|
||||
.cursorrules
|
||||
.cursorrules
|
||||
*.md
|
||||
.qodo
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"ci": {
|
||||
"collect": {
|
||||
"url": ["http://localhost:5173/"],
|
||||
"startServerCommand": "pnpm run start",
|
||||
"numberOfRuns": 3
|
||||
},
|
||||
"assert": {
|
||||
"assertions": {
|
||||
"categories:performance": ["warn", {"minScore": 0.8}],
|
||||
"categories:accessibility": ["warn", {"minScore": 0.9}],
|
||||
"categories:best-practices": ["warn", {"minScore": 0.8}],
|
||||
"categories:seo": ["warn", {"minScore": 0.8}]
|
||||
}
|
||||
},
|
||||
"upload": {
|
||||
"target": "temporary-public-storage"
|
||||
}
|
||||
}
|
||||
}
|
||||
2
.tool-versions
Normal file
2
.tool-versions
Normal file
@@ -0,0 +1,2 @@
|
||||
nodejs 20.15.1
|
||||
pnpm 9.4.0
|
||||
92
CHANGES.md
92
CHANGES.md
@@ -1,92 +0,0 @@
|
||||
# File and Folder Locking Feature Implementation
|
||||
|
||||
## Overview
|
||||
|
||||
This implementation adds persistent file and folder locking functionality to the BoltDIY project. When a file or folder is locked, it cannot be modified by either the user or the AI until it is unlocked. All locks are scoped to the current chat/project to prevent locks from one project affecting files with matching names in other projects.
|
||||
|
||||
## New Files
|
||||
|
||||
### 1. `app/components/chat/LockAlert.tsx`
|
||||
|
||||
- A dedicated alert component for displaying lock-related error messages
|
||||
- Features a distinctive amber/yellow color scheme and lock icon
|
||||
- Provides clear instructions to the user about locked files
|
||||
|
||||
### 2. `app/lib/persistence/lockedFiles.ts`
|
||||
|
||||
- Core functionality for persisting file and folder locks in localStorage
|
||||
- Provides functions for adding, removing, and retrieving locked files and folders
|
||||
- Defines the lock modes: "full" (no modifications) and "scoped" (only additions allowed)
|
||||
- Implements chat ID scoping to isolate locks to specific projects
|
||||
|
||||
### 3. `app/utils/fileLocks.ts`
|
||||
|
||||
- Utility functions for checking if a file or folder is locked
|
||||
- Helps avoid circular dependencies between components and stores
|
||||
- Provides a consistent interface for lock checking across the application
|
||||
- Extracts chat ID from URL for project-specific lock scoping
|
||||
|
||||
## Modified Files
|
||||
|
||||
### 1. `app/components/chat/ChatAlert.tsx`
|
||||
|
||||
- Updated to use the new LockAlert component for locked file errors
|
||||
- Maintains backward compatibility with other error types
|
||||
|
||||
### 2. `app/components/editor/codemirror/CodeMirrorEditor.tsx`
|
||||
|
||||
- Added checks to prevent editing of locked files
|
||||
- Updated to use the new fileLocks utility
|
||||
- Displays appropriate tooltips when a user attempts to edit a locked file
|
||||
|
||||
### 3. `app/components/workbench/EditorPanel.tsx`
|
||||
|
||||
- Added safety checks for unsavedFiles to prevent errors
|
||||
- Improved handling of locked files in the editor panel
|
||||
|
||||
### 4. `app/components/workbench/FileTree.tsx`
|
||||
|
||||
- Added visual indicators for locked files and folders in the file tree
|
||||
- Improved handling of locked files and folders in the file tree
|
||||
- Added context menu options for locking and unlocking folders
|
||||
|
||||
### 5. `app/lib/stores/editor.ts`
|
||||
|
||||
- Added checks to prevent updating locked files
|
||||
- Improved error handling for locked files
|
||||
|
||||
### 6. `app/lib/stores/files.ts`
|
||||
|
||||
- Added core functionality for locking and unlocking files and folders
|
||||
- Implemented persistence of locked files and folders across page refreshes
|
||||
- Added methods for checking if a file or folder is locked
|
||||
- Added chat ID scoping to prevent locks from affecting other projects
|
||||
|
||||
### 7. `app/lib/stores/workbench.ts`
|
||||
|
||||
- Added methods for locking and unlocking files and folders
|
||||
- Improved error handling for locked files and folders
|
||||
- Fixed issues with alert initialization
|
||||
- Added support for chat ID scoping of locks
|
||||
|
||||
### 8. `app/types/actions.ts`
|
||||
|
||||
- Added `isLockedFile` property to the ActionAlert interface
|
||||
- Improved type definitions for locked file alerts
|
||||
|
||||
## Key Features
|
||||
|
||||
1. **Persistent File and Folder Locking**: Locks are stored in localStorage and persist across page refreshes
|
||||
2. **Visual Indicators**: Locked files and folders are clearly marked in the UI with lock icons
|
||||
3. **Improved Error Messages**: Clear, visually distinct error messages when attempting to modify locked items
|
||||
4. **Lock Modes**: Support for both full locks (no modifications) and scoped locks (only additions allowed)
|
||||
5. **Prevention of AI Modifications**: The AI is prevented from modifying locked files and folders
|
||||
6. **Project-Specific Locks**: Locks are scoped to the current chat/project to prevent conflicts
|
||||
7. **Recursive Folder Locking**: Locking a folder automatically locks all files and subfolders within it
|
||||
|
||||
## UI Improvements
|
||||
|
||||
1. **Enhanced Alert Design**: Modern, visually appealing alert design with better spacing and typography
|
||||
2. **Contextual Icons**: Different icons and colors for different types of alerts
|
||||
3. **Improved Error Details**: Better formatting of error details with monospace font and left border
|
||||
4. **Responsive Buttons**: Better positioned and styled buttons with appropriate hover effects
|
||||
141
Dockerfile
141
Dockerfile
@@ -1,103 +1,94 @@
|
||||
# ---- build stage ----
|
||||
FROM node:22-bookworm-slim AS build
|
||||
ARG BASE=node:20.18.0
|
||||
FROM ${BASE} AS base
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# CI-friendly env
|
||||
ENV HUSKY=0
|
||||
ENV CI=true
|
||||
# Install dependencies (this step is cached as long as the dependencies don't change)
|
||||
COPY package.json pnpm-lock.yaml ./
|
||||
|
||||
# Use pnpm
|
||||
RUN corepack enable && corepack prepare pnpm@9.15.9 --activate
|
||||
RUN npm install -g corepack@latest
|
||||
|
||||
# Ensure git is available for build and runtime scripts
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
RUN corepack enable pnpm && pnpm install
|
||||
|
||||
# Accept (optional) build-time public URL for Remix/Vite (Coolify can pass it)
|
||||
ARG VITE_PUBLIC_APP_URL
|
||||
ENV VITE_PUBLIC_APP_URL=${VITE_PUBLIC_APP_URL}
|
||||
|
||||
# Install deps efficiently
|
||||
COPY package.json pnpm-lock.yaml* ./
|
||||
RUN pnpm fetch
|
||||
|
||||
# Copy source and build
|
||||
# Copy the rest of your app's source code
|
||||
COPY . .
|
||||
# install with dev deps (needed to build)
|
||||
RUN pnpm install --offline --frozen-lockfile
|
||||
|
||||
# Build the Remix app (SSR + client)
|
||||
RUN NODE_OPTIONS=--max-old-space-size=4096 pnpm run build
|
||||
# Expose the port the app runs on
|
||||
EXPOSE 5173
|
||||
|
||||
# ---- production dependencies stage ----
|
||||
FROM build AS prod-deps
|
||||
# Production image
|
||||
FROM base AS bolt-ai-production
|
||||
|
||||
# Keep only production deps for runtime
|
||||
RUN pnpm prune --prod --ignore-scripts
|
||||
|
||||
|
||||
# ---- production stage ----
|
||||
FROM prod-deps AS bolt-ai-production
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=5173
|
||||
ENV HOST=0.0.0.0
|
||||
|
||||
# Non-sensitive build arguments
|
||||
# Define environment variables with default values or let them be overridden
|
||||
ARG GROQ_API_KEY
|
||||
ARG HuggingFace_API_KEY
|
||||
ARG OPENAI_API_KEY
|
||||
ARG ANTHROPIC_API_KEY
|
||||
ARG OPEN_ROUTER_API_KEY
|
||||
ARG GOOGLE_GENERATIVE_AI_API_KEY
|
||||
ARG OLLAMA_API_BASE_URL
|
||||
ARG XAI_API_KEY
|
||||
ARG TOGETHER_API_KEY
|
||||
ARG TOGETHER_API_BASE_URL
|
||||
ARG AWS_BEDROCK_CONFIG
|
||||
ARG VITE_LOG_LEVEL=debug
|
||||
ARG DEFAULT_NUM_CTX
|
||||
|
||||
# Set non-sensitive environment variables
|
||||
ENV WRANGLER_SEND_METRICS=false \
|
||||
GROQ_API_KEY=${GROQ_API_KEY} \
|
||||
HuggingFace_KEY=${HuggingFace_API_KEY} \
|
||||
OPENAI_API_KEY=${OPENAI_API_KEY} \
|
||||
ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} \
|
||||
OPEN_ROUTER_API_KEY=${OPEN_ROUTER_API_KEY} \
|
||||
GOOGLE_GENERATIVE_AI_API_KEY=${GOOGLE_GENERATIVE_AI_API_KEY} \
|
||||
OLLAMA_API_BASE_URL=${OLLAMA_API_BASE_URL} \
|
||||
XAI_API_KEY=${XAI_API_KEY} \
|
||||
TOGETHER_API_KEY=${TOGETHER_API_KEY} \
|
||||
TOGETHER_API_BASE_URL=${TOGETHER_API_BASE_URL} \
|
||||
AWS_BEDROCK_CONFIG=${AWS_BEDROCK_CONFIG} \
|
||||
VITE_LOG_LEVEL=${VITE_LOG_LEVEL} \
|
||||
DEFAULT_NUM_CTX=${DEFAULT_NUM_CTX} \
|
||||
DEFAULT_NUM_CTX=${DEFAULT_NUM_CTX}\
|
||||
RUNNING_IN_DOCKER=true
|
||||
|
||||
# Note: API keys should be provided at runtime via docker run -e or docker-compose
|
||||
# Example: docker run -e OPENAI_API_KEY=your_key_here ...
|
||||
|
||||
# Install curl for healthchecks and copy bindings script
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy built files and scripts
|
||||
COPY --from=prod-deps /app/build /app/build
|
||||
COPY --from=prod-deps /app/node_modules /app/node_modules
|
||||
COPY --from=prod-deps /app/package.json /app/package.json
|
||||
COPY --from=prod-deps /app/bindings.sh /app/bindings.sh
|
||||
|
||||
# Pre-configure wrangler to disable metrics
|
||||
RUN mkdir -p /root/.config/.wrangler && \
|
||||
echo '{"enabled":false}' > /root/.config/.wrangler/metrics.json
|
||||
|
||||
# Make bindings script executable
|
||||
RUN chmod +x /app/bindings.sh
|
||||
RUN pnpm run build
|
||||
|
||||
EXPOSE 5173
|
||||
CMD [ "pnpm", "run", "dockerstart"]
|
||||
|
||||
# Healthcheck for deployment platforms
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=5 \
|
||||
CMD curl -fsS http://localhost:5173/ || exit 1
|
||||
# Development image
|
||||
FROM base AS bolt-ai-development
|
||||
|
||||
# Start using dockerstart script with Wrangler
|
||||
CMD ["pnpm", "run", "dockerstart"]
|
||||
|
||||
|
||||
# ---- development stage ----
|
||||
FROM build AS development
|
||||
|
||||
# Non-sensitive development arguments
|
||||
# Define the same environment variables for development
|
||||
ARG GROQ_API_KEY
|
||||
ARG HuggingFace
|
||||
ARG OPENAI_API_KEY
|
||||
ARG ANTHROPIC_API_KEY
|
||||
ARG OPEN_ROUTER_API_KEY
|
||||
ARG GOOGLE_GENERATIVE_AI_API_KEY
|
||||
ARG OLLAMA_API_BASE_URL
|
||||
ARG XAI_API_KEY
|
||||
ARG TOGETHER_API_KEY
|
||||
ARG TOGETHER_API_BASE_URL
|
||||
ARG VITE_LOG_LEVEL=debug
|
||||
ARG DEFAULT_NUM_CTX
|
||||
|
||||
# Set non-sensitive environment variables for development
|
||||
ENV VITE_LOG_LEVEL=${VITE_LOG_LEVEL} \
|
||||
DEFAULT_NUM_CTX=${DEFAULT_NUM_CTX} \
|
||||
ENV GROQ_API_KEY=${GROQ_API_KEY} \
|
||||
HuggingFace_API_KEY=${HuggingFace_API_KEY} \
|
||||
OPENAI_API_KEY=${OPENAI_API_KEY} \
|
||||
ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} \
|
||||
OPEN_ROUTER_API_KEY=${OPEN_ROUTER_API_KEY} \
|
||||
GOOGLE_GENERATIVE_AI_API_KEY=${GOOGLE_GENERATIVE_AI_API_KEY} \
|
||||
OLLAMA_API_BASE_URL=${OLLAMA_API_BASE_URL} \
|
||||
XAI_API_KEY=${XAI_API_KEY} \
|
||||
TOGETHER_API_KEY=${TOGETHER_API_KEY} \
|
||||
TOGETHER_API_BASE_URL=${TOGETHER_API_BASE_URL} \
|
||||
AWS_BEDROCK_CONFIG=${AWS_BEDROCK_CONFIG} \
|
||||
VITE_LOG_LEVEL=${VITE_LOG_LEVEL} \
|
||||
DEFAULT_NUM_CTX=${DEFAULT_NUM_CTX}\
|
||||
RUNNING_IN_DOCKER=true
|
||||
|
||||
# Note: API keys should be provided at runtime via docker run -e or docker-compose
|
||||
# Example: docker run -e OPENAI_API_KEY=your_key_here ...
|
||||
|
||||
RUN mkdir -p /app/run
|
||||
CMD ["pnpm", "run", "dev", "--host"]
|
||||
RUN mkdir -p ${WORKDIR}/run
|
||||
CMD pnpm run dev --host
|
||||
|
||||
386
README.md
386
README.md
@@ -1,13 +1,15 @@
|
||||
# bolt.diy
|
||||
# bolt.diy (Previously oTToDev)
|
||||
|
||||
[](https://bolt.diy)
|
||||
|
||||
Welcome to bolt.diy, the official open source version of Bolt.new, which allows you to choose the LLM that you use for each prompt! Currently, you can use OpenAI, Anthropic, Ollama, OpenRouter, Gemini, LMStudio, Mistral, xAI, HuggingFace, DeepSeek, Groq, Cohere, Together, Perplexity, Moonshot (Kimi), Hyperbolic, GitHub Models, Amazon Bedrock, and OpenAI-like providers - and it is easily extended to use any other model supported by the Vercel AI SDK! See the instructions below for running this locally and extending it to include more models.
|
||||
Welcome to bolt.diy, the official open source version of Bolt.new (previously known as oTToDev and bolt.new ANY LLM), which allows you to choose the LLM that you use for each prompt! Currently, you can use OpenAI, Anthropic, Ollama, OpenRouter, Gemini, LMStudio, Mistral, xAI, HuggingFace, DeepSeek, or Groq models - and it is easily extended to use any other model supported by the Vercel AI SDK! See the instructions below for running this locally and extending it to include more models.
|
||||
|
||||
-----
|
||||
Check the [bolt.diy Docs](https://stackblitz-labs.github.io/bolt.diy/) for more official installation instructions and additional information.
|
||||
---
|
||||
|
||||
Check the [bolt.diy Docs](https://stackblitz-labs.github.io/bolt.diy/) for more offical installation instructions and more informations.
|
||||
|
||||
---
|
||||
|
||||
-----
|
||||
Also [this pinned post in our community](https://thinktank.ottomator.ai/t/videos-tutorial-helpful-content/3243) has a bunch of incredible resources for running and deploying bolt.diy yourself!
|
||||
|
||||
We have also launched an experimental agent called the "bolt.diy Expert" that can answer common questions about bolt.diy. Find it here on the [oTTomator Live Agent Studio](https://studio.ottomator.ai/).
|
||||
@@ -17,13 +19,10 @@ bolt.diy was originally started by [Cole Medin](https://www.youtube.com/@ColeMed
|
||||
## Table of Contents
|
||||
|
||||
- [Join the Community](#join-the-community)
|
||||
- [Recent Major Additions](#recent-major-additions)
|
||||
- [Requested Additions](#requested-additions)
|
||||
- [Features](#features)
|
||||
- [Setup](#setup)
|
||||
- [Quick Installation](#quick-installation)
|
||||
- [Manual Installation](#manual-installation)
|
||||
- [Configuring API Keys and Providers](#configuring-api-keys-and-providers)
|
||||
- [Setup Using Git (For Developers only)](#setup-using-git-for-developers-only)
|
||||
- [Run the Application](#run-the-application)
|
||||
- [Available Scripts](#available-scripts)
|
||||
- [Contributing](#contributing)
|
||||
- [Roadmap](#roadmap)
|
||||
@@ -41,52 +40,70 @@ you to understand where the current areas of focus are.
|
||||
If you want to know what we are working on, what we are planning to work on, or if you want to contribute to the
|
||||
project, please check the [project management guide](./PROJECT.md) to get started easily.
|
||||
|
||||
## Recent Major Additions
|
||||
## Requested Additions
|
||||
|
||||
### ✅ Completed Features
|
||||
- **19+ AI Provider Integrations** - OpenAI, Anthropic, Google, Groq, xAI, DeepSeek, Mistral, Cohere, Together, Perplexity, HuggingFace, Ollama, LM Studio, OpenRouter, Moonshot, Hyperbolic, GitHub Models, Amazon Bedrock, OpenAI-like
|
||||
- **Electron Desktop App** - Native desktop experience with full functionality
|
||||
- **Advanced Deployment Options** - Netlify, Vercel, and GitHub Pages deployment
|
||||
- **Supabase Integration** - Database management and query capabilities
|
||||
- **Data Visualization & Analysis** - Charts, graphs, and data analysis tools
|
||||
- **MCP (Model Context Protocol)** - Enhanced AI tool integration
|
||||
- **Search Functionality** - Codebase search and navigation
|
||||
- **File Locking System** - Prevents conflicts during AI code generation
|
||||
- **Diff View** - Visual representation of AI-made changes
|
||||
- **Git Integration** - Clone, import, and deployment capabilities
|
||||
- **Expo App Creation** - React Native development support
|
||||
- **Voice Prompting** - Audio input for prompts
|
||||
- **Bulk Chat Operations** - Delete multiple chats at once
|
||||
- **Project Snapshot Restoration** - Restore projects from snapshots on reload
|
||||
|
||||
### 🔄 In Progress / Planned
|
||||
- **File Locking & Diff Improvements** - Enhanced conflict prevention
|
||||
- **Backend Agent Architecture** - Move from single model calls to agent-based system
|
||||
- **LLM Prompt Optimization** - Better performance for smaller models
|
||||
- **Project Planning Documentation** - LLM-generated project plans in markdown
|
||||
- **VSCode Integration** - Git-like confirmations and workflows
|
||||
- **Document Upload for Knowledge** - Reference materials and coding style guides
|
||||
- **Additional Provider Integrations** - Azure OpenAI, Vertex AI, Granite
|
||||
- ✅ OpenRouter Integration (@coleam00)
|
||||
- ✅ Gemini Integration (@jonathands)
|
||||
- ✅ Autogenerate Ollama models from what is downloaded (@yunatamos)
|
||||
- ✅ Filter models by provider (@jasonm23)
|
||||
- ✅ Download project as ZIP (@fabwaseem)
|
||||
- ✅ Improvements to the main bolt.new prompt in `app\lib\.server\llm\prompts.ts` (@kofi-bhr)
|
||||
- ✅ DeepSeek API Integration (@zenith110)
|
||||
- ✅ Mistral API Integration (@ArulGandhi)
|
||||
- ✅ "Open AI Like" API Integration (@ZerxZ)
|
||||
- ✅ Ability to sync files (one way sync) to local folder (@muzafferkadir)
|
||||
- ✅ Containerize the application with Docker for easy installation (@aaronbolton)
|
||||
- ✅ Publish projects directly to GitHub (@goncaloalves)
|
||||
- ✅ Ability to enter API keys in the UI (@ali00209)
|
||||
- ✅ xAI Grok Beta Integration (@milutinke)
|
||||
- ✅ LM Studio Integration (@karrot0)
|
||||
- ✅ HuggingFace Integration (@ahsan3219)
|
||||
- ✅ Bolt terminal to see the output of LLM run commands (@thecodacus)
|
||||
- ✅ Streaming of code output (@thecodacus)
|
||||
- ✅ Ability to revert code to earlier version (@wonderwhy-er)
|
||||
- ✅ Chat history backup and restore functionality (@sidbetatester)
|
||||
- ✅ Cohere Integration (@hasanraiyan)
|
||||
- ✅ Dynamic model max token length (@hasanraiyan)
|
||||
- ✅ Better prompt enhancing (@SujalXplores)
|
||||
- ✅ Prompt caching (@SujalXplores)
|
||||
- ✅ Load local projects into the app (@wonderwhy-er)
|
||||
- ✅ Together Integration (@mouimet-infinisoft)
|
||||
- ✅ Mobile friendly (@qwikode)
|
||||
- ✅ Better prompt enhancing (@SujalXplores)
|
||||
- ✅ Attach images to prompts (@atrokhym)(@stijnus)
|
||||
- ✅ Added Git Clone button (@thecodacus)
|
||||
- ✅ Git Import from url (@thecodacus)
|
||||
- ✅ PromptLibrary to have different variations of prompts for different use cases (@thecodacus)
|
||||
- ✅ Detect package.json and commands to auto install & run preview for folder and git import (@wonderwhy-er)
|
||||
- ✅ Selection tool to target changes visually (@emcconnell)
|
||||
- ✅ Detect terminal Errors and ask bolt to fix it (@thecodacus)
|
||||
- ✅ Detect preview Errors and ask bolt to fix it (@wonderwhy-er)
|
||||
- ✅ Add Starter Template Options (@thecodacus)
|
||||
- ✅ Perplexity Integration (@meetpateltech)
|
||||
- ✅ AWS Bedrock Integration (@kunjabijukchhe)
|
||||
- ⬜ **HIGH PRIORITY** - Prevent bolt from rewriting files as often (file locking and diffs)
|
||||
- ⬜ **HIGH PRIORITY** - Better prompting for smaller LLMs (code window sometimes doesn't start)
|
||||
- ⬜ **HIGH PRIORITY** - Run agents in the backend as opposed to a single model call
|
||||
- ⬜ Deploy directly to Vercel/Netlify/other similar platforms
|
||||
- ⬜ Have LLM plan the project in a MD file for better results/transparency
|
||||
- ⬜ VSCode Integration with git-like confirmations
|
||||
- ⬜ Upload documents for knowledge - UI design templates, a code base to reference coding style, etc.
|
||||
- ⬜ Voice prompting
|
||||
- ⬜ Azure Open AI API Integration
|
||||
- ⬜ Vertex AI Integration
|
||||
- ⬜ Granite Integration
|
||||
- ✅ Popout Window for Web Container(@stijnus)
|
||||
- ✅ Ability to change Popout window size (@stijnus)
|
||||
|
||||
## Features
|
||||
|
||||
- **AI-powered full-stack web development** for **NodeJS based applications** directly in your browser.
|
||||
- **Support for 19+ LLMs** with an extensible architecture to integrate additional models.
|
||||
- **Support for multiple LLMs** with an extensible architecture to integrate additional models.
|
||||
- **Attach images to prompts** for better contextual understanding.
|
||||
- **Integrated terminal** to view output of LLM-run commands.
|
||||
- **Revert code to earlier versions** for easier debugging and quicker changes.
|
||||
- **Download projects as ZIP** for easy portability and sync to a folder on the host.
|
||||
- **Download projects as ZIP** for easy portability.
|
||||
- **Integration-ready Docker support** for a hassle-free setup.
|
||||
- **Deploy directly** to **Netlify**, **Vercel**, or **GitHub Pages**.
|
||||
- **Electron desktop app** for native desktop experience.
|
||||
- **Data visualization and analysis** with integrated charts and graphs.
|
||||
- **Git integration** with clone, import, and deployment capabilities.
|
||||
- **MCP (Model Context Protocol)** support for enhanced AI tool integration.
|
||||
- **Search functionality** to search through your codebase.
|
||||
- **File locking system** to prevent conflicts during AI code generation.
|
||||
- **Diff view** to see changes made by the AI.
|
||||
- **Supabase integration** for database management and queries.
|
||||
- **Expo app creation** for React Native development.
|
||||
|
||||
## Setup
|
||||
|
||||
@@ -94,20 +111,17 @@ If you're new to installing software from GitHub, don't worry! If you encounter
|
||||
|
||||
Let's get you up and running with the stable version of Bolt.DIY!
|
||||
|
||||
## Quick Installation
|
||||
## Quick Download
|
||||
|
||||
[](https://github.com/stackblitz-labs/bolt.diy/releases/latest) ← Click here to go to the latest release version!
|
||||
[](https://github.com/stackblitz-labs/bolt.diy/releases/latest) ← Click here to go the the latest release version!
|
||||
|
||||
- Download the binary for your platform (available for Windows, macOS, and Linux)
|
||||
- **Note**: For macOS, if you get the error "This app is damaged", run:
|
||||
```bash
|
||||
xattr -cr /path/to/Bolt.app
|
||||
```
|
||||
- Next **click source.zip**
|
||||
|
||||
## Manual installation
|
||||
## Prerequisites
|
||||
|
||||
Before you begin, you'll need to install two important pieces of software:
|
||||
|
||||
### Option 1: Node.js
|
||||
### Install Node.js
|
||||
|
||||
Node.js is required to run the application.
|
||||
|
||||
@@ -154,205 +168,61 @@ You have two options for running Bolt.DIY: directly on your machine or using Doc
|
||||
|
||||
### Option 2: Using Docker
|
||||
|
||||
This option requires Docker and is great when you want an isolated environment or to mirror the production image.
|
||||
This option requires some familiarity with Docker but provides a more isolated environment.
|
||||
|
||||
#### Additional Prerequisite
|
||||
|
||||
- Install Docker: [Download Docker](https://www.docker.com/)
|
||||
|
||||
#### Steps
|
||||
#### Steps:
|
||||
|
||||
1. **Prepare Environment Variables**
|
||||
|
||||
Copy the provided examples and add your provider keys:
|
||||
1. **Build the Docker Image**:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
cp .env.example .env.local
|
||||
# Using npm script:
|
||||
npm run dockerbuild
|
||||
|
||||
# OR using direct Docker command:
|
||||
docker build . --target bolt-ai-development
|
||||
```
|
||||
|
||||
The runtime scripts inside the container source `.env` and `.env.local`, so keep any API keys you need in one of those files.
|
||||
|
||||
2. **Build an Image**
|
||||
|
||||
2. **Run the Container**:
|
||||
```bash
|
||||
# Development image (bind-mounts your local source when run)
|
||||
pnpm run dockerbuild
|
||||
# ≈ docker build -t bolt-ai:development -t bolt-ai:latest --target development .
|
||||
|
||||
# Production image (self-contained build artifacts)
|
||||
pnpm run dockerbuild:prod
|
||||
# ≈ docker build -t bolt-ai:production -t bolt-ai:latest --target bolt-ai-production .
|
||||
```
|
||||
|
||||
3. **Run the Container**
|
||||
|
||||
```bash
|
||||
# Development workflow with hot reload
|
||||
docker compose --profile development up
|
||||
|
||||
# Production-style container using composed services
|
||||
docker compose --profile production up
|
||||
|
||||
# One-off production container (exposes the app on port 5173)
|
||||
docker run --rm -p 5173:5173 --env-file .env.local bolt-ai:latest
|
||||
```
|
||||
|
||||
When the container starts it runs `pnpm run dockerstart`, which in turn executes `bindings.sh` to pass Cloudflare bindings through Wrangler. You can override this command in `docker-compose.yaml` if you need a different startup routine.
|
||||
|
||||
### Option 3: Desktop Application (Electron)
|
||||
|
||||
For users who prefer a native desktop experience, bolt.diy is also available as an Electron desktop application:
|
||||
|
||||
1. **Download the Desktop App**:
|
||||
- Visit the [latest release](https://github.com/stackblitz-labs/bolt.diy/releases/latest)
|
||||
- Download the appropriate binary for your operating system
|
||||
- For macOS: Extract and run the `.dmg` file
|
||||
- For Windows: Run the `.exe` installer
|
||||
- For Linux: Extract and run the AppImage or install the `.deb` package
|
||||
|
||||
2. **Alternative**: Build from Source:
|
||||
```bash
|
||||
# Install dependencies
|
||||
pnpm install
|
||||
|
||||
# Build the Electron app
|
||||
pnpm electron:build:dist # For all platforms
|
||||
# OR platform-specific:
|
||||
pnpm electron:build:mac # macOS
|
||||
pnpm electron:build:win # Windows
|
||||
pnpm electron:build:linux # Linux
|
||||
```
|
||||
|
||||
The desktop app provides the same full functionality as the web version with additional native features.
|
||||
|
||||
## Configuring API Keys and Providers
|
||||
|
||||
Bolt.diy features a modern, intuitive settings interface for managing AI providers and API keys. The settings are organized into dedicated panels for easy navigation and configuration.
|
||||
### Adding Your API Keys
|
||||
|
||||
### Accessing Provider Settings
|
||||
Setting up your API keys in Bolt.DIY is straightforward:
|
||||
|
||||
1. **Open Settings**: Click the settings icon (⚙️) in the sidebar to access the settings panel
|
||||
2. **Navigate to Providers**: Select the "Providers" tab from the settings menu
|
||||
3. **Choose Provider Type**: Switch between "Cloud Providers" and "Local Providers" tabs
|
||||
1. Open the home page (main interface)
|
||||
2. Select your desired provider from the dropdown menu
|
||||
3. Click the pencil (edit) icon
|
||||
4. Enter your API key in the secure input field
|
||||
|
||||
### Cloud Providers Configuration
|
||||

|
||||
|
||||
The Cloud Providers tab displays all cloud-based AI services in an organized card layout:
|
||||
### Configuring Custom Base URLs
|
||||
|
||||
#### Adding API Keys
|
||||
1. **Select Provider**: Browse the grid of available cloud providers (OpenAI, Anthropic, Google, etc.)
|
||||
2. **Toggle Provider**: Use the switch to enable/disable each provider
|
||||
3. **Set API Key**:
|
||||
- Click the provider card to expand its configuration
|
||||
- Click on the "API Key" field to enter edit mode
|
||||
- Paste your API key and press Enter to save
|
||||
- The interface shows real-time validation with green checkmarks for valid keys
|
||||
For providers that support custom base URLs (such as Ollama or LM Studio), follow these steps:
|
||||
|
||||
#### Advanced Features
|
||||
- **Bulk Toggle**: Use "Enable All Cloud" to toggle all cloud providers at once
|
||||
- **Visual Status**: Green checkmarks indicate properly configured providers
|
||||
- **Provider Icons**: Each provider has a distinctive icon for easy identification
|
||||
- **Descriptions**: Helpful descriptions explain each provider's capabilities
|
||||
1. Click the settings icon in the sidebar to open the settings menu
|
||||

|
||||
|
||||
### Local Providers Configuration
|
||||
2. Navigate to the "Providers" tab
|
||||
3. Search for your provider using the search bar
|
||||
4. Enter your custom base URL in the designated field
|
||||

|
||||
|
||||
The Local Providers tab manages local AI installations and custom endpoints:
|
||||
> **Note**: Custom base URLs are particularly useful when running local instances of AI models or using custom API endpoints.
|
||||
|
||||
#### Ollama Configuration
|
||||
1. **Enable Ollama**: Toggle the Ollama provider switch
|
||||
2. **Configure Endpoint**: Set the API endpoint (defaults to `http://127.0.0.1:11434`)
|
||||
3. **Model Management**:
|
||||
- View all installed models with size and parameter information
|
||||
- Update models to latest versions with one click
|
||||
- Delete unused models
|
||||
- Install new models by entering model names
|
||||
### Supported Providers
|
||||
|
||||
#### Other Local Providers
|
||||
- **LM Studio**: Configure custom base URLs for LM Studio endpoints
|
||||
- **OpenAI-like**: Connect to any OpenAI-compatible API endpoint
|
||||
- **Auto-detection**: The system automatically detects environment variables for base URLs
|
||||
|
||||
### Environment Variables vs UI Configuration
|
||||
|
||||
Bolt.diy supports both methods for maximum flexibility:
|
||||
|
||||
#### Environment Variables (Recommended for Production)
|
||||
Set API keys and base URLs in your `.env.local` file:
|
||||
```bash
|
||||
# API Keys
|
||||
OPENAI_API_KEY=your_openai_key_here
|
||||
ANTHROPIC_API_KEY=your_anthropic_key_here
|
||||
|
||||
# Custom Base URLs
|
||||
OLLAMA_BASE_URL=http://127.0.0.1:11434
|
||||
LMSTUDIO_BASE_URL=http://127.0.0.1:1234
|
||||
```
|
||||
|
||||
#### UI-Based Configuration
|
||||
- **Real-time Updates**: Changes take effect immediately
|
||||
- **Secure Storage**: API keys are stored securely in browser cookies
|
||||
- **Visual Feedback**: Clear indicators show configuration status
|
||||
- **Easy Management**: Edit, view, and manage keys through the interface
|
||||
|
||||
### Provider-Specific Features
|
||||
|
||||
#### OpenRouter
|
||||
- **Free Models Filter**: Toggle to show only free models when browsing
|
||||
- **Pricing Information**: View input/output costs for each model
|
||||
- **Model Search**: Fuzzy search through all available models
|
||||
|
||||
#### Ollama
|
||||
- **Model Installer**: Built-in interface to install new models
|
||||
- **Progress Tracking**: Real-time download progress for model updates
|
||||
- **Model Details**: View model size, parameters, and quantization levels
|
||||
- **Auto-refresh**: Automatically detects newly installed models
|
||||
|
||||
#### Search & Navigation
|
||||
- **Fuzzy Search**: Type-ahead search across all providers and models
|
||||
- **Keyboard Navigation**: Use arrow keys and Enter to navigate quickly
|
||||
- **Clear Search**: Press `Cmd+K` (Mac) or `Ctrl+K` (Windows/Linux) to clear search
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
#### Common Issues
|
||||
- **API Key Not Recognized**: Ensure you're using the correct API key format for each provider
|
||||
- **Base URL Issues**: Verify the endpoint URL is correct and accessible
|
||||
- **Model Not Loading**: Check that the provider is enabled and properly configured
|
||||
- **Environment Variables Not Working**: Restart the application after adding new environment variables
|
||||
|
||||
#### Status Indicators
|
||||
- 🟢 **Green Checkmark**: Provider properly configured and ready to use
|
||||
- 🔴 **Red X**: Configuration missing or invalid
|
||||
- 🟡 **Yellow Indicator**: Provider enabled but may need additional setup
|
||||
- 🔵 **Blue Pencil**: Click to edit configuration
|
||||
|
||||
### Supported Providers Overview
|
||||
|
||||
#### Cloud Providers
|
||||
- **OpenAI** - GPT-4, GPT-3.5, and other OpenAI models
|
||||
- **Anthropic** - Claude 3.5 Sonnet, Claude 3 Opus, and other Claude models
|
||||
- **Google (Gemini)** - Gemini 1.5 Pro, Gemini 1.5 Flash, and other Gemini models
|
||||
- **Groq** - Fast inference with Llama, Mixtral, and other models
|
||||
- **xAI** - Grok models including Grok-2 and Grok-2 Vision
|
||||
- **DeepSeek** - DeepSeek Coder and other DeepSeek models
|
||||
- **Mistral** - Mixtral, Mistral 7B, and other Mistral models
|
||||
- **Cohere** - Command R, Command R+, and other Cohere models
|
||||
- **Together AI** - Various open-source models
|
||||
- **Perplexity** - Sonar models for search and reasoning
|
||||
- **HuggingFace** - Access to HuggingFace model hub
|
||||
- **OpenRouter** - Unified API for multiple model providers
|
||||
- **Moonshot (Kimi)** - Kimi AI models
|
||||
- **Hyperbolic** - High-performance model inference
|
||||
- **GitHub Models** - Models available through GitHub
|
||||
- **Amazon Bedrock** - AWS managed AI models
|
||||
|
||||
#### Local Providers
|
||||
- **Ollama** - Run open-source models locally with advanced model management
|
||||
- **LM Studio** - Local model inference with LM Studio
|
||||
- **OpenAI-like** - Connect to any OpenAI-compatible API endpoint
|
||||
|
||||
> **💡 Pro Tip**: Start with OpenAI or Anthropic for the best results, then explore other providers based on your specific needs and budget considerations.
|
||||
- Ollama
|
||||
- LM Studio
|
||||
- OpenAILike
|
||||
|
||||
## Setup Using Git (For Developers only)
|
||||
|
||||
@@ -372,7 +242,8 @@ This method is recommended for developers who want to:
|
||||
1. **Clone the Repository**:
|
||||
|
||||
```bash
|
||||
git clone -b stable https://github.com/stackblitz-labs/bolt.diy.git
|
||||
# Using HTTPS
|
||||
git clone https://github.com/stackblitz-labs/bolt.diy.git
|
||||
```
|
||||
|
||||
2. **Navigate to Project Directory**:
|
||||
@@ -381,30 +252,20 @@ This method is recommended for developers who want to:
|
||||
cd bolt.diy
|
||||
```
|
||||
|
||||
3. **Install Dependencies**:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
4. **Start the Development Server**:
|
||||
```bash
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
5. **(OPTIONAL)** Switch to the Main Branch if you want to use pre-release/testbranch:
|
||||
3. **Switch to the Main Branch**:
|
||||
```bash
|
||||
git checkout main
|
||||
```
|
||||
4. **Install Dependencies**:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
5. **Start the Development Server**:
|
||||
```bash
|
||||
pnpm run dev
|
||||
```
|
||||
Hint: Be aware that this can have beta-features and more likely got bugs than the stable release
|
||||
|
||||
>**Open the WebUI to test (Default: http://localhost:5173)**
|
||||
> - Beginners:
|
||||
> - Try to use a sophisticated Provider/Model like Anthropic with Claude Sonnet 3.x Models to get best results
|
||||
> - Explanation: The System Prompt currently implemented in bolt.diy cant cover the best performance for all providers and models out there. So it works better with some models, then other, even if the models itself are perfect for >programming
|
||||
> - Future: Planned is a Plugin/Extentions-Library so there can be different System Prompts for different Models, which will help to get better results
|
||||
|
||||
#### Staying Updated
|
||||
|
||||
@@ -419,7 +280,7 @@ To get the latest changes from the repository:
|
||||
2. **Pull Latest Updates**:
|
||||
|
||||
```bash
|
||||
git pull
|
||||
git pull origin main
|
||||
```
|
||||
|
||||
3. **Update Dependencies**:
|
||||
@@ -470,25 +331,7 @@ Remember to always commit your local changes or stash them before pulling update
|
||||
- **`pnpm run typecheck`**: Runs TypeScript type checking.
|
||||
- **`pnpm run typegen`**: Generates TypeScript types using Wrangler.
|
||||
- **`pnpm run deploy`**: Deploys the project to Cloudflare Pages.
|
||||
- **`pnpm run lint`**: Runs ESLint to check for code issues.
|
||||
- **`pnpm run lint:fix`**: Automatically fixes linting issues.
|
||||
- **`pnpm run clean`**: Cleans build artifacts and cache.
|
||||
- **`pnpm run prepare`**: Sets up husky for git hooks.
|
||||
- **Docker Scripts**:
|
||||
- **`pnpm run dockerbuild`**: Builds the Docker image for development.
|
||||
- **`pnpm run dockerbuild:prod`**: Builds the Docker image for production.
|
||||
- **`pnpm run dockerrun`**: Runs the Docker container.
|
||||
- **`pnpm run dockerstart`**: Starts the Docker container with proper bindings.
|
||||
- **Electron Scripts**:
|
||||
- **`pnpm electron:build:deps`**: Builds Electron main and preload scripts.
|
||||
- **`pnpm electron:build:main`**: Builds the Electron main process.
|
||||
- **`pnpm electron:build:preload`**: Builds the Electron preload script.
|
||||
- **`pnpm electron:build:renderer`**: Builds the Electron renderer.
|
||||
- **`pnpm electron:build:unpack`**: Creates an unpacked Electron build.
|
||||
- **`pnpm electron:build:mac`**: Builds for macOS.
|
||||
- **`pnpm electron:build:win`**: Builds for Windows.
|
||||
- **`pnpm electron:build:linux`**: Builds for Linux.
|
||||
- **`pnpm electron:build:dist`**: Builds for all platforms.
|
||||
|
||||
---
|
||||
|
||||
@@ -507,10 +350,3 @@ Explore upcoming features and priorities on our [Roadmap](https://roadmap.sh/r/o
|
||||
## FAQ
|
||||
|
||||
For answers to common questions, issues, and to see a list of recommended models, visit our [FAQ Page](FAQ.md).
|
||||
|
||||
|
||||
# Licensing
|
||||
**Who needs a commercial WebContainer API license?**
|
||||
|
||||
bolt.diy source code is distributed as MIT, but it uses WebContainers API that [requires licensing](https://webcontainers.io/enterprise) for production usage in a commercial, for-profit setting. (Prototypes or POCs do not require a commercial license.) If you're using the API to meet the needs of your customers, prospective customers, and/or employees, you need a license to ensure compliance with our Terms of Service. Usage of the API in violation of these terms may result in your access being revoked.
|
||||
# Test commit to trigger Security Analysis workflow
|
||||
|
||||
@@ -5,6 +5,12 @@ import { classNames } from '~/utils/classNames';
|
||||
import { profileStore } from '~/lib/stores/profile';
|
||||
import type { TabType, Profile } from './types';
|
||||
|
||||
const BetaLabel = () => (
|
||||
<span className="px-1.5 py-0.5 rounded-full bg-purple-500/10 dark:bg-purple-500/20 text-[10px] font-medium text-purple-600 dark:text-purple-400 ml-2">
|
||||
BETA
|
||||
</span>
|
||||
);
|
||||
|
||||
interface AvatarDropdownProps {
|
||||
onSelectTab: (tab: TabType) => void;
|
||||
}
|
||||
@@ -30,7 +36,7 @@ export const AvatarDropdown = ({ onSelectTab }: AvatarDropdownProps) => {
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full rounded-full flex items-center justify-center bg-white dark:bg-gray-800 text-gray-400 dark:text-gray-500">
|
||||
<div className="i-ph:user w-6 h-6" />
|
||||
<div className="i-ph:question w-6 h-6" />
|
||||
</div>
|
||||
)}
|
||||
</motion.button>
|
||||
@@ -66,7 +72,7 @@ export const AvatarDropdown = ({ onSelectTab }: AvatarDropdownProps) => {
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center text-gray-400 dark:text-gray-500 font-medium text-lg">
|
||||
<div className="i-ph:user w-6 h-6" />
|
||||
<span className="relative -top-0.5">?</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -122,12 +128,11 @@ export const AvatarDropdown = ({ onSelectTab }: AvatarDropdownProps) => {
|
||||
'outline-none',
|
||||
'group',
|
||||
)}
|
||||
onClick={() =>
|
||||
window.open('https://github.com/stackblitz-labs/bolt.diy/issues/new?template=bug_report.yml', '_blank')
|
||||
}
|
||||
onClick={() => onSelectTab('task-manager')}
|
||||
>
|
||||
<div className="i-ph:bug w-4 h-4 text-gray-400 group-hover:text-purple-500 dark:group-hover:text-purple-400 transition-colors" />
|
||||
Report Bug
|
||||
<div className="i-ph:activity w-4 h-4 text-gray-400 group-hover:text-purple-500 dark:group-hover:text-purple-400 transition-colors" />
|
||||
Task Manager
|
||||
<BetaLabel />
|
||||
</DropdownMenu.Item>
|
||||
|
||||
<DropdownMenu.Item
|
||||
@@ -140,33 +145,11 @@ export const AvatarDropdown = ({ onSelectTab }: AvatarDropdownProps) => {
|
||||
'outline-none',
|
||||
'group',
|
||||
)}
|
||||
onClick={async () => {
|
||||
try {
|
||||
const { downloadDebugLog } = await import('~/utils/debugLogger');
|
||||
await downloadDebugLog();
|
||||
} catch (error) {
|
||||
console.error('Failed to download debug log:', error);
|
||||
}
|
||||
}}
|
||||
onClick={() => onSelectTab('service-status')}
|
||||
>
|
||||
<div className="i-ph:download w-4 h-4 text-gray-400 group-hover:text-purple-500 dark:group-hover:text-purple-400 transition-colors" />
|
||||
Download Debug Log
|
||||
</DropdownMenu.Item>
|
||||
|
||||
<DropdownMenu.Item
|
||||
className={classNames(
|
||||
'flex items-center gap-2 px-4 py-2.5',
|
||||
'text-sm text-gray-700 dark:text-gray-200',
|
||||
'hover:bg-purple-50 dark:hover:bg-purple-500/10',
|
||||
'hover:text-purple-500 dark:hover:text-purple-400',
|
||||
'cursor-pointer transition-all duration-200',
|
||||
'outline-none',
|
||||
'group',
|
||||
)}
|
||||
onClick={() => window.open('https://stackblitz-labs.github.io/bolt.diy/', '_blank')}
|
||||
>
|
||||
<div className="i-ph:question w-4 h-4 text-gray-400 group-hover:text-purple-500 dark:group-hover:text-purple-400 transition-colors" />
|
||||
Help & Documentation
|
||||
<div className="i-ph:heartbeat w-4 h-4 text-gray-400 group-hover:text-purple-500 dark:group-hover:text-purple-400 transition-colors" />
|
||||
Service Status
|
||||
<BetaLabel />
|
||||
</DropdownMenu.Item>
|
||||
</DropdownMenu.Content>
|
||||
</DropdownMenu.Portal>
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
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 '~/utils/classNames';
|
||||
import { TabManagement } from '~/components/@settings/shared/components/TabManagement';
|
||||
import { TabTile } from '~/components/@settings/shared/components/TabTile';
|
||||
import { useUpdateCheck } from '~/lib/hooks/useUpdateCheck';
|
||||
import { useFeatures } from '~/lib/hooks/useFeatures';
|
||||
import { useNotifications } from '~/lib/hooks/useNotifications';
|
||||
import { useConnectionStatus } from '~/lib/hooks/useConnectionStatus';
|
||||
import { tabConfigurationStore, resetTabConfiguration } from '~/lib/stores/settings';
|
||||
import { useDebugStatus } from '~/lib/hooks/useDebugStatus';
|
||||
import {
|
||||
tabConfigurationStore,
|
||||
developerModeStore,
|
||||
setDeveloperMode,
|
||||
resetTabConfiguration,
|
||||
} from '~/lib/stores/settings';
|
||||
import { profileStore } from '~/lib/stores/profile';
|
||||
import type { TabType, Profile } from './types';
|
||||
import { TAB_LABELS, DEFAULT_TAB_CONFIG, TAB_DESCRIPTIONS } from './constants';
|
||||
import type { TabType, TabVisibilityConfig, Profile } from './types';
|
||||
import { TAB_LABELS, DEFAULT_TAB_CONFIG } from './constants';
|
||||
import { DialogTitle } from '~/components/ui/Dialog';
|
||||
import { AvatarDropdown } from './AvatarDropdown';
|
||||
import BackgroundRays from '~/components/ui/BackgroundRays';
|
||||
@@ -19,24 +29,62 @@ import ProfileTab from '~/components/@settings/tabs/profile/ProfileTab';
|
||||
import SettingsTab from '~/components/@settings/tabs/settings/SettingsTab';
|
||||
import NotificationsTab from '~/components/@settings/tabs/notifications/NotificationsTab';
|
||||
import FeaturesTab from '~/components/@settings/tabs/features/FeaturesTab';
|
||||
import { DataTab } from '~/components/@settings/tabs/data/DataTab';
|
||||
import DataTab from '~/components/@settings/tabs/data/DataTab';
|
||||
import DebugTab from '~/components/@settings/tabs/debug/DebugTab';
|
||||
import { EventLogsTab } from '~/components/@settings/tabs/event-logs/EventLogsTab';
|
||||
import GitHubTab from '~/components/@settings/tabs/github/GitHubTab';
|
||||
import GitLabTab from '~/components/@settings/tabs/gitlab/GitLabTab';
|
||||
import SupabaseTab from '~/components/@settings/tabs/supabase/SupabaseTab';
|
||||
import VercelTab from '~/components/@settings/tabs/vercel/VercelTab';
|
||||
import NetlifyTab from '~/components/@settings/tabs/netlify/NetlifyTab';
|
||||
import UpdateTab from '~/components/@settings/tabs/update/UpdateTab';
|
||||
import ConnectionsTab from '~/components/@settings/tabs/connections/ConnectionsTab';
|
||||
import CloudProvidersTab from '~/components/@settings/tabs/providers/cloud/CloudProvidersTab';
|
||||
import ServiceStatusTab from '~/components/@settings/tabs/providers/status/ServiceStatusTab';
|
||||
import LocalProvidersTab from '~/components/@settings/tabs/providers/local/LocalProvidersTab';
|
||||
import McpTab from '~/components/@settings/tabs/mcp/McpTab';
|
||||
import TaskManagerTab from '~/components/@settings/tabs/task-manager/TaskManagerTab';
|
||||
|
||||
interface ControlPanelProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
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<TabType, string> = {
|
||||
profile: 'Manage your profile and account settings',
|
||||
settings: 'Configure application preferences',
|
||||
notifications: 'View and manage your notifications',
|
||||
features: 'Explore new and upcoming features',
|
||||
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<TabType>(['local-providers', 'mcp']);
|
||||
const BETA_TABS = new Set<TabType>(['task-manager', 'service-status', 'update', 'local-providers']);
|
||||
|
||||
const BetaLabel = () => (
|
||||
<div className="absolute top-2 right-2 px-1.5 py-0.5 rounded-full bg-purple-500/10 dark:bg-purple-500/20">
|
||||
@@ -44,6 +92,66 @@ const BetaLabel = () => (
|
||||
</div>
|
||||
);
|
||||
|
||||
const AnimatedSwitch = ({ checked, onCheckedChange, id, label }: AnimatedSwitchProps) => {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id={id}
|
||||
checked={checked}
|
||||
onCheckedChange={onCheckedChange}
|
||||
className={classNames(
|
||||
'relative inline-flex h-6 w-11 items-center rounded-full',
|
||||
'transition-all duration-300 ease-[cubic-bezier(0.87,_0,_0.13,_1)]',
|
||||
'bg-gray-200 dark:bg-gray-700',
|
||||
'data-[state=checked]:bg-purple-500',
|
||||
'focus:outline-none focus:ring-2 focus:ring-purple-500/20',
|
||||
'cursor-pointer',
|
||||
'group',
|
||||
)}
|
||||
>
|
||||
<motion.span
|
||||
className={classNames(
|
||||
'absolute left-[2px] top-[2px]',
|
||||
'inline-block h-5 w-5 rounded-full',
|
||||
'bg-white shadow-lg',
|
||||
'transition-shadow duration-300',
|
||||
'group-hover:shadow-md group-active:shadow-sm',
|
||||
'group-hover:scale-95 group-active:scale-90',
|
||||
)}
|
||||
initial={false}
|
||||
transition={{
|
||||
type: 'spring',
|
||||
stiffness: 500,
|
||||
damping: 30,
|
||||
duration: 0.2,
|
||||
}}
|
||||
animate={{
|
||||
x: checked ? '1.25rem' : '0rem',
|
||||
}}
|
||||
>
|
||||
<motion.div
|
||||
className="absolute inset-0 rounded-full bg-white"
|
||||
initial={false}
|
||||
animate={{
|
||||
scale: checked ? 1 : 0.8,
|
||||
}}
|
||||
transition={{ duration: 0.2 }}
|
||||
/>
|
||||
</motion.span>
|
||||
<span className="sr-only">Toggle {label}</span>
|
||||
</Switch>
|
||||
<div className="flex items-center gap-2">
|
||||
<label
|
||||
htmlFor={id}
|
||||
className="text-sm text-gray-500 dark:text-gray-400 select-none cursor-pointer whitespace-nowrap w-[88px]"
|
||||
>
|
||||
{label}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
|
||||
// State
|
||||
const [activeTab, setActiveTab] = useState<TabType | null>(null);
|
||||
@@ -52,12 +160,15 @@ 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(() => {
|
||||
@@ -75,6 +186,41 @@ 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<TabType>();
|
||||
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) => {
|
||||
@@ -89,7 +235,33 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
|
||||
return tab.visible && tab.window === 'user';
|
||||
})
|
||||
.sort((a, b) => a.order - b.order);
|
||||
}, [tabConfiguration, profile?.preferences?.notifications, baseTabConfig]);
|
||||
}, [tabConfiguration, developerMode, profile?.preferences?.notifications, baseTabConfig]);
|
||||
|
||||
// Optimize animation performance with layout animations
|
||||
const gridLayoutVariants = {
|
||||
hidden: { opacity: 0 },
|
||||
visible: {
|
||||
opacity: 1,
|
||||
transition: {
|
||||
staggerChildren: 0.05,
|
||||
delayChildren: 0.1,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const itemVariants = {
|
||||
hidden: { opacity: 0, scale: 0.8 },
|
||||
visible: {
|
||||
opacity: 1,
|
||||
scale: 1,
|
||||
transition: {
|
||||
type: 'spring',
|
||||
stiffness: 200,
|
||||
damping: 20,
|
||||
mass: 0.6,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Reset to default view when modal opens/closes
|
||||
useEffect(() => {
|
||||
@@ -121,7 +293,21 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
|
||||
}
|
||||
};
|
||||
|
||||
const getTabComponent = (tabId: TabType) => {
|
||||
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 <TabManagement />;
|
||||
}
|
||||
|
||||
switch (tabId) {
|
||||
case 'profile':
|
||||
return <ProfileTab />;
|
||||
@@ -137,21 +323,18 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
|
||||
return <CloudProvidersTab />;
|
||||
case 'local-providers':
|
||||
return <LocalProvidersTab />;
|
||||
case 'github':
|
||||
return <GitHubTab />;
|
||||
case 'gitlab':
|
||||
return <GitLabTab />;
|
||||
case 'supabase':
|
||||
return <SupabaseTab />;
|
||||
case 'vercel':
|
||||
return <VercelTab />;
|
||||
case 'netlify':
|
||||
return <NetlifyTab />;
|
||||
case 'connection':
|
||||
return <ConnectionsTab />;
|
||||
case 'debug':
|
||||
return <DebugTab />;
|
||||
case 'event-logs':
|
||||
return <EventLogsTab />;
|
||||
case 'mcp':
|
||||
return <McpTab />;
|
||||
|
||||
case 'update':
|
||||
return <UpdateTab />;
|
||||
case 'task-manager':
|
||||
return <TaskManagerTab />;
|
||||
case 'service-status':
|
||||
return <ServiceStatusTab />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
@@ -159,16 +342,16 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
|
||||
|
||||
const getTabUpdateStatus = (tabId: TabType): boolean => {
|
||||
switch (tabId) {
|
||||
case 'update':
|
||||
return hasUpdate;
|
||||
case 'features':
|
||||
return hasNewFeatures;
|
||||
case 'notifications':
|
||||
return hasUnreadNotifications;
|
||||
case 'github':
|
||||
case 'gitlab':
|
||||
case 'supabase':
|
||||
case 'vercel':
|
||||
case 'netlify':
|
||||
case 'connection':
|
||||
return hasConnectionIssues;
|
||||
case 'debug':
|
||||
return hasActiveWarnings;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
@@ -176,20 +359,24 @@ 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':
|
||||
return `${unreadNotifications.length} unread notification${unreadNotifications.length === 1 ? '' : 's'}`;
|
||||
case 'github':
|
||||
case 'gitlab':
|
||||
case 'supabase':
|
||||
case 'vercel':
|
||||
case 'netlify':
|
||||
case 'connection':
|
||||
return currentIssue === 'disconnected'
|
||||
? 'Connection lost'
|
||||
: 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 '';
|
||||
}
|
||||
@@ -202,19 +389,21 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
|
||||
|
||||
// Acknowledge notifications based on tab
|
||||
switch (tabId) {
|
||||
case 'update':
|
||||
acknowledgeUpdate();
|
||||
break;
|
||||
case 'features':
|
||||
acknowledgeAllFeatures();
|
||||
break;
|
||||
case 'notifications':
|
||||
markAllAsRead();
|
||||
break;
|
||||
case 'github':
|
||||
case 'gitlab':
|
||||
case 'supabase':
|
||||
case 'vercel':
|
||||
case 'netlify':
|
||||
case 'connection':
|
||||
acknowledgeIssue();
|
||||
break;
|
||||
case 'debug':
|
||||
acknowledgeAllIssues();
|
||||
break;
|
||||
}
|
||||
|
||||
// Clear loading state after a delay
|
||||
@@ -224,8 +413,16 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
|
||||
return (
|
||||
<RadixDialog.Root open={open}>
|
||||
<RadixDialog.Portal>
|
||||
<div className="fixed inset-0 flex items-center justify-center z-[100] modern-scrollbar">
|
||||
<RadixDialog.Overlay className="absolute inset-0 bg-black/70 dark:bg-black/80 backdrop-blur-sm transition-opacity duration-200" />
|
||||
<div className="fixed inset-0 flex items-center justify-center z-[100]">
|
||||
<RadixDialog.Overlay asChild>
|
||||
<motion.div
|
||||
className="absolute inset-0 bg-black/50 backdrop-blur-sm"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
/>
|
||||
</RadixDialog.Overlay>
|
||||
|
||||
<RadixDialog.Content
|
||||
aria-describedby={undefined}
|
||||
@@ -233,17 +430,19 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
|
||||
onPointerDownOutside={handleClose}
|
||||
className="relative z-[101]"
|
||||
>
|
||||
<div
|
||||
<motion.div
|
||||
className={classNames(
|
||||
'w-[1200px] h-[90vh]',
|
||||
'bg-bolt-elements-background-depth-1',
|
||||
'bg-[#FAFAFA] dark:bg-[#0A0A0A]',
|
||||
'rounded-2xl shadow-2xl',
|
||||
'border border-bolt-elements-borderColor',
|
||||
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
|
||||
'flex flex-col overflow-hidden',
|
||||
'relative',
|
||||
'transform transition-all duration-200 ease-out',
|
||||
open ? 'opacity-100 scale-100 translate-y-0' : 'opacity-0 scale-95 translate-y-4',
|
||||
)}
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div className="absolute inset-0 overflow-hidden rounded-2xl">
|
||||
<BackgroundRays />
|
||||
@@ -255,7 +454,7 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
|
||||
{(activeTab || showTabManagement) && (
|
||||
<button
|
||||
onClick={handleBack}
|
||||
className="flex items-center justify-center w-8 h-8 rounded-full bg-transparent hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-colors duration-150"
|
||||
className="flex items-center justify-center w-8 h-8 rounded-full bg-transparent hover:bg-purple-500/10 dark:hover:bg-purple-500/20 group transition-all duration-200"
|
||||
>
|
||||
<div className="i-ph:arrow-left w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-purple-500 transition-colors" />
|
||||
</button>
|
||||
@@ -266,8 +465,18 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-6">
|
||||
{/* Mode Toggle */}
|
||||
<div className="flex items-center gap-2 min-w-[140px] border-r border-gray-200 dark:border-gray-800 pr-6">
|
||||
<AnimatedSwitch
|
||||
id="developer-mode"
|
||||
checked={developerMode}
|
||||
onCheckedChange={handleDeveloperModeChange}
|
||||
label={developerMode ? 'Developer Mode' : 'User Mode'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Avatar and Dropdown */}
|
||||
<div className="pl-6">
|
||||
<div className="border-l border-gray-200 dark:border-gray-800 pl-6">
|
||||
<AvatarDropdown onSelectTab={handleTabClick} />
|
||||
</div>
|
||||
|
||||
@@ -295,48 +504,49 @@ export const ControlPanel = ({ open, onClose }: ControlPanelProps) => {
|
||||
'touch-auto',
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={classNames(
|
||||
'p-6 transition-opacity duration-150',
|
||||
activeTab || showTabManagement ? 'opacity-100' : 'opacity-100',
|
||||
)}
|
||||
<motion.div
|
||||
key={activeTab || 'home'}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="p-6"
|
||||
>
|
||||
{activeTab ? (
|
||||
{showTabManagement ? (
|
||||
<TabManagement />
|
||||
) : activeTab ? (
|
||||
getTabComponent(activeTab)
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 relative">
|
||||
{visibleTabs.map((tab, index) => (
|
||||
<div
|
||||
key={tab.id}
|
||||
className={classNames(
|
||||
'aspect-[1.5/1] transition-transform duration-100 ease-out',
|
||||
'hover:scale-[1.01]',
|
||||
)}
|
||||
style={{
|
||||
animationDelay: `${index * 30}ms`,
|
||||
animation: open ? 'fadeInUp 200ms ease-out forwards' : 'none',
|
||||
}}
|
||||
>
|
||||
<TabTile
|
||||
tab={tab}
|
||||
onClick={() => handleTabClick(tab.id as TabType)}
|
||||
isActive={activeTab === tab.id}
|
||||
hasUpdate={getTabUpdateStatus(tab.id)}
|
||||
statusMessage={getStatusMessage(tab.id)}
|
||||
description={TAB_DESCRIPTIONS[tab.id]}
|
||||
isLoading={loadingTab === tab.id}
|
||||
className="h-full relative"
|
||||
>
|
||||
{BETA_TABS.has(tab.id) && <BetaLabel />}
|
||||
</TabTile>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<motion.div
|
||||
className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 relative"
|
||||
variants={gridLayoutVariants}
|
||||
initial="hidden"
|
||||
animate="visible"
|
||||
>
|
||||
<AnimatePresence mode="popLayout">
|
||||
{(visibleTabs as TabWithDevType[]).map((tab: TabWithDevType) => (
|
||||
<motion.div key={tab.id} layout variants={itemVariants} className="aspect-[1.5/1]">
|
||||
<TabTile
|
||||
tab={tab}
|
||||
onClick={() => handleTabClick(tab.id as TabType)}
|
||||
isActive={activeTab === tab.id}
|
||||
hasUpdate={getTabUpdateStatus(tab.id)}
|
||||
statusMessage={getStatusMessage(tab.id)}
|
||||
description={TAB_DESCRIPTIONS[tab.id]}
|
||||
isLoading={loadingTab === tab.id}
|
||||
className="h-full relative"
|
||||
>
|
||||
{BETA_TABS.has(tab.id) && <BetaLabel />}
|
||||
</TabTile>
|
||||
</motion.div>
|
||||
))}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</RadixDialog.Content>
|
||||
</div>
|
||||
</RadixDialog.Portal>
|
||||
|
||||
88
app/components/@settings/core/constants.ts
Normal file
88
app/components/@settings/core/constants.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import type { TabType } from './types';
|
||||
|
||||
export const TAB_ICONS: Record<TabType, string> = {
|
||||
profile: 'i-ph:user-circle-fill',
|
||||
settings: 'i-ph:gear-six-fill',
|
||||
notifications: 'i-ph:bell-fill',
|
||||
features: 'i-ph:star-fill',
|
||||
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<TabType, string> = {
|
||||
profile: 'Profile',
|
||||
settings: 'Settings',
|
||||
notifications: 'Notifications',
|
||||
features: 'Features',
|
||||
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<TabType, string> = {
|
||||
profile: 'Manage your profile and account settings',
|
||||
settings: 'Configure application preferences',
|
||||
notifications: 'View and manage your notifications',
|
||||
features: 'Explore new and upcoming features',
|
||||
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 = [
|
||||
// User Window Tabs (Always visible by default)
|
||||
{ id: 'features', visible: true, window: 'user' as const, order: 0 },
|
||||
{ id: 'data', visible: true, window: 'user' as const, order: 1 },
|
||||
{ id: 'cloud-providers', visible: true, window: 'user' as const, order: 2 },
|
||||
{ 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 },
|
||||
];
|
||||
@@ -1,108 +0,0 @@
|
||||
import type { TabType } from './types';
|
||||
import { User, Settings, Bell, Star, Database, Cloud, Laptop, Github, Wrench, List } from 'lucide-react';
|
||||
|
||||
// GitLab icon component
|
||||
const GitLabIcon = () => (
|
||||
<svg viewBox="0 0 24 24" className="w-4 h-4">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M22.65 14.39L12 22.13 1.35 14.39a.84.84 0 0 1-.3-.94l1.22-3.78 2.44-7.51A.42.42 0 0 1 4.82 2a.43.43 0 0 1 .58 0 .42.42 0 0 1 .11.18l2.44 7.49h8.1l2.44-7.51A.42.42 0 0 1 18.6 2a.43.43 0 0 1 .58 0 .42.42 0 0 1 .11.18l2.44 7.51L23 13.45a.84.84 0 0 1-.35.94z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// Vercel icon component
|
||||
const VercelIcon = () => (
|
||||
<svg viewBox="0 0 24 24" className="w-4 h-4">
|
||||
<path fill="currentColor" d="M12 2L2 19.777h20L12 2z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
// Netlify icon component
|
||||
const NetlifyIcon = () => (
|
||||
<svg viewBox="0 0 24 24" className="w-4 h-4">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M16.934 8.519a1.044 1.044 0 0 1 .303-.23l2.349-1.045a.983.983 0 0 1 .905 0c.264.12.49.328.651.599l.518 1.065c.17.35.17.761 0 1.11l-.518 1.065a1.119 1.119 0 0 1-.651.599l-2.35 1.045a1.013 1.013 0 0 1-.904 0l-2.35-1.045a1.119 1.119 0 0 1-.651-.599L13.718 9.02a1.2 1.2 0 0 1 0-1.11l.518-1.065a1.119 1.119 0 0 1 .651-.599l2.35-1.045a.983.983 0 0 1 .697-.061zm-6.051 5.751a1.044 1.044 0 0 1 .303-.23l2.349-1.045a.983.983 0 0 1 .905 0c.264.12.49.328.651.599l.518 1.065c.17.35.17.761 0 1.11l-.518 1.065a1.119 1.119 0 0 1-.651.599l-2.35 1.045a1.013 1.013 0 0 1-.904 0l-2.35-1.045a1.119 1.119 0 0 1-.651-.599l-.518-1.065a1.2 1.2 0 0 1 0-1.11l.518-1.065a1.119 1.119 0 0 1 .651-.599l2.35-1.045a.983.983 0 0 1 .697-.061z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// Supabase icon component
|
||||
const SupabaseIcon = () => (
|
||||
<svg viewBox="0 0 24 24" className="w-4 h-4">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M21.362 9.354H12V.396a.396.396 0 0 0-.716-.233L2.203 12.424l-.401.562a1.04 1.04 0 0 0 .836 1.659H12V21.6a.396.396 0 0 0 .716.233l9.081-12.261.401-.562a1.04 1.04 0 0 0-.836-1.656z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const TAB_ICONS: Record<TabType, React.ComponentType<{ className?: string }>> = {
|
||||
profile: User,
|
||||
settings: Settings,
|
||||
notifications: Bell,
|
||||
features: Star,
|
||||
data: Database,
|
||||
'cloud-providers': Cloud,
|
||||
'local-providers': Laptop,
|
||||
github: Github,
|
||||
gitlab: () => <GitLabIcon />,
|
||||
netlify: () => <NetlifyIcon />,
|
||||
vercel: () => <VercelIcon />,
|
||||
supabase: () => <SupabaseIcon />,
|
||||
'event-logs': List,
|
||||
mcp: Wrench,
|
||||
};
|
||||
|
||||
export const TAB_LABELS: Record<TabType, string> = {
|
||||
profile: 'Profile',
|
||||
settings: 'Settings',
|
||||
notifications: 'Notifications',
|
||||
features: 'Features',
|
||||
data: 'Data Management',
|
||||
'cloud-providers': 'Cloud Providers',
|
||||
'local-providers': 'Local Providers',
|
||||
github: 'GitHub',
|
||||
gitlab: 'GitLab',
|
||||
netlify: 'Netlify',
|
||||
vercel: 'Vercel',
|
||||
supabase: 'Supabase',
|
||||
'event-logs': 'Event Logs',
|
||||
mcp: 'MCP Servers',
|
||||
};
|
||||
|
||||
export const TAB_DESCRIPTIONS: Record<TabType, string> = {
|
||||
profile: 'Manage your profile and account settings',
|
||||
settings: 'Configure application preferences',
|
||||
notifications: 'View and manage your notifications',
|
||||
features: 'Explore new and upcoming features',
|
||||
data: 'Manage your data and storage',
|
||||
'cloud-providers': 'Configure cloud AI providers and models',
|
||||
'local-providers': 'Configure local AI providers and models',
|
||||
github: 'Connect and manage GitHub integration',
|
||||
gitlab: 'Connect and manage GitLab integration',
|
||||
netlify: 'Configure Netlify deployment settings',
|
||||
vercel: 'Manage Vercel projects and deployments',
|
||||
supabase: 'Setup Supabase database connection',
|
||||
'event-logs': 'View system events and logs',
|
||||
mcp: 'Configure MCP (Model Context Protocol) servers',
|
||||
};
|
||||
|
||||
export const DEFAULT_TAB_CONFIG = [
|
||||
// User Window Tabs (Always visible by default)
|
||||
{ id: 'features', visible: true, window: 'user' as const, order: 0 },
|
||||
{ id: 'data', visible: true, window: 'user' as const, order: 1 },
|
||||
{ id: 'cloud-providers', visible: true, window: 'user' as const, order: 2 },
|
||||
{ id: 'local-providers', visible: true, window: 'user' as const, order: 3 },
|
||||
{ id: 'github', visible: true, window: 'user' as const, order: 4 },
|
||||
{ id: 'gitlab', visible: true, window: 'user' as const, order: 5 },
|
||||
{ id: 'netlify', visible: true, window: 'user' as const, order: 6 },
|
||||
{ id: 'vercel', visible: true, window: 'user' as const, order: 7 },
|
||||
{ id: 'supabase', visible: true, window: 'user' as const, order: 8 },
|
||||
{ id: 'notifications', visible: true, window: 'user' as const, order: 9 },
|
||||
{ id: 'event-logs', visible: true, window: 'user' as const, order: 10 },
|
||||
{ id: 'mcp', visible: true, window: 'user' as const, order: 11 },
|
||||
|
||||
// User Window Tabs (In dropdown, initially hidden)
|
||||
];
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { User, Folder, Wifi, Settings, Box, Sliders } from 'lucide-react';
|
||||
|
||||
export type SettingCategory = 'profile' | 'file_sharing' | 'connectivity' | 'system' | 'services' | 'preferences';
|
||||
|
||||
@@ -11,13 +10,13 @@ export type TabType =
|
||||
| 'data'
|
||||
| 'cloud-providers'
|
||||
| 'local-providers'
|
||||
| 'github'
|
||||
| 'gitlab'
|
||||
| 'netlify'
|
||||
| 'vercel'
|
||||
| 'supabase'
|
||||
| 'service-status'
|
||||
| 'connection'
|
||||
| 'debug'
|
||||
| 'event-logs'
|
||||
| 'mcp';
|
||||
| 'update'
|
||||
| 'task-manager'
|
||||
| 'tab-management';
|
||||
|
||||
export type WindowType = 'user' | 'developer';
|
||||
|
||||
@@ -64,6 +63,7 @@ export interface UserTabConfig extends TabVisibilityConfig {
|
||||
|
||||
export interface TabWindowConfig {
|
||||
userTabs: UserTabConfig[];
|
||||
developerTabs: DevTabConfig[];
|
||||
}
|
||||
|
||||
export const TAB_LABELS: Record<TabType, string> = {
|
||||
@@ -74,13 +74,13 @@ export const TAB_LABELS: Record<TabType, string> = {
|
||||
data: 'Data Management',
|
||||
'cloud-providers': 'Cloud Providers',
|
||||
'local-providers': 'Local Providers',
|
||||
github: 'GitHub',
|
||||
gitlab: 'GitLab',
|
||||
netlify: 'Netlify',
|
||||
vercel: 'Vercel',
|
||||
supabase: 'Supabase',
|
||||
'service-status': 'Service Status',
|
||||
connection: 'Connections',
|
||||
debug: 'Debug',
|
||||
'event-logs': 'Event Logs',
|
||||
mcp: 'MCP Servers',
|
||||
update: 'Updates',
|
||||
'task-manager': 'Task Manager',
|
||||
'tab-management': 'Tab Management',
|
||||
};
|
||||
|
||||
export const categoryLabels: Record<SettingCategory, string> = {
|
||||
@@ -92,13 +92,13 @@ export const categoryLabels: Record<SettingCategory, string> = {
|
||||
preferences: 'Preferences',
|
||||
};
|
||||
|
||||
export const categoryIcons: Record<SettingCategory, React.ComponentType<{ className?: string }>> = {
|
||||
profile: User,
|
||||
file_sharing: Folder,
|
||||
connectivity: Wifi,
|
||||
system: Settings,
|
||||
services: Box,
|
||||
preferences: Sliders,
|
||||
export const categoryIcons: Record<SettingCategory, string> = {
|
||||
profile: 'i-ph:user-circle',
|
||||
file_sharing: 'i-ph:folder-simple',
|
||||
connectivity: 'i-ph:wifi-high',
|
||||
system: 'i-ph:gear',
|
||||
services: 'i-ph:cube',
|
||||
preferences: 'i-ph:sliders',
|
||||
};
|
||||
|
||||
export interface Profile {
|
||||
|
||||
@@ -7,6 +7,8 @@ export { TAB_LABELS, TAB_DESCRIPTIONS, DEFAULT_TAB_CONFIG } from './core/constan
|
||||
|
||||
// Shared components
|
||||
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';
|
||||
|
||||
163
app/components/@settings/shared/components/DraggableTabList.tsx
Normal file
163
app/components/@settings/shared/components/DraggableTabList.tsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import { useDrag, useDrop } from 'react-dnd';
|
||||
import { motion } from 'framer-motion';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import type { TabVisibilityConfig } from '~/components/@settings/core/types';
|
||||
import { TAB_LABELS } from '~/components/@settings/core/types';
|
||||
import { Switch } from '~/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 (
|
||||
<motion.div
|
||||
ref={ref}
|
||||
initial={false}
|
||||
animate={{
|
||||
scale: isDragging ? 1.02 : 1,
|
||||
boxShadow: isDragging ? '0 8px 16px rgba(0,0,0,0.1)' : 'none',
|
||||
}}
|
||||
className={classNames(
|
||||
'flex items-center justify-between p-4 rounded-lg',
|
||||
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
|
||||
'border border-[#E5E5E5] dark:border-[#333333]',
|
||||
isDragging ? 'z-50' : '',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="cursor-grab">
|
||||
<div className="i-ph:dots-six-vertical w-4 h-4 text-bolt-elements-textSecondary" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium text-bolt-elements-textPrimary">{TAB_LABELS[tab.id]}</div>
|
||||
{showControls && (
|
||||
<div className="text-xs text-bolt-elements-textSecondary">
|
||||
Order: {tab.order}, Window: {tab.window}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{showControls && !tab.locked && (
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
checked={tab.visible}
|
||||
onCheckedChange={(checked: boolean) => onVisibilityChange?.(tab, checked)}
|
||||
className="data-[state=checked]:bg-purple-500"
|
||||
aria-label={`Toggle ${TAB_LABELS[tab.id]} visibility`}
|
||||
/>
|
||||
<label className="text-sm text-bolt-elements-textSecondary">Visible</label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-sm text-bolt-elements-textSecondary">User</label>
|
||||
<Switch
|
||||
checked={tab.window === 'developer'}
|
||||
onCheckedChange={(checked: boolean) => onWindowChange?.(tab, checked ? 'developer' : 'user')}
|
||||
className="data-[state=checked]:bg-purple-500"
|
||||
aria-label={`Toggle ${TAB_LABELS[tab.id]} window assignment`}
|
||||
/>
|
||||
<label className="text-sm text-bolt-elements-textSecondary">Dev</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
);
|
||||
};
|
||||
|
||||
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 (
|
||||
<div className="space-y-2">
|
||||
{tabs.map((tab, index) => (
|
||||
<DraggableTabItem
|
||||
key={tab.id}
|
||||
tab={tab}
|
||||
index={index}
|
||||
moveTab={moveTab}
|
||||
showControls={showControls}
|
||||
onWindowChange={onWindowChange}
|
||||
onVisibilityChange={onVisibilityChange}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
380
app/components/@settings/shared/components/TabManagement.tsx
Normal file
380
app/components/@settings/shared/components/TabManagement.tsx
Normal file
@@ -0,0 +1,380 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { Switch } from '~/components/ui/Switch';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { tabConfigurationStore } from '~/lib/stores/settings';
|
||||
import { TAB_LABELS } from '~/components/@settings/core/constants';
|
||||
import type { TabType } from '~/components/@settings/core/types';
|
||||
import { toast } from 'react-toastify';
|
||||
import { TbLayoutGrid } from 'react-icons/tb';
|
||||
import { useSettingsStore } from '~/lib/stores/settings';
|
||||
|
||||
// Define tab icons mapping
|
||||
const TAB_ICONS: Record<TabType, string> = {
|
||||
profile: 'i-ph:user-circle-fill',
|
||||
settings: 'i-ph:gear-six-fill',
|
||||
notifications: 'i-ph:bell-fill',
|
||||
features: 'i-ph:star-fill',
|
||||
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
|
||||
const DEFAULT_USER_TABS: TabType[] = [
|
||||
'features',
|
||||
'data',
|
||||
'cloud-providers',
|
||||
'local-providers',
|
||||
'connection',
|
||||
'notifications',
|
||||
'event-logs',
|
||||
];
|
||||
|
||||
// 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];
|
||||
|
||||
// Define which tabs are beta
|
||||
const BETA_TABS = new Set<TabType>(['task-manager', 'service-status', 'update', 'local-providers']);
|
||||
|
||||
// Beta label component
|
||||
const BetaLabel = () => (
|
||||
<span className="px-1.5 py-0.5 text-[10px] rounded-full bg-purple-500/10 text-purple-500 font-medium">BETA</span>
|
||||
);
|
||||
|
||||
export const TabManagement = () => {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const tabConfiguration = useStore(tabConfigurationStore);
|
||||
const { setSelectedTab } = useSettingsStore();
|
||||
|
||||
const handleTabVisibilityChange = (tabId: TabType, checked: boolean) => {
|
||||
// Get current tab configuration
|
||||
const currentTab = tabConfiguration.userTabs.find((tab) => tab.id === tabId);
|
||||
|
||||
// If tab doesn't exist in configuration, create it
|
||||
if (!currentTab) {
|
||||
const newTab = {
|
||||
id: tabId,
|
||||
visible: checked,
|
||||
window: 'user' as const,
|
||||
order: tabConfiguration.userTabs.length,
|
||||
};
|
||||
|
||||
const updatedTabs = [...tabConfiguration.userTabs, newTab];
|
||||
|
||||
tabConfigurationStore.set({
|
||||
...tabConfiguration,
|
||||
userTabs: updatedTabs,
|
||||
});
|
||||
|
||||
toast.success(`Tab ${checked ? 'enabled' : 'disabled'} successfully`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if tab can be enabled in user mode
|
||||
const canBeEnabled = DEFAULT_USER_TABS.includes(tabId) || OPTIONAL_USER_TABS.includes(tabId);
|
||||
|
||||
if (!canBeEnabled && checked) {
|
||||
toast.error('This tab cannot be enabled in user mode');
|
||||
return;
|
||||
}
|
||||
|
||||
// Update tab visibility
|
||||
const updatedTabs = tabConfiguration.userTabs.map((tab) => {
|
||||
if (tab.id === tabId) {
|
||||
return { ...tab, visible: checked };
|
||||
}
|
||||
|
||||
return tab;
|
||||
});
|
||||
|
||||
// Update store
|
||||
tabConfigurationStore.set({
|
||||
...tabConfiguration,
|
||||
userTabs: updatedTabs,
|
||||
});
|
||||
|
||||
// Show success message
|
||||
toast.success(`Tab ${checked ? 'enabled' : 'disabled'} successfully`);
|
||||
};
|
||||
|
||||
// Create a map of existing tab configurations
|
||||
const tabConfigMap = new Map(tabConfiguration.userTabs.map((tab) => [tab.id, tab]));
|
||||
|
||||
// Generate the complete list of tabs, including those not in the configuration
|
||||
const allTabs = ALL_USER_TABS.map((tabId) => {
|
||||
return (
|
||||
tabConfigMap.get(tabId) || {
|
||||
id: tabId,
|
||||
visible: false,
|
||||
window: 'user' as const,
|
||||
order: -1,
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
// Filter tabs based on search query
|
||||
const filteredTabs = allTabs.filter((tab) => TAB_LABELS[tab.id].toLowerCase().includes(searchQuery.toLowerCase()));
|
||||
|
||||
useEffect(() => {
|
||||
// Reset to first tab when component unmounts
|
||||
return () => {
|
||||
setSelectedTab('user'); // Reset to user tab when unmounting
|
||||
};
|
||||
}, [setSelectedTab]);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<motion.div
|
||||
className="space-y-4"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between gap-4 mt-8 mb-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={classNames(
|
||||
'w-8 h-8 flex items-center justify-center rounded-lg',
|
||||
'bg-bolt-elements-background-depth-3',
|
||||
'text-purple-500',
|
||||
)}
|
||||
>
|
||||
<TbLayoutGrid className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="text-md font-medium text-bolt-elements-textPrimary">Tab Management</h4>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">Configure visible tabs and their order</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
<div className="relative w-64">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<div className="i-ph:magnifying-glass w-4 h-4 text-gray-400" />
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder="Search tabs..."
|
||||
className={classNames(
|
||||
'w-full pl-10 pr-4 py-2 rounded-lg',
|
||||
'bg-bolt-elements-background-depth-2',
|
||||
'border border-bolt-elements-borderColor',
|
||||
'text-bolt-elements-textPrimary',
|
||||
'placeholder-bolt-elements-textTertiary',
|
||||
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
|
||||
'transition-all duration-200',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tab Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{/* Default Section Header */}
|
||||
{filteredTabs.some((tab) => DEFAULT_USER_TABS.includes(tab.id)) && (
|
||||
<div className="col-span-full flex items-center gap-2 mt-4 mb-2">
|
||||
<div className="i-ph:star-fill w-4 h-4 text-purple-500" />
|
||||
<span className="text-sm font-medium text-bolt-elements-textPrimary">Default Tabs</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Default Tabs */}
|
||||
{filteredTabs
|
||||
.filter((tab) => DEFAULT_USER_TABS.includes(tab.id))
|
||||
.map((tab, index) => (
|
||||
<motion.div
|
||||
key={tab.id}
|
||||
className={classNames(
|
||||
'rounded-lg border bg-bolt-elements-background text-bolt-elements-textPrimary',
|
||||
'bg-bolt-elements-background-depth-2',
|
||||
'hover:bg-bolt-elements-background-depth-3',
|
||||
'transition-all duration-200',
|
||||
'relative overflow-hidden group',
|
||||
)}
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: index * 0.1 }}
|
||||
whileHover={{ scale: 1.02 }}
|
||||
>
|
||||
{/* Status Badges */}
|
||||
<div className="absolute top-1 right-1.5 flex gap-1">
|
||||
<span className="px-1.5 py-0.25 text-xs rounded-full bg-purple-500/10 text-purple-500 font-medium mr-2">
|
||||
Default
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-4 p-4">
|
||||
<motion.div
|
||||
className={classNames(
|
||||
'w-10 h-10 flex items-center justify-center rounded-xl',
|
||||
'bg-bolt-elements-background-depth-3 group-hover:bg-bolt-elements-background-depth-4',
|
||||
'transition-all duration-200',
|
||||
tab.visible ? 'text-purple-500' : 'text-bolt-elements-textSecondary',
|
||||
)}
|
||||
whileHover={{ scale: 1.1 }}
|
||||
whileTap={{ scale: 0.9 }}
|
||||
>
|
||||
<div
|
||||
className={classNames('w-6 h-6', 'transition-transform duration-200', 'group-hover:rotate-12')}
|
||||
>
|
||||
<div className={classNames(TAB_ICONS[tab.id], 'w-full h-full')} />
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary group-hover:text-purple-500 transition-colors">
|
||||
{TAB_LABELS[tab.id]}
|
||||
</h4>
|
||||
{BETA_TABS.has(tab.id) && <BetaLabel />}
|
||||
</div>
|
||||
<p className="text-xs text-bolt-elements-textSecondary mt-0.5">
|
||||
{tab.visible ? 'Visible in user mode' : 'Hidden in user mode'}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={tab.visible}
|
||||
onCheckedChange={(checked) => {
|
||||
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),
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<motion.div
|
||||
className="absolute inset-0 border-2 border-purple-500/0 rounded-lg pointer-events-none"
|
||||
animate={{
|
||||
borderColor: tab.visible ? 'rgba(168, 85, 247, 0.2)' : 'rgba(168, 85, 247, 0)',
|
||||
scale: tab.visible ? 1 : 0.98,
|
||||
}}
|
||||
transition={{ duration: 0.2 }}
|
||||
/>
|
||||
</motion.div>
|
||||
))}
|
||||
|
||||
{/* Optional Section Header */}
|
||||
{filteredTabs.some((tab) => OPTIONAL_USER_TABS.includes(tab.id)) && (
|
||||
<div className="col-span-full flex items-center gap-2 mt-8 mb-2">
|
||||
<div className="i-ph:plus-circle-fill w-4 h-4 text-blue-500" />
|
||||
<span className="text-sm font-medium text-bolt-elements-textPrimary">Optional Tabs</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Optional Tabs */}
|
||||
{filteredTabs
|
||||
.filter((tab) => OPTIONAL_USER_TABS.includes(tab.id))
|
||||
.map((tab, index) => (
|
||||
<motion.div
|
||||
key={tab.id}
|
||||
className={classNames(
|
||||
'rounded-lg border bg-bolt-elements-background text-bolt-elements-textPrimary',
|
||||
'bg-bolt-elements-background-depth-2',
|
||||
'hover:bg-bolt-elements-background-depth-3',
|
||||
'transition-all duration-200',
|
||||
'relative overflow-hidden group',
|
||||
)}
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: index * 0.1 }}
|
||||
whileHover={{ scale: 1.02 }}
|
||||
>
|
||||
{/* Status Badges */}
|
||||
<div className="absolute top-1 right-1.5 flex gap-1">
|
||||
<span className="px-1.5 py-0.25 text-xs rounded-full bg-blue-500/10 text-blue-500 font-medium mr-2">
|
||||
Optional
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-4 p-4">
|
||||
<motion.div
|
||||
className={classNames(
|
||||
'w-10 h-10 flex items-center justify-center rounded-xl',
|
||||
'bg-bolt-elements-background-depth-3 group-hover:bg-bolt-elements-background-depth-4',
|
||||
'transition-all duration-200',
|
||||
tab.visible ? 'text-purple-500' : 'text-bolt-elements-textSecondary',
|
||||
)}
|
||||
whileHover={{ scale: 1.1 }}
|
||||
whileTap={{ scale: 0.9 }}
|
||||
>
|
||||
<div
|
||||
className={classNames('w-6 h-6', 'transition-transform duration-200', 'group-hover:rotate-12')}
|
||||
>
|
||||
<div className={classNames(TAB_ICONS[tab.id], 'w-full h-full')} />
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary group-hover:text-purple-500 transition-colors">
|
||||
{TAB_LABELS[tab.id]}
|
||||
</h4>
|
||||
{BETA_TABS.has(tab.id) && <BetaLabel />}
|
||||
</div>
|
||||
<p className="text-xs text-bolt-elements-textSecondary mt-0.5">
|
||||
{tab.visible ? 'Visible in user mode' : 'Hidden in user mode'}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={tab.visible}
|
||||
onCheckedChange={(checked) => {
|
||||
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),
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<motion.div
|
||||
className="absolute inset-0 border-2 border-purple-500/0 rounded-lg pointer-events-none"
|
||||
animate={{
|
||||
borderColor: tab.visible ? 'rgba(168, 85, 247, 0.2)' : 'rgba(168, 85, 247, 0)',
|
||||
scale: tab.visible ? 1 : 0.98,
|
||||
}}
|
||||
transition={{ duration: 0.2 }}
|
||||
/>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,8 +1,8 @@
|
||||
import { motion } from 'framer-motion';
|
||||
import * as Tooltip from '@radix-ui/react-tooltip';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import type { TabVisibilityConfig } from '~/components/@settings/core/types';
|
||||
import { TAB_LABELS, TAB_ICONS } from '~/components/@settings/core/constants';
|
||||
import { GlowingEffect } from '~/components/ui/GlowingEffect';
|
||||
|
||||
interface TabTileProps {
|
||||
tab: TabVisibilityConfig;
|
||||
@@ -28,122 +28,106 @@ export const TabTile: React.FC<TabTileProps> = ({
|
||||
children,
|
||||
}: TabTileProps) => {
|
||||
return (
|
||||
<Tooltip.Provider delayDuration={0}>
|
||||
<Tooltip.Provider delayDuration={200}>
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger asChild>
|
||||
<div className={classNames('min-h-[160px] list-none', className || '')}>
|
||||
<div className="relative h-full rounded-xl border border-[#E5E5E5] dark:border-[#333333] p-0.5">
|
||||
<GlowingEffect
|
||||
blur={0}
|
||||
borderWidth={1}
|
||||
spread={20}
|
||||
glow={true}
|
||||
disabled={false}
|
||||
proximity={40}
|
||||
inactiveZone={0.3}
|
||||
movementDuration={0.4}
|
||||
/>
|
||||
<div
|
||||
onClick={onClick}
|
||||
<motion.div
|
||||
onClick={onClick}
|
||||
className={classNames(
|
||||
'relative flex flex-col items-center p-6 rounded-xl',
|
||||
'w-full h-full min-h-[160px]',
|
||||
'bg-white dark:bg-[#141414]',
|
||||
'border border-[#E5E5E5] dark:border-[#333333]',
|
||||
'group',
|
||||
'hover:bg-purple-50 dark:hover:bg-[#1a1a1a]',
|
||||
'hover:border-purple-200 dark:hover:border-purple-900/30',
|
||||
isActive ? 'border-purple-500 dark:border-purple-500/50 bg-purple-500/5 dark:bg-purple-500/10' : '',
|
||||
isLoading ? 'cursor-wait opacity-70' : '',
|
||||
className || '',
|
||||
)}
|
||||
>
|
||||
{/* Main Content */}
|
||||
<div className="flex flex-col items-center justify-center flex-1 w-full">
|
||||
{/* Icon */}
|
||||
<motion.div
|
||||
className={classNames(
|
||||
'relative flex flex-col items-center justify-center h-full p-4 rounded-lg',
|
||||
'bg-white dark:bg-[#141414]',
|
||||
'group cursor-pointer',
|
||||
'hover:bg-purple-50 dark:hover:bg-[#1a1a1a]',
|
||||
'transition-colors duration-100 ease-out',
|
||||
isActive ? 'bg-purple-500/5 dark:bg-purple-500/10' : '',
|
||||
isLoading ? 'cursor-wait opacity-70 pointer-events-none' : '',
|
||||
'relative',
|
||||
'w-14 h-14',
|
||||
'flex items-center justify-center',
|
||||
'rounded-xl',
|
||||
'bg-gray-100 dark:bg-gray-800',
|
||||
'ring-1 ring-gray-200 dark:ring-gray-700',
|
||||
'group-hover:bg-purple-100 dark:group-hover:bg-gray-700/80',
|
||||
'group-hover:ring-purple-200 dark:group-hover:ring-purple-800/30',
|
||||
isActive ? 'bg-purple-500/10 dark:bg-purple-500/10 ring-purple-500/30 dark:ring-purple-500/20' : '',
|
||||
)}
|
||||
>
|
||||
{/* Icon */}
|
||||
<div
|
||||
<motion.div
|
||||
className={classNames(
|
||||
'relative',
|
||||
'w-14 h-14',
|
||||
'flex items-center justify-center',
|
||||
'rounded-xl',
|
||||
'bg-gray-100 dark:bg-gray-800',
|
||||
'ring-1 ring-gray-200 dark:ring-gray-700',
|
||||
'group-hover:bg-purple-100 dark:group-hover:bg-gray-700/80',
|
||||
'group-hover:ring-purple-200 dark:group-hover:ring-purple-800/30',
|
||||
'transition-all duration-100 ease-out',
|
||||
isActive ? 'bg-purple-500/10 dark:bg-purple-500/10 ring-purple-500/30 dark:ring-purple-500/20' : '',
|
||||
TAB_ICONS[tab.id],
|
||||
'w-8 h-8',
|
||||
'text-gray-600 dark:text-gray-300',
|
||||
'group-hover:text-purple-500 dark:group-hover:text-purple-400/80',
|
||||
isActive ? 'text-purple-500 dark:text-purple-400/90' : '',
|
||||
)}
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
{/* Label and Description */}
|
||||
<div className="flex flex-col items-center mt-5 w-full">
|
||||
<h3
|
||||
className={classNames(
|
||||
'text-[15px] font-medium leading-snug mb-2',
|
||||
'text-gray-700 dark:text-gray-200',
|
||||
'group-hover:text-purple-600 dark:group-hover:text-purple-300/90',
|
||||
isActive ? 'text-purple-500 dark:text-purple-400/90' : '',
|
||||
)}
|
||||
>
|
||||
{(() => {
|
||||
const IconComponent = TAB_ICONS[tab.id];
|
||||
return (
|
||||
<IconComponent
|
||||
className={classNames(
|
||||
'w-8 h-8',
|
||||
'text-gray-600 dark:text-gray-300',
|
||||
'group-hover:text-purple-500 dark:group-hover:text-purple-400/80',
|
||||
'transition-colors duration-100 ease-out',
|
||||
isActive ? 'text-purple-500 dark:text-purple-400/90' : '',
|
||||
)}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
|
||||
{/* Label and Description */}
|
||||
<div className="flex flex-col items-center mt-4 w-full">
|
||||
<h3
|
||||
{TAB_LABELS[tab.id]}
|
||||
</h3>
|
||||
{description && (
|
||||
<p
|
||||
className={classNames(
|
||||
'text-[15px] font-medium leading-snug mb-2',
|
||||
'text-gray-700 dark:text-gray-200',
|
||||
'group-hover:text-purple-600 dark:group-hover:text-purple-300/90',
|
||||
'transition-colors duration-100 ease-out',
|
||||
isActive ? 'text-purple-500 dark:text-purple-400/90' : '',
|
||||
'text-[13px] leading-relaxed',
|
||||
'text-gray-500 dark:text-gray-400',
|
||||
'max-w-[85%]',
|
||||
'text-center',
|
||||
'group-hover:text-purple-500 dark:group-hover:text-purple-400/70',
|
||||
isActive ? 'text-purple-400 dark:text-purple-400/80' : '',
|
||||
)}
|
||||
>
|
||||
{TAB_LABELS[tab.id]}
|
||||
</h3>
|
||||
{description && (
|
||||
<p
|
||||
className={classNames(
|
||||
'text-[13px] leading-relaxed',
|
||||
'text-gray-500 dark:text-gray-400',
|
||||
'max-w-[85%]',
|
||||
'text-center',
|
||||
'group-hover:text-purple-500 dark:group-hover:text-purple-400/70',
|
||||
'transition-colors duration-100 ease-out',
|
||||
isActive ? 'text-purple-400 dark:text-purple-400/80' : '',
|
||||
)}
|
||||
>
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Update Indicator with Tooltip */}
|
||||
{hasUpdate && (
|
||||
<>
|
||||
<div className="absolute top-4 right-4 w-2 h-2 rounded-full bg-purple-500 dark:bg-purple-400 animate-pulse" />
|
||||
<Tooltip.Portal>
|
||||
<Tooltip.Content
|
||||
className={classNames(
|
||||
'px-3 py-1.5 rounded-lg',
|
||||
'bg-[#18181B] text-white',
|
||||
'text-sm font-medium',
|
||||
'select-none',
|
||||
'z-[100]',
|
||||
)}
|
||||
side="top"
|
||||
sideOffset={5}
|
||||
>
|
||||
{statusMessage}
|
||||
<Tooltip.Arrow className="fill-[#18181B]" />
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Portal>
|
||||
</>
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Children (e.g. Beta Label) */}
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Update Indicator with Tooltip */}
|
||||
{hasUpdate && (
|
||||
<>
|
||||
<div className="absolute top-4 right-4 w-2 h-2 rounded-full bg-purple-500 dark:bg-purple-400 animate-pulse" />
|
||||
<Tooltip.Portal>
|
||||
<Tooltip.Content
|
||||
className={classNames(
|
||||
'px-3 py-1.5 rounded-lg',
|
||||
'bg-[#18181B] text-white',
|
||||
'text-sm font-medium',
|
||||
'select-none',
|
||||
'z-[100]',
|
||||
)}
|
||||
side="top"
|
||||
sideOffset={5}
|
||||
>
|
||||
{statusMessage}
|
||||
<Tooltip.Arrow className="fill-[#18181B]" />
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Portal>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Children (e.g. Beta Label) */}
|
||||
{children}
|
||||
</motion.div>
|
||||
</Tooltip.Trigger>
|
||||
</Tooltip.Root>
|
||||
</Tooltip.Provider>
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
import React from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
interface TokenTypeOption {
|
||||
value: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface ConnectionFormProps {
|
||||
isConnected: boolean;
|
||||
isConnecting: boolean;
|
||||
token: string;
|
||||
onTokenChange: (token: string) => void;
|
||||
onConnect: (e: React.FormEvent) => void;
|
||||
onDisconnect: () => void;
|
||||
error?: string;
|
||||
serviceName: string;
|
||||
tokenLabel?: string;
|
||||
tokenPlaceholder?: string;
|
||||
getTokenUrl: string;
|
||||
environmentVariable?: string;
|
||||
tokenTypes?: TokenTypeOption[];
|
||||
selectedTokenType?: string;
|
||||
onTokenTypeChange?: (type: string) => void;
|
||||
connectedMessage?: string;
|
||||
children?: React.ReactNode; // For additional form fields
|
||||
}
|
||||
|
||||
export function ConnectionForm({
|
||||
isConnected,
|
||||
isConnecting,
|
||||
token,
|
||||
onTokenChange,
|
||||
onConnect,
|
||||
onDisconnect,
|
||||
error,
|
||||
serviceName,
|
||||
tokenLabel = 'Access Token',
|
||||
tokenPlaceholder,
|
||||
getTokenUrl,
|
||||
environmentVariable,
|
||||
tokenTypes,
|
||||
selectedTokenType,
|
||||
onTokenTypeChange,
|
||||
connectedMessage = `Connected to ${serviceName}`,
|
||||
children,
|
||||
}: ConnectionFormProps) {
|
||||
return (
|
||||
<motion.div
|
||||
className="bg-bolt-elements-background dark:bg-bolt-elements-background border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<div className="p-6 space-y-6">
|
||||
{!isConnected ? (
|
||||
<div className="space-y-4">
|
||||
{environmentVariable && (
|
||||
<div className="text-xs text-bolt-elements-textSecondary bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-1 p-3 rounded-lg mb-4">
|
||||
<p className="flex items-center gap-1 mb-1">
|
||||
<span className="i-ph:lightbulb w-3.5 h-3.5 text-bolt-elements-icon-success dark:text-bolt-elements-icon-success" />
|
||||
<span className="font-medium">Tip:</span> You can also set the{' '}
|
||||
<code className="px-1 py-0.5 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 rounded">
|
||||
{environmentVariable}
|
||||
</code>{' '}
|
||||
environment variable to connect automatically.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={onConnect} className="space-y-4">
|
||||
{tokenTypes && tokenTypes.length > 1 && onTokenTypeChange && (
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mb-2">
|
||||
Token Type
|
||||
</label>
|
||||
<select
|
||||
value={selectedTokenType}
|
||||
onChange={(e) => onTokenTypeChange(e.target.value)}
|
||||
disabled={isConnecting}
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-1',
|
||||
'border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor',
|
||||
'text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-item-contentAccent dark:focus:ring-bolt-elements-item-contentAccent',
|
||||
'disabled:opacity-50',
|
||||
)}
|
||||
>
|
||||
{tokenTypes.map((type) => (
|
||||
<option key={type.value} value={type.value}>
|
||||
{type.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{selectedTokenType && tokenTypes.find((t) => t.value === selectedTokenType)?.description && (
|
||||
<p className="mt-1 text-xs text-bolt-elements-textTertiary">
|
||||
{tokenTypes.find((t) => t.value === selectedTokenType)?.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary mb-2">{tokenLabel}</label>
|
||||
<input
|
||||
type="password"
|
||||
value={token}
|
||||
onChange={(e) => onTokenChange(e.target.value)}
|
||||
disabled={isConnecting}
|
||||
placeholder={tokenPlaceholder || `Enter your ${serviceName} access token`}
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-1',
|
||||
'border border-bolt-elements-borderColor',
|
||||
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive',
|
||||
'disabled:opacity-50',
|
||||
)}
|
||||
/>
|
||||
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
|
||||
<a
|
||||
href={getTokenUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-bolt-elements-borderColorActive hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
Get your token
|
||||
<div className="i-ph:arrow-square-out w-4 h-4" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{children}
|
||||
|
||||
{error && (
|
||||
<div className="p-4 rounded-lg bg-red-50 border border-red-200 dark:bg-red-900/20 dark:border-red-700">
|
||||
<p className="text-sm text-red-800 dark:text-red-200">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isConnecting || !token.trim()}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-[#303030] text-white',
|
||||
'hover:bg-[#5E41D0] hover:text-white',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200',
|
||||
'transform active:scale-95',
|
||||
)}
|
||||
>
|
||||
{isConnecting ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap animate-spin" />
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:plug-charging w-4 h-4" />
|
||||
Connect
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={onDisconnect}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-red-500 text-white',
|
||||
'hover:bg-red-600',
|
||||
)}
|
||||
>
|
||||
<div className="i-ph:plug w-4 h-4" />
|
||||
Disconnect
|
||||
</button>
|
||||
<span className="text-sm text-bolt-elements-textSecondary flex items-center gap-1">
|
||||
<div className="i-ph:check-circle w-4 h-4 text-green-500" />
|
||||
{connectedMessage}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import React from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
export interface ConnectionTestResult {
|
||||
status: 'success' | 'error' | 'testing';
|
||||
message: string;
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
interface ConnectionTestIndicatorProps {
|
||||
testResult: ConnectionTestResult | null;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ConnectionTestIndicator({ testResult, className }: ConnectionTestIndicatorProps) {
|
||||
if (!testResult) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className={classNames(
|
||||
'p-4 rounded-lg border',
|
||||
{
|
||||
'bg-green-50 border-green-200 dark:bg-green-900/20 dark:border-green-700': testResult.status === 'success',
|
||||
'bg-red-50 border-red-200 dark:bg-red-900/20 dark:border-red-700': testResult.status === 'error',
|
||||
'bg-blue-50 border-blue-200 dark:bg-blue-900/20 dark:border-blue-700': testResult.status === 'testing',
|
||||
},
|
||||
className,
|
||||
)}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{testResult.status === 'success' && (
|
||||
<div className="i-ph:check-circle w-5 h-5 text-green-600 dark:text-green-400" />
|
||||
)}
|
||||
{testResult.status === 'error' && (
|
||||
<div className="i-ph:warning-circle w-5 h-5 text-red-600 dark:text-red-400" />
|
||||
)}
|
||||
{testResult.status === 'testing' && (
|
||||
<div className="i-ph:spinner-gap w-5 h-5 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
)}
|
||||
<span
|
||||
className={classNames('text-sm font-medium', {
|
||||
'text-green-800 dark:text-green-200': testResult.status === 'success',
|
||||
'text-red-800 dark:text-red-200': testResult.status === 'error',
|
||||
'text-blue-800 dark:text-blue-200': testResult.status === 'testing',
|
||||
})}
|
||||
>
|
||||
{testResult.message}
|
||||
</span>
|
||||
</div>
|
||||
{testResult.timestamp && (
|
||||
<p className="text-xs text-gray-500 mt-1">{new Date(testResult.timestamp).toLocaleString()}</p>
|
||||
)}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import React from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import type { ServiceError } from '~/lib/utils/serviceErrorHandler';
|
||||
|
||||
interface ErrorStateProps {
|
||||
error?: ServiceError | string;
|
||||
title?: string;
|
||||
onRetry?: () => void;
|
||||
onDismiss?: () => void;
|
||||
retryLabel?: string;
|
||||
className?: string;
|
||||
showDetails?: boolean;
|
||||
}
|
||||
|
||||
export function ErrorState({
|
||||
error,
|
||||
title = 'Something went wrong',
|
||||
onRetry,
|
||||
onDismiss,
|
||||
retryLabel = 'Try again',
|
||||
className,
|
||||
showDetails = false,
|
||||
}: ErrorStateProps) {
|
||||
const errorMessage = typeof error === 'string' ? error : error?.message || 'An unknown error occurred';
|
||||
const isServiceError = typeof error === 'object' && error !== null;
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className={classNames(
|
||||
'p-6 rounded-lg border border-red-200 bg-red-50 dark:border-red-700 dark:bg-red-900/20',
|
||||
className,
|
||||
)}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="i-ph:warning-circle w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-sm font-medium text-red-800 dark:text-red-200 mb-1">{title}</h3>
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{errorMessage}</p>
|
||||
|
||||
{showDetails && isServiceError && error.details && (
|
||||
<details className="mt-3">
|
||||
<summary className="text-xs text-red-600 dark:text-red-400 cursor-pointer hover:underline">
|
||||
Technical details
|
||||
</summary>
|
||||
<pre className="mt-2 text-xs text-red-600 dark:text-red-400 bg-red-100 dark:bg-red-900/30 p-2 rounded overflow-auto">
|
||||
{JSON.stringify(error.details, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2 mt-4">
|
||||
{onRetry && (
|
||||
<Button
|
||||
onClick={onRetry}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-700 border-red-300 hover:bg-red-100 dark:text-red-300 dark:border-red-600 dark:hover:bg-red-900/30"
|
||||
>
|
||||
<div className="i-ph:arrows-clockwise w-4 h-4 mr-1" />
|
||||
{retryLabel}
|
||||
</Button>
|
||||
)}
|
||||
{onDismiss && (
|
||||
<Button
|
||||
onClick={onDismiss}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-700 border-red-300 hover:bg-red-100 dark:text-red-300 dark:border-red-600 dark:hover:bg-red-900/30"
|
||||
>
|
||||
Dismiss
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ConnectionErrorProps {
|
||||
service: string;
|
||||
error: ServiceError | string;
|
||||
onRetryConnection: () => void;
|
||||
onClearError?: () => void;
|
||||
}
|
||||
|
||||
export function ConnectionError({ service, error, onRetryConnection, onClearError }: ConnectionErrorProps) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={error}
|
||||
title={`Failed to connect to ${service}`}
|
||||
onRetry={onRetryConnection}
|
||||
onDismiss={onClearError}
|
||||
retryLabel="Retry connection"
|
||||
showDetails={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import React from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
interface LoadingStateProps {
|
||||
message?: string;
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
className?: string;
|
||||
showProgress?: boolean;
|
||||
progress?: number;
|
||||
}
|
||||
|
||||
export function LoadingState({
|
||||
message = 'Loading...',
|
||||
size = 'md',
|
||||
className,
|
||||
showProgress = false,
|
||||
progress = 0,
|
||||
}: LoadingStateProps) {
|
||||
const sizeClasses = {
|
||||
sm: 'w-4 h-4',
|
||||
md: 'w-6 h-6',
|
||||
lg: 'w-8 h-8',
|
||||
};
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className={classNames('flex flex-col items-center justify-center gap-3', className)}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={classNames(
|
||||
'i-ph:spinner-gap animate-spin text-bolt-elements-item-contentAccent',
|
||||
sizeClasses[size],
|
||||
)}
|
||||
/>
|
||||
<span className="text-bolt-elements-textSecondary">{message}</span>
|
||||
</div>
|
||||
|
||||
{showProgress && (
|
||||
<div className="w-full max-w-xs">
|
||||
<div className="w-full bg-bolt-elements-background-depth-2 rounded-full h-1">
|
||||
<motion.div
|
||||
className="bg-bolt-elements-item-contentAccent h-1 rounded-full"
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: `${progress}%` }}
|
||||
transition={{ duration: 0.3 }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SkeletonProps {
|
||||
className?: string;
|
||||
lines?: number;
|
||||
}
|
||||
|
||||
export function Skeleton({ className, lines = 1 }: SkeletonProps) {
|
||||
return (
|
||||
<div className={classNames('animate-pulse', className)}>
|
||||
{Array.from({ length: lines }, (_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={classNames(
|
||||
'bg-bolt-elements-background-depth-2 rounded',
|
||||
i === lines - 1 ? 'h-4' : 'h-4 mb-2',
|
||||
i === lines - 1 && lines > 1 ? 'w-3/4' : 'w-full',
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ServiceLoadingProps {
|
||||
serviceName: string;
|
||||
operation: string;
|
||||
progress?: number;
|
||||
}
|
||||
|
||||
export function ServiceLoading({ serviceName, operation, progress }: ServiceLoadingProps) {
|
||||
return (
|
||||
<LoadingState
|
||||
message={`${operation} ${serviceName}...`}
|
||||
showProgress={progress !== undefined}
|
||||
progress={progress}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import React, { memo } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
|
||||
interface ServiceHeaderProps {
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
title: string;
|
||||
description?: string;
|
||||
onTestConnection?: () => void;
|
||||
isTestingConnection?: boolean;
|
||||
additionalInfo?: React.ReactNode;
|
||||
delay?: number;
|
||||
}
|
||||
|
||||
export const ServiceHeader = memo(
|
||||
({
|
||||
icon: Icon, // eslint-disable-line @typescript-eslint/naming-convention
|
||||
title,
|
||||
description,
|
||||
onTestConnection,
|
||||
isTestingConnection,
|
||||
additionalInfo,
|
||||
delay = 0.1,
|
||||
}: ServiceHeaderProps) => {
|
||||
return (
|
||||
<>
|
||||
<motion.div
|
||||
className="flex items-center justify-between gap-2"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon className="w-5 h-5" />
|
||||
<h2 className="text-lg font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
{title}
|
||||
</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{additionalInfo}
|
||||
{onTestConnection && (
|
||||
<Button
|
||||
onClick={onTestConnection}
|
||||
disabled={isTestingConnection}
|
||||
variant="outline"
|
||||
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:bg-bolt-elements-item-backgroundActive/10 dark:hover:text-bolt-elements-textPrimary transition-colors"
|
||||
>
|
||||
{isTestingConnection ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap w-4 h-4 animate-spin" />
|
||||
Testing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:plug-charging w-4 h-4" />
|
||||
Test Connection
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{description && (
|
||||
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1,6 +0,0 @@
|
||||
export { ConnectionTestIndicator } from './ConnectionTestIndicator';
|
||||
export type { ConnectionTestResult } from './ConnectionTestIndicator';
|
||||
export { ServiceHeader } from './ServiceHeader';
|
||||
export { ConnectionForm } from './ConnectionForm';
|
||||
export { LoadingState, Skeleton, ServiceLoading } from './LoadingState';
|
||||
export { ErrorState, ConnectionError } from './ErrorState';
|
||||
615
app/components/@settings/tabs/connections/ConnectionsTab.tsx
Normal file
615
app/components/@settings/tabs/connections/ConnectionsTab.tsx
Normal file
@@ -0,0 +1,615 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { logStore } from '~/lib/stores/logs';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { motion } from 'framer-motion';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
interface GitHubUserResponse {
|
||||
login: string;
|
||||
avatar_url: string;
|
||||
html_url: string;
|
||||
name: string;
|
||||
bio: string;
|
||||
public_repos: number;
|
||||
followers: number;
|
||||
following: number;
|
||||
created_at: string;
|
||||
public_gists: number;
|
||||
}
|
||||
|
||||
interface GitHubRepoInfo {
|
||||
name: string;
|
||||
full_name: string;
|
||||
html_url: string;
|
||||
description: string;
|
||||
stargazers_count: number;
|
||||
forks_count: number;
|
||||
default_branch: string;
|
||||
updated_at: string;
|
||||
languages_url: string;
|
||||
}
|
||||
|
||||
interface GitHubOrganization {
|
||||
login: string;
|
||||
avatar_url: string;
|
||||
html_url: string;
|
||||
}
|
||||
|
||||
interface GitHubEvent {
|
||||
id: string;
|
||||
type: string;
|
||||
repo: {
|
||||
name: string;
|
||||
};
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface GitHubLanguageStats {
|
||||
[language: string]: number;
|
||||
}
|
||||
|
||||
interface GitHubStats {
|
||||
repos: GitHubRepoInfo[];
|
||||
totalStars: number;
|
||||
totalForks: number;
|
||||
organizations: GitHubOrganization[];
|
||||
recentActivity: GitHubEvent[];
|
||||
languages: GitHubLanguageStats;
|
||||
totalGists: number;
|
||||
}
|
||||
|
||||
interface GitHubConnection {
|
||||
user: GitHubUserResponse | null;
|
||||
token: string;
|
||||
tokenType: 'classic' | 'fine-grained';
|
||||
stats?: GitHubStats;
|
||||
}
|
||||
|
||||
export default function ConnectionsTab() {
|
||||
const [connection, setConnection] = useState<GitHubConnection>({
|
||||
user: null,
|
||||
token: '',
|
||||
tokenType: 'classic',
|
||||
});
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const [isFetchingStats, setIsFetchingStats] = useState(false);
|
||||
|
||||
// Load saved connection on mount
|
||||
useEffect(() => {
|
||||
const savedConnection = localStorage.getItem('github_connection');
|
||||
|
||||
if (savedConnection) {
|
||||
const parsed = JSON.parse(savedConnection);
|
||||
|
||||
// Ensure backward compatibility with existing connections
|
||||
if (!parsed.tokenType) {
|
||||
parsed.tokenType = 'classic';
|
||||
}
|
||||
|
||||
setConnection(parsed);
|
||||
|
||||
if (parsed.user && parsed.token) {
|
||||
fetchGitHubStats(parsed.token);
|
||||
}
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
}, []);
|
||||
|
||||
const fetchGitHubStats = async (token: string) => {
|
||||
try {
|
||||
setIsFetchingStats(true);
|
||||
|
||||
// Fetch repositories - only owned by the authenticated user
|
||||
const reposResponse = await fetch(
|
||||
'https://api.github.com/user/repos?sort=updated&per_page=10&affiliation=owner,organization_member,collaborator',
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!reposResponse.ok) {
|
||||
throw new Error('Failed to fetch repositories');
|
||||
}
|
||||
|
||||
const repos = (await reposResponse.json()) as GitHubRepoInfo[];
|
||||
|
||||
// Fetch organizations
|
||||
const orgsResponse = await fetch('https://api.github.com/user/orgs', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!orgsResponse.ok) {
|
||||
throw new Error('Failed to fetch organizations');
|
||||
}
|
||||
|
||||
const organizations = (await orgsResponse.json()) as GitHubOrganization[];
|
||||
|
||||
// Fetch recent activity
|
||||
const eventsResponse = await fetch('https://api.github.com/users/' + connection.user?.login + '/events/public', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!eventsResponse.ok) {
|
||||
throw new Error('Failed to fetch events');
|
||||
}
|
||||
|
||||
const recentActivity = ((await eventsResponse.json()) as GitHubEvent[]).slice(0, 5);
|
||||
|
||||
// Fetch languages for each repository
|
||||
const languagePromises = repos.map((repo) =>
|
||||
fetch(repo.languages_url, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
}).then((res) => res.json() as Promise<Record<string, number>>),
|
||||
);
|
||||
|
||||
const repoLanguages = await Promise.all(languagePromises);
|
||||
const languages: GitHubLanguageStats = {};
|
||||
|
||||
repoLanguages.forEach((repoLang) => {
|
||||
Object.entries(repoLang).forEach(([lang, bytes]) => {
|
||||
languages[lang] = (languages[lang] || 0) + bytes;
|
||||
});
|
||||
});
|
||||
|
||||
// Calculate total stats
|
||||
const totalStars = repos.reduce((acc, repo) => acc + repo.stargazers_count, 0);
|
||||
const totalForks = repos.reduce((acc, repo) => acc + repo.forks_count, 0);
|
||||
const totalGists = connection.user?.public_gists || 0;
|
||||
|
||||
setConnection((prev) => ({
|
||||
...prev,
|
||||
stats: {
|
||||
repos,
|
||||
totalStars,
|
||||
totalForks,
|
||||
organizations,
|
||||
recentActivity,
|
||||
languages,
|
||||
totalGists,
|
||||
},
|
||||
}));
|
||||
} catch (error) {
|
||||
logStore.logError('Failed to fetch GitHub stats', { error });
|
||||
toast.error('Failed to fetch GitHub statistics');
|
||||
} finally {
|
||||
setIsFetchingStats(false);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchGithubUser = async (token: string) => {
|
||||
try {
|
||||
setIsConnecting(true);
|
||||
|
||||
const response = await fetch('https://api.github.com/user', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Invalid token or unauthorized');
|
||||
}
|
||||
|
||||
const data = (await response.json()) as GitHubUserResponse;
|
||||
const newConnection: GitHubConnection = {
|
||||
user: data,
|
||||
token,
|
||||
tokenType: connection.tokenType,
|
||||
};
|
||||
|
||||
// Save connection
|
||||
localStorage.setItem('github_connection', JSON.stringify(newConnection));
|
||||
setConnection(newConnection);
|
||||
|
||||
// Fetch additional stats
|
||||
await fetchGitHubStats(token);
|
||||
|
||||
toast.success('Successfully connected to GitHub');
|
||||
} catch (error) {
|
||||
logStore.logError('Failed to authenticate with GitHub', { error });
|
||||
toast.error('Failed to connect to GitHub');
|
||||
setConnection({ user: null, token: '', tokenType: 'classic' });
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleConnect = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
await fetchGithubUser(connection.token);
|
||||
};
|
||||
|
||||
const handleDisconnect = () => {
|
||||
localStorage.removeItem('github_connection');
|
||||
setConnection({ user: null, token: '', tokenType: 'classic' });
|
||||
toast.success('Disconnected from GitHub');
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingSpinner />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<motion.div
|
||||
className="flex items-center gap-2 mb-2"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<div className="i-ph:plugs-connected w-5 h-5 text-purple-500" />
|
||||
<h2 className="text-lg font-medium text-bolt-elements-textPrimary">Connection Settings</h2>
|
||||
</motion.div>
|
||||
<p className="text-sm text-bolt-elements-textSecondary mb-6">
|
||||
Manage your external service connections and integrations
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
{/* GitHub Connection */}
|
||||
<motion.div
|
||||
className="bg-[#FFFFFF] dark:bg-[#0A0A0A] rounded-lg border border-[#E5E5E5] dark:border-[#1A1A1A]"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<div className="p-6 space-y-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="i-ph:github-logo w-5 h-5 text-bolt-elements-textPrimary" />
|
||||
<h3 className="text-base font-medium text-bolt-elements-textPrimary">GitHub Connection</h3>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary mb-2">Token Type</label>
|
||||
<select
|
||||
value={connection.tokenType}
|
||||
onChange={(e) =>
|
||||
setConnection((prev) => ({ ...prev, tokenType: e.target.value as 'classic' | 'fine-grained' }))
|
||||
}
|
||||
disabled={isConnecting || !!connection.user}
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-[#F8F8F8] dark:bg-[#1A1A1A]',
|
||||
'border border-[#E5E5E5] dark:border-[#333333]',
|
||||
'text-bolt-elements-textPrimary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-purple-500',
|
||||
'disabled:opacity-50',
|
||||
)}
|
||||
>
|
||||
<option value="classic">Personal Access Token (Classic)</option>
|
||||
<option value="fine-grained">Fine-grained Token</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary mb-2">
|
||||
{connection.tokenType === 'classic' ? 'Personal Access Token' : 'Fine-grained Token'}
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={connection.token}
|
||||
onChange={(e) => setConnection((prev) => ({ ...prev, token: e.target.value }))}
|
||||
disabled={isConnecting || !!connection.user}
|
||||
placeholder={`Enter your GitHub ${connection.tokenType === 'classic' ? 'personal access token' : 'fine-grained token'}`}
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-[#F8F8F8] dark:bg-[#1A1A1A]',
|
||||
'border border-[#E5E5E5] dark:border-[#333333]',
|
||||
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-purple-500',
|
||||
'disabled:opacity-50',
|
||||
)}
|
||||
/>
|
||||
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
|
||||
<a
|
||||
href={`https://github.com/settings/tokens${connection.tokenType === 'fine-grained' ? '/beta' : '/new'}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-purple-500 hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
Get your token
|
||||
<div className="i-ph:arrow-square-out w-10 h-5" />
|
||||
</a>
|
||||
<span className="mx-2">•</span>
|
||||
<span>
|
||||
Required scopes:{' '}
|
||||
{connection.tokenType === 'classic'
|
||||
? 'repo, read:org, read:user'
|
||||
: 'Repository access, Organization access'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
{!connection.user ? (
|
||||
<button
|
||||
onClick={handleConnect}
|
||||
disabled={isConnecting || !connection.token}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-purple-500 text-white',
|
||||
'hover:bg-purple-600',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
)}
|
||||
>
|
||||
{isConnecting ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap animate-spin" />
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:plug-charging w-4 h-4" />
|
||||
Connect
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={handleDisconnect}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-red-500 text-white',
|
||||
'hover:bg-red-600',
|
||||
)}
|
||||
>
|
||||
<div className="i-ph:plug-x w-4 h-4" />
|
||||
Disconnect
|
||||
</button>
|
||||
)}
|
||||
|
||||
{connection.user && (
|
||||
<span className="text-sm text-bolt-elements-textSecondary flex items-center gap-1">
|
||||
<div className="i-ph:check-circle w-4 h-4" />
|
||||
Connected to GitHub
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{connection.user && (
|
||||
<div className="p-4 bg-[#F8F8F8] dark:bg-[#1A1A1A] rounded-lg">
|
||||
<div className="flex items-center gap-4">
|
||||
<img
|
||||
src={connection.user.avatar_url}
|
||||
alt={connection.user.login}
|
||||
className="w-12 h-12 rounded-full"
|
||||
/>
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary">{connection.user.name}</h4>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">@{connection.user.login}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isFetchingStats ? (
|
||||
<div className="mt-4 flex items-center gap-2 text-sm text-bolt-elements-textSecondary">
|
||||
<div className="i-ph:spinner-gap w-4 h-4 animate-spin" />
|
||||
Fetching GitHub stats...
|
||||
</div>
|
||||
) : (
|
||||
connection.stats && (
|
||||
<div className="mt-4 grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">Public Repos</p>
|
||||
<p className="text-lg font-medium text-bolt-elements-textPrimary">
|
||||
{connection.user.public_repos}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">Total Stars</p>
|
||||
<p className="text-lg font-medium text-bolt-elements-textPrimary">
|
||||
{connection.stats.totalStars}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">Total Forks</p>
|
||||
<p className="text-lg font-medium text-bolt-elements-textPrimary">
|
||||
{connection.stats.totalForks}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{connection.user && connection.stats && (
|
||||
<div className="mt-6 border-t border-[#E5E5E5] dark:border-[#1A1A1A] pt-6">
|
||||
<div className="flex items-center gap-4 mb-6">
|
||||
<img
|
||||
src={connection.user.avatar_url}
|
||||
alt={connection.user.login}
|
||||
className="w-16 h-16 rounded-full"
|
||||
/>
|
||||
<div>
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary">
|
||||
{connection.user.name || connection.user.login}
|
||||
</h3>
|
||||
{connection.user.bio && (
|
||||
<p className="text-sm text-bolt-elements-textSecondary">{connection.user.bio}</p>
|
||||
)}
|
||||
<div className="flex gap-4 mt-2 text-sm text-bolt-elements-textSecondary">
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:users w-4 h-4" />
|
||||
{connection.user.followers} followers
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:star w-4 h-4" />
|
||||
{connection.stats.totalStars} stars
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:git-fork w-4 h-4" />
|
||||
{connection.stats.totalForks} forks
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Organizations Section */}
|
||||
{connection.stats.organizations.length > 0 && (
|
||||
<div className="mb-6">
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary mb-3">Organizations</h4>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{connection.stats.organizations.map((org) => (
|
||||
<a
|
||||
key={org.login}
|
||||
href={org.html_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 p-2 rounded-lg bg-[#F8F8F8] dark:bg-[#1A1A1A] hover:bg-[#F0F0F0] dark:hover:bg-[#252525] transition-colors"
|
||||
>
|
||||
<img src={org.avatar_url} alt={org.login} className="w-6 h-6 rounded-md" />
|
||||
<span className="text-sm text-bolt-elements-textPrimary">{org.login}</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Languages Section */}
|
||||
<div className="mb-6">
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary mb-3">Top Languages</h4>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(connection.stats.languages)
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.slice(0, 5)
|
||||
.map(([language]) => (
|
||||
<span
|
||||
key={language}
|
||||
className="px-3 py-1 text-xs rounded-full bg-purple-500/10 text-purple-500 dark:bg-purple-500/20"
|
||||
>
|
||||
{language}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recent Activity Section */}
|
||||
<div className="mb-6">
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary mb-3">Recent Activity</h4>
|
||||
<div className="space-y-3">
|
||||
{connection.stats.recentActivity.map((event) => (
|
||||
<div key={event.id} className="p-3 rounded-lg bg-[#F8F8F8] dark:bg-[#1A1A1A] text-sm">
|
||||
<div className="flex items-center gap-2 text-bolt-elements-textPrimary">
|
||||
<div className="i-ph:git-commit w-4 h-4 text-bolt-elements-textSecondary" />
|
||||
<span className="font-medium">{event.type.replace('Event', '')}</span>
|
||||
<span>on</span>
|
||||
<a
|
||||
href={`https://github.com/${event.repo.name}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-purple-500 hover:underline"
|
||||
>
|
||||
{event.repo.name}
|
||||
</a>
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-bolt-elements-textSecondary">
|
||||
{new Date(event.created_at).toLocaleDateString()} at{' '}
|
||||
{new Date(event.created_at).toLocaleTimeString()}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Additional Stats */}
|
||||
<div className="grid grid-cols-4 gap-4 mb-6">
|
||||
<div className="p-4 rounded-lg bg-[#F8F8F8] dark:bg-[#1A1A1A]">
|
||||
<div className="text-sm text-bolt-elements-textSecondary">Member Since</div>
|
||||
<div className="text-lg font-medium text-bolt-elements-textPrimary">
|
||||
{new Date(connection.user.created_at).toLocaleDateString()}
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4 rounded-lg bg-[#F8F8F8] dark:bg-[#1A1A1A]">
|
||||
<div className="text-sm text-bolt-elements-textSecondary">Public Gists</div>
|
||||
<div className="text-lg font-medium text-bolt-elements-textPrimary">
|
||||
{connection.stats.totalGists}
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4 rounded-lg bg-[#F8F8F8] dark:bg-[#1A1A1A]">
|
||||
<div className="text-sm text-bolt-elements-textSecondary">Organizations</div>
|
||||
<div className="text-lg font-medium text-bolt-elements-textPrimary">
|
||||
{connection.stats.organizations.length}
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4 rounded-lg bg-[#F8F8F8] dark:bg-[#1A1A1A]">
|
||||
<div className="text-sm text-bolt-elements-textSecondary">Languages</div>
|
||||
<div className="text-lg font-medium text-bolt-elements-textPrimary">
|
||||
{Object.keys(connection.stats.languages).length}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Existing repositories section */}
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary mb-3">Recent Repositories</h4>
|
||||
<div className="space-y-3">
|
||||
{connection.stats.repos.map((repo) => (
|
||||
<a
|
||||
key={repo.full_name}
|
||||
href={repo.html_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block p-3 rounded-lg bg-[#F8F8F8] dark:bg-[#1A1A1A] hover:bg-[#F0F0F0] dark:hover:bg-[#252525] transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h5 className="text-sm font-medium text-bolt-elements-textPrimary flex items-center gap-2">
|
||||
<div className="i-ph:git-repository w-4 h-4 text-bolt-elements-textSecondary" />
|
||||
{repo.name}
|
||||
</h5>
|
||||
{repo.description && (
|
||||
<p className="text-xs text-bolt-elements-textSecondary mt-1">{repo.description}</p>
|
||||
)}
|
||||
<div className="flex items-center gap-2 mt-2 text-xs text-bolt-elements-textSecondary">
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:git-branch w-3 h-3" />
|
||||
{repo.default_branch}
|
||||
</span>
|
||||
<span>•</span>
|
||||
<span>Updated {new Date(repo.updated_at).toLocaleDateString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-xs text-bolt-elements-textSecondary">
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:star w-3 h-3" />
|
||||
{repo.stargazers_count}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:git-fork w-3 h-3" />
|
||||
{repo.forks_count}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoadingSpinner() {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="i-ph:spinner-gap-bold animate-spin w-4 h-4" />
|
||||
<span className="text-bolt-elements-textSecondary">Loading...</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import type { GitHubAuthState } from '~/components/@settings/tabs/connections/types/GitHub';
|
||||
import Cookies from 'js-cookie';
|
||||
import { getLocalStorage } from '~/lib/persistence';
|
||||
|
||||
const GITHUB_TOKEN_KEY = 'github_token';
|
||||
|
||||
interface ConnectionFormProps {
|
||||
authState: GitHubAuthState;
|
||||
setAuthState: React.Dispatch<React.SetStateAction<GitHubAuthState>>;
|
||||
onSave: (e: React.FormEvent) => void;
|
||||
onDisconnect: () => void;
|
||||
}
|
||||
|
||||
export function ConnectionForm({ authState, setAuthState, onSave, onDisconnect }: ConnectionFormProps) {
|
||||
// Check for saved token on mount
|
||||
useEffect(() => {
|
||||
const savedToken = Cookies.get(GITHUB_TOKEN_KEY) || getLocalStorage(GITHUB_TOKEN_KEY);
|
||||
|
||||
if (savedToken && !authState.tokenInfo?.token) {
|
||||
setAuthState((prev: GitHubAuthState) => ({
|
||||
...prev,
|
||||
tokenInfo: {
|
||||
token: savedToken,
|
||||
scope: [],
|
||||
avatar_url: '',
|
||||
name: null,
|
||||
created_at: new Date().toISOString(),
|
||||
followers: 0,
|
||||
},
|
||||
}));
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="rounded-xl bg-white dark:bg-[#0A0A0A] border border-[#E5E5E5] dark:border-[#1A1A1A] overflow-hidden">
|
||||
<div className="p-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 rounded-lg bg-[#F5F5F5] dark:bg-[#1A1A1A] border border-[#E5E5E5] dark:border-[#1A1A1A]">
|
||||
<div className="i-ph:plug-fill text-bolt-elements-textTertiary" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary">Connection Settings</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">Configure your GitHub connection</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={onSave} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="username" className="block text-sm font-medium text-bolt-elements-textSecondary mb-2">
|
||||
GitHub Username
|
||||
</label>
|
||||
<input
|
||||
id="username"
|
||||
type="text"
|
||||
value={authState.username}
|
||||
onChange={(e) => setAuthState((prev: GitHubAuthState) => ({ ...prev, username: e.target.value }))}
|
||||
className={classNames(
|
||||
'w-full px-4 py-2.5 bg-[#F5F5F5] dark:bg-[#1A1A1A] border rounded-lg',
|
||||
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary text-base',
|
||||
'border-[#E5E5E5] dark:border-[#1A1A1A]',
|
||||
'focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500',
|
||||
'transition-all duration-200',
|
||||
)}
|
||||
placeholder="e.g., octocat"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<label htmlFor="token" className="block text-sm font-medium text-bolt-elements-textSecondary">
|
||||
Personal Access Token
|
||||
</label>
|
||||
<a
|
||||
href="https://github.com/settings/tokens/new?scopes=repo,user,read:org,workflow,delete_repo,write:packages,read:packages"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={classNames(
|
||||
'inline-flex items-center gap-1.5 text-xs',
|
||||
'text-purple-500 hover:text-purple-600 dark:text-purple-400 dark:hover:text-purple-300',
|
||||
'transition-colors duration-200',
|
||||
)}
|
||||
>
|
||||
<span>Generate new token</span>
|
||||
<div className="i-ph:plus-circle" />
|
||||
</a>
|
||||
</div>
|
||||
<input
|
||||
id="token"
|
||||
type="password"
|
||||
value={authState.tokenInfo?.token || ''}
|
||||
onChange={(e) =>
|
||||
setAuthState((prev: GitHubAuthState) => ({
|
||||
...prev,
|
||||
tokenInfo: {
|
||||
token: e.target.value,
|
||||
scope: [],
|
||||
avatar_url: '',
|
||||
name: null,
|
||||
created_at: new Date().toISOString(),
|
||||
followers: 0,
|
||||
},
|
||||
username: '',
|
||||
isConnected: false,
|
||||
isVerifying: false,
|
||||
isLoadingRepos: false,
|
||||
}))
|
||||
}
|
||||
className={classNames(
|
||||
'w-full px-4 py-2.5 bg-[#F5F5F5] dark:bg-[#1A1A1A] border rounded-lg',
|
||||
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary text-base',
|
||||
'border-[#E5E5E5] dark:border-[#1A1A1A]',
|
||||
'focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500',
|
||||
'transition-all duration-200',
|
||||
)}
|
||||
placeholder="ghp_xxxxxxxxxxxx"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between pt-4 border-t border-[#E5E5E5] dark:border-[#1A1A1A]">
|
||||
<div className="flex items-center gap-4">
|
||||
{!authState.isConnected ? (
|
||||
<button
|
||||
type="submit"
|
||||
disabled={authState.isVerifying || !authState.username || !authState.tokenInfo?.token}
|
||||
className={classNames(
|
||||
'inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors',
|
||||
'bg-purple-500 hover:bg-purple-600',
|
||||
'text-white',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
)}
|
||||
>
|
||||
{authState.isVerifying ? (
|
||||
<>
|
||||
<div className="i-ph:spinner animate-spin" />
|
||||
<span>Verifying...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:plug-fill" />
|
||||
<span>Connect</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
onClick={onDisconnect}
|
||||
className={classNames(
|
||||
'inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors',
|
||||
'bg-[#F5F5F5] hover:bg-red-500/10 hover:text-red-500',
|
||||
'dark:bg-[#1A1A1A] dark:hover:bg-red-500/20 dark:hover:text-red-500',
|
||||
'text-bolt-elements-textPrimary',
|
||||
)}
|
||||
>
|
||||
<div className="i-ph:plug-fill" />
|
||||
<span>Disconnect</span>
|
||||
</button>
|
||||
<span className="inline-flex items-center gap-2 px-3 py-1.5 text-sm text-green-600 dark:text-green-400 bg-green-500/5 rounded-lg border border-green-500/20">
|
||||
<div className="i-ph:check-circle-fill" />
|
||||
<span>Connected</span>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{authState.rateLimits && (
|
||||
<div className="flex items-center gap-2 text-sm text-bolt-elements-textTertiary">
|
||||
<div className="i-ph:clock-countdown opacity-60" />
|
||||
<span>Rate limit resets at {authState.rateLimits.reset.toLocaleTimeString()}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { useState } from 'react';
|
||||
import * as Dialog from '@radix-ui/react-dialog';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import type { GitHubRepoInfo } from '~/components/@settings/tabs/connections/types/GitHub';
|
||||
import { GitBranch } from '@phosphor-icons/react';
|
||||
|
||||
interface GitHubBranch {
|
||||
name: string;
|
||||
default?: boolean;
|
||||
}
|
||||
|
||||
interface CreateBranchDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onConfirm: (branchName: string, sourceBranch: string) => void;
|
||||
repository: GitHubRepoInfo;
|
||||
branches?: GitHubBranch[];
|
||||
}
|
||||
|
||||
export function CreateBranchDialog({ isOpen, onClose, onConfirm, repository, branches }: CreateBranchDialogProps) {
|
||||
const [branchName, setBranchName] = useState('');
|
||||
const [sourceBranch, setSourceBranch] = useState(branches?.find((b) => b.default)?.name || 'main');
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
onConfirm(branchName, sourceBranch);
|
||||
setBranchName('');
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog.Root open={isOpen} onOpenChange={onClose}>
|
||||
<Dialog.Portal>
|
||||
<Dialog.Overlay className="fixed inset-0 bg-black/50 dark:bg-black/80" />
|
||||
<Dialog.Content
|
||||
className={classNames(
|
||||
'fixed top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%]',
|
||||
'w-full max-w-md p-6 rounded-xl shadow-lg',
|
||||
'bg-white dark:bg-[#0A0A0A]',
|
||||
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
|
||||
)}
|
||||
>
|
||||
<Dialog.Title className="text-lg font-medium text-bolt-elements-textPrimary mb-4">
|
||||
Create New Branch
|
||||
</Dialog.Title>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="branchName" className="block text-sm font-medium text-bolt-elements-textSecondary mb-2">
|
||||
Branch Name
|
||||
</label>
|
||||
<input
|
||||
id="branchName"
|
||||
type="text"
|
||||
value={branchName}
|
||||
onChange={(e) => setBranchName(e.target.value)}
|
||||
placeholder="feature/my-new-branch"
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg',
|
||||
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
|
||||
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
|
||||
'text-bolt-elements-textPrimary placeholder:text-bolt-elements-textTertiary',
|
||||
'focus:outline-none focus:ring-2 focus:ring-purple-500/50',
|
||||
)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="sourceBranch"
|
||||
className="block text-sm font-medium text-bolt-elements-textSecondary mb-2"
|
||||
>
|
||||
Source Branch
|
||||
</label>
|
||||
<select
|
||||
id="sourceBranch"
|
||||
value={sourceBranch}
|
||||
onChange={(e) => setSourceBranch(e.target.value)}
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg',
|
||||
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
|
||||
'border border-[#E5E5E5] dark:border-[#1A1A1A]',
|
||||
'text-bolt-elements-textPrimary',
|
||||
'focus:outline-none focus:ring-2 focus:ring-purple-500/50',
|
||||
)}
|
||||
>
|
||||
{branches?.map((branch) => (
|
||||
<option key={branch.name} value={branch.name}>
|
||||
{branch.name} {branch.default ? '(default)' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 p-3 bg-[#F5F5F5] dark:bg-[#1A1A1A] rounded-lg">
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textSecondary mb-2">Branch Overview</h4>
|
||||
<ul className="space-y-2 text-sm text-bolt-elements-textSecondary">
|
||||
<li className="flex items-center gap-2">
|
||||
<GitBranch className="text-lg" />
|
||||
Repository: {repository.name}
|
||||
</li>
|
||||
{branchName && (
|
||||
<li className="flex items-center gap-2">
|
||||
<div className="i-ph:check-circle text-green-500" />
|
||||
New branch will be created as: {branchName}
|
||||
</li>
|
||||
)}
|
||||
<li className="flex items-center gap-2">
|
||||
<div className="i-ph:check-circle text-green-500" />
|
||||
Based on: {sourceBranch}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm font-medium',
|
||||
'text-bolt-elements-textPrimary',
|
||||
'bg-[#F5F5F5] dark:bg-[#1A1A1A]',
|
||||
'hover:bg-purple-500/10 hover:text-purple-500',
|
||||
'dark:hover:bg-purple-500/20 dark:hover:text-purple-500',
|
||||
'transition-colors',
|
||||
)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm font-medium',
|
||||
'text-white bg-purple-500',
|
||||
'hover:bg-purple-600',
|
||||
'transition-colors',
|
||||
)}
|
||||
>
|
||||
Create Branch
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog.Content>
|
||||
</Dialog.Portal>
|
||||
</Dialog.Root>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
import * as Dialog from '@radix-ui/react-dialog';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { motion } from 'framer-motion';
|
||||
import { getLocalStorage } from '~/lib/persistence';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import type { GitHubUserResponse } from '~/types/GitHub';
|
||||
import { logStore } from '~/lib/stores/logs';
|
||||
import { workbenchStore } from '~/lib/stores/workbench';
|
||||
import { extractRelativePath } from '~/utils/diff';
|
||||
import { formatSize } from '~/utils/formatSize';
|
||||
import type { FileMap, File } from '~/lib/stores/files';
|
||||
import { Octokit } from '@octokit/rest';
|
||||
|
||||
interface PushToGitHubDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onPush: (repoName: string, username?: string, token?: string, isPrivate?: boolean) => Promise<string>;
|
||||
}
|
||||
|
||||
interface GitHubRepo {
|
||||
name: string;
|
||||
full_name: string;
|
||||
html_url: string;
|
||||
description: string;
|
||||
stargazers_count: number;
|
||||
forks_count: number;
|
||||
default_branch: string;
|
||||
updated_at: string;
|
||||
language: string;
|
||||
private: boolean;
|
||||
}
|
||||
|
||||
export function PushToGitHubDialog({ isOpen, onClose, onPush }: PushToGitHubDialogProps) {
|
||||
const [repoName, setRepoName] = useState('');
|
||||
const [isPrivate, setIsPrivate] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [user, setUser] = useState<GitHubUserResponse | null>(null);
|
||||
const [recentRepos, setRecentRepos] = useState<GitHubRepo[]>([]);
|
||||
const [isFetchingRepos, setIsFetchingRepos] = useState(false);
|
||||
const [showSuccessDialog, setShowSuccessDialog] = useState(false);
|
||||
const [createdRepoUrl, setCreatedRepoUrl] = useState('');
|
||||
const [pushedFiles, setPushedFiles] = useState<{ path: string; size: number }[]>([]);
|
||||
|
||||
// Load GitHub connection on mount
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
const connection = getLocalStorage('github_connection');
|
||||
|
||||
if (connection?.user && connection?.token) {
|
||||
setUser(connection.user);
|
||||
|
||||
// Only fetch if we have both user and token
|
||||
if (connection.token.trim()) {
|
||||
fetchRecentRepos(connection.token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const fetchRecentRepos = async (token: string) => {
|
||||
if (!token) {
|
||||
logStore.logError('No GitHub token available');
|
||||
toast.error('GitHub authentication required');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsFetchingRepos(true);
|
||||
|
||||
const response = await fetch(
|
||||
'https://api.github.com/user/repos?sort=updated&per_page=5&type=all&affiliation=owner,organization_member',
|
||||
{
|
||||
headers: {
|
||||
Accept: 'application/vnd.github.v3+json',
|
||||
Authorization: `Bearer ${token.trim()}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
|
||||
if (response.status === 401) {
|
||||
toast.error('GitHub token expired. Please reconnect your account.');
|
||||
|
||||
// Clear invalid token
|
||||
const connection = getLocalStorage('github_connection');
|
||||
|
||||
if (connection) {
|
||||
localStorage.removeItem('github_connection');
|
||||
setUser(null);
|
||||
}
|
||||
} else {
|
||||
logStore.logError('Failed to fetch GitHub repositories', {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
error: errorData,
|
||||
});
|
||||
toast.error(`Failed to fetch repositories: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const repos = (await response.json()) as GitHubRepo[];
|
||||
setRecentRepos(repos);
|
||||
} catch (error) {
|
||||
logStore.logError('Failed to fetch GitHub repositories', { error });
|
||||
toast.error('Failed to fetch recent repositories');
|
||||
} finally {
|
||||
setIsFetchingRepos(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
const connection = getLocalStorage('github_connection');
|
||||
|
||||
if (!connection?.token || !connection?.user) {
|
||||
toast.error('Please connect your GitHub account in Settings > Connections first');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!repoName.trim()) {
|
||||
toast.error('Repository name is required');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Check if repository exists first
|
||||
const octokit = new Octokit({ auth: connection.token });
|
||||
|
||||
try {
|
||||
await octokit.repos.get({
|
||||
owner: connection.user.login,
|
||||
repo: repoName,
|
||||
});
|
||||
|
||||
// If we get here, the repo exists
|
||||
const confirmOverwrite = window.confirm(
|
||||
`Repository "${repoName}" already exists. Do you want to update it? This will add or modify files in the repository.`,
|
||||
);
|
||||
|
||||
if (!confirmOverwrite) {
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
// 404 means repo doesn't exist, which is what we want for new repos
|
||||
if (error instanceof Error && 'status' in error && error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const repoUrl = await onPush(repoName, connection.user.login, connection.token, isPrivate);
|
||||
setCreatedRepoUrl(repoUrl);
|
||||
|
||||
// Get list of pushed files
|
||||
const files = workbenchStore.files.get();
|
||||
const filesList = Object.entries(files as FileMap)
|
||||
.filter(([, dirent]) => dirent?.type === 'file' && !dirent.isBinary)
|
||||
.map(([path, dirent]) => ({
|
||||
path: extractRelativePath(path),
|
||||
size: new TextEncoder().encode((dirent as File).content || '').length,
|
||||
}));
|
||||
|
||||
setPushedFiles(filesList);
|
||||
setShowSuccessDialog(true);
|
||||
} catch (error) {
|
||||
console.error('Error pushing to GitHub:', error);
|
||||
toast.error('Failed to push to GitHub. Please check your repository name and try again.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setRepoName('');
|
||||
setIsPrivate(false);
|
||||
setShowSuccessDialog(false);
|
||||
setCreatedRepoUrl('');
|
||||
onClose();
|
||||
};
|
||||
|
||||
// Success Dialog
|
||||
if (showSuccessDialog) {
|
||||
return (
|
||||
<Dialog.Root open={isOpen} onOpenChange={(open) => !open && handleClose()}>
|
||||
<Dialog.Portal>
|
||||
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999]" />
|
||||
<div className="fixed inset-0 flex items-center justify-center z-[9999]">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="w-[90vw] md:w-[600px] max-h-[85vh] overflow-y-auto"
|
||||
>
|
||||
<Dialog.Content className="bg-white dark:bg-[#1E1E1E] rounded-lg border border-[#E5E5E5] dark:border-[#333333] shadow-xl">
|
||||
<div className="p-6 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 text-green-500">
|
||||
<div className="i-ph:check-circle w-5 h-5" />
|
||||
<h3 className="text-lg font-medium">Successfully pushed to GitHub</h3>
|
||||
</div>
|
||||
<Dialog.Close
|
||||
onClick={handleClose}
|
||||
className="p-2 text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-gray-400"
|
||||
>
|
||||
<div className="i-ph:x w-5 h-5" />
|
||||
</Dialog.Close>
|
||||
</div>
|
||||
|
||||
<div className="bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 rounded-lg p-3 text-left">
|
||||
<p className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark mb-2">
|
||||
Repository URL
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="flex-1 text-sm bg-bolt-elements-background dark:bg-bolt-elements-background-dark px-3 py-2 rounded border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark font-mono">
|
||||
{createdRepoUrl}
|
||||
</code>
|
||||
<motion.button
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(createdRepoUrl);
|
||||
toast.success('URL copied to clipboard');
|
||||
}}
|
||||
className="p-2 text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary dark:text-bolt-elements-textSecondary-dark dark:hover:text-bolt-elements-textPrimary-dark"
|
||||
whileHover={{ scale: 1.1 }}
|
||||
whileTap={{ scale: 0.9 }}
|
||||
>
|
||||
<div className="i-ph:copy w-4 h-4" />
|
||||
</motion.button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 rounded-lg p-3">
|
||||
<p className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark mb-2">
|
||||
Pushed Files ({pushedFiles.length})
|
||||
</p>
|
||||
<div className="max-h-[200px] overflow-y-auto custom-scrollbar">
|
||||
{pushedFiles.map((file) => (
|
||||
<div
|
||||
key={file.path}
|
||||
className="flex items-center justify-between py-1 text-sm text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark"
|
||||
>
|
||||
<span className="font-mono truncate flex-1">{file.path}</span>
|
||||
<span className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark ml-2">
|
||||
{formatSize(file.size)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<motion.a
|
||||
href={createdRepoUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="px-4 py-2 rounded-lg bg-purple-500 text-white hover:bg-purple-600 text-sm inline-flex items-center gap-2"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
<div className="i-ph:github-logo w-4 h-4" />
|
||||
View Repository
|
||||
</motion.a>
|
||||
<motion.button
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(createdRepoUrl);
|
||||
toast.success('URL copied to clipboard');
|
||||
}}
|
||||
className="px-4 py-2 rounded-lg bg-[#F5F5F5] dark:bg-[#1A1A1A] text-gray-600 dark:text-gray-400 hover:bg-[#E5E5E5] dark:hover:bg-[#252525] text-sm inline-flex items-center gap-2"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
<div className="i-ph:copy w-4 h-4" />
|
||||
Copy URL
|
||||
</motion.button>
|
||||
<motion.button
|
||||
onClick={handleClose}
|
||||
className="px-4 py-2 rounded-lg bg-[#F5F5F5] dark:bg-[#1A1A1A] text-gray-600 dark:text-gray-400 hover:bg-[#E5E5E5] dark:hover:bg-[#252525] text-sm"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
Close
|
||||
</motion.button>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog.Content>
|
||||
</motion.div>
|
||||
</div>
|
||||
</Dialog.Portal>
|
||||
</Dialog.Root>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<Dialog.Root open={isOpen} onOpenChange={(open) => !open && handleClose()}>
|
||||
<Dialog.Portal>
|
||||
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999]" />
|
||||
<div className="fixed inset-0 flex items-center justify-center z-[9999]">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="w-[90vw] md:w-[500px]"
|
||||
>
|
||||
<Dialog.Content className="bg-white dark:bg-[#0A0A0A] rounded-lg p-6 border border-[#E5E5E5] dark:border-[#1A1A1A] shadow-xl">
|
||||
<div className="text-center space-y-4">
|
||||
<motion.div
|
||||
initial={{ scale: 0.8 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
className="mx-auto w-12 h-12 rounded-xl bg-bolt-elements-background-depth-3 flex items-center justify-center text-purple-500"
|
||||
>
|
||||
<div className="i-ph:github-logo w-6 h-6" />
|
||||
</motion.div>
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-white">GitHub Connection Required</h3>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Please connect your GitHub account in Settings {'>'} Connections to push your code to GitHub.
|
||||
</p>
|
||||
<motion.button
|
||||
className="px-4 py-2 rounded-lg bg-purple-500 text-white text-sm hover:bg-purple-600 inline-flex items-center gap-2"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
onClick={handleClose}
|
||||
>
|
||||
<div className="i-ph:x-circle" />
|
||||
Close
|
||||
</motion.button>
|
||||
</div>
|
||||
</Dialog.Content>
|
||||
</motion.div>
|
||||
</div>
|
||||
</Dialog.Portal>
|
||||
</Dialog.Root>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog.Root open={isOpen} onOpenChange={(open) => !open && handleClose()}>
|
||||
<Dialog.Portal>
|
||||
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999]" />
|
||||
<div className="fixed inset-0 flex items-center justify-center z-[9999]">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="w-[90vw] md:w-[500px]"
|
||||
>
|
||||
<Dialog.Content className="bg-white dark:bg-[#0A0A0A] rounded-lg border border-[#E5E5E5] dark:border-[#1A1A1A] shadow-xl">
|
||||
<div className="p-6">
|
||||
<div className="flex items-center gap-4 mb-6">
|
||||
<motion.div
|
||||
initial={{ scale: 0.8 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
className="w-10 h-10 rounded-xl bg-bolt-elements-background-depth-3 flex items-center justify-center text-purple-500"
|
||||
>
|
||||
<div className="i-ph:git-branch w-5 h-5" />
|
||||
</motion.div>
|
||||
<div>
|
||||
<Dialog.Title className="text-lg font-medium text-gray-900 dark:text-white">
|
||||
Push to GitHub
|
||||
</Dialog.Title>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Push your code to a new or existing GitHub repository
|
||||
</p>
|
||||
</div>
|
||||
<Dialog.Close
|
||||
className="ml-auto p-2 text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-gray-400"
|
||||
onClick={handleClose}
|
||||
>
|
||||
<div className="i-ph:x w-5 h-5" />
|
||||
</Dialog.Close>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 mb-6 p-3 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 rounded-lg">
|
||||
<img src={user.avatar_url} alt={user.login} className="w-10 h-10 rounded-full" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-900 dark:text-white">{user.name || user.login}</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">@{user.login}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="repoName" className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Repository Name
|
||||
</label>
|
||||
<input
|
||||
id="repoName"
|
||||
type="text"
|
||||
value={repoName}
|
||||
onChange={(e) => setRepoName(e.target.value)}
|
||||
placeholder="my-awesome-project"
|
||||
className="w-full px-4 py-2 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 border border-[#E5E5E5] dark:border-[#1A1A1A] text-gray-900 dark:text-white placeholder-gray-400"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{recentRepos.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm text-gray-600 dark:text-gray-400">Recent Repositories</label>
|
||||
<div className="space-y-2">
|
||||
{recentRepos.map((repo) => (
|
||||
<motion.button
|
||||
key={repo.full_name}
|
||||
type="button"
|
||||
onClick={() => setRepoName(repo.name)}
|
||||
className="w-full p-3 text-left rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 hover:bg-bolt-elements-background-depth-3 dark:hover:bg-bolt-elements-background-depth-4 transition-colors group"
|
||||
whileHover={{ scale: 1.01 }}
|
||||
whileTap={{ scale: 0.99 }}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="i-ph:git-repository w-4 h-4 text-purple-500" />
|
||||
<span className="text-sm font-medium text-gray-900 dark:text-white group-hover:text-purple-500">
|
||||
{repo.name}
|
||||
</span>
|
||||
</div>
|
||||
{repo.private && (
|
||||
<span className="text-xs px-2 py-1 rounded-full bg-purple-500/10 text-purple-500">
|
||||
Private
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{repo.description && (
|
||||
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400 line-clamp-2">
|
||||
{repo.description}
|
||||
</p>
|
||||
)}
|
||||
<div className="mt-2 flex items-center gap-3 text-xs text-gray-400 dark:text-gray-500">
|
||||
{repo.language && (
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:code w-3 h-3" />
|
||||
{repo.language}
|
||||
</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:star w-3 h-3" />
|
||||
{repo.stargazers_count.toLocaleString()}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:git-fork w-3 h-3" />
|
||||
{repo.forks_count.toLocaleString()}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:clock w-3 h-3" />
|
||||
{new Date(repo.updated_at).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
</motion.button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isFetchingRepos && (
|
||||
<div className="flex items-center justify-center py-4 text-gray-500 dark:text-gray-400">
|
||||
<div className="i-ph:spinner-gap-bold animate-spin w-4 h-4 mr-2" />
|
||||
Loading repositories...
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="private"
|
||||
checked={isPrivate}
|
||||
onChange={(e) => setIsPrivate(e.target.checked)}
|
||||
className="rounded border-[#E5E5E5] dark:border-[#1A1A1A] text-purple-500 focus:ring-purple-500 dark:bg-[#0A0A0A]"
|
||||
/>
|
||||
<label htmlFor="private" className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Make repository private
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 flex gap-2">
|
||||
<motion.button
|
||||
type="button"
|
||||
onClick={handleClose}
|
||||
className="px-4 py-2 rounded-lg bg-[#F5F5F5] dark:bg-[#1A1A1A] text-gray-600 dark:text-gray-400 hover:bg-[#E5E5E5] dark:hover:bg-[#252525] text-sm"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
Cancel
|
||||
</motion.button>
|
||||
<motion.button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className={classNames(
|
||||
'flex-1 px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 text-sm inline-flex items-center justify-center gap-2',
|
||||
isLoading ? 'opacity-50 cursor-not-allowed' : '',
|
||||
)}
|
||||
whileHover={!isLoading ? { scale: 1.02 } : {}}
|
||||
whileTap={!isLoading ? { scale: 0.98 } : {}}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap-bold animate-spin w-4 h-4" />
|
||||
Pushing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:git-branch w-4 h-4" />
|
||||
Push to GitHub
|
||||
</>
|
||||
)}
|
||||
</motion.button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</Dialog.Content>
|
||||
</motion.div>
|
||||
</div>
|
||||
</Dialog.Portal>
|
||||
</Dialog.Root>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,693 @@
|
||||
import type { GitHubRepoInfo, GitHubContent, RepositoryStats } from '~/types/GitHub';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import * as Dialog from '@radix-ui/react-dialog';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { getLocalStorage } from '~/lib/persistence';
|
||||
import { motion } from 'framer-motion';
|
||||
import { formatSize } from '~/utils/formatSize';
|
||||
import { Input } from '~/components/ui/Input';
|
||||
|
||||
interface GitHubTreeResponse {
|
||||
tree: Array<{
|
||||
path: string;
|
||||
type: string;
|
||||
size?: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface RepositorySelectionDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSelect: (url: string) => void;
|
||||
}
|
||||
|
||||
interface SearchFilters {
|
||||
language?: string;
|
||||
stars?: number;
|
||||
forks?: number;
|
||||
}
|
||||
|
||||
interface StatsDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onConfirm: () => void;
|
||||
stats: RepositoryStats;
|
||||
isLargeRepo?: boolean;
|
||||
}
|
||||
|
||||
function StatsDialog({ isOpen, onClose, onConfirm, stats, isLargeRepo }: StatsDialogProps) {
|
||||
return (
|
||||
<Dialog.Root open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<Dialog.Portal>
|
||||
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999]" />
|
||||
<div className="fixed inset-0 flex items-center justify-center z-[9999]">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="w-[90vw] md:w-[500px]"
|
||||
>
|
||||
<Dialog.Content className="bg-white dark:bg-[#1E1E1E] rounded-lg border border-[#E5E5E5] dark:border-[#333333] shadow-xl">
|
||||
<div className="p-6 space-y-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-medium text-[#111111] dark:text-white">Repository Overview</h3>
|
||||
<div className="mt-4 space-y-2">
|
||||
<p className="text-sm text-[#666666] dark:text-[#999999]">Repository Statistics:</p>
|
||||
<div className="space-y-2 text-sm text-[#111111] dark:text-white">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="i-ph:files text-purple-500 w-4 h-4" />
|
||||
<span>Total Files: {stats.totalFiles}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="i-ph:database text-purple-500 w-4 h-4" />
|
||||
<span>Total Size: {formatSize(stats.totalSize)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="i-ph:code text-purple-500 w-4 h-4" />
|
||||
<span>
|
||||
Languages:{' '}
|
||||
{Object.entries(stats.languages)
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.slice(0, 3)
|
||||
.map(([lang, size]) => `${lang} (${formatSize(size)})`)
|
||||
.join(', ')}
|
||||
</span>
|
||||
</div>
|
||||
{stats.hasPackageJson && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="i-ph:package text-purple-500 w-4 h-4" />
|
||||
<span>Has package.json</span>
|
||||
</div>
|
||||
)}
|
||||
{stats.hasDependencies && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="i-ph:tree-structure text-purple-500 w-4 h-4" />
|
||||
<span>Has dependencies</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{isLargeRepo && (
|
||||
<div className="mt-4 p-3 bg-yellow-50 dark:bg-yellow-500/10 rounded-lg text-sm flex items-start gap-2">
|
||||
<span className="i-ph:warning text-yellow-600 dark:text-yellow-500 w-4 h-4 flex-shrink-0 mt-0.5" />
|
||||
<div className="text-yellow-800 dark:text-yellow-500">
|
||||
This repository is quite large ({formatSize(stats.totalSize)}). Importing it might take a while
|
||||
and could impact performance.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t border-[#E5E5E5] dark:border-[#333333] p-4 flex justify-end gap-3 bg-[#F9F9F9] dark:bg-[#252525] rounded-b-lg">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 rounded-lg bg-[#F5F5F5] dark:bg-[#333333] text-[#666666] hover:text-[#111111] dark:text-[#999999] dark:hover:text-white transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={onConfirm}
|
||||
className="px-4 py-2 rounded-lg bg-purple-500 text-white hover:bg-purple-600 transition-colors"
|
||||
>
|
||||
OK
|
||||
</button>
|
||||
</div>
|
||||
</Dialog.Content>
|
||||
</motion.div>
|
||||
</div>
|
||||
</Dialog.Portal>
|
||||
</Dialog.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export function RepositorySelectionDialog({ isOpen, onClose, onSelect }: RepositorySelectionDialogProps) {
|
||||
const [selectedRepository, setSelectedRepository] = useState<GitHubRepoInfo | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [repositories, setRepositories] = useState<GitHubRepoInfo[]>([]);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [searchResults, setSearchResults] = useState<GitHubRepoInfo[]>([]);
|
||||
const [activeTab, setActiveTab] = useState<'my-repos' | 'search' | 'url'>('my-repos');
|
||||
const [customUrl, setCustomUrl] = useState('');
|
||||
const [branches, setBranches] = useState<{ name: string; default?: boolean }[]>([]);
|
||||
const [selectedBranch, setSelectedBranch] = useState('');
|
||||
const [filters, setFilters] = useState<SearchFilters>({});
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const [stats, setStats] = useState<RepositoryStats | null>(null);
|
||||
const [showStatsDialog, setShowStatsDialog] = useState(false);
|
||||
const [currentStats, setCurrentStats] = useState<RepositoryStats | null>(null);
|
||||
const [pendingGitUrl, setPendingGitUrl] = useState<string>('');
|
||||
|
||||
// Fetch user's repositories when dialog opens
|
||||
useEffect(() => {
|
||||
if (isOpen && activeTab === 'my-repos') {
|
||||
fetchUserRepos();
|
||||
}
|
||||
}, [isOpen, activeTab]);
|
||||
|
||||
const fetchUserRepos = async () => {
|
||||
const connection = getLocalStorage('github_connection');
|
||||
|
||||
if (!connection?.token) {
|
||||
toast.error('Please connect your GitHub account first');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch('https://api.github.com/user/repos?sort=updated&per_page=100&type=all', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch repositories');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Add type assertion and validation
|
||||
if (
|
||||
Array.isArray(data) &&
|
||||
data.every((item) => typeof item === 'object' && item !== null && 'full_name' in item)
|
||||
) {
|
||||
setRepositories(data as GitHubRepoInfo[]);
|
||||
} else {
|
||||
throw new Error('Invalid repository data format');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching repos:', error);
|
||||
toast.error('Failed to fetch your repositories');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSearch = async (query: string) => {
|
||||
setIsLoading(true);
|
||||
setSearchResults([]);
|
||||
|
||||
try {
|
||||
let searchQuery = query;
|
||||
|
||||
if (filters.language) {
|
||||
searchQuery += ` language:${filters.language}`;
|
||||
}
|
||||
|
||||
if (filters.stars) {
|
||||
searchQuery += ` stars:>${filters.stars}`;
|
||||
}
|
||||
|
||||
if (filters.forks) {
|
||||
searchQuery += ` forks:>${filters.forks}`;
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`https://api.github.com/search/repositories?q=${encodeURIComponent(searchQuery)}&sort=stars&order=desc`,
|
||||
{
|
||||
headers: {
|
||||
Accept: 'application/vnd.github.v3+json',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to search repositories');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Add type assertion and validation
|
||||
if (typeof data === 'object' && data !== null && 'items' in data && Array.isArray(data.items)) {
|
||||
setSearchResults(data.items as GitHubRepoInfo[]);
|
||||
} else {
|
||||
throw new Error('Invalid search results format');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error searching repos:', error);
|
||||
toast.error('Failed to search repositories');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchBranches = async (repo: GitHubRepoInfo) => {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(`https://api.github.com/repos/${repo.full_name}/branches`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${getLocalStorage('github_connection')?.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch branches');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Add type assertion and validation
|
||||
if (Array.isArray(data) && data.every((item) => typeof item === 'object' && item !== null && 'name' in item)) {
|
||||
setBranches(
|
||||
data.map((branch) => ({
|
||||
name: branch.name,
|
||||
default: branch.name === repo.default_branch,
|
||||
})),
|
||||
);
|
||||
} else {
|
||||
throw new Error('Invalid branch data format');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching branches:', error);
|
||||
toast.error('Failed to fetch branches');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRepoSelect = async (repo: GitHubRepoInfo) => {
|
||||
setSelectedRepository(repo);
|
||||
await fetchBranches(repo);
|
||||
};
|
||||
|
||||
const formatGitUrl = (url: string): string => {
|
||||
// Remove any tree references and ensure .git extension
|
||||
const baseUrl = url
|
||||
.replace(/\/tree\/[^/]+/, '') // Remove /tree/branch-name
|
||||
.replace(/\/$/, '') // Remove trailing slash
|
||||
.replace(/\.git$/, ''); // Remove .git if present
|
||||
return `${baseUrl}.git`;
|
||||
};
|
||||
|
||||
const verifyRepository = async (repoUrl: string): Promise<RepositoryStats | null> => {
|
||||
try {
|
||||
const [owner, repo] = repoUrl
|
||||
.replace(/\.git$/, '')
|
||||
.split('/')
|
||||
.slice(-2);
|
||||
|
||||
const connection = getLocalStorage('github_connection');
|
||||
const headers: HeadersInit = connection?.token ? { Authorization: `Bearer ${connection.token}` } : {};
|
||||
|
||||
// Fetch repository tree
|
||||
const treeResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}/git/trees/main?recursive=1`, {
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!treeResponse.ok) {
|
||||
throw new Error('Failed to fetch repository structure');
|
||||
}
|
||||
|
||||
const treeData = (await treeResponse.json()) as GitHubTreeResponse;
|
||||
|
||||
// Calculate repository stats
|
||||
let totalSize = 0;
|
||||
let totalFiles = 0;
|
||||
const languages: { [key: string]: number } = {};
|
||||
let hasPackageJson = false;
|
||||
let hasDependencies = false;
|
||||
|
||||
for (const file of treeData.tree) {
|
||||
if (file.type === 'blob') {
|
||||
totalFiles++;
|
||||
|
||||
if (file.size) {
|
||||
totalSize += file.size;
|
||||
}
|
||||
|
||||
// Check for package.json
|
||||
if (file.path === 'package.json') {
|
||||
hasPackageJson = true;
|
||||
|
||||
// Fetch package.json content to check dependencies
|
||||
const contentResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}/contents/package.json`, {
|
||||
headers,
|
||||
});
|
||||
|
||||
if (contentResponse.ok) {
|
||||
const content = (await contentResponse.json()) as GitHubContent;
|
||||
const packageJson = JSON.parse(Buffer.from(content.content, 'base64').toString());
|
||||
hasDependencies = !!(
|
||||
packageJson.dependencies ||
|
||||
packageJson.devDependencies ||
|
||||
packageJson.peerDependencies
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Detect language based on file extension
|
||||
const ext = file.path.split('.').pop()?.toLowerCase();
|
||||
|
||||
if (ext) {
|
||||
languages[ext] = (languages[ext] || 0) + (file.size || 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const stats: RepositoryStats = {
|
||||
totalFiles,
|
||||
totalSize,
|
||||
languages,
|
||||
hasPackageJson,
|
||||
hasDependencies,
|
||||
};
|
||||
|
||||
setStats(stats);
|
||||
|
||||
return stats;
|
||||
} catch (error) {
|
||||
console.error('Error verifying repository:', error);
|
||||
toast.error('Failed to verify repository');
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = async () => {
|
||||
try {
|
||||
let gitUrl: string;
|
||||
|
||||
if (activeTab === 'url' && customUrl) {
|
||||
gitUrl = formatGitUrl(customUrl);
|
||||
} else if (selectedRepository) {
|
||||
gitUrl = formatGitUrl(selectedRepository.html_url);
|
||||
|
||||
if (selectedBranch) {
|
||||
gitUrl = `${gitUrl}#${selectedBranch}`;
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify repository before importing
|
||||
const stats = await verifyRepository(gitUrl);
|
||||
|
||||
if (!stats) {
|
||||
return;
|
||||
}
|
||||
|
||||
setCurrentStats(stats);
|
||||
setPendingGitUrl(gitUrl);
|
||||
setShowStatsDialog(true);
|
||||
} catch (error) {
|
||||
console.error('Error preparing repository:', error);
|
||||
toast.error('Failed to prepare repository. Please try again.');
|
||||
}
|
||||
};
|
||||
|
||||
const handleStatsConfirm = () => {
|
||||
setShowStatsDialog(false);
|
||||
|
||||
if (pendingGitUrl) {
|
||||
onSelect(pendingGitUrl);
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
const handleFilterChange = (key: keyof SearchFilters, value: string) => {
|
||||
let parsedValue: string | number | undefined = value;
|
||||
|
||||
if (key === 'stars' || key === 'forks') {
|
||||
parsedValue = value ? parseInt(value, 10) : undefined;
|
||||
}
|
||||
|
||||
setFilters((prev) => ({ ...prev, [key]: parsedValue }));
|
||||
handleSearch(searchQuery);
|
||||
};
|
||||
|
||||
// Handle dialog close properly
|
||||
const handleClose = () => {
|
||||
setIsLoading(false); // Reset loading state
|
||||
setSearchQuery(''); // Reset search
|
||||
setSearchResults([]); // Reset results
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog.Root
|
||||
open={isOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
handleClose();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Dialog.Portal>
|
||||
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50" />
|
||||
<Dialog.Content className="fixed top-[50%] left-[50%] -translate-x-1/2 -translate-y-1/2 w-[90vw] md:w-[600px] max-h-[85vh] overflow-hidden bg-white dark:bg-[#1A1A1A] rounded-xl shadow-xl z-[51] border border-[#E5E5E5] dark:border-[#333333]">
|
||||
<div className="p-4 border-b border-[#E5E5E5] dark:border-[#333333] flex items-center justify-between">
|
||||
<Dialog.Title className="text-lg font-semibold text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark">
|
||||
Import GitHub Repository
|
||||
</Dialog.Title>
|
||||
<Dialog.Close
|
||||
onClick={handleClose}
|
||||
className={classNames(
|
||||
'p-2 rounded-lg transition-all duration-200 ease-in-out',
|
||||
'text-bolt-elements-textTertiary hover:text-bolt-elements-textPrimary',
|
||||
'dark:text-bolt-elements-textTertiary-dark dark:hover:text-bolt-elements-textPrimary-dark',
|
||||
'hover:bg-bolt-elements-background-depth-2 dark:hover:bg-bolt-elements-background-depth-3',
|
||||
'focus:outline-none focus:ring-2 focus:ring-bolt-elements-borderColor dark:focus:ring-bolt-elements-borderColor-dark',
|
||||
)}
|
||||
>
|
||||
<span className="i-ph:x block w-5 h-5" aria-hidden="true" />
|
||||
<span className="sr-only">Close dialog</span>
|
||||
</Dialog.Close>
|
||||
</div>
|
||||
|
||||
<div className="p-4">
|
||||
<div className="flex gap-2 mb-4">
|
||||
<TabButton active={activeTab === 'my-repos'} onClick={() => setActiveTab('my-repos')}>
|
||||
<span className="i-ph:book-bookmark" />
|
||||
My Repos
|
||||
</TabButton>
|
||||
<TabButton active={activeTab === 'search'} onClick={() => setActiveTab('search')}>
|
||||
<span className="i-ph:magnifying-glass" />
|
||||
Search
|
||||
</TabButton>
|
||||
<TabButton active={activeTab === 'url'} onClick={() => setActiveTab('url')}>
|
||||
<span className="i-ph:link" />
|
||||
URL
|
||||
</TabButton>
|
||||
</div>
|
||||
|
||||
{activeTab === 'url' ? (
|
||||
<div className="space-y-4">
|
||||
<Input
|
||||
placeholder="Enter repository URL"
|
||||
value={customUrl}
|
||||
onChange={(e) => setCustomUrl(e.target.value)}
|
||||
className={classNames('w-full', {
|
||||
'border-red-500': false,
|
||||
})}
|
||||
/>
|
||||
<button
|
||||
onClick={handleImport}
|
||||
disabled={!customUrl}
|
||||
className="w-full h-10 px-4 py-2 rounded-lg bg-purple-500 text-white hover:bg-purple-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 flex items-center gap-2 justify-center"
|
||||
>
|
||||
Import Repository
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{activeTab === 'search' && (
|
||||
<div className="space-y-4 mb-4">
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search repositories..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => {
|
||||
setSearchQuery(e.target.value);
|
||||
handleSearch(e.target.value);
|
||||
}}
|
||||
className="flex-1 px-4 py-2 rounded-lg bg-[#F5F5F5] dark:bg-[#252525] border border-[#E5E5E5] dark:border-[#333333] text-bolt-elements-textPrimary"
|
||||
/>
|
||||
<button
|
||||
onClick={() => setFilters({})}
|
||||
className="px-3 py-2 rounded-lg bg-[#F5F5F5] dark:bg-[#252525] text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary"
|
||||
>
|
||||
<span className="i-ph:funnel-simple" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Filter by language..."
|
||||
value={filters.language || ''}
|
||||
onChange={(e) => {
|
||||
setFilters({ ...filters, language: e.target.value });
|
||||
handleSearch(searchQuery);
|
||||
}}
|
||||
className="px-3 py-1.5 text-sm rounded-lg bg-[#F5F5F5] dark:bg-[#252525] border border-[#E5E5E5] dark:border-[#333333]"
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
placeholder="Min stars..."
|
||||
value={filters.stars || ''}
|
||||
onChange={(e) => handleFilterChange('stars', e.target.value)}
|
||||
className="px-3 py-1.5 text-sm rounded-lg bg-[#F5F5F5] dark:bg-[#252525] border border-[#E5E5E5] dark:border-[#333333]"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
placeholder="Min forks..."
|
||||
value={filters.forks || ''}
|
||||
onChange={(e) => handleFilterChange('forks', e.target.value)}
|
||||
className="px-3 py-1.5 text-sm rounded-lg bg-[#F5F5F5] dark:bg-[#252525] border border-[#E5E5E5] dark:border-[#333333]"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3 max-h-[400px] overflow-y-auto pr-2 custom-scrollbar">
|
||||
{selectedRepository ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setSelectedRepository(null)}
|
||||
className="p-1.5 rounded-lg hover:bg-[#F5F5F5] dark:hover:bg-[#252525]"
|
||||
>
|
||||
<span className="i-ph:arrow-left w-4 h-4" />
|
||||
</button>
|
||||
<h3 className="font-medium">{selectedRepository.full_name}</h3>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm text-bolt-elements-textSecondary">Select Branch</label>
|
||||
<select
|
||||
value={selectedBranch}
|
||||
onChange={(e) => setSelectedBranch(e.target.value)}
|
||||
className="w-full px-3 py-2 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark focus:outline-none focus:ring-2 focus:ring-bolt-elements-borderColor dark:focus:ring-bolt-elements-borderColor-dark"
|
||||
>
|
||||
{branches.map((branch) => (
|
||||
<option
|
||||
key={branch.name}
|
||||
value={branch.name}
|
||||
className="bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark"
|
||||
>
|
||||
{branch.name} {branch.default ? '(default)' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
onClick={handleImport}
|
||||
className="w-full h-10 px-4 py-2 rounded-lg bg-purple-500 text-white hover:bg-purple-600 transition-all duration-200 flex items-center gap-2 justify-center"
|
||||
>
|
||||
Import Selected Branch
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<RepositoryList
|
||||
repos={activeTab === 'my-repos' ? repositories : searchResults}
|
||||
isLoading={isLoading}
|
||||
onSelect={handleRepoSelect}
|
||||
activeTab={activeTab}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Dialog.Content>
|
||||
</Dialog.Portal>
|
||||
{currentStats && (
|
||||
<StatsDialog
|
||||
isOpen={showStatsDialog}
|
||||
onClose={handleStatsConfirm}
|
||||
onConfirm={handleStatsConfirm}
|
||||
stats={currentStats}
|
||||
isLargeRepo={currentStats.totalSize > 50 * 1024 * 1024}
|
||||
/>
|
||||
)}
|
||||
</Dialog.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function TabButton({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={classNames(
|
||||
'px-4 py-2 h-10 rounded-lg transition-all duration-200 flex items-center gap-2 min-w-[120px] justify-center',
|
||||
active
|
||||
? 'bg-purple-500 text-white hover:bg-purple-600'
|
||||
: 'bg-[#F5F5F5] dark:bg-[#252525] text-bolt-elements-textPrimary dark:text-white hover:bg-[#E5E5E5] dark:hover:bg-[#333333] border border-[#E5E5E5] dark:border-[#333333]',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function RepositoryList({
|
||||
repos,
|
||||
isLoading,
|
||||
onSelect,
|
||||
activeTab,
|
||||
}: {
|
||||
repos: GitHubRepoInfo[];
|
||||
isLoading: boolean;
|
||||
onSelect: (repo: GitHubRepoInfo) => void;
|
||||
activeTab: string;
|
||||
}) {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-8 text-bolt-elements-textSecondary">
|
||||
<span className="i-ph:spinner animate-spin mr-2" />
|
||||
Loading repositories...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (repos.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-8 text-bolt-elements-textSecondary">
|
||||
<span className="i-ph:folder-simple-dashed w-12 h-12 mb-2 opacity-50" />
|
||||
<p>{activeTab === 'my-repos' ? 'No repositories found' : 'Search for repositories'}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return repos.map((repo) => <RepositoryCard key={repo.full_name} repo={repo} onSelect={() => onSelect(repo)} />);
|
||||
}
|
||||
|
||||
function RepositoryCard({ repo, onSelect }: { repo: GitHubRepoInfo; onSelect: () => void }) {
|
||||
return (
|
||||
<div className="p-4 rounded-lg bg-[#F5F5F5] dark:bg-[#252525] border border-[#E5E5E5] dark:border-[#333333] hover:border-purple-500/50 transition-colors">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="i-ph:git-repository text-bolt-elements-textTertiary" />
|
||||
<h3 className="font-medium text-bolt-elements-textPrimary dark:text-white">{repo.name}</h3>
|
||||
</div>
|
||||
<button
|
||||
onClick={onSelect}
|
||||
className="px-4 py-2 h-10 rounded-lg bg-purple-500 text-white hover:bg-purple-600 transition-all duration-200 flex items-center gap-2 min-w-[120px] justify-center"
|
||||
>
|
||||
<span className="i-ph:download-simple w-4 h-4" />
|
||||
Import
|
||||
</button>
|
||||
</div>
|
||||
{repo.description && <p className="text-sm text-bolt-elements-textSecondary mb-3">{repo.description}</p>}
|
||||
<div className="flex items-center gap-4 text-sm text-bolt-elements-textTertiary">
|
||||
{repo.language && (
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="i-ph:code" />
|
||||
{repo.language}
|
||||
</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="i-ph:star" />
|
||||
{repo.stargazers_count.toLocaleString()}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="i-ph:clock" />
|
||||
{new Date(repo.updated_at).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
95
app/components/@settings/tabs/connections/types/GitHub.ts
Normal file
95
app/components/@settings/tabs/connections/types/GitHub.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
export interface GitHubUserResponse {
|
||||
login: string;
|
||||
avatar_url: string;
|
||||
html_url: string;
|
||||
name: string;
|
||||
bio: string;
|
||||
public_repos: number;
|
||||
followers: number;
|
||||
following: number;
|
||||
public_gists: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface GitHubRepoInfo {
|
||||
name: string;
|
||||
full_name: string;
|
||||
html_url: string;
|
||||
description: string;
|
||||
stargazers_count: number;
|
||||
forks_count: number;
|
||||
default_branch: string;
|
||||
updated_at: string;
|
||||
language: string;
|
||||
languages_url: string;
|
||||
}
|
||||
|
||||
export interface GitHubOrganization {
|
||||
login: string;
|
||||
avatar_url: string;
|
||||
description: string;
|
||||
html_url: string;
|
||||
}
|
||||
|
||||
export interface GitHubEvent {
|
||||
id: string;
|
||||
type: string;
|
||||
created_at: string;
|
||||
repo: {
|
||||
name: string;
|
||||
url: string;
|
||||
};
|
||||
payload: {
|
||||
action?: string;
|
||||
ref?: string;
|
||||
ref_type?: string;
|
||||
description?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface GitHubLanguageStats {
|
||||
[key: string]: number;
|
||||
}
|
||||
|
||||
export interface GitHubStats {
|
||||
repos: GitHubRepoInfo[];
|
||||
totalStars: number;
|
||||
totalForks: number;
|
||||
organizations: GitHubOrganization[];
|
||||
recentActivity: GitHubEvent[];
|
||||
languages: GitHubLanguageStats;
|
||||
totalGists: number;
|
||||
}
|
||||
|
||||
export interface GitHubConnection {
|
||||
user: GitHubUserResponse | null;
|
||||
token: string;
|
||||
tokenType: 'classic' | 'fine-grained';
|
||||
stats?: GitHubStats;
|
||||
}
|
||||
|
||||
export interface GitHubTokenInfo {
|
||||
token: string;
|
||||
scope: string[];
|
||||
avatar_url: string;
|
||||
name: string | null;
|
||||
created_at: string;
|
||||
followers: number;
|
||||
}
|
||||
|
||||
export interface GitHubRateLimits {
|
||||
limit: number;
|
||||
remaining: number;
|
||||
reset: Date;
|
||||
used: number;
|
||||
}
|
||||
|
||||
export interface GitHubAuthState {
|
||||
username: string;
|
||||
tokenInfo: GitHubTokenInfo | null;
|
||||
isConnected: boolean;
|
||||
isVerifying: boolean;
|
||||
isLoadingRepos: boolean;
|
||||
rateLimits?: GitHubRateLimits;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,384 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Chart as ChartJS,
|
||||
CategoryScale,
|
||||
LinearScale,
|
||||
BarElement,
|
||||
Title,
|
||||
Tooltip,
|
||||
Legend,
|
||||
ArcElement,
|
||||
PointElement,
|
||||
LineElement,
|
||||
} from 'chart.js';
|
||||
import { Bar, Pie } from 'react-chartjs-2';
|
||||
import type { Chat } from '~/lib/persistence/chats';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
// Register ChartJS components
|
||||
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, ArcElement, PointElement, LineElement);
|
||||
|
||||
type DataVisualizationProps = {
|
||||
chats: Chat[];
|
||||
};
|
||||
|
||||
export function DataVisualization({ chats }: DataVisualizationProps) {
|
||||
const [chatsByDate, setChatsByDate] = useState<Record<string, number>>({});
|
||||
const [messagesByRole, setMessagesByRole] = useState<Record<string, number>>({});
|
||||
const [apiKeyUsage, setApiKeyUsage] = useState<Array<{ provider: string; count: number }>>([]);
|
||||
const [averageMessagesPerChat, setAverageMessagesPerChat] = useState<number>(0);
|
||||
const [isDarkMode, setIsDarkMode] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
setIsDarkMode(isDark);
|
||||
|
||||
const observer = new MutationObserver((mutations) => {
|
||||
mutations.forEach((mutation) => {
|
||||
if (mutation.attributeName === 'class') {
|
||||
setIsDarkMode(document.documentElement.classList.contains('dark'));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
observer.observe(document.documentElement, { attributes: true });
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!chats || chats.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Process chat data
|
||||
const chatDates: Record<string, number> = {};
|
||||
const roleCounts: Record<string, number> = {};
|
||||
const apiUsage: Record<string, number> = {};
|
||||
let totalMessages = 0;
|
||||
|
||||
chats.forEach((chat) => {
|
||||
const date = new Date(chat.timestamp).toLocaleDateString();
|
||||
chatDates[date] = (chatDates[date] || 0) + 1;
|
||||
|
||||
chat.messages.forEach((message) => {
|
||||
roleCounts[message.role] = (roleCounts[message.role] || 0) + 1;
|
||||
totalMessages++;
|
||||
|
||||
if (message.role === 'assistant') {
|
||||
const providerMatch = message.content.match(/provider:\s*([\w-]+)/i);
|
||||
const provider = providerMatch ? providerMatch[1] : 'unknown';
|
||||
apiUsage[provider] = (apiUsage[provider] || 0) + 1;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const sortedDates = Object.keys(chatDates).sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
|
||||
const sortedChatsByDate: Record<string, number> = {};
|
||||
sortedDates.forEach((date) => {
|
||||
sortedChatsByDate[date] = chatDates[date];
|
||||
});
|
||||
|
||||
setChatsByDate(sortedChatsByDate);
|
||||
setMessagesByRole(roleCounts);
|
||||
setApiKeyUsage(Object.entries(apiUsage).map(([provider, count]) => ({ provider, count })));
|
||||
setAverageMessagesPerChat(totalMessages / chats.length);
|
||||
}, [chats]);
|
||||
|
||||
// Get theme colors from CSS variables to ensure theme consistency
|
||||
const getThemeColor = (varName: string): string => {
|
||||
// Get the CSS variable value from document root
|
||||
if (typeof document !== 'undefined') {
|
||||
return getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
|
||||
}
|
||||
|
||||
// Fallback for SSR
|
||||
return isDarkMode ? '#FFFFFF' : '#000000';
|
||||
};
|
||||
|
||||
// Theme-aware chart colors with enhanced dark mode visibility using CSS variables
|
||||
const chartColors = {
|
||||
grid: isDarkMode ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.1)',
|
||||
text: getThemeColor('--bolt-elements-textPrimary'),
|
||||
textSecondary: getThemeColor('--bolt-elements-textSecondary'),
|
||||
background: getThemeColor('--bolt-elements-bg-depth-1'),
|
||||
accent: getThemeColor('--bolt-elements-button-primary-text'),
|
||||
border: getThemeColor('--bolt-elements-borderColor'),
|
||||
};
|
||||
|
||||
const getChartColors = (index: number) => {
|
||||
// Define color palettes based on Bolt design tokens
|
||||
const baseColors = [
|
||||
// Indigo
|
||||
{
|
||||
base: getThemeColor('--bolt-elements-button-primary-text'),
|
||||
},
|
||||
|
||||
// Pink
|
||||
{
|
||||
base: isDarkMode ? 'rgb(244, 114, 182)' : 'rgb(236, 72, 153)',
|
||||
},
|
||||
|
||||
// Green
|
||||
{
|
||||
base: getThemeColor('--bolt-elements-icon-success'),
|
||||
},
|
||||
|
||||
// Yellow
|
||||
{
|
||||
base: isDarkMode ? 'rgb(250, 204, 21)' : 'rgb(234, 179, 8)',
|
||||
},
|
||||
|
||||
// Blue
|
||||
{
|
||||
base: isDarkMode ? 'rgb(56, 189, 248)' : 'rgb(14, 165, 233)',
|
||||
},
|
||||
];
|
||||
|
||||
// Get the base color for this index
|
||||
const color = baseColors[index % baseColors.length].base;
|
||||
|
||||
// Parse color and generate variations with appropriate opacity
|
||||
let r = 0,
|
||||
g = 0,
|
||||
b = 0;
|
||||
|
||||
// Handle rgb/rgba format
|
||||
const rgbMatch = color.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
|
||||
const rgbaMatch = color.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*([0-9.]+)\)/);
|
||||
|
||||
if (rgbMatch) {
|
||||
[, r, g, b] = rgbMatch.map(Number);
|
||||
} else if (rgbaMatch) {
|
||||
[, r, g, b] = rgbaMatch.map(Number);
|
||||
} else if (color.startsWith('#')) {
|
||||
// Handle hex format
|
||||
const hex = color.slice(1);
|
||||
const bigint = parseInt(hex, 16);
|
||||
r = (bigint >> 16) & 255;
|
||||
g = (bigint >> 8) & 255;
|
||||
b = bigint & 255;
|
||||
}
|
||||
|
||||
return {
|
||||
bg: `rgba(${r}, ${g}, ${b}, ${isDarkMode ? 0.7 : 0.5})`,
|
||||
border: `rgba(${r}, ${g}, ${b}, ${isDarkMode ? 0.9 : 0.8})`,
|
||||
};
|
||||
};
|
||||
|
||||
const chartData = {
|
||||
history: {
|
||||
labels: Object.keys(chatsByDate),
|
||||
datasets: [
|
||||
{
|
||||
label: 'Chats Created',
|
||||
data: Object.values(chatsByDate),
|
||||
backgroundColor: getChartColors(0).bg,
|
||||
borderColor: getChartColors(0).border,
|
||||
borderWidth: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
roles: {
|
||||
labels: Object.keys(messagesByRole),
|
||||
datasets: [
|
||||
{
|
||||
label: 'Messages by Role',
|
||||
data: Object.values(messagesByRole),
|
||||
backgroundColor: Object.keys(messagesByRole).map((_, i) => getChartColors(i).bg),
|
||||
borderColor: Object.keys(messagesByRole).map((_, i) => getChartColors(i).border),
|
||||
borderWidth: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
apiUsage: {
|
||||
labels: apiKeyUsage.map((item) => item.provider),
|
||||
datasets: [
|
||||
{
|
||||
label: 'API Usage',
|
||||
data: apiKeyUsage.map((item) => item.count),
|
||||
backgroundColor: apiKeyUsage.map((_, i) => getChartColors(i).bg),
|
||||
borderColor: apiKeyUsage.map((_, i) => getChartColors(i).border),
|
||||
borderWidth: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const baseChartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
color: chartColors.text,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: 'top' as const,
|
||||
labels: {
|
||||
color: chartColors.text,
|
||||
font: {
|
||||
weight: 'bold' as const,
|
||||
size: 12,
|
||||
},
|
||||
padding: 16,
|
||||
usePointStyle: true,
|
||||
},
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
color: chartColors.text,
|
||||
font: {
|
||||
size: 16,
|
||||
weight: 'bold' as const,
|
||||
},
|
||||
padding: 16,
|
||||
},
|
||||
tooltip: {
|
||||
titleColor: chartColors.text,
|
||||
bodyColor: chartColors.text,
|
||||
backgroundColor: isDarkMode
|
||||
? 'rgba(23, 23, 23, 0.8)' // Dark bg using Tailwind gray-900
|
||||
: 'rgba(255, 255, 255, 0.8)', // Light bg
|
||||
borderColor: chartColors.border,
|
||||
borderWidth: 1,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const chartOptions = {
|
||||
...baseChartOptions,
|
||||
plugins: {
|
||||
...baseChartOptions.plugins,
|
||||
title: {
|
||||
...baseChartOptions.plugins.title,
|
||||
text: 'Chat History',
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
grid: {
|
||||
color: chartColors.grid,
|
||||
drawBorder: false,
|
||||
},
|
||||
border: {
|
||||
display: false,
|
||||
},
|
||||
ticks: {
|
||||
color: chartColors.text,
|
||||
font: {
|
||||
weight: 500,
|
||||
},
|
||||
},
|
||||
},
|
||||
y: {
|
||||
grid: {
|
||||
color: chartColors.grid,
|
||||
drawBorder: false,
|
||||
},
|
||||
border: {
|
||||
display: false,
|
||||
},
|
||||
ticks: {
|
||||
color: chartColors.text,
|
||||
font: {
|
||||
weight: 500,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const pieOptions = {
|
||||
...baseChartOptions,
|
||||
plugins: {
|
||||
...baseChartOptions.plugins,
|
||||
title: {
|
||||
...baseChartOptions.plugins.title,
|
||||
text: 'Message Distribution',
|
||||
},
|
||||
legend: {
|
||||
...baseChartOptions.plugins.legend,
|
||||
position: 'right' as const,
|
||||
},
|
||||
datalabels: {
|
||||
color: chartColors.text,
|
||||
font: {
|
||||
weight: 'bold' as const,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if (chats.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-8">
|
||||
<div className="i-ph-chart-line-duotone w-12 h-12 mx-auto mb-4 text-bolt-elements-textTertiary opacity-80" />
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-2">No Data Available</h3>
|
||||
<p className="text-bolt-elements-textSecondary">
|
||||
Start creating chats to see your usage statistics and data visualization.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const cardClasses = classNames(
|
||||
'p-6 rounded-lg shadow-sm',
|
||||
'bg-bolt-elements-bg-depth-1',
|
||||
'border border-bolt-elements-borderColor',
|
||||
);
|
||||
|
||||
const statClasses = classNames('text-3xl font-bold text-bolt-elements-textPrimary', 'flex items-center gap-3');
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<div className={cardClasses}>
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Total Chats</h3>
|
||||
<div className={statClasses}>
|
||||
<div className="i-ph-chats-duotone w-8 h-8 text-indigo-500 dark:text-indigo-400" />
|
||||
<span>{chats.length}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={cardClasses}>
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Total Messages</h3>
|
||||
<div className={statClasses}>
|
||||
<div className="i-ph-chat-text-duotone w-8 h-8 text-pink-500 dark:text-pink-400" />
|
||||
<span>{Object.values(messagesByRole).reduce((sum, count) => sum + count, 0)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={cardClasses}>
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-4">Avg. Messages/Chat</h3>
|
||||
<div className={statClasses}>
|
||||
<div className="i-ph-chart-bar-duotone w-8 h-8 text-green-500 dark:text-green-400" />
|
||||
<span>{averageMessagesPerChat.toFixed(1)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className={cardClasses}>
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-6">Chat History</h3>
|
||||
<div className="h-64">
|
||||
<Bar data={chartData.history} options={chartOptions} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={cardClasses}>
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-6">Message Distribution</h3>
|
||||
<div className="h-64">
|
||||
<Pie data={chartData.roles} options={pieOptions} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{apiKeyUsage.length > 0 && (
|
||||
<div className={cardClasses}>
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-6">API Usage by Provider</h3>
|
||||
<div className="h-64">
|
||||
<Pie data={chartData.apiUsage} options={pieOptions} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
2045
app/components/@settings/tabs/debug/DebugTab.tsx
Normal file
2045
app/components/@settings/tabs/debug/DebugTab.tsx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -763,7 +763,7 @@ export function EventLogsTab() {
|
||||
{
|
||||
id: 'json',
|
||||
label: 'Export as JSON',
|
||||
icon: 'i-ph:file-js',
|
||||
icon: 'i-ph:file-json',
|
||||
handler: exportAsJSON,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,281 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useGitHubConnection, useGitHubStats } from '~/lib/hooks';
|
||||
import { LoadingState, ErrorState, ConnectionTestIndicator, RepositoryCard } from './components/shared';
|
||||
import { GitHubConnection } from './components/GitHubConnection';
|
||||
import { GitHubUserProfile } from './components/GitHubUserProfile';
|
||||
import { GitHubStats } from './components/GitHubStats';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '~/components/ui/Collapsible';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import { GitHubErrorBoundary } from './components/GitHubErrorBoundary';
|
||||
import { GitHubProgressiveLoader } from './components/GitHubProgressiveLoader';
|
||||
import { GitHubCacheManager } from './components/GitHubCacheManager';
|
||||
|
||||
interface ConnectionTestResult {
|
||||
status: 'success' | 'error' | 'testing';
|
||||
message: string;
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
// GitHub logo SVG component
|
||||
const GithubLogo = () => (
|
||||
<svg viewBox="0 0 24 24" className="w-5 h-5">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export default function GitHubTab() {
|
||||
const { connection, isConnected, isLoading, error, testConnection } = useGitHubConnection();
|
||||
const {
|
||||
stats,
|
||||
isLoading: isStatsLoading,
|
||||
error: statsError,
|
||||
} = useGitHubStats(
|
||||
connection,
|
||||
{
|
||||
autoFetch: true,
|
||||
cacheTimeout: 30 * 60 * 1000, // 30 minutes
|
||||
},
|
||||
isConnected && connection ? !connection.token : false,
|
||||
); // Use server-side when no token but connected
|
||||
|
||||
const [connectionTest, setConnectionTest] = useState<ConnectionTestResult | null>(null);
|
||||
const [isStatsExpanded, setIsStatsExpanded] = useState(false);
|
||||
const [isReposExpanded, setIsReposExpanded] = useState(false);
|
||||
|
||||
const handleTestConnection = async () => {
|
||||
if (!connection?.user) {
|
||||
setConnectionTest({
|
||||
status: 'error',
|
||||
message: 'No connection established',
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setConnectionTest({
|
||||
status: 'testing',
|
||||
message: 'Testing connection...',
|
||||
});
|
||||
|
||||
try {
|
||||
const isValid = await testConnection();
|
||||
|
||||
if (isValid) {
|
||||
setConnectionTest({
|
||||
status: 'success',
|
||||
message: `Connected successfully as ${connection.user.login}`,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
} else {
|
||||
setConnectionTest({
|
||||
status: 'error',
|
||||
message: 'Connection test failed',
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
setConnectionTest({
|
||||
status: 'error',
|
||||
message: `Connection failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Loading state for initial connection check
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<GithubLogo />
|
||||
<h2 className="text-lg font-medium text-bolt-elements-textPrimary">GitHub Integration</h2>
|
||||
</div>
|
||||
<LoadingState message="Checking GitHub connection..." />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Error state for connection issues
|
||||
if (error && !connection) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<GithubLogo />
|
||||
<h2 className="text-lg font-medium text-bolt-elements-textPrimary">GitHub Integration</h2>
|
||||
</div>
|
||||
<ErrorState
|
||||
title="Connection Error"
|
||||
message={error}
|
||||
onRetry={() => window.location.reload()}
|
||||
retryLabel="Reload Page"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Not connected state
|
||||
if (!isConnected || !connection) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<GithubLogo />
|
||||
<h2 className="text-lg font-medium text-bolt-elements-textPrimary">GitHub Integration</h2>
|
||||
</div>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">
|
||||
Connect your GitHub account to enable advanced repository management features, statistics, and seamless
|
||||
integration.
|
||||
</p>
|
||||
<GitHubConnection connectionTest={connectionTest} onTestConnection={handleTestConnection} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<GitHubErrorBoundary>
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<motion.div
|
||||
className="flex items-center justify-between gap-2"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<GithubLogo />
|
||||
<h2 className="text-lg font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
GitHub Integration
|
||||
</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{connection?.rateLimit && (
|
||||
<div className="flex items-center gap-2 px-3 py-1 bg-bolt-elements-background-depth-1 rounded-lg text-xs">
|
||||
<div className="i-ph:cloud w-4 h-4 text-bolt-elements-textSecondary" />
|
||||
<span className="text-bolt-elements-textSecondary">
|
||||
API: {connection.rateLimit.remaining}/{connection.rateLimit.limit}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
|
||||
Manage your GitHub integration with advanced repository features and comprehensive statistics
|
||||
</p>
|
||||
|
||||
{/* Connection Test Results */}
|
||||
<ConnectionTestIndicator
|
||||
status={connectionTest?.status || null}
|
||||
message={connectionTest?.message}
|
||||
timestamp={connectionTest?.timestamp}
|
||||
/>
|
||||
|
||||
{/* Connection Component */}
|
||||
<GitHubConnection connectionTest={connectionTest} onTestConnection={handleTestConnection} />
|
||||
|
||||
{/* User Profile */}
|
||||
{connection.user && <GitHubUserProfile user={connection.user} />}
|
||||
|
||||
{/* Stats Section */}
|
||||
<GitHubStats connection={connection} isExpanded={isStatsExpanded} onToggleExpanded={setIsStatsExpanded} />
|
||||
|
||||
{/* Repositories Section */}
|
||||
{stats?.repos && stats.repos.length > 0 && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.4 }}
|
||||
className="border-t border-bolt-elements-borderColor pt-6"
|
||||
>
|
||||
<Collapsible open={isReposExpanded} onOpenChange={setIsReposExpanded}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div className="flex items-center justify-between p-4 rounded-lg bg-bolt-elements-background dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70 dark:hover:border-bolt-elements-borderColorActive/70 transition-all duration-200">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="i-ph:folder w-4 h-4 text-bolt-elements-item-contentAccent" />
|
||||
<span className="text-sm font-medium text-bolt-elements-textPrimary">
|
||||
All Repositories ({stats.repos.length})
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown
|
||||
className={classNames(
|
||||
'w-4 h-4 transform transition-transform duration-200 text-bolt-elements-textSecondary',
|
||||
isReposExpanded ? 'rotate-180' : '',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
|
||||
<CollapsibleContent className="overflow-hidden">
|
||||
<div className="mt-4 space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{(isReposExpanded ? stats.repos : stats.repos.slice(0, 12)).map((repo) => (
|
||||
<RepositoryCard
|
||||
key={repo.full_name}
|
||||
repository={repo}
|
||||
variant="detailed"
|
||||
showHealthScore
|
||||
showExtendedMetrics
|
||||
onSelect={() => window.open(repo.html_url, '_blank', 'noopener,noreferrer')}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{stats.repos.length > 12 && !isReposExpanded && (
|
||||
<div className="text-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setIsReposExpanded(true)}
|
||||
className="text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary"
|
||||
>
|
||||
Show {stats.repos.length - 12} more repositories
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Stats Error State */}
|
||||
{statsError && !stats && (
|
||||
<ErrorState
|
||||
title="Failed to Load Statistics"
|
||||
message={statsError}
|
||||
onRetry={() => window.location.reload()}
|
||||
retryLabel="Retry"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Stats Loading State */}
|
||||
{isStatsLoading && !stats && (
|
||||
<GitHubProgressiveLoader
|
||||
isLoading={isStatsLoading}
|
||||
loadingMessage="Loading GitHub statistics..."
|
||||
showProgress={true}
|
||||
progressSteps={[
|
||||
{ key: 'user', label: 'Fetching user info', completed: !!connection?.user, loading: !connection?.user },
|
||||
{ key: 'repos', label: 'Loading repositories', completed: false, loading: true },
|
||||
{ key: 'stats', label: 'Calculating statistics', completed: false },
|
||||
{ key: 'cache', label: 'Updating cache', completed: false },
|
||||
]}
|
||||
>
|
||||
<div />
|
||||
</GitHubProgressiveLoader>
|
||||
)}
|
||||
|
||||
{/* Cache Management Section - Only show when connected */}
|
||||
{isConnected && connection && (
|
||||
<div className="mt-8 pt-6 border-t border-bolt-elements-borderColor">
|
||||
<GitHubCacheManager showStats={true} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</GitHubErrorBoundary>
|
||||
);
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import * as Dialog from '@radix-ui/react-dialog';
|
||||
import { motion } from 'framer-motion';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { useGitHubConnection } from '~/lib/hooks';
|
||||
|
||||
interface GitHubAuthDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
export function GitHubAuthDialog({ isOpen, onClose, onSuccess }: GitHubAuthDialogProps) {
|
||||
const { connect, isConnecting, error } = useGitHubConnection();
|
||||
const [token, setToken] = useState('');
|
||||
const [tokenType, setTokenType] = useState<'classic' | 'fine-grained'>('classic');
|
||||
|
||||
const handleConnect = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!token.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await connect(token, tokenType);
|
||||
setToken(''); // Clear token on successful connection
|
||||
onSuccess?.();
|
||||
onClose();
|
||||
} catch {
|
||||
// Error handling is done in the hook
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setToken('');
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog.Root open={isOpen}>
|
||||
<Dialog.Portal>
|
||||
<Dialog.Overlay className="fixed inset-0 bg-black/50 z-[200]" />
|
||||
<Dialog.Content
|
||||
className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-[201] w-full max-w-md"
|
||||
onEscapeKeyDown={handleClose}
|
||||
onPointerDownOutside={handleClose}
|
||||
>
|
||||
<motion.div
|
||||
className="bg-bolt-elements-background border border-bolt-elements-borderColor rounded-lg shadow-lg"
|
||||
initial={{ opacity: 0, scale: 0.9 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.9 }}
|
||||
>
|
||||
<div className="p-6 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold text-bolt-elements-textPrimary">Connect to GitHub</h2>
|
||||
<button
|
||||
onClick={handleClose}
|
||||
className="p-1 rounded-md hover:bg-bolt-elements-item-backgroundActive/10"
|
||||
>
|
||||
<div className="i-ph:x w-4 h-4 text-bolt-elements-textSecondary" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-bolt-elements-textSecondary bg-bolt-elements-background-depth-1 p-3 rounded-lg">
|
||||
<p className="flex items-center gap-1 mb-1">
|
||||
<span className="i-ph:lightbulb w-3.5 h-3.5 text-bolt-elements-icon-success" />
|
||||
<span className="font-medium">Tip:</span> You need a GitHub token to deploy repositories.
|
||||
</p>
|
||||
<p>Required scopes: repo, read:org, read:user</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleConnect} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary mb-2">Token Type</label>
|
||||
<select
|
||||
value={tokenType}
|
||||
onChange={(e) => setTokenType(e.target.value as 'classic' | 'fine-grained')}
|
||||
disabled={isConnecting}
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-1',
|
||||
'border border-bolt-elements-borderColor',
|
||||
'text-bolt-elements-textPrimary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-item-contentAccent',
|
||||
'disabled:opacity-50',
|
||||
)}
|
||||
>
|
||||
<option value="classic">Personal Access Token (Classic)</option>
|
||||
<option value="fine-grained">Fine-grained Token</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary mb-2">
|
||||
{tokenType === 'classic' ? 'Personal Access Token' : 'Fine-grained Token'}
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
disabled={isConnecting}
|
||||
placeholder={`Enter your GitHub ${
|
||||
tokenType === 'classic' ? 'personal access token' : 'fine-grained token'
|
||||
}`}
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-1',
|
||||
'border border-bolt-elements-borderColor',
|
||||
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive',
|
||||
'disabled:opacity-50',
|
||||
)}
|
||||
/>
|
||||
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
|
||||
<a
|
||||
href={`https://github.com/settings/tokens${tokenType === 'fine-grained' ? '/beta' : '/new'}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-bolt-elements-borderColorActive hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
Get your token
|
||||
<div className="i-ph:arrow-square-out w-4 h-4" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-4 rounded-lg bg-red-50 border border-red-200 dark:bg-red-900/20 dark:border-red-700">
|
||||
<p className="text-sm text-red-800 dark:text-red-200">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-end gap-3 pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClose}
|
||||
className="px-4 py-2 text-sm text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isConnecting || !token.trim()}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-[#303030] text-white',
|
||||
'hover:bg-[#5E41D0] hover:text-white',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200',
|
||||
)}
|
||||
>
|
||||
{isConnecting ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap animate-spin" />
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:plug-charging w-4 h-4" />
|
||||
Connect
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</motion.div>
|
||||
</Dialog.Content>
|
||||
</Dialog.Portal>
|
||||
</Dialog.Root>
|
||||
);
|
||||
}
|
||||
@@ -1,367 +0,0 @@
|
||||
import React, { useState, useCallback, useEffect, useMemo } from 'react';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { Database, Trash2, RefreshCw, Clock, HardDrive, CheckCircle } from 'lucide-react';
|
||||
|
||||
interface CacheEntry {
|
||||
key: string;
|
||||
size: number;
|
||||
timestamp: number;
|
||||
lastAccessed: number;
|
||||
data: any;
|
||||
}
|
||||
|
||||
interface CacheStats {
|
||||
totalSize: number;
|
||||
totalEntries: number;
|
||||
oldestEntry: number;
|
||||
newestEntry: number;
|
||||
hitRate?: number;
|
||||
}
|
||||
|
||||
interface GitHubCacheManagerProps {
|
||||
className?: string;
|
||||
showStats?: boolean;
|
||||
}
|
||||
|
||||
// Cache management utilities
|
||||
class CacheManagerService {
|
||||
private static readonly _cachePrefix = 'github_';
|
||||
private static readonly _cacheKeys = [
|
||||
'github_connection',
|
||||
'github_stats_cache',
|
||||
'github_repositories_cache',
|
||||
'github_user_cache',
|
||||
'github_rate_limits',
|
||||
];
|
||||
|
||||
static getCacheEntries(): CacheEntry[] {
|
||||
const entries: CacheEntry[] = [];
|
||||
|
||||
for (const key of this._cacheKeys) {
|
||||
try {
|
||||
const data = localStorage.getItem(key);
|
||||
|
||||
if (data) {
|
||||
const parsed = JSON.parse(data);
|
||||
entries.push({
|
||||
key,
|
||||
size: new Blob([data]).size,
|
||||
timestamp: parsed.timestamp || Date.now(),
|
||||
lastAccessed: parsed.lastAccessed || Date.now(),
|
||||
data: parsed,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to parse cache entry: ${key}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return entries.sort((a, b) => b.lastAccessed - a.lastAccessed);
|
||||
}
|
||||
|
||||
static getCacheStats(): CacheStats {
|
||||
const entries = this.getCacheEntries();
|
||||
|
||||
if (entries.length === 0) {
|
||||
return {
|
||||
totalSize: 0,
|
||||
totalEntries: 0,
|
||||
oldestEntry: 0,
|
||||
newestEntry: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const totalSize = entries.reduce((sum, entry) => sum + entry.size, 0);
|
||||
const timestamps = entries.map((e) => e.timestamp);
|
||||
|
||||
return {
|
||||
totalSize,
|
||||
totalEntries: entries.length,
|
||||
oldestEntry: Math.min(...timestamps),
|
||||
newestEntry: Math.max(...timestamps),
|
||||
};
|
||||
}
|
||||
|
||||
static clearCache(keys?: string[]): void {
|
||||
const keysToRemove = keys || this._cacheKeys;
|
||||
|
||||
for (const key of keysToRemove) {
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
}
|
||||
|
||||
static clearExpiredCache(maxAge: number = 24 * 60 * 60 * 1000): number {
|
||||
const entries = this.getCacheEntries();
|
||||
const now = Date.now();
|
||||
let removedCount = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
if (now - entry.timestamp > maxAge) {
|
||||
localStorage.removeItem(entry.key);
|
||||
removedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return removedCount;
|
||||
}
|
||||
|
||||
static compactCache(): void {
|
||||
const entries = this.getCacheEntries();
|
||||
|
||||
for (const entry of entries) {
|
||||
try {
|
||||
// Re-serialize with minimal data
|
||||
const compacted = {
|
||||
...entry.data,
|
||||
lastAccessed: Date.now(),
|
||||
};
|
||||
localStorage.setItem(entry.key, JSON.stringify(compacted));
|
||||
} catch (error) {
|
||||
console.warn(`Failed to compact cache entry: ${entry.key}`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static formatSize(bytes: number): string {
|
||||
if (bytes === 0) {
|
||||
return '0 B';
|
||||
}
|
||||
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
|
||||
}
|
||||
}
|
||||
|
||||
export function GitHubCacheManager({ className = '', showStats = true }: GitHubCacheManagerProps) {
|
||||
const [cacheEntries, setCacheEntries] = useState<CacheEntry[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [lastClearTime, setLastClearTime] = useState<number | null>(null);
|
||||
|
||||
const refreshCacheData = useCallback(() => {
|
||||
setCacheEntries(CacheManagerService.getCacheEntries());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
refreshCacheData();
|
||||
}, [refreshCacheData]);
|
||||
|
||||
const cacheStats = useMemo(() => CacheManagerService.getCacheStats(), [cacheEntries]);
|
||||
|
||||
const handleClearAll = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
CacheManagerService.clearCache();
|
||||
setLastClearTime(Date.now());
|
||||
refreshCacheData();
|
||||
|
||||
// Trigger a page refresh to update all components
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1000);
|
||||
} catch (error) {
|
||||
console.error('Failed to clear cache:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [refreshCacheData]);
|
||||
|
||||
const handleClearExpired = useCallback(() => {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const removedCount = CacheManagerService.clearExpiredCache();
|
||||
refreshCacheData();
|
||||
|
||||
if (removedCount > 0) {
|
||||
// Show success message or trigger update
|
||||
console.log(`Removed ${removedCount} expired cache entries`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to clear expired cache:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [refreshCacheData]);
|
||||
|
||||
const handleCompactCache = useCallback(() => {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
CacheManagerService.compactCache();
|
||||
refreshCacheData();
|
||||
} catch (error) {
|
||||
console.error('Failed to compact cache:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [refreshCacheData]);
|
||||
|
||||
const handleClearSpecific = useCallback(
|
||||
(key: string) => {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
CacheManagerService.clearCache([key]);
|
||||
refreshCacheData();
|
||||
} catch (error) {
|
||||
console.error(`Failed to clear cache key: ${key}`, error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[refreshCacheData],
|
||||
);
|
||||
|
||||
if (!showStats && cacheEntries.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'space-y-4 p-4 bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor rounded-lg',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="w-4 h-4 text-bolt-elements-item-contentAccent" />
|
||||
<h3 className="text-sm font-medium text-bolt-elements-textPrimary">GitHub Cache Management</h3>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" onClick={refreshCacheData} disabled={isLoading}>
|
||||
<RefreshCw className={classNames('w-3 h-3', isLoading ? 'animate-spin' : '')} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showStats && (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
<div className="bg-bolt-elements-background-depth-2 p-3 rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<HardDrive className="w-3 h-3 text-bolt-elements-textSecondary" />
|
||||
<span className="text-xs font-medium text-bolt-elements-textSecondary">Total Size</span>
|
||||
</div>
|
||||
<p className="text-sm font-semibold text-bolt-elements-textPrimary">
|
||||
{CacheManagerService.formatSize(cacheStats.totalSize)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-bolt-elements-background-depth-2 p-3 rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Database className="w-3 h-3 text-bolt-elements-textSecondary" />
|
||||
<span className="text-xs font-medium text-bolt-elements-textSecondary">Entries</span>
|
||||
</div>
|
||||
<p className="text-sm font-semibold text-bolt-elements-textPrimary">{cacheStats.totalEntries}</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-bolt-elements-background-depth-2 p-3 rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Clock className="w-3 h-3 text-bolt-elements-textSecondary" />
|
||||
<span className="text-xs font-medium text-bolt-elements-textSecondary">Oldest</span>
|
||||
</div>
|
||||
<p className="text-xs text-bolt-elements-textSecondary">
|
||||
{cacheStats.oldestEntry ? new Date(cacheStats.oldestEntry).toLocaleDateString() : 'N/A'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-bolt-elements-background-depth-2 p-3 rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<CheckCircle className="w-3 h-3 text-bolt-elements-textSecondary" />
|
||||
<span className="text-xs font-medium text-bolt-elements-textSecondary">Status</span>
|
||||
</div>
|
||||
<p className="text-xs text-green-600 dark:text-green-400">
|
||||
{cacheStats.totalEntries > 0 ? 'Active' : 'Empty'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{cacheEntries.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-medium text-bolt-elements-textSecondary">
|
||||
Cache Entries ({cacheEntries.length})
|
||||
</h4>
|
||||
|
||||
<div className="space-y-2 max-h-48 overflow-y-auto">
|
||||
{cacheEntries.map((entry) => (
|
||||
<div
|
||||
key={entry.key}
|
||||
className="flex items-center justify-between p-2 bg-bolt-elements-background-depth-2 rounded border border-bolt-elements-borderColor"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-bolt-elements-textPrimary truncate">
|
||||
{entry.key.replace('github_', '')}
|
||||
</p>
|
||||
<p className="text-xs text-bolt-elements-textSecondary">
|
||||
{CacheManagerService.formatSize(entry.size)} • {new Date(entry.lastAccessed).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleClearSpecific(entry.key)}
|
||||
disabled={isLoading}
|
||||
className="ml-2"
|
||||
>
|
||||
<Trash2 className="w-3 h-3 text-red-500" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-2 pt-2 border-t border-bolt-elements-borderColor">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClearExpired}
|
||||
disabled={isLoading}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<Clock className="w-3 h-3" />
|
||||
<span className="text-xs">Clear Expired</span>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleCompactCache}
|
||||
disabled={isLoading}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<RefreshCw className="w-3 h-3" />
|
||||
<span className="text-xs">Compact</span>
|
||||
</Button>
|
||||
|
||||
{cacheEntries.length > 0 && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClearAll}
|
||||
disabled={isLoading}
|
||||
className="flex items-center gap-1 text-red-600 hover:text-red-700 border-red-200 hover:border-red-300"
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
<span className="text-xs">Clear All</span>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{lastClearTime && (
|
||||
<div className="flex items-center gap-2 p-2 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-700 rounded text-xs text-green-700 dark:text-green-400">
|
||||
<CheckCircle className="w-3 h-3" />
|
||||
<span>Cache cleared successfully at {new Date(lastClearTime).toLocaleTimeString()}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
import React from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { useGitHubConnection } from '~/lib/hooks';
|
||||
|
||||
interface ConnectionTestResult {
|
||||
status: 'success' | 'error' | 'testing';
|
||||
message: string;
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
interface GitHubConnectionProps {
|
||||
connectionTest: ConnectionTestResult | null;
|
||||
onTestConnection: () => void;
|
||||
}
|
||||
|
||||
export function GitHubConnection({ connectionTest, onTestConnection }: GitHubConnectionProps) {
|
||||
const { isConnected, isLoading, isConnecting, connect, disconnect, error } = useGitHubConnection();
|
||||
|
||||
const [token, setToken] = React.useState('');
|
||||
const [tokenType, setTokenType] = React.useState<'classic' | 'fine-grained'>('classic');
|
||||
|
||||
const handleConnect = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
console.log('handleConnect called with token:', token ? 'token provided' : 'no token', 'tokenType:', tokenType);
|
||||
|
||||
if (!token.trim()) {
|
||||
console.log('No token provided, returning early');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('Calling connect function...');
|
||||
await connect(token, tokenType);
|
||||
console.log('Connect function completed successfully');
|
||||
setToken(''); // Clear token on successful connection
|
||||
} catch (error) {
|
||||
console.log('Connect function failed:', error);
|
||||
|
||||
// Error handling is done in the hook
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="i-ph:spinner-gap-bold animate-spin w-4 h-4" />
|
||||
<span className="text-bolt-elements-textSecondary">Loading connection...</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className="bg-bolt-elements-background dark:bg-bolt-elements-background border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<div className="p-6 space-y-6">
|
||||
{!isConnected && (
|
||||
<div className="text-xs text-bolt-elements-textSecondary bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-1 p-3 rounded-lg mb-4">
|
||||
<p className="flex items-center gap-1 mb-1">
|
||||
<span className="i-ph:lightbulb w-3.5 h-3.5 text-bolt-elements-icon-success dark:text-bolt-elements-icon-success" />
|
||||
<span className="font-medium">Tip:</span> You can also set the{' '}
|
||||
<code className="px-1 py-0.5 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 rounded">
|
||||
VITE_GITHUB_ACCESS_TOKEN
|
||||
</code>{' '}
|
||||
environment variable to connect automatically.
|
||||
</p>
|
||||
<p>
|
||||
For fine-grained tokens, also set{' '}
|
||||
<code className="px-1 py-0.5 bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 rounded">
|
||||
VITE_GITHUB_TOKEN_TYPE=fine-grained
|
||||
</code>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleConnect} className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mb-2">
|
||||
Token Type
|
||||
</label>
|
||||
<select
|
||||
value={tokenType}
|
||||
onChange={(e) => setTokenType(e.target.value as 'classic' | 'fine-grained')}
|
||||
disabled={isConnecting || isConnected}
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-1',
|
||||
'border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor',
|
||||
'text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-item-contentAccent dark:focus:ring-bolt-elements-item-contentAccent',
|
||||
'disabled:opacity-50',
|
||||
)}
|
||||
>
|
||||
<option value="classic">Personal Access Token (Classic)</option>
|
||||
<option value="fine-grained">Fine-grained Token</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mb-2">
|
||||
{tokenType === 'classic' ? 'Personal Access Token' : 'Fine-grained Token'}
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
disabled={isConnecting || isConnected}
|
||||
placeholder={`Enter your GitHub ${
|
||||
tokenType === 'classic' ? 'personal access token' : 'fine-grained token'
|
||||
}`}
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-[#F8F8F8] dark:bg-[#1A1A1A]',
|
||||
'border border-[#E5E5E5] dark:border-[#333333]',
|
||||
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive',
|
||||
'disabled:opacity-50',
|
||||
)}
|
||||
/>
|
||||
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
|
||||
<a
|
||||
href={`https://github.com/settings/tokens${tokenType === 'fine-grained' ? '/beta' : '/new'}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-bolt-elements-borderColorActive hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
Get your token
|
||||
<div className="i-ph:arrow-square-out w-4 h-4" />
|
||||
</a>
|
||||
<span className="mx-2">•</span>
|
||||
<span>
|
||||
Required scopes:{' '}
|
||||
{tokenType === 'classic' ? 'repo, read:org, read:user' : 'Repository access, Organization access'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-4 rounded-lg bg-red-50 border border-red-200 dark:bg-red-900/20 dark:border-red-700">
|
||||
<p className="text-sm text-red-800 dark:text-red-200">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
{!isConnected ? (
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isConnecting || !token.trim()}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-[#303030] text-white',
|
||||
'hover:bg-[#5E41D0] hover:text-white',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200',
|
||||
'transform active:scale-95',
|
||||
)}
|
||||
>
|
||||
{isConnecting ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap animate-spin" />
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:plug-charging w-4 h-4" />
|
||||
Connect
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={disconnect}
|
||||
type="button"
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-red-500 text-white',
|
||||
'hover:bg-red-600',
|
||||
)}
|
||||
>
|
||||
<div className="i-ph:plug w-4 h-4" />
|
||||
Disconnect
|
||||
</button>
|
||||
<span className="text-sm text-bolt-elements-textSecondary flex items-center gap-1">
|
||||
<div className="i-ph:check-circle w-4 h-4 text-green-500" />
|
||||
Connected to GitHub
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => window.open('https://github.com/dashboard', '_blank', 'noopener,noreferrer')}
|
||||
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:text-bolt-elements-textPrimary transition-colors"
|
||||
>
|
||||
<div className="i-ph:layout w-4 h-4" />
|
||||
Dashboard
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onTestConnection}
|
||||
disabled={connectionTest?.status === 'testing'}
|
||||
variant="outline"
|
||||
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:text-bolt-elements-textPrimary transition-colors"
|
||||
>
|
||||
{connectionTest?.status === 'testing' ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap w-4 h-4 animate-spin" />
|
||||
Testing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:plug-charging w-4 h-4" />
|
||||
Test Connection
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
import React, { Component } from 'react';
|
||||
import type { ReactNode, ErrorInfo } from 'react';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
fallback?: ReactNode;
|
||||
onError?: (error: Error, errorInfo: ErrorInfo) => void;
|
||||
}
|
||||
|
||||
interface State {
|
||||
hasError: boolean;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
export class GitHubErrorBoundary extends Component<Props, State> {
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.state = { hasError: false, error: null };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: Error): State {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
||||
console.error('GitHub Error Boundary caught an error:', error, errorInfo);
|
||||
|
||||
if (this.props.onError) {
|
||||
this.props.onError(error, errorInfo);
|
||||
}
|
||||
}
|
||||
|
||||
handleRetry = () => {
|
||||
this.setState({ hasError: false, error: null });
|
||||
};
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
if (this.props.fallback) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center p-8 text-center space-y-4 bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor rounded-lg">
|
||||
<div className="w-12 h-12 rounded-full bg-red-50 dark:bg-red-900/20 flex items-center justify-center">
|
||||
<AlertTriangle className="w-6 h-6 text-red-500" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-2">GitHub Integration Error</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary mb-4 max-w-md">
|
||||
Something went wrong while loading GitHub data. This could be due to network issues, API limits, or a
|
||||
temporary problem.
|
||||
</p>
|
||||
|
||||
{this.state.error && (
|
||||
<details className="text-xs text-bolt-elements-textTertiary mb-4">
|
||||
<summary className="cursor-pointer hover:text-bolt-elements-textSecondary">Show error details</summary>
|
||||
<pre className="mt-2 p-2 bg-bolt-elements-background-depth-2 rounded text-left overflow-auto">
|
||||
{this.state.error.message}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={this.handleRetry}>
|
||||
Try Again
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => window.location.reload()}>
|
||||
Reload Page
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
// Higher-order component for wrapping components with error boundary
|
||||
export function withGitHubErrorBoundary<P extends object>(component: React.ComponentType<P>) {
|
||||
return function WrappedComponent(props: P) {
|
||||
return <GitHubErrorBoundary>{React.createElement(component, props)}</GitHubErrorBoundary>;
|
||||
};
|
||||
}
|
||||
|
||||
// Hook for handling async errors in GitHub operations
|
||||
export function useGitHubErrorHandler() {
|
||||
const handleError = React.useCallback((error: unknown, context?: string) => {
|
||||
console.error(`GitHub Error ${context ? `(${context})` : ''}:`, error);
|
||||
|
||||
/*
|
||||
* You could integrate with error tracking services here
|
||||
* For example: Sentry, LogRocket, etc.
|
||||
*/
|
||||
|
||||
return error instanceof Error ? error.message : 'An unknown error occurred';
|
||||
}, []);
|
||||
|
||||
return { handleError };
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
import React, { useState, useCallback, useMemo } from 'react';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { Loader2, ChevronDown, RefreshCw, AlertCircle, CheckCircle } from 'lucide-react';
|
||||
|
||||
interface ProgressiveLoaderProps {
|
||||
isLoading: boolean;
|
||||
isRefreshing?: boolean;
|
||||
error?: string | null;
|
||||
onRetry?: () => void;
|
||||
onRefresh?: () => void;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
loadingMessage?: string;
|
||||
refreshingMessage?: string;
|
||||
showProgress?: boolean;
|
||||
progressSteps?: Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
completed: boolean;
|
||||
loading?: boolean;
|
||||
error?: boolean;
|
||||
}>;
|
||||
}
|
||||
|
||||
export function GitHubProgressiveLoader({
|
||||
isLoading,
|
||||
isRefreshing = false,
|
||||
error,
|
||||
onRetry,
|
||||
onRefresh,
|
||||
children,
|
||||
className = '',
|
||||
loadingMessage = 'Loading...',
|
||||
refreshingMessage = 'Refreshing...',
|
||||
showProgress = false,
|
||||
progressSteps = [],
|
||||
}: ProgressiveLoaderProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
|
||||
// Calculate progress percentage
|
||||
const progress = useMemo(() => {
|
||||
if (!showProgress || progressSteps.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const completed = progressSteps.filter((step) => step.completed).length;
|
||||
|
||||
return Math.round((completed / progressSteps.length) * 100);
|
||||
}, [showProgress, progressSteps]);
|
||||
|
||||
const handleToggleExpanded = useCallback(() => {
|
||||
setIsExpanded((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
// Loading state with progressive steps
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className={classNames('flex flex-col items-center justify-center py-8', className)}>
|
||||
<div className="relative mb-4">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-bolt-elements-item-contentAccent" />
|
||||
{showProgress && progress > 0 && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<span className="text-xs font-medium text-bolt-elements-item-contentAccent">{progress}%</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="text-center space-y-2">
|
||||
<p className="text-sm font-medium text-bolt-elements-textPrimary">{loadingMessage}</p>
|
||||
|
||||
{showProgress && progressSteps.length > 0 && (
|
||||
<div className="w-full max-w-sm">
|
||||
{/* Progress bar */}
|
||||
<div className="w-full bg-bolt-elements-background-depth-2 rounded-full h-2 mb-3">
|
||||
<motion.div
|
||||
className="bg-bolt-elements-item-contentAccent h-2 rounded-full"
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: `${progress}%` }}
|
||||
transition={{ duration: 0.5, ease: 'easeOut' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Steps toggle */}
|
||||
<button
|
||||
onClick={handleToggleExpanded}
|
||||
className="flex items-center justify-center gap-2 text-xs text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors"
|
||||
>
|
||||
<span>Show details</span>
|
||||
<ChevronDown
|
||||
className={classNames(
|
||||
'w-3 h-3 transform transition-transform duration-200',
|
||||
isExpanded ? 'rotate-180' : '',
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
|
||||
{/* Progress steps */}
|
||||
<AnimatePresence>
|
||||
{isExpanded && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, height: 0 }}
|
||||
animate={{ opacity: 1, height: 'auto' }}
|
||||
exit={{ opacity: 0, height: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="mt-3 space-y-2 overflow-hidden"
|
||||
>
|
||||
{progressSteps.map((step) => (
|
||||
<div key={step.key} className="flex items-center gap-2 text-xs">
|
||||
{step.error ? (
|
||||
<AlertCircle className="w-3 h-3 text-red-500 flex-shrink-0" />
|
||||
) : step.completed ? (
|
||||
<CheckCircle className="w-3 h-3 text-green-500 flex-shrink-0" />
|
||||
) : step.loading ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin text-bolt-elements-item-contentAccent flex-shrink-0" />
|
||||
) : (
|
||||
<div className="w-3 h-3 rounded-full border border-bolt-elements-borderColor flex-shrink-0" />
|
||||
)}
|
||||
<span
|
||||
className={classNames(
|
||||
step.error
|
||||
? 'text-red-500'
|
||||
: step.completed
|
||||
? 'text-green-600 dark:text-green-400'
|
||||
: step.loading
|
||||
? 'text-bolt-elements-textPrimary'
|
||||
: 'text-bolt-elements-textSecondary',
|
||||
)}
|
||||
>
|
||||
{step.label}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (error) {
|
||||
return (
|
||||
<div className={classNames('flex flex-col items-center justify-center py-8 text-center space-y-4', className)}>
|
||||
<div className="w-10 h-10 rounded-full bg-red-50 dark:bg-red-900/20 flex items-center justify-center">
|
||||
<AlertCircle className="w-5 h-5 text-red-500" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-bolt-elements-textPrimary mb-1">Failed to Load</h3>
|
||||
<p className="text-xs text-bolt-elements-textSecondary mb-4 max-w-sm">{error}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{onRetry && (
|
||||
<Button variant="outline" size="sm" onClick={onRetry} className="text-xs">
|
||||
<RefreshCw className="w-3 h-3 mr-1" />
|
||||
Try Again
|
||||
</Button>
|
||||
)}
|
||||
{onRefresh && (
|
||||
<Button variant="outline" size="sm" onClick={onRefresh} className="text-xs">
|
||||
<RefreshCw className="w-3 h-3 mr-1" />
|
||||
Refresh
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Success state - render children with optional refresh indicator
|
||||
return (
|
||||
<div className={classNames('relative', className)}>
|
||||
{isRefreshing && (
|
||||
<div className="absolute top-0 right-0 z-10">
|
||||
<div className="flex items-center gap-2 px-2 py-1 bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor rounded-lg shadow-sm">
|
||||
<Loader2 className="w-3 h-3 animate-spin text-bolt-elements-item-contentAccent" />
|
||||
<span className="text-xs text-bolt-elements-textSecondary">{refreshingMessage}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Hook for managing progressive loading steps
|
||||
export function useProgressiveLoader() {
|
||||
const [steps, setSteps] = useState<
|
||||
Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
completed: boolean;
|
||||
loading?: boolean;
|
||||
error?: boolean;
|
||||
}>
|
||||
>([]);
|
||||
|
||||
const addStep = useCallback((key: string, label: string) => {
|
||||
setSteps((prev) => [
|
||||
...prev.filter((step) => step.key !== key),
|
||||
{ key, label, completed: false, loading: false, error: false },
|
||||
]);
|
||||
}, []);
|
||||
|
||||
const updateStep = useCallback(
|
||||
(
|
||||
key: string,
|
||||
updates: {
|
||||
completed?: boolean;
|
||||
loading?: boolean;
|
||||
error?: boolean;
|
||||
label?: string;
|
||||
},
|
||||
) => {
|
||||
setSteps((prev) => prev.map((step) => (step.key === key ? { ...step, ...updates } : step)));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const removeStep = useCallback((key: string) => {
|
||||
setSteps((prev) => prev.filter((step) => step.key !== key));
|
||||
}, []);
|
||||
|
||||
const clearSteps = useCallback(() => {
|
||||
setSteps([]);
|
||||
}, []);
|
||||
|
||||
const startStep = useCallback(
|
||||
(key: string) => {
|
||||
updateStep(key, { loading: true, error: false });
|
||||
},
|
||||
[updateStep],
|
||||
);
|
||||
|
||||
const completeStep = useCallback(
|
||||
(key: string) => {
|
||||
updateStep(key, { completed: true, loading: false, error: false });
|
||||
},
|
||||
[updateStep],
|
||||
);
|
||||
|
||||
const errorStep = useCallback(
|
||||
(key: string) => {
|
||||
updateStep(key, { error: true, loading: false });
|
||||
},
|
||||
[updateStep],
|
||||
);
|
||||
|
||||
return {
|
||||
steps,
|
||||
addStep,
|
||||
updateStep,
|
||||
removeStep,
|
||||
clearSteps,
|
||||
startStep,
|
||||
completeStep,
|
||||
errorStep,
|
||||
};
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
import React from 'react';
|
||||
import type { GitHubRepoInfo } from '~/types/GitHub';
|
||||
|
||||
interface GitHubRepositoryCardProps {
|
||||
repo: GitHubRepoInfo;
|
||||
onClone?: (repo: GitHubRepoInfo) => void;
|
||||
}
|
||||
|
||||
export function GitHubRepositoryCard({ repo, onClone }: GitHubRepositoryCardProps) {
|
||||
return (
|
||||
<a
|
||||
key={repo.name}
|
||||
href={repo.html_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="group block p-4 rounded-lg bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive transition-all duration-200"
|
||||
>
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex-1 space-y-3">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="i-ph:git-repository w-4 h-4 text-bolt-elements-icon-info" />
|
||||
<h5 className="text-sm font-medium text-bolt-elements-textPrimary group-hover:text-bolt-elements-item-contentAccent transition-colors">
|
||||
{repo.name}
|
||||
</h5>
|
||||
{repo.private && (
|
||||
<div className="i-ph:lock w-3 h-3 text-bolt-elements-textTertiary" title="Private repository" />
|
||||
)}
|
||||
{repo.fork && (
|
||||
<div className="i-ph:git-fork w-3 h-3 text-bolt-elements-textTertiary" title="Forked repository" />
|
||||
)}
|
||||
{repo.archived && (
|
||||
<div className="i-ph:archive w-3 h-3 text-bolt-elements-textTertiary" title="Archived repository" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-xs text-bolt-elements-textSecondary">
|
||||
<span className="flex items-center gap-1" title="Stars">
|
||||
<div className="i-ph:star w-3.5 h-3.5 text-bolt-elements-icon-warning" />
|
||||
{repo.stargazers_count.toLocaleString()}
|
||||
</span>
|
||||
<span className="flex items-center gap-1" title="Forks">
|
||||
<div className="i-ph:git-fork w-3.5 h-3.5 text-bolt-elements-icon-info" />
|
||||
{repo.forks_count.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{repo.description && (
|
||||
<p className="text-xs text-bolt-elements-textSecondary line-clamp-2">{repo.description}</p>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-3 text-xs text-bolt-elements-textSecondary">
|
||||
<span className="flex items-center gap-1" title="Default Branch">
|
||||
<div className="i-ph:git-branch w-3.5 h-3.5" />
|
||||
{repo.default_branch}
|
||||
</span>
|
||||
{repo.language && (
|
||||
<span className="flex items-center gap-1" title="Primary Language">
|
||||
<div className="w-2 h-2 rounded-full bg-current opacity-60" />
|
||||
{repo.language}
|
||||
</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1" title="Last Updated">
|
||||
<div className="i-ph:clock w-3.5 h-3.5" />
|
||||
{new Date(repo.updated_at).toLocaleDateString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Repository topics/tags */}
|
||||
{repo.topics && repo.topics.length > 0 && (
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
{repo.topics.slice(0, 3).map((topic) => (
|
||||
<span
|
||||
key={topic}
|
||||
className="px-2 py-0.5 rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400"
|
||||
title={`Topic: ${topic}`}
|
||||
>
|
||||
{topic}
|
||||
</span>
|
||||
))}
|
||||
{repo.topics.length > 3 && (
|
||||
<span className="text-bolt-elements-textTertiary">+{repo.topics.length - 3} more</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Repository size if available */}
|
||||
{repo.size && (
|
||||
<div className="text-xs text-bolt-elements-textTertiary">Size: {(repo.size / 1024).toFixed(1)} MB</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Bottom section with Clone button positioned at bottom right */}
|
||||
<div className="flex items-center justify-between pt-3 mt-auto">
|
||||
<span className="flex items-center gap-1 text-xs text-bolt-elements-textSecondary group-hover:text-bolt-elements-item-contentAccent transition-colors">
|
||||
<div className="i-ph:arrow-square-out w-3.5 h-3.5" />
|
||||
View
|
||||
</span>
|
||||
{onClone && (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onClone(repo);
|
||||
}}
|
||||
className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-bolt-elements-background-depth-2 hover:bg-bolt-elements-background-depth-3 text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors"
|
||||
title="Clone repository"
|
||||
>
|
||||
<div className="i-ph:git-branch w-3.5 h-3.5" />
|
||||
Clone
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -1,312 +0,0 @@
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { BranchSelector } from '~/components/ui/BranchSelector';
|
||||
import { GitHubRepositoryCard } from './GitHubRepositoryCard';
|
||||
import type { GitHubRepoInfo } from '~/types/GitHub';
|
||||
import { useGitHubConnection, useGitHubStats } from '~/lib/hooks';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { Search, RefreshCw, GitBranch, Calendar, Filter } from 'lucide-react';
|
||||
|
||||
interface GitHubRepositorySelectorProps {
|
||||
onClone?: (repoUrl: string, branch?: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
type SortOption = 'updated' | 'stars' | 'name' | 'created';
|
||||
type FilterOption = 'all' | 'own' | 'forks' | 'archived';
|
||||
|
||||
export function GitHubRepositorySelector({ onClone, className }: GitHubRepositorySelectorProps) {
|
||||
const { connection, isConnected } = useGitHubConnection();
|
||||
const {
|
||||
stats,
|
||||
isLoading: isStatsLoading,
|
||||
refreshStats,
|
||||
} = useGitHubStats(connection, {
|
||||
autoFetch: true,
|
||||
cacheTimeout: 30 * 60 * 1000, // 30 minutes
|
||||
});
|
||||
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortBy, setSortBy] = useState<SortOption>('updated');
|
||||
const [filterBy, setFilterBy] = useState<FilterOption>('all');
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [selectedRepo, setSelectedRepo] = useState<GitHubRepoInfo | null>(null);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [isBranchSelectorOpen, setIsBranchSelectorOpen] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const repositories = stats?.repos || [];
|
||||
const REPOS_PER_PAGE = 12;
|
||||
|
||||
// Filter and search repositories
|
||||
const filteredRepositories = useMemo(() => {
|
||||
if (!repositories) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filtered = repositories.filter((repo: GitHubRepoInfo) => {
|
||||
// Search filter
|
||||
const matchesSearch =
|
||||
!searchQuery ||
|
||||
repo.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
repo.description?.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
repo.full_name.toLowerCase().includes(searchQuery.toLowerCase());
|
||||
|
||||
// Type filter
|
||||
let matchesFilter = true;
|
||||
|
||||
switch (filterBy) {
|
||||
case 'own':
|
||||
matchesFilter = !repo.fork;
|
||||
break;
|
||||
case 'forks':
|
||||
matchesFilter = repo.fork === true;
|
||||
break;
|
||||
case 'archived':
|
||||
matchesFilter = repo.archived === true;
|
||||
break;
|
||||
case 'all':
|
||||
default:
|
||||
matchesFilter = true;
|
||||
break;
|
||||
}
|
||||
|
||||
return matchesSearch && matchesFilter;
|
||||
});
|
||||
|
||||
// Sort repositories
|
||||
filtered.sort((a: GitHubRepoInfo, b: GitHubRepoInfo) => {
|
||||
switch (sortBy) {
|
||||
case 'name':
|
||||
return a.name.localeCompare(b.name);
|
||||
case 'stars':
|
||||
return b.stargazers_count - a.stargazers_count;
|
||||
case 'created':
|
||||
return new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime(); // Using updated_at as proxy
|
||||
case 'updated':
|
||||
default:
|
||||
return new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime();
|
||||
}
|
||||
});
|
||||
|
||||
return filtered;
|
||||
}, [repositories, searchQuery, sortBy, filterBy]);
|
||||
|
||||
// Pagination
|
||||
const totalPages = Math.ceil(filteredRepositories.length / REPOS_PER_PAGE);
|
||||
const startIndex = (currentPage - 1) * REPOS_PER_PAGE;
|
||||
const currentRepositories = filteredRepositories.slice(startIndex, startIndex + REPOS_PER_PAGE);
|
||||
|
||||
const handleRefresh = async () => {
|
||||
setIsRefreshing(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await refreshStats();
|
||||
} catch (err) {
|
||||
console.error('Failed to refresh GitHub repositories:', err);
|
||||
setError(err instanceof Error ? err.message : 'Failed to refresh repositories');
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCloneRepository = (repo: GitHubRepoInfo) => {
|
||||
setSelectedRepo(repo);
|
||||
setIsBranchSelectorOpen(true);
|
||||
};
|
||||
|
||||
const handleBranchSelect = (branch: string) => {
|
||||
if (onClone && selectedRepo) {
|
||||
const cloneUrl = selectedRepo.html_url + '.git';
|
||||
onClone(cloneUrl, branch);
|
||||
}
|
||||
|
||||
setSelectedRepo(null);
|
||||
};
|
||||
|
||||
const handleCloseBranchSelector = () => {
|
||||
setIsBranchSelectorOpen(false);
|
||||
setSelectedRepo(null);
|
||||
};
|
||||
|
||||
// Reset to first page when filters change
|
||||
useEffect(() => {
|
||||
setCurrentPage(1);
|
||||
}, [searchQuery, sortBy, filterBy]);
|
||||
|
||||
if (!isConnected || !connection) {
|
||||
return (
|
||||
<div className="text-center p-8">
|
||||
<p className="text-bolt-elements-textSecondary mb-4">Please connect to GitHub first to browse repositories</p>
|
||||
<Button variant="outline" onClick={() => window.location.reload()}>
|
||||
Refresh Connection
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isStatsLoading && !stats) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center p-8 space-y-4">
|
||||
<div className="animate-spin w-8 h-8 border-2 border-bolt-elements-borderColorActive border-t-transparent rounded-full" />
|
||||
<p className="text-sm text-bolt-elements-textSecondary">Loading repositories...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!repositories.length) {
|
||||
return (
|
||||
<div className="text-center p-8">
|
||||
<GitBranch className="w-12 h-12 text-bolt-elements-textTertiary mx-auto mb-4" />
|
||||
<p className="text-bolt-elements-textSecondary mb-4">No repositories found</p>
|
||||
<Button variant="outline" onClick={handleRefresh} disabled={isRefreshing}>
|
||||
<RefreshCw className={classNames('w-4 h-4 mr-2', { 'animate-spin': isRefreshing })} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className={classNames('space-y-6', className)}
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
{/* Header with stats */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-bolt-elements-textPrimary">Select Repository to Clone</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">
|
||||
{filteredRepositories.length} of {repositories.length} repositories
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleRefresh}
|
||||
disabled={isRefreshing}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<RefreshCw className={classNames('w-4 h-4', { 'animate-spin': isRefreshing })} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && repositories.length > 0 && (
|
||||
<div className="p-3 rounded-lg bg-yellow-50 border border-yellow-200 dark:bg-yellow-900/20 dark:border-yellow-700">
|
||||
<p className="text-sm text-yellow-800 dark:text-yellow-200">Warning: {error}. Showing cached data.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Search and Filters */}
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
{/* Search */}
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bolt-elements-textTertiary" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search repositories..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 rounded-lg bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sort */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="w-4 h-4 text-bolt-elements-textTertiary" />
|
||||
<select
|
||||
value={sortBy}
|
||||
onChange={(e) => setSortBy(e.target.value as SortOption)}
|
||||
className="px-3 py-2 rounded-lg bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor text-bolt-elements-textPrimary text-sm focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive"
|
||||
>
|
||||
<option value="updated">Recently updated</option>
|
||||
<option value="stars">Most starred</option>
|
||||
<option value="name">Name (A-Z)</option>
|
||||
<option value="created">Recently created</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Filter */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Filter className="w-4 h-4 text-bolt-elements-textTertiary" />
|
||||
<select
|
||||
value={filterBy}
|
||||
onChange={(e) => setFilterBy(e.target.value as FilterOption)}
|
||||
className="px-3 py-2 rounded-lg bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor text-bolt-elements-textPrimary text-sm focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive"
|
||||
>
|
||||
<option value="all">All repositories</option>
|
||||
<option value="own">Own repositories</option>
|
||||
<option value="forks">Forked repositories</option>
|
||||
<option value="archived">Archived repositories</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Repository Grid */}
|
||||
{currentRepositories.length > 0 ? (
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{currentRepositories.map((repo) => (
|
||||
<GitHubRepositoryCard key={repo.id} repo={repo} onClone={() => handleCloneRepository(repo)} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-between pt-4 border-t border-bolt-elements-borderColor">
|
||||
<div className="text-sm text-bolt-elements-textSecondary">
|
||||
Showing {Math.min(startIndex + 1, filteredRepositories.length)} to{' '}
|
||||
{Math.min(startIndex + REPOS_PER_PAGE, filteredRepositories.length)} of {filteredRepositories.length}{' '}
|
||||
repositories
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
|
||||
disabled={currentPage === 1}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
Previous
|
||||
</Button>
|
||||
<span className="text-sm text-bolt-elements-textSecondary px-3">
|
||||
{currentPage} of {totalPages}
|
||||
</span>
|
||||
<Button
|
||||
onClick={() => setCurrentPage((prev) => Math.min(totalPages, prev + 1))}
|
||||
disabled={currentPage === totalPages}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="text-center py-8">
|
||||
<p className="text-bolt-elements-textSecondary">No repositories found matching your search criteria.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Branch Selector Modal */}
|
||||
{selectedRepo && (
|
||||
<BranchSelector
|
||||
provider="github"
|
||||
repoOwner={selectedRepo.full_name.split('/')[0]}
|
||||
repoName={selectedRepo.full_name.split('/')[1]}
|
||||
token={connection?.token || ''}
|
||||
defaultBranch={selectedRepo.default_branch}
|
||||
onBranchSelect={handleBranchSelect}
|
||||
onClose={handleCloseBranchSelector}
|
||||
isOpen={isBranchSelectorOpen}
|
||||
/>
|
||||
)}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -1,291 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '~/components/ui/Collapsible';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { useGitHubStats } from '~/lib/hooks';
|
||||
import type { GitHubConnection, GitHubStats as GitHubStatsType } from '~/types/GitHub';
|
||||
import { GitHubErrorBoundary } from './GitHubErrorBoundary';
|
||||
|
||||
interface GitHubStatsProps {
|
||||
connection: GitHubConnection;
|
||||
isExpanded: boolean;
|
||||
onToggleExpanded: (expanded: boolean) => void;
|
||||
}
|
||||
|
||||
export function GitHubStats({ connection, isExpanded, onToggleExpanded }: GitHubStatsProps) {
|
||||
const { stats, isLoading, isRefreshing, refreshStats, isStale } = useGitHubStats(
|
||||
connection,
|
||||
{
|
||||
autoFetch: true,
|
||||
cacheTimeout: 30 * 60 * 1000, // 30 minutes
|
||||
},
|
||||
!connection?.token,
|
||||
); // Use server-side if no token
|
||||
|
||||
return (
|
||||
<GitHubErrorBoundary>
|
||||
<GitHubStatsContent
|
||||
stats={stats}
|
||||
isLoading={isLoading}
|
||||
isRefreshing={isRefreshing}
|
||||
refreshStats={refreshStats}
|
||||
isStale={isStale}
|
||||
isExpanded={isExpanded}
|
||||
onToggleExpanded={onToggleExpanded}
|
||||
/>
|
||||
</GitHubErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
function GitHubStatsContent({
|
||||
stats,
|
||||
isLoading,
|
||||
isRefreshing,
|
||||
refreshStats,
|
||||
isStale,
|
||||
isExpanded,
|
||||
onToggleExpanded,
|
||||
}: {
|
||||
stats: GitHubStatsType | null;
|
||||
isLoading: boolean;
|
||||
isRefreshing: boolean;
|
||||
refreshStats: () => Promise<void>;
|
||||
isStale: boolean;
|
||||
isExpanded: boolean;
|
||||
onToggleExpanded: (expanded: boolean) => void;
|
||||
}) {
|
||||
if (!stats) {
|
||||
return (
|
||||
<div className="mt-6 border-t border-bolt-elements-borderColor dark:border-bolt-elements-borderColor pt-6">
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<div className="flex items-center gap-2">
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap-bold animate-spin w-4 h-4" />
|
||||
<span className="text-bolt-elements-textSecondary">Loading GitHub stats...</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-bolt-elements-textSecondary">No stats available</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-6 border-t border-bolt-elements-borderColor dark:border-bolt-elements-borderColor pt-6">
|
||||
<Collapsible open={isExpanded} onOpenChange={onToggleExpanded}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div className="flex items-center justify-between p-4 rounded-lg bg-bolt-elements-background dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70 dark:hover:border-bolt-elements-borderColorActive/70 transition-all duration-200">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="i-ph:chart-bar w-4 h-4 text-bolt-elements-item-contentAccent" />
|
||||
<span className="text-sm font-medium text-bolt-elements-textPrimary">
|
||||
GitHub Stats
|
||||
{isStale && <span className="text-bolt-elements-textTertiary ml-1">(Stale)</span>}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
refreshStats();
|
||||
}}
|
||||
disabled={isRefreshing}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-xs"
|
||||
>
|
||||
{isRefreshing ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap w-3 h-3 animate-spin" />
|
||||
Refreshing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:arrows-clockwise w-3 h-3" />
|
||||
Refresh
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<div
|
||||
className={classNames(
|
||||
'i-ph:caret-down w-4 h-4 transform transition-transform duration-200 text-bolt-elements-textSecondary',
|
||||
isExpanded ? 'rotate-180' : '',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
|
||||
<CollapsibleContent className="overflow-hidden">
|
||||
<div className="space-y-4 mt-4">
|
||||
{/* Languages Section */}
|
||||
<div className="mb-6">
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary mb-3">Top Languages</h4>
|
||||
{stats.mostUsedLanguages && stats.mostUsedLanguages.length > 0 ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{stats.mostUsedLanguages.slice(0, 15).map(({ language, bytes, repos }) => (
|
||||
<span
|
||||
key={language}
|
||||
className="px-3 py-1 text-xs rounded-full bg-bolt-elements-sidebar-buttonBackgroundDefault text-bolt-elements-sidebar-buttonText"
|
||||
title={`${language}: ${(bytes / 1024 / 1024).toFixed(2)}MB across ${repos} repos`}
|
||||
>
|
||||
{language} ({repos})
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="text-xs text-bolt-elements-textSecondary">
|
||||
Based on actual codebase size across repositories
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(stats.languages)
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.slice(0, 5)
|
||||
.map(([language]) => (
|
||||
<span
|
||||
key={language}
|
||||
className="px-3 py-1 text-xs rounded-full bg-bolt-elements-sidebar-buttonBackgroundDefault text-bolt-elements-sidebar-buttonText"
|
||||
>
|
||||
{language}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* GitHub Overview Summary */}
|
||||
<div className="mb-6 p-4 bg-bolt-elements-background-depth-1 rounded-lg border border-bolt-elements-borderColor">
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary mb-3">GitHub Overview</h4>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-bolt-elements-textPrimary">
|
||||
{(stats.publicRepos || 0) + (stats.privateRepos || 0)}
|
||||
</div>
|
||||
<div className="text-xs text-bolt-elements-textSecondary">Total Repositories</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-bolt-elements-textPrimary">{stats.totalBranches || 0}</div>
|
||||
<div className="text-xs text-bolt-elements-textSecondary">Total Branches</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-bolt-elements-textPrimary">
|
||||
{stats.organizations?.length || 0}
|
||||
</div>
|
||||
<div className="text-xs text-bolt-elements-textSecondary">Organizations</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-bolt-elements-textPrimary">
|
||||
{Object.keys(stats.languages).length}
|
||||
</div>
|
||||
<div className="text-xs text-bolt-elements-textSecondary">Languages Used</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Activity Summary */}
|
||||
<div className="mb-6">
|
||||
<h5 className="text-sm font-medium text-bolt-elements-textPrimary mb-2">Activity Summary</h5>
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
{[
|
||||
{
|
||||
label: 'Total Branches',
|
||||
value: stats.totalBranches || 0,
|
||||
icon: 'i-ph:git-branch',
|
||||
iconColor: 'text-bolt-elements-icon-info',
|
||||
},
|
||||
{
|
||||
label: 'Contributors',
|
||||
value: stats.totalContributors || 0,
|
||||
icon: 'i-ph:users',
|
||||
iconColor: 'text-bolt-elements-icon-success',
|
||||
},
|
||||
{
|
||||
label: 'Issues',
|
||||
value: stats.totalIssues || 0,
|
||||
icon: 'i-ph:circle',
|
||||
iconColor: 'text-bolt-elements-icon-warning',
|
||||
},
|
||||
{
|
||||
label: 'Pull Requests',
|
||||
value: stats.totalPullRequests || 0,
|
||||
icon: 'i-ph:git-pull-request',
|
||||
iconColor: 'text-bolt-elements-icon-accent',
|
||||
},
|
||||
].map((stat, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex flex-col p-3 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor"
|
||||
>
|
||||
<span className="text-xs text-bolt-elements-textSecondary">{stat.label}</span>
|
||||
<span className="text-lg font-medium text-bolt-elements-textPrimary flex items-center gap-1">
|
||||
<div className={`${stat.icon} w-4 h-4 ${stat.iconColor}`} />
|
||||
{stat.value.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Organizations Section */}
|
||||
{stats.organizations && stats.organizations.length > 0 && (
|
||||
<div>
|
||||
<h5 className="text-sm font-medium text-bolt-elements-textPrimary mb-2">Organizations</h5>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{stats.organizations.map((org) => (
|
||||
<a
|
||||
key={org.login}
|
||||
href={org.html_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-3 p-3 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive dark:hover:border-bolt-elements-borderColorActive transition-all duration-200"
|
||||
>
|
||||
<img
|
||||
src={org.avatar_url}
|
||||
alt={org.login}
|
||||
className="w-8 h-8 rounded-full border border-bolt-elements-borderColor"
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h6 className="text-sm font-medium text-bolt-elements-textPrimary truncate">
|
||||
{org.name || org.login}
|
||||
</h6>
|
||||
<p className="text-xs text-bolt-elements-textSecondary truncate">{org.login}</p>
|
||||
{org.description && (
|
||||
<p className="text-xs text-bolt-elements-textTertiary truncate">{org.description}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-bolt-elements-textSecondary">
|
||||
{org.public_repos && (
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:folder w-3 h-3" />
|
||||
{org.public_repos}
|
||||
</span>
|
||||
)}
|
||||
{org.followers && (
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:users w-3 h-3" />
|
||||
{org.followers}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Last Updated */}
|
||||
<div className="pt-2 border-t border-bolt-elements-borderColor">
|
||||
<span className="text-xs text-bolt-elements-textSecondary">
|
||||
Last updated: {stats.lastUpdated ? new Date(stats.lastUpdated).toLocaleString() : 'Never'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import React from 'react';
|
||||
import type { GitHubUserResponse } from '~/types/GitHub';
|
||||
|
||||
interface GitHubUserProfileProps {
|
||||
user: GitHubUserResponse;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function GitHubUserProfile({ user, className = '' }: GitHubUserProfileProps) {
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center gap-4 p-4 bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-1 rounded-lg ${className}`}
|
||||
>
|
||||
<img
|
||||
src={user.avatar_url}
|
||||
alt={user.login}
|
||||
className="w-12 h-12 rounded-full border-2 border-bolt-elements-item-contentAccent dark:border-bolt-elements-item-contentAccent"
|
||||
/>
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
{user.name || user.login}
|
||||
</h4>
|
||||
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">@{user.login}</p>
|
||||
{user.bio && (
|
||||
<p className="text-xs text-bolt-elements-textTertiary dark:text-bolt-elements-textTertiary mt-1">
|
||||
{user.bio}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-4 mt-2 text-xs text-bolt-elements-textSecondary">
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:users w-3 h-3" />
|
||||
{user.followers} followers
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:folder w-3 h-3" />
|
||||
{user.public_repos} public repos
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="i-ph:file-text w-3 h-3" />
|
||||
{user.public_gists} gists
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,264 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Loader2, AlertCircle, CheckCircle, Info, Github } from 'lucide-react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
interface LoadingStateProps {
|
||||
message?: string;
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function LoadingState({ message = 'Loading...', size = 'md', className = '' }: LoadingStateProps) {
|
||||
const sizeClasses = {
|
||||
sm: 'w-4 h-4',
|
||||
md: 'w-6 h-6',
|
||||
lg: 'w-8 h-8',
|
||||
};
|
||||
|
||||
const textSizeClasses = {
|
||||
sm: 'text-sm',
|
||||
md: 'text-base',
|
||||
lg: 'text-lg',
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'flex flex-col items-center justify-center py-8 text-bolt-elements-textSecondary',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<Loader2 className={classNames('animate-spin mb-2', sizeClasses[size])} />
|
||||
<p className={classNames('text-bolt-elements-textSecondary', textSizeClasses[size])}>{message}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ErrorStateProps {
|
||||
title?: string;
|
||||
message: string;
|
||||
onRetry?: () => void;
|
||||
retryLabel?: string;
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ErrorState({
|
||||
title = 'Error',
|
||||
message,
|
||||
onRetry,
|
||||
retryLabel = 'Try Again',
|
||||
size = 'md',
|
||||
className = '',
|
||||
}: ErrorStateProps) {
|
||||
const sizeClasses = {
|
||||
sm: 'w-4 h-4',
|
||||
md: 'w-6 h-6',
|
||||
lg: 'w-8 h-8',
|
||||
};
|
||||
|
||||
const textSizeClasses = {
|
||||
sm: 'text-sm',
|
||||
md: 'text-base',
|
||||
lg: 'text-lg',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames('flex flex-col items-center justify-center py-8 text-center', className)}>
|
||||
<AlertCircle className={classNames('text-red-500 mb-2', sizeClasses[size])} />
|
||||
<h3 className={classNames('font-medium text-bolt-elements-textPrimary mb-1', textSizeClasses[size])}>{title}</h3>
|
||||
<p className={classNames('text-bolt-elements-textSecondary mb-4', textSizeClasses[size])}>{message}</p>
|
||||
{onRetry && (
|
||||
<button
|
||||
onClick={onRetry}
|
||||
className="px-4 py-2 bg-bolt-elements-item-contentAccent text-white rounded-lg hover:bg-bolt-elements-item-contentAccent/90 transition-colors"
|
||||
>
|
||||
{retryLabel}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SuccessStateProps {
|
||||
title?: string;
|
||||
message: string;
|
||||
onAction?: () => void;
|
||||
actionLabel?: string;
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function SuccessState({
|
||||
title = 'Success',
|
||||
message,
|
||||
onAction,
|
||||
actionLabel = 'Continue',
|
||||
size = 'md',
|
||||
className = '',
|
||||
}: SuccessStateProps) {
|
||||
const sizeClasses = {
|
||||
sm: 'w-4 h-4',
|
||||
md: 'w-6 h-6',
|
||||
lg: 'w-8 h-8',
|
||||
};
|
||||
|
||||
const textSizeClasses = {
|
||||
sm: 'text-sm',
|
||||
md: 'text-base',
|
||||
lg: 'text-lg',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames('flex flex-col items-center justify-center py-8 text-center', className)}>
|
||||
<CheckCircle className={classNames('text-green-500 mb-2', sizeClasses[size])} />
|
||||
<h3 className={classNames('font-medium text-bolt-elements-textPrimary mb-1', textSizeClasses[size])}>{title}</h3>
|
||||
<p className={classNames('text-bolt-elements-textSecondary mb-4', textSizeClasses[size])}>{message}</p>
|
||||
{onAction && (
|
||||
<button
|
||||
onClick={onAction}
|
||||
className="px-4 py-2 bg-bolt-elements-item-contentAccent text-white rounded-lg hover:bg-bolt-elements-item-contentAccent/90 transition-colors"
|
||||
>
|
||||
{actionLabel}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface GitHubConnectionRequiredProps {
|
||||
onConnect?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function GitHubConnectionRequired({ onConnect, className = '' }: GitHubConnectionRequiredProps) {
|
||||
return (
|
||||
<div className={classNames('flex flex-col items-center justify-center py-12 text-center', className)}>
|
||||
<Github className="w-12 h-12 text-bolt-elements-textTertiary mb-4" />
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-2">GitHub Connection Required</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary mb-6 max-w-md">
|
||||
Please connect your GitHub account to access this feature. You'll be able to browse repositories, push code, and
|
||||
manage your GitHub integration.
|
||||
</p>
|
||||
{onConnect && (
|
||||
<button
|
||||
onClick={onConnect}
|
||||
className="px-6 py-3 bg-bolt-elements-item-contentAccent text-white rounded-lg hover:bg-bolt-elements-item-contentAccent/90 transition-colors flex items-center gap-2"
|
||||
>
|
||||
<Github className="w-4 h-4" />
|
||||
Connect GitHub
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface InformationStateProps {
|
||||
title: string;
|
||||
message: string;
|
||||
icon?: React.ComponentType<{ className?: string }>;
|
||||
onAction?: () => void;
|
||||
actionLabel?: string;
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function InformationState({
|
||||
title,
|
||||
message,
|
||||
icon = Info,
|
||||
onAction,
|
||||
actionLabel = 'Got it',
|
||||
size = 'md',
|
||||
className = '',
|
||||
}: InformationStateProps) {
|
||||
const sizeClasses = {
|
||||
sm: 'w-4 h-4',
|
||||
md: 'w-6 h-6',
|
||||
lg: 'w-8 h-8',
|
||||
};
|
||||
|
||||
const textSizeClasses = {
|
||||
sm: 'text-sm',
|
||||
md: 'text-base',
|
||||
lg: 'text-lg',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames('flex flex-col items-center justify-center py-8 text-center', className)}>
|
||||
{React.createElement(icon, { className: classNames('text-blue-500 mb-2', sizeClasses[size]) })}
|
||||
<h3 className={classNames('font-medium text-bolt-elements-textPrimary mb-1', textSizeClasses[size])}>{title}</h3>
|
||||
<p className={classNames('text-bolt-elements-textSecondary mb-4', textSizeClasses[size])}>{message}</p>
|
||||
{onAction && (
|
||||
<button
|
||||
onClick={onAction}
|
||||
className="px-4 py-2 bg-bolt-elements-item-contentAccent text-white rounded-lg hover:bg-bolt-elements-item-contentAccent/90 transition-colors"
|
||||
>
|
||||
{actionLabel}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ConnectionTestIndicatorProps {
|
||||
status: 'success' | 'error' | 'testing' | null;
|
||||
message?: string;
|
||||
timestamp?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ConnectionTestIndicator({ status, message, timestamp, className = '' }: ConnectionTestIndicatorProps) {
|
||||
if (!status) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const getStatusColor = () => {
|
||||
switch (status) {
|
||||
case 'success':
|
||||
return 'bg-green-50 border-green-200 dark:bg-green-900/20 dark:border-green-700';
|
||||
case 'error':
|
||||
return 'bg-red-50 border-red-200 dark:bg-red-900/20 dark:border-red-700';
|
||||
case 'testing':
|
||||
return 'bg-blue-50 border-blue-200 dark:bg-blue-900/20 dark:border-blue-700';
|
||||
default:
|
||||
return 'bg-gray-50 border-gray-200 dark:bg-gray-900/20 dark:border-gray-700';
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusIcon = () => {
|
||||
switch (status) {
|
||||
case 'success':
|
||||
return <CheckCircle className="w-5 h-5 text-green-600 dark:text-green-400" />;
|
||||
case 'error':
|
||||
return <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400" />;
|
||||
case 'testing':
|
||||
return <Loader2 className="w-5 h-5 animate-spin text-blue-600 dark:text-blue-400" />;
|
||||
default:
|
||||
return <Info className="w-5 h-5 text-gray-600 dark:text-gray-400" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusTextColor = () => {
|
||||
switch (status) {
|
||||
case 'success':
|
||||
return 'text-green-800 dark:text-green-200';
|
||||
case 'error':
|
||||
return 'text-red-800 dark:text-red-200';
|
||||
case 'testing':
|
||||
return 'text-blue-800 dark:text-blue-200';
|
||||
default:
|
||||
return 'text-gray-800 dark:text-gray-200';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames(`p-4 rounded-lg border ${getStatusColor()}`, className)}>
|
||||
<div className="flex items-center gap-2">
|
||||
{getStatusIcon()}
|
||||
<span className={classNames('text-sm font-medium', getStatusTextColor())}>{message || status}</span>
|
||||
</div>
|
||||
{timestamp && <p className="text-xs text-gray-500 mt-1">{new Date(timestamp).toLocaleString()}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,361 +0,0 @@
|
||||
import React from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { formatSize } from '~/utils/formatSize';
|
||||
import type { GitHubRepoInfo } from '~/types/GitHub';
|
||||
import {
|
||||
Star,
|
||||
GitFork,
|
||||
Clock,
|
||||
Lock,
|
||||
Archive,
|
||||
GitBranch,
|
||||
Users,
|
||||
Database,
|
||||
Tag,
|
||||
Heart,
|
||||
ExternalLink,
|
||||
Circle,
|
||||
GitPullRequest,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface RepositoryCardProps {
|
||||
repository: GitHubRepoInfo;
|
||||
variant?: 'default' | 'compact' | 'detailed';
|
||||
onSelect?: () => void;
|
||||
showHealthScore?: boolean;
|
||||
showExtendedMetrics?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RepositoryCard({
|
||||
repository,
|
||||
variant = 'default',
|
||||
onSelect,
|
||||
showHealthScore = false,
|
||||
showExtendedMetrics = false,
|
||||
className = '',
|
||||
}: RepositoryCardProps) {
|
||||
const daysSinceUpdate = Math.floor((Date.now() - new Date(repository.updated_at).getTime()) / (1000 * 60 * 60 * 24));
|
||||
|
||||
const formatTimeAgo = () => {
|
||||
if (daysSinceUpdate === 0) {
|
||||
return 'Today';
|
||||
}
|
||||
|
||||
if (daysSinceUpdate === 1) {
|
||||
return '1 day ago';
|
||||
}
|
||||
|
||||
if (daysSinceUpdate < 7) {
|
||||
return `${daysSinceUpdate} days ago`;
|
||||
}
|
||||
|
||||
if (daysSinceUpdate < 30) {
|
||||
return `${Math.floor(daysSinceUpdate / 7)} weeks ago`;
|
||||
}
|
||||
|
||||
return new Date(repository.updated_at).toLocaleDateString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
});
|
||||
};
|
||||
|
||||
const calculateHealthScore = () => {
|
||||
const hasStars = repository.stargazers_count > 0;
|
||||
const hasRecentActivity = daysSinceUpdate < 30;
|
||||
const hasContributors = (repository.contributors_count || 0) > 1;
|
||||
const hasDescription = !!repository.description;
|
||||
const hasTopics = (repository.topics || []).length > 0;
|
||||
const hasLicense = !!repository.license;
|
||||
|
||||
const healthScore = [hasStars, hasRecentActivity, hasContributors, hasDescription, hasTopics, hasLicense].filter(
|
||||
Boolean,
|
||||
).length;
|
||||
|
||||
const maxScore = 6;
|
||||
const percentage = Math.round((healthScore / maxScore) * 100);
|
||||
|
||||
const getScoreColor = (score: number) => {
|
||||
if (score >= 5) {
|
||||
return 'text-green-500';
|
||||
}
|
||||
|
||||
if (score >= 3) {
|
||||
return 'text-yellow-500';
|
||||
}
|
||||
|
||||
return 'text-red-500';
|
||||
};
|
||||
|
||||
return {
|
||||
percentage,
|
||||
color: getScoreColor(healthScore),
|
||||
score: healthScore,
|
||||
maxScore,
|
||||
};
|
||||
};
|
||||
|
||||
const getHealthIndicatorColor = () => {
|
||||
const isActive = daysSinceUpdate < 7;
|
||||
const isHealthy = daysSinceUpdate < 30 && !repository.archived && repository.stargazers_count > 0;
|
||||
|
||||
if (repository.archived) {
|
||||
return 'bg-gray-500';
|
||||
}
|
||||
|
||||
if (isActive) {
|
||||
return 'bg-green-500';
|
||||
}
|
||||
|
||||
if (isHealthy) {
|
||||
return 'bg-blue-500';
|
||||
}
|
||||
|
||||
return 'bg-yellow-500';
|
||||
};
|
||||
|
||||
const getHealthTitle = () => {
|
||||
if (repository.archived) {
|
||||
return 'Archived';
|
||||
}
|
||||
|
||||
if (daysSinceUpdate < 7) {
|
||||
return 'Very Active';
|
||||
}
|
||||
|
||||
if (daysSinceUpdate < 30 && repository.stargazers_count > 0) {
|
||||
return 'Healthy';
|
||||
}
|
||||
|
||||
return 'Needs Attention';
|
||||
};
|
||||
|
||||
const health = showHealthScore ? calculateHealthScore() : null;
|
||||
|
||||
if (variant === 'compact') {
|
||||
return (
|
||||
<button
|
||||
onClick={onSelect}
|
||||
className={classNames(
|
||||
'w-full text-left p-3 rounded-lg border border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive hover:bg-bolt-elements-background-depth-1 transition-all duration-200',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary">{repository.name}</h4>
|
||||
{repository.private && <Lock className="w-3 h-3 text-bolt-elements-textTertiary" />}
|
||||
{repository.fork && <GitFork className="w-3 h-3 text-bolt-elements-textTertiary" />}
|
||||
{repository.archived && <Archive className="w-3 h-3 text-bolt-elements-textTertiary" />}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 text-xs text-bolt-elements-textSecondary">
|
||||
<span className="flex items-center gap-1">
|
||||
<Star className="w-3 h-3" />
|
||||
{repository.stargazers_count}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<GitFork className="w-3 h-3" />
|
||||
{repository.forks_count}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{repository.description && (
|
||||
<p className="text-xs text-bolt-elements-textSecondary mb-2 line-clamp-2">{repository.description}</p>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3 text-xs text-bolt-elements-textTertiary">
|
||||
{repository.language && (
|
||||
<span className="flex items-center gap-1">
|
||||
<div className="w-2 h-2 rounded-full bg-current opacity-60" />
|
||||
{repository.language}
|
||||
</span>
|
||||
)}
|
||||
{repository.size && <span>{formatSize(repository.size * 1024)}</span>}
|
||||
</div>
|
||||
|
||||
<span className="flex items-center gap-1 text-xs text-bolt-elements-textTertiary">
|
||||
<Clock className="w-3 h-3" />
|
||||
{formatTimeAgo()}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const Component = onSelect ? 'button' : 'div';
|
||||
const interactiveProps = onSelect
|
||||
? {
|
||||
onClick: onSelect,
|
||||
className: classNames(
|
||||
'group cursor-pointer hover:border-bolt-elements-borderColorActive dark:hover:border-bolt-elements-borderColorActive transition-all duration-200',
|
||||
className,
|
||||
),
|
||||
}
|
||||
: { className };
|
||||
|
||||
return (
|
||||
<Component
|
||||
{...interactiveProps}
|
||||
className={classNames(
|
||||
'block p-4 rounded-lg bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor relative',
|
||||
interactiveProps.className,
|
||||
)}
|
||||
>
|
||||
{/* Repository Health Indicator */}
|
||||
{variant === 'detailed' && (
|
||||
<div
|
||||
className={`absolute top-2 right-2 w-2 h-2 rounded-full ${getHealthIndicatorColor()}`}
|
||||
title={`Repository Health: ${getHealthTitle()}`}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="w-4 h-4 text-bolt-elements-icon-tertiary" />
|
||||
<h5
|
||||
className={classNames(
|
||||
'text-sm font-medium text-bolt-elements-textPrimary',
|
||||
onSelect && 'group-hover:text-bolt-elements-item-contentAccent transition-colors',
|
||||
)}
|
||||
>
|
||||
{repository.name}
|
||||
</h5>
|
||||
{repository.fork && (
|
||||
<span title="Forked repository">
|
||||
<GitFork className="w-3 h-3 text-bolt-elements-textTertiary" />
|
||||
</span>
|
||||
)}
|
||||
{repository.archived && (
|
||||
<span title="Archived repository">
|
||||
<Archive className="w-3 h-3 text-bolt-elements-textTertiary" />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-xs text-bolt-elements-textSecondary">
|
||||
<span className="flex items-center gap-1" title="Stars">
|
||||
<Star className="w-3.5 h-3.5 text-bolt-elements-icon-warning" />
|
||||
{repository.stargazers_count.toLocaleString()}
|
||||
</span>
|
||||
<span className="flex items-center gap-1" title="Forks">
|
||||
<GitFork className="w-3.5 h-3.5 text-bolt-elements-icon-info" />
|
||||
{repository.forks_count.toLocaleString()}
|
||||
</span>
|
||||
{showExtendedMetrics && repository.issues_count !== undefined && (
|
||||
<span className="flex items-center gap-1" title="Open Issues">
|
||||
<Circle className="w-3.5 h-3.5 text-bolt-elements-icon-error" />
|
||||
{repository.issues_count}
|
||||
</span>
|
||||
)}
|
||||
{showExtendedMetrics && repository.pull_requests_count !== undefined && (
|
||||
<span className="flex items-center gap-1" title="Pull Requests">
|
||||
<GitPullRequest className="w-3.5 h-3.5 text-bolt-elements-icon-success" />
|
||||
{repository.pull_requests_count}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{repository.description && (
|
||||
<p className="text-xs text-bolt-elements-textSecondary line-clamp-2">{repository.description}</p>
|
||||
)}
|
||||
|
||||
{/* Repository metrics bar */}
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
{repository.license && (
|
||||
<span className="px-2 py-0.5 rounded-full bg-bolt-elements-background-depth-2 text-bolt-elements-textTertiary">
|
||||
{repository.license.spdx_id || repository.license.name}
|
||||
</span>
|
||||
)}
|
||||
{repository.topics &&
|
||||
repository.topics.slice(0, 2).map((topic) => (
|
||||
<span
|
||||
key={topic}
|
||||
className="px-2 py-0.5 rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400"
|
||||
>
|
||||
{topic}
|
||||
</span>
|
||||
))}
|
||||
{repository.archived && (
|
||||
<span className="px-2 py-0.5 rounded-full bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400">
|
||||
Archived
|
||||
</span>
|
||||
)}
|
||||
{repository.fork && (
|
||||
<span className="px-2 py-0.5 rounded-full bg-purple-100 text-purple-800 dark:bg-purple-900/20 dark:text-purple-400">
|
||||
Fork
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3 text-xs text-bolt-elements-textSecondary">
|
||||
<span className="flex items-center gap-1" title="Default Branch">
|
||||
<GitBranch className="w-3.5 h-3.5" />
|
||||
{repository.default_branch}
|
||||
</span>
|
||||
{showExtendedMetrics && repository.branches_count && (
|
||||
<span className="flex items-center gap-1" title="Total Branches">
|
||||
<GitFork className="w-3.5 h-3.5" />
|
||||
{repository.branches_count}
|
||||
</span>
|
||||
)}
|
||||
{showExtendedMetrics && repository.contributors_count && (
|
||||
<span className="flex items-center gap-1" title="Contributors">
|
||||
<Users className="w-3.5 h-3.5" />
|
||||
{repository.contributors_count}
|
||||
</span>
|
||||
)}
|
||||
{repository.size && (
|
||||
<span className="flex items-center gap-1" title="Size">
|
||||
<Database className="w-3.5 h-3.5" />
|
||||
{(repository.size / 1024).toFixed(1)}MB
|
||||
</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1" title="Last Updated">
|
||||
<Clock className="w-3.5 h-3.5" />
|
||||
{formatTimeAgo()}
|
||||
</span>
|
||||
{repository.topics && repository.topics.length > 0 && (
|
||||
<span className="flex items-center gap-1" title={`Topics: ${repository.topics.join(', ')}`}>
|
||||
<Tag className="w-3.5 h-3.5" />
|
||||
{repository.topics.length}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Repository Health Score */}
|
||||
{health && (
|
||||
<div
|
||||
className="flex items-center gap-1"
|
||||
title={`Health Score: ${health.percentage}% (${health.score}/${health.maxScore})`}
|
||||
>
|
||||
<Heart className={`w-3.5 h-3.5 ${health.color}`} />
|
||||
<span className={`text-xs font-medium ${health.color}`}>{health.percentage}%</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{onSelect && (
|
||||
<span
|
||||
className={classNames(
|
||||
'flex items-center gap-1 ml-2 transition-colors',
|
||||
'group-hover:text-bolt-elements-item-contentAccent',
|
||||
)}
|
||||
>
|
||||
<ExternalLink className="w-3.5 h-3.5" />
|
||||
View
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Component>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
export { RepositoryCard } from './RepositoryCard';
|
||||
|
||||
// GitHubDialog components not yet implemented
|
||||
export {
|
||||
LoadingState,
|
||||
ErrorState,
|
||||
SuccessState,
|
||||
GitHubConnectionRequired,
|
||||
InformationState,
|
||||
ConnectionTestIndicator,
|
||||
} from './GitHubStateIndicators';
|
||||
@@ -1,305 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useGitLabConnection } from '~/lib/hooks';
|
||||
import GitLabConnection from './components/GitLabConnection';
|
||||
import { StatsDisplay } from './components/StatsDisplay';
|
||||
import { RepositoryList } from './components/RepositoryList';
|
||||
|
||||
// GitLab logo SVG component
|
||||
const GitLabLogo = () => (
|
||||
<svg viewBox="0 0 24 24" className="w-5 h-5">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M22.65 14.39L12 22.13 1.35 14.39a.84.84 0 0 1-.3-.94l1.22-3.78 2.44-7.51A.42.42 0 0 1 4.82 2a.43.43 0 0 1 .58 0 .42.42 0 0 1 .11.18l2.44 7.49h8.1l2.44-7.51A.42.42 0 0 1 18.6 2a.43.43 0 0 1 .58 0 .42.42 0 0 1 .11.18l2.44 7.51L23 13.45a.84.84 0 0 1-.35.94z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
interface ConnectionTestResult {
|
||||
status: 'success' | 'error' | 'testing';
|
||||
message: string;
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
export default function GitLabTab() {
|
||||
const { connection, isConnected, isLoading, error, testConnection, refreshStats } = useGitLabConnection();
|
||||
const [connectionTest, setConnectionTest] = useState<ConnectionTestResult | null>(null);
|
||||
const [isRefreshingStats, setIsRefreshingStats] = useState(false);
|
||||
|
||||
const handleTestConnection = async () => {
|
||||
if (!connection?.user) {
|
||||
setConnectionTest({
|
||||
status: 'error',
|
||||
message: 'No connection established',
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setConnectionTest({
|
||||
status: 'testing',
|
||||
message: 'Testing connection...',
|
||||
});
|
||||
|
||||
try {
|
||||
const isValid = await testConnection();
|
||||
|
||||
if (isValid) {
|
||||
setConnectionTest({
|
||||
status: 'success',
|
||||
message: `Connected successfully as ${connection.user.username}`,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
} else {
|
||||
setConnectionTest({
|
||||
status: 'error',
|
||||
message: 'Connection test failed',
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
setConnectionTest({
|
||||
status: 'error',
|
||||
message: `Connection failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Loading state for initial connection check
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitLabLogo />
|
||||
<h2 className="text-lg font-medium text-bolt-elements-textPrimary">GitLab Integration</h2>
|
||||
</div>
|
||||
<div className="flex items-center justify-center p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="i-ph:spinner-gap-bold animate-spin w-4 h-4" />
|
||||
<span className="text-bolt-elements-textSecondary">Loading...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Error state for connection issues
|
||||
if (error && !connection) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitLabLogo />
|
||||
<h2 className="text-lg font-medium text-bolt-elements-textPrimary">GitLab Integration</h2>
|
||||
</div>
|
||||
<div className="text-sm text-red-600 dark:text-red-400 p-3 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800">
|
||||
{error}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Not connected state
|
||||
if (!isConnected || !connection) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitLabLogo />
|
||||
<h2 className="text-lg font-medium text-bolt-elements-textPrimary">GitLab Integration</h2>
|
||||
</div>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">
|
||||
Connect your GitLab account to enable advanced repository management features, statistics, and seamless
|
||||
integration.
|
||||
</p>
|
||||
<GitLabConnection connectionTest={connectionTest} onTestConnection={handleTestConnection} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<motion.div
|
||||
className="flex items-center justify-between gap-2"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<GitLabLogo />
|
||||
<h2 className="text-lg font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
GitLab Integration
|
||||
</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{connection?.rateLimit && (
|
||||
<div className="flex items-center gap-2 px-3 py-1 bg-bolt-elements-background-depth-1 rounded-lg text-xs">
|
||||
<div className="i-ph:cloud w-4 h-4 text-bolt-elements-textSecondary" />
|
||||
<span className="text-bolt-elements-textSecondary">
|
||||
API: {connection.rateLimit.remaining}/{connection.rateLimit.limit}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<p className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
|
||||
Manage your GitLab integration with advanced repository features and comprehensive statistics
|
||||
</p>
|
||||
|
||||
{/* Connection Test Results */}
|
||||
{connectionTest && (
|
||||
<div
|
||||
className={`p-3 rounded-lg border ${
|
||||
connectionTest.status === 'success'
|
||||
? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800'
|
||||
: connectionTest.status === 'error'
|
||||
? 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800'
|
||||
: 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={`w-4 h-4 ${
|
||||
connectionTest.status === 'success'
|
||||
? 'text-green-600'
|
||||
: connectionTest.status === 'error'
|
||||
? 'text-red-600'
|
||||
: 'text-blue-600'
|
||||
}`}
|
||||
>
|
||||
{connectionTest.status === 'success' ? (
|
||||
<div className="i-ph:check-circle" />
|
||||
) : connectionTest.status === 'error' ? (
|
||||
<div className="i-ph:x-circle" />
|
||||
) : (
|
||||
<div className="i-ph:spinner animate-spin" />
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className={`text-sm ${
|
||||
connectionTest.status === 'success'
|
||||
? 'text-green-800 dark:text-green-200'
|
||||
: connectionTest.status === 'error'
|
||||
? 'text-red-800 dark:text-red-200'
|
||||
: 'text-blue-800 dark:text-blue-200'
|
||||
}`}
|
||||
>
|
||||
{connectionTest.message}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* GitLab Connection Component */}
|
||||
<GitLabConnection connectionTest={connectionTest} onTestConnection={handleTestConnection} />
|
||||
|
||||
{/* User Profile Section */}
|
||||
{connection?.user && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.3 }}
|
||||
className="border-t border-bolt-elements-borderColor pt-6"
|
||||
>
|
||||
<div className="flex items-center gap-4 p-4 bg-bolt-elements-background-depth-1 rounded-lg">
|
||||
<div className="w-12 h-12 rounded-full border-2 border-bolt-elements-item-contentAccent flex items-center justify-center bg-bolt-elements-background-depth-2 overflow-hidden">
|
||||
{connection.user.avatar_url &&
|
||||
connection.user.avatar_url !== 'null' &&
|
||||
connection.user.avatar_url !== '' ? (
|
||||
<img
|
||||
src={connection.user.avatar_url}
|
||||
alt={connection.user.username}
|
||||
className="w-full h-full rounded-full object-cover"
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
|
||||
const parent = target.parentElement;
|
||||
|
||||
if (parent) {
|
||||
parent.innerHTML = (connection.user?.name || connection.user?.username || 'U')
|
||||
.charAt(0)
|
||||
.toUpperCase();
|
||||
parent.classList.add(
|
||||
'text-white',
|
||||
'font-semibold',
|
||||
'text-sm',
|
||||
'flex',
|
||||
'items-center',
|
||||
'justify-center',
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full rounded-full bg-bolt-elements-item-contentAccent flex items-center justify-center text-white font-semibold text-sm">
|
||||
{(connection.user?.name || connection.user?.username || 'U').charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary">
|
||||
{connection.user?.name || connection.user?.username}
|
||||
</h4>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">{connection.user?.username}</p>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* GitLab Stats Section */}
|
||||
{connection?.stats && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.4 }}
|
||||
className="border-t border-bolt-elements-borderColor pt-6"
|
||||
>
|
||||
<h3 className="text-base font-medium text-bolt-elements-textPrimary mb-4">Statistics</h3>
|
||||
<StatsDisplay
|
||||
stats={connection.stats}
|
||||
onRefresh={async () => {
|
||||
setIsRefreshingStats(true);
|
||||
|
||||
try {
|
||||
await refreshStats();
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh stats:', error);
|
||||
} finally {
|
||||
setIsRefreshingStats(false);
|
||||
}
|
||||
}}
|
||||
isRefreshing={isRefreshingStats}
|
||||
/>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* GitLab Repositories Section */}
|
||||
{connection?.stats?.projects && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.5 }}
|
||||
className="border-t border-bolt-elements-borderColor pt-6"
|
||||
>
|
||||
<RepositoryList
|
||||
repositories={connection.stats.projects}
|
||||
onRefresh={async () => {
|
||||
setIsRefreshingStats(true);
|
||||
|
||||
try {
|
||||
await refreshStats();
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh repositories:', error);
|
||||
} finally {
|
||||
setIsRefreshingStats(false);
|
||||
}
|
||||
}}
|
||||
isRefreshing={isRefreshingStats}
|
||||
/>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
import * as Dialog from '@radix-ui/react-dialog';
|
||||
import { useState } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { toast } from 'react-toastify';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { useGitLabConnection } from '~/lib/hooks';
|
||||
|
||||
interface GitLabAuthDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function GitLabAuthDialog({ isOpen, onClose }: GitLabAuthDialogProps) {
|
||||
const { isConnecting, error, connect } = useGitLabConnection();
|
||||
const [token, setToken] = useState('');
|
||||
const [gitlabUrl, setGitlabUrl] = useState('https://gitlab.com');
|
||||
|
||||
const handleConnect = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!token.trim()) {
|
||||
toast.error('Please enter your GitLab access token');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await connect(token, gitlabUrl);
|
||||
toast.success('Successfully connected to GitLab!');
|
||||
setToken('');
|
||||
onClose();
|
||||
} catch (error) {
|
||||
// Error handling is done in the hook
|
||||
console.error('GitLab connect failed:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog.Root open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<Dialog.Portal>
|
||||
<Dialog.Overlay className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[10000]" />
|
||||
<div className="fixed inset-0 flex items-center justify-center z-[10000]">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="w-[90vw] md:w-[500px]"
|
||||
>
|
||||
<Dialog.Content
|
||||
className="bg-white dark:bg-bolt-elements-background-depth-1 rounded-lg p-6 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark shadow-xl"
|
||||
aria-describedby="gitlab-auth-description"
|
||||
>
|
||||
<Dialog.Title className="text-lg font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark mb-4">
|
||||
Connect to GitLab
|
||||
</Dialog.Title>
|
||||
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-10 h-10 rounded-xl bg-orange-500/10 flex items-center justify-center text-orange-500">
|
||||
<svg viewBox="0 0 24 24" className="w-5 h-5">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M22.65 14.39L12 22.13 1.35 14.39a.84.84 0 0 1-.3-.94l1.22-3.78 2.44-7.51A.42.42 0 0 1 4.82 2a.43.43 0 0 1 .58 0 .42.42 0 0 1 .11.18l2.44 7.49h8.1l2.44-7.51A.42.42 0 0 1 18.6 2a.43.43 0 0 1 .58 0 .42.42 0 0 1 .11.18l2.44 7.51L23 13.45a.84.84 0 0 1-.35.94z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark">
|
||||
GitLab Connection
|
||||
</h3>
|
||||
<p
|
||||
id="gitlab-auth-description"
|
||||
className="text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark"
|
||||
>
|
||||
Connect your GitLab account to deploy your projects
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleConnect} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark mb-2">
|
||||
GitLab URL
|
||||
</label>
|
||||
<input
|
||||
type="url"
|
||||
value={gitlabUrl}
|
||||
onChange={(e) => setGitlabUrl(e.target.value)}
|
||||
disabled={isConnecting}
|
||||
placeholder="https://gitlab.com"
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3',
|
||||
'border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark',
|
||||
'text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark',
|
||||
'placeholder-bolt-elements-textTertiary dark:placeholder-bolt-elements-textTertiary-dark',
|
||||
'focus:outline-none focus:ring-2 focus:ring-orange-500',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark mb-2">
|
||||
Access Token
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
disabled={isConnecting}
|
||||
placeholder="Enter your GitLab access token"
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3',
|
||||
'border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark',
|
||||
'text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary-dark',
|
||||
'placeholder-bolt-elements-textTertiary dark:placeholder-bolt-elements-textTertiary-dark',
|
||||
'focus:outline-none focus:ring-2 focus:ring-orange-500',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
)}
|
||||
required
|
||||
/>
|
||||
<div className="mt-2 text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark">
|
||||
<a
|
||||
href={`${gitlabUrl}/-/user_settings/personal_access_tokens`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-orange-500 hover:text-orange-600 hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
Get your token
|
||||
<div className="i-ph:arrow-square-out w-3 h-3" />
|
||||
</a>
|
||||
<span className="mx-2">•</span>
|
||||
<span>Required scopes: api, read_repository</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700">
|
||||
<p className="text-sm text-red-800 dark:text-red-200">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<motion.button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 rounded-lg bg-bolt-elements-background-depth-2 dark:bg-bolt-elements-background-depth-3 text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary-dark hover:bg-bolt-elements-background-depth-3 dark:hover:bg-bolt-elements-background-depth-4 text-sm border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark"
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
disabled={isConnecting}
|
||||
>
|
||||
Cancel
|
||||
</motion.button>
|
||||
<motion.button
|
||||
type="submit"
|
||||
disabled={isConnecting || !token.trim()}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm inline-flex items-center gap-2',
|
||||
'bg-orange-500 text-white hover:bg-orange-600',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
)}
|
||||
whileHover={!isConnecting && token.trim() ? { scale: 1.02 } : {}}
|
||||
whileTap={!isConnecting && token.trim() ? { scale: 0.98 } : {}}
|
||||
>
|
||||
{isConnecting ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap animate-spin w-4 h-4" />
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:plug-charging w-4 h-4" />
|
||||
Connect to GitLab
|
||||
</>
|
||||
)}
|
||||
</motion.button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog.Content>
|
||||
</motion.div>
|
||||
</div>
|
||||
</Dialog.Portal>
|
||||
</Dialog.Root>
|
||||
);
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { toast } from 'react-toastify';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { useGitLabConnection } from '~/lib/hooks';
|
||||
|
||||
interface ConnectionTestResult {
|
||||
status: 'success' | 'error' | 'testing';
|
||||
message: string;
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
interface GitLabConnectionProps {
|
||||
connectionTest: ConnectionTestResult | null;
|
||||
onTestConnection: () => void;
|
||||
}
|
||||
|
||||
export default function GitLabConnection({ connectionTest, onTestConnection }: GitLabConnectionProps) {
|
||||
const { isConnected, isConnecting, connection, error, connect, disconnect } = useGitLabConnection();
|
||||
|
||||
const [token, setToken] = useState('');
|
||||
const [gitlabUrl, setGitlabUrl] = useState('https://gitlab.com');
|
||||
|
||||
const handleConnect = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
console.log('GitLab connect attempt:', {
|
||||
token: token ? `${token.substring(0, 10)}...` : 'empty',
|
||||
gitlabUrl,
|
||||
tokenLength: token.length,
|
||||
});
|
||||
|
||||
if (!token.trim()) {
|
||||
console.log('Token is empty, not attempting connection');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('Calling connect function...');
|
||||
await connect(token, gitlabUrl);
|
||||
console.log('Connect function completed successfully');
|
||||
setToken(''); // Clear token on successful connection
|
||||
} catch (error) {
|
||||
console.error('GitLab connect failed:', error);
|
||||
|
||||
// Error handling is done in the hook
|
||||
}
|
||||
};
|
||||
|
||||
const handleDisconnect = () => {
|
||||
disconnect();
|
||||
toast.success('Disconnected from GitLab');
|
||||
};
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className="bg-bolt-elements-background border border-bolt-elements-borderColor rounded-lg"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<div className="p-6 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-5 h-5 text-orange-600">
|
||||
<svg viewBox="0 0 24 24" className="w-5 h-5">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M22.65 14.39L12 22.13 1.35 14.39a.84.84 0 0 1-.3-.94l1.22-3.78 2.44-7.51A.42.42 0 0 1 4.82 2a.43.43 0 0 1 .58 0 .42.42 0 0 1 .11.18l2.44 7.49h8.1l2.44-7.51A.42.42 0 0 1 18.6 2a.43.43 0 0 1 .58 0 .42.42 0 0 1 .11.18l2.44 7.51L23 13.45a.84.84 0 0 1-.35.94z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="text-base font-medium text-bolt-elements-textPrimary">GitLab Connection</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!isConnected && (
|
||||
<div className="text-xs text-bolt-elements-textSecondary bg-bolt-elements-background-depth-1 p-3 rounded-lg mb-4">
|
||||
<p className="flex items-center gap-1 mb-1">
|
||||
<span className="i-ph:lightbulb w-3.5 h-3.5 text-bolt-elements-icon-success" />
|
||||
<span className="font-medium">Tip:</span> You can also set the{' '}
|
||||
<code className="px-1 py-0.5 bg-bolt-elements-background-depth-2 rounded">VITE_GITLAB_ACCESS_TOKEN</code>{' '}
|
||||
environment variable to connect automatically.
|
||||
</p>
|
||||
<p>
|
||||
For self-hosted GitLab instances, also set{' '}
|
||||
<code className="px-1 py-0.5 bg-bolt-elements-background-depth-2 rounded">
|
||||
VITE_GITLAB_URL=https://your-gitlab-instance.com
|
||||
</code>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleConnect}>
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary mb-2">GitLab URL</label>
|
||||
<input
|
||||
type="text"
|
||||
value={gitlabUrl}
|
||||
onChange={(e) => setGitlabUrl(e.target.value)}
|
||||
disabled={isConnecting || isConnected}
|
||||
placeholder="https://gitlab.com"
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-1',
|
||||
'border border-bolt-elements-borderColor',
|
||||
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive',
|
||||
'disabled:opacity-50',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-bolt-elements-textSecondary mb-2">Access Token</label>
|
||||
<input
|
||||
type="password"
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
disabled={isConnecting || isConnected}
|
||||
placeholder="Enter your GitLab access token"
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-1',
|
||||
'border border-bolt-elements-borderColor',
|
||||
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive',
|
||||
'disabled:opacity-50',
|
||||
)}
|
||||
/>
|
||||
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
|
||||
<a
|
||||
href={`${gitlabUrl}/-/user_settings/personal_access_tokens`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-bolt-elements-borderColorActive hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
Get your token
|
||||
<div className="i-ph:arrow-square-out w-4 h-4" />
|
||||
</a>
|
||||
<span className="mx-2">•</span>
|
||||
<span>Required scopes: api, read_repository</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-4 rounded-lg bg-red-50 border border-red-200 dark:bg-red-900/20 dark:border-red-700">
|
||||
<p className="text-sm text-red-800 dark:text-red-200">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
{!isConnected ? (
|
||||
<>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isConnecting || !token.trim()}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-[#FC6D26] text-white',
|
||||
'hover:bg-[#E24329] hover:text-white',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200',
|
||||
'transform active:scale-95',
|
||||
)}
|
||||
>
|
||||
{isConnecting ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap animate-spin" />
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:plug-charging w-4 h-4" />
|
||||
Connect
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
console.log('Manual test:', { token: token ? `${token.substring(0, 10)}...` : 'empty', gitlabUrl })
|
||||
}
|
||||
className="px-4 py-2 rounded-lg text-sm bg-gray-500 text-white hover:bg-gray-600"
|
||||
>
|
||||
Test Values
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={handleDisconnect}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-red-500 text-white',
|
||||
'hover:bg-red-600',
|
||||
)}
|
||||
>
|
||||
<div className="i-ph:plug w-4 h-4" />
|
||||
Disconnect
|
||||
</button>
|
||||
<span className="text-sm text-bolt-elements-textSecondary flex items-center gap-1">
|
||||
<div className="i-ph:check-circle w-4 h-4 text-green-500" />
|
||||
Connected to GitLab
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
window.open(
|
||||
`${connection?.gitlabUrl || 'https://gitlab.com'}/dashboard`,
|
||||
'_blank',
|
||||
'noopener,noreferrer',
|
||||
)
|
||||
}
|
||||
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:text-bolt-elements-textPrimary transition-colors"
|
||||
>
|
||||
<div className="i-ph:layout w-4 h-4" />
|
||||
Dashboard
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onTestConnection}
|
||||
disabled={connectionTest?.status === 'testing'}
|
||||
variant="outline"
|
||||
className="flex items-center gap-2 hover:bg-bolt-elements-item-backgroundActive/10 hover:text-bolt-elements-textPrimary dark:hover:text-bolt-elements-textPrimary transition-colors"
|
||||
>
|
||||
{connectionTest?.status === 'testing' ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap w-4 h-4 animate-spin" />
|
||||
Testing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:plug-charging w-4 h-4" />
|
||||
Test Connection
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -1,358 +0,0 @@
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { BranchSelector } from '~/components/ui/BranchSelector';
|
||||
import { RepositoryCard } from './RepositoryCard';
|
||||
import type { GitLabProjectInfo } from '~/types/GitLab';
|
||||
import { useGitLabConnection } from '~/lib/hooks';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { Search, RefreshCw, GitBranch, Calendar, Filter } from 'lucide-react';
|
||||
|
||||
interface GitLabRepositorySelectorProps {
|
||||
onClone?: (repoUrl: string, branch?: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
type SortOption = 'updated' | 'stars' | 'name' | 'created';
|
||||
type FilterOption = 'all' | 'owned' | 'member';
|
||||
|
||||
export function GitLabRepositorySelector({ onClone, className }: GitLabRepositorySelectorProps) {
|
||||
const { connection, isConnected } = useGitLabConnection();
|
||||
const [repositories, setRepositories] = useState<GitLabProjectInfo[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortBy, setSortBy] = useState<SortOption>('updated');
|
||||
const [filterBy, setFilterBy] = useState<FilterOption>('all');
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [selectedRepo, setSelectedRepo] = useState<GitLabProjectInfo | null>(null);
|
||||
const [isBranchSelectorOpen, setIsBranchSelectorOpen] = useState(false);
|
||||
|
||||
const REPOS_PER_PAGE = 12;
|
||||
|
||||
// Fetch repositories
|
||||
const fetchRepositories = async (refresh = false) => {
|
||||
if (!isConnected || !connection?.token) {
|
||||
return;
|
||||
}
|
||||
|
||||
const loadingState = refresh ? setIsRefreshing : setIsLoading;
|
||||
loadingState(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/gitlab-projects', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
token: connection.token,
|
||||
gitlabUrl: connection.gitlabUrl || 'https://gitlab.com',
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData: any = await response.json().catch(() => ({ error: 'Failed to fetch repositories' }));
|
||||
throw new Error(errorData.error || 'Failed to fetch repositories');
|
||||
}
|
||||
|
||||
const data: any = await response.json();
|
||||
setRepositories(data.projects || []);
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch GitLab repositories:', err);
|
||||
setError(err instanceof Error ? err.message : 'Failed to fetch repositories');
|
||||
|
||||
// Fallback to empty array on error
|
||||
setRepositories([]);
|
||||
} finally {
|
||||
loadingState(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Filter and search repositories
|
||||
const filteredRepositories = useMemo(() => {
|
||||
if (!repositories) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filtered = repositories.filter((repo: GitLabProjectInfo) => {
|
||||
// Search filter
|
||||
const matchesSearch =
|
||||
!searchQuery ||
|
||||
repo.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
repo.description?.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
repo.path_with_namespace.toLowerCase().includes(searchQuery.toLowerCase());
|
||||
|
||||
// Type filter
|
||||
let matchesFilter = true;
|
||||
|
||||
switch (filterBy) {
|
||||
case 'owned':
|
||||
// This would need owner information from the API response
|
||||
matchesFilter = true; // For now, show all
|
||||
break;
|
||||
case 'member':
|
||||
// This would need member information from the API response
|
||||
matchesFilter = true; // For now, show all
|
||||
break;
|
||||
case 'all':
|
||||
default:
|
||||
matchesFilter = true;
|
||||
break;
|
||||
}
|
||||
|
||||
return matchesSearch && matchesFilter;
|
||||
});
|
||||
|
||||
// Sort repositories
|
||||
filtered.sort((a: GitLabProjectInfo, b: GitLabProjectInfo) => {
|
||||
switch (sortBy) {
|
||||
case 'name':
|
||||
return a.name.localeCompare(b.name);
|
||||
case 'stars':
|
||||
return b.star_count - a.star_count;
|
||||
case 'created':
|
||||
return new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime(); // Using updated_at as proxy
|
||||
case 'updated':
|
||||
default:
|
||||
return new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime();
|
||||
}
|
||||
});
|
||||
|
||||
return filtered;
|
||||
}, [repositories, searchQuery, sortBy, filterBy]);
|
||||
|
||||
// Pagination
|
||||
const totalPages = Math.ceil(filteredRepositories.length / REPOS_PER_PAGE);
|
||||
const startIndex = (currentPage - 1) * REPOS_PER_PAGE;
|
||||
const currentRepositories = filteredRepositories.slice(startIndex, startIndex + REPOS_PER_PAGE);
|
||||
|
||||
const handleRefresh = () => {
|
||||
fetchRepositories(true);
|
||||
};
|
||||
|
||||
const handleCloneRepository = (repo: GitLabProjectInfo) => {
|
||||
setSelectedRepo(repo);
|
||||
setIsBranchSelectorOpen(true);
|
||||
};
|
||||
|
||||
const handleBranchSelect = (branch: string) => {
|
||||
if (onClone && selectedRepo) {
|
||||
onClone(selectedRepo.http_url_to_repo, branch);
|
||||
}
|
||||
|
||||
setSelectedRepo(null);
|
||||
};
|
||||
|
||||
const handleCloseBranchSelector = () => {
|
||||
setIsBranchSelectorOpen(false);
|
||||
setSelectedRepo(null);
|
||||
};
|
||||
|
||||
// Reset to first page when filters change
|
||||
useEffect(() => {
|
||||
setCurrentPage(1);
|
||||
}, [searchQuery, sortBy, filterBy]);
|
||||
|
||||
// Fetch repositories when connection is ready
|
||||
useEffect(() => {
|
||||
if (isConnected && connection?.token) {
|
||||
fetchRepositories();
|
||||
}
|
||||
}, [isConnected, connection?.token]);
|
||||
|
||||
if (!isConnected || !connection) {
|
||||
return (
|
||||
<div className="text-center p-8">
|
||||
<p className="text-bolt-elements-textSecondary mb-4">Please connect to GitLab first to browse repositories</p>
|
||||
<Button variant="outline" onClick={() => window.location.reload()}>
|
||||
Refresh Connection
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error && !repositories.length) {
|
||||
return (
|
||||
<div className="text-center p-8">
|
||||
<div className="text-red-500 mb-4">
|
||||
<GitBranch className="w-12 h-12 mx-auto mb-2" />
|
||||
<p className="font-medium">Failed to load repositories</p>
|
||||
<p className="text-sm text-bolt-elements-textSecondary mt-1">{error}</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={handleRefresh} disabled={isRefreshing}>
|
||||
<RefreshCw className={classNames('w-4 h-4 mr-2', { 'animate-spin': isRefreshing })} />
|
||||
Try Again
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading && !repositories.length) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center p-8 space-y-4">
|
||||
<div className="animate-spin w-8 h-8 border-2 border-bolt-elements-borderColorActive border-t-transparent rounded-full" />
|
||||
<p className="text-sm text-bolt-elements-textSecondary">Loading repositories...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!repositories.length && !isLoading) {
|
||||
return (
|
||||
<div className="text-center p-8">
|
||||
<GitBranch className="w-12 h-12 text-bolt-elements-textTertiary mx-auto mb-4" />
|
||||
<p className="text-bolt-elements-textSecondary mb-4">No repositories found</p>
|
||||
<Button variant="outline" onClick={handleRefresh} disabled={isRefreshing}>
|
||||
<RefreshCw className={classNames('w-4 h-4 mr-2', { 'animate-spin': isRefreshing })} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className={classNames('space-y-6', className)}
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
{/* Header with stats */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-bolt-elements-textPrimary">Select Repository to Clone</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">
|
||||
{filteredRepositories.length} of {repositories.length} repositories
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleRefresh}
|
||||
disabled={isRefreshing}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<RefreshCw className={classNames('w-4 h-4', { 'animate-spin': isRefreshing })} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && repositories.length > 0 && (
|
||||
<div className="p-3 rounded-lg bg-yellow-50 border border-yellow-200 dark:bg-yellow-900/20 dark:border-yellow-700">
|
||||
<p className="text-sm text-yellow-800 dark:text-yellow-200">Warning: {error}. Showing cached data.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Search and Filters */}
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
{/* Search */}
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bolt-elements-textTertiary" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search repositories..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 rounded-lg bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sort */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="w-4 h-4 text-bolt-elements-textTertiary" />
|
||||
<select
|
||||
value={sortBy}
|
||||
onChange={(e) => setSortBy(e.target.value as SortOption)}
|
||||
className="px-3 py-2 rounded-lg bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor text-bolt-elements-textPrimary text-sm focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive"
|
||||
>
|
||||
<option value="updated">Recently updated</option>
|
||||
<option value="stars">Most starred</option>
|
||||
<option value="name">Name (A-Z)</option>
|
||||
<option value="created">Recently created</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Filter */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Filter className="w-4 h-4 text-bolt-elements-textTertiary" />
|
||||
<select
|
||||
value={filterBy}
|
||||
onChange={(e) => setFilterBy(e.target.value as FilterOption)}
|
||||
className="px-3 py-2 rounded-lg bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor text-bolt-elements-textPrimary text-sm focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive"
|
||||
>
|
||||
<option value="all">All repositories</option>
|
||||
<option value="owned">Owned repositories</option>
|
||||
<option value="member">Member repositories</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Repository Grid */}
|
||||
{currentRepositories.length > 0 ? (
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{currentRepositories.map((repo) => (
|
||||
<div key={repo.id} className="relative">
|
||||
<RepositoryCard repo={repo} onClone={() => handleCloneRepository(repo)} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-between pt-4 border-t border-bolt-elements-borderColor">
|
||||
<div className="text-sm text-bolt-elements-textSecondary">
|
||||
Showing {Math.min(startIndex + 1, filteredRepositories.length)} to{' '}
|
||||
{Math.min(startIndex + REPOS_PER_PAGE, filteredRepositories.length)} of {filteredRepositories.length}{' '}
|
||||
repositories
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
|
||||
disabled={currentPage === 1}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
Previous
|
||||
</Button>
|
||||
<span className="text-sm text-bolt-elements-textSecondary px-3">
|
||||
{currentPage} of {totalPages}
|
||||
</span>
|
||||
<Button
|
||||
onClick={() => setCurrentPage((prev) => Math.min(totalPages, prev + 1))}
|
||||
disabled={currentPage === totalPages}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="text-center py-8">
|
||||
<p className="text-bolt-elements-textSecondary">No repositories found matching your search criteria.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Branch Selector Modal */}
|
||||
{selectedRepo && (
|
||||
<BranchSelector
|
||||
provider="gitlab"
|
||||
repoOwner={selectedRepo.path_with_namespace.split('/')[0]}
|
||||
repoName={selectedRepo.path_with_namespace.split('/')[1]}
|
||||
projectId={selectedRepo.id}
|
||||
token={connection?.token || ''}
|
||||
gitlabUrl={connection?.gitlabUrl}
|
||||
defaultBranch={selectedRepo.default_branch}
|
||||
onBranchSelect={handleBranchSelect}
|
||||
onClose={handleCloseBranchSelector}
|
||||
isOpen={isBranchSelectorOpen}
|
||||
/>
|
||||
)}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import React from 'react';
|
||||
import type { GitLabProjectInfo } from '~/types/GitLab';
|
||||
|
||||
interface RepositoryCardProps {
|
||||
repo: GitLabProjectInfo;
|
||||
onClone?: (repo: GitLabProjectInfo) => void;
|
||||
}
|
||||
|
||||
export function RepositoryCard({ repo, onClone }: RepositoryCardProps) {
|
||||
return (
|
||||
<a
|
||||
key={repo.name}
|
||||
href={repo.http_url_to_repo}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="group block p-4 rounded-lg bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive transition-all duration-200"
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="i-ph:git-repository w-4 h-4 text-bolt-elements-icon-info" />
|
||||
<h5 className="text-sm font-medium text-bolt-elements-textPrimary group-hover:text-bolt-elements-item-contentAccent transition-colors">
|
||||
{repo.name}
|
||||
</h5>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-xs text-bolt-elements-textSecondary">
|
||||
<span className="flex items-center gap-1" title="Stars">
|
||||
<div className="i-ph:star w-3.5 h-3.5 text-bolt-elements-icon-warning" />
|
||||
{repo.star_count.toLocaleString()}
|
||||
</span>
|
||||
<span className="flex items-center gap-1" title="Forks">
|
||||
<div className="i-ph:git-fork w-3.5 h-3.5 text-bolt-elements-icon-info" />
|
||||
{repo.forks_count.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{repo.description && (
|
||||
<p className="text-xs text-bolt-elements-textSecondary line-clamp-2">{repo.description}</p>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-3 text-xs text-bolt-elements-textSecondary">
|
||||
<span className="flex items-center gap-1" title="Default Branch">
|
||||
<div className="i-ph:git-branch w-3.5 h-3.5" />
|
||||
{repo.default_branch}
|
||||
</span>
|
||||
<span className="flex items-center gap-1" title="Last Updated">
|
||||
<div className="i-ph:clock w-3.5 h-3.5" />
|
||||
{new Date(repo.updated_at).toLocaleDateString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
})}
|
||||
</span>
|
||||
<div className="flex items-center gap-2 ml-auto">
|
||||
{onClone && (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onClone(repo);
|
||||
}}
|
||||
className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-bolt-elements-background-depth-2 hover:bg-bolt-elements-background-depth-3 text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-colors"
|
||||
title="Clone repository"
|
||||
>
|
||||
<div className="i-ph:git-branch w-3.5 h-3.5" />
|
||||
Clone
|
||||
</button>
|
||||
)}
|
||||
<span className="flex items-center gap-1 group-hover:text-bolt-elements-item-contentAccent transition-colors">
|
||||
<div className="i-ph:arrow-square-out w-3.5 h-3.5" />
|
||||
View
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
import React, { useState, useMemo } from 'react';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { RepositoryCard } from './RepositoryCard';
|
||||
import type { GitLabProjectInfo } from '~/types/GitLab';
|
||||
|
||||
interface RepositoryListProps {
|
||||
repositories: GitLabProjectInfo[];
|
||||
onClone?: (repo: GitLabProjectInfo) => void;
|
||||
onRefresh?: () => void;
|
||||
isRefreshing?: boolean;
|
||||
}
|
||||
|
||||
const MAX_REPOS_PER_PAGE = 20;
|
||||
|
||||
export function RepositoryList({ repositories, onClone, onRefresh, isRefreshing }: RepositoryListProps) {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [isSearching, setIsSearching] = useState(false);
|
||||
|
||||
const filteredRepositories = useMemo(() => {
|
||||
if (!searchQuery) {
|
||||
return repositories;
|
||||
}
|
||||
|
||||
setIsSearching(true);
|
||||
|
||||
const filtered = repositories.filter(
|
||||
(repo) =>
|
||||
repo.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
repo.path_with_namespace.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
(repo.description && repo.description.toLowerCase().includes(searchQuery.toLowerCase())),
|
||||
);
|
||||
|
||||
setIsSearching(false);
|
||||
|
||||
return filtered;
|
||||
}, [repositories, searchQuery]);
|
||||
|
||||
const totalPages = Math.ceil(filteredRepositories.length / MAX_REPOS_PER_PAGE);
|
||||
const startIndex = (currentPage - 1) * MAX_REPOS_PER_PAGE;
|
||||
const endIndex = startIndex + MAX_REPOS_PER_PAGE;
|
||||
const currentRepositories = filteredRepositories.slice(startIndex, endIndex);
|
||||
|
||||
const handleSearch = (query: string) => {
|
||||
setSearchQuery(query);
|
||||
setCurrentPage(1); // Reset to first page when searching
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary">
|
||||
Repositories ({filteredRepositories.length})
|
||||
</h4>
|
||||
{onRefresh && (
|
||||
<Button
|
||||
onClick={onRefresh}
|
||||
disabled={isRefreshing}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
{isRefreshing ? (
|
||||
<div className="i-ph:spinner animate-spin w-4 h-4" />
|
||||
) : (
|
||||
<div className="i-ph:arrows-clockwise w-4 h-4" />
|
||||
)}
|
||||
Refresh
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Search Input */}
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search repositories..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => handleSearch(e.target.value)}
|
||||
className="w-full px-4 py-2 pl-10 rounded-lg bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive"
|
||||
/>
|
||||
<div className="absolute left-3 top-1/2 -translate-y-1/2">
|
||||
{isSearching ? (
|
||||
<div className="i-ph:spinner animate-spin w-4 h-4 text-bolt-elements-textSecondary" />
|
||||
) : (
|
||||
<div className="i-ph:magnifying-glass w-4 h-4 text-bolt-elements-textSecondary" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Repository Grid */}
|
||||
<div className="space-y-4">
|
||||
{filteredRepositories.length === 0 ? (
|
||||
<div className="text-center py-8 text-bolt-elements-textSecondary">
|
||||
{searchQuery ? 'No repositories found matching your search.' : 'No repositories available.'}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{currentRepositories.map((repo) => (
|
||||
<RepositoryCard key={repo.id} repo={repo} onClone={onClone} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Pagination Controls */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-between pt-4 border-t border-bolt-elements-borderColor">
|
||||
<div className="text-sm text-bolt-elements-textSecondary">
|
||||
Showing {Math.min(startIndex + 1, filteredRepositories.length)} to{' '}
|
||||
{Math.min(endIndex, filteredRepositories.length)} of {filteredRepositories.length} repositories
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
|
||||
disabled={currentPage === 1}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
<div className="i-ph:caret-left w-4 h-4" />
|
||||
Previous
|
||||
</Button>
|
||||
<span className="text-sm text-bolt-elements-textSecondary px-3">
|
||||
{currentPage} of {totalPages}
|
||||
</span>
|
||||
<Button
|
||||
onClick={() => setCurrentPage((prev) => Math.min(totalPages, prev + 1))}
|
||||
disabled={currentPage === totalPages}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
Next
|
||||
<div className="i-ph:caret-right w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import type { GitLabStats } from '~/types/GitLab';
|
||||
|
||||
interface StatsDisplayProps {
|
||||
stats: GitLabStats;
|
||||
onRefresh?: () => void;
|
||||
isRefreshing?: boolean;
|
||||
}
|
||||
|
||||
export function StatsDisplay({ stats, onRefresh, isRefreshing }: StatsDisplayProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Repository Stats */}
|
||||
<div>
|
||||
<h5 className="text-sm font-medium text-bolt-elements-textPrimary mb-2">Repository Stats</h5>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{[
|
||||
{
|
||||
label: 'Public Repos',
|
||||
value: stats.publicProjects,
|
||||
},
|
||||
{
|
||||
label: 'Private Repos',
|
||||
value: stats.privateProjects,
|
||||
},
|
||||
].map((stat, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex flex-col p-3 rounded-lg bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor"
|
||||
>
|
||||
<span className="text-xs text-bolt-elements-textSecondary">{stat.label}</span>
|
||||
<span className="text-lg font-medium text-bolt-elements-textPrimary">{stat.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Contribution Stats */}
|
||||
<div>
|
||||
<h5 className="text-sm font-medium text-bolt-elements-textPrimary mb-2">Contribution Stats</h5>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{[
|
||||
{
|
||||
label: 'Stars',
|
||||
value: stats.stars || 0,
|
||||
icon: 'i-ph:star',
|
||||
iconColor: 'text-bolt-elements-icon-warning',
|
||||
},
|
||||
{
|
||||
label: 'Forks',
|
||||
value: stats.forks || 0,
|
||||
icon: 'i-ph:git-fork',
|
||||
iconColor: 'text-bolt-elements-icon-info',
|
||||
},
|
||||
{
|
||||
label: 'Followers',
|
||||
value: stats.followers || 0,
|
||||
icon: 'i-ph:users',
|
||||
iconColor: 'text-bolt-elements-icon-success',
|
||||
},
|
||||
].map((stat, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex flex-col p-3 rounded-lg bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor"
|
||||
>
|
||||
<span className="text-xs text-bolt-elements-textSecondary">{stat.label}</span>
|
||||
<span className="text-lg font-medium text-bolt-elements-textPrimary flex items-center gap-1">
|
||||
<div className={`${stat.icon} w-4 h-4 ${stat.iconColor}`} />
|
||||
{stat.value}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 border-t border-bolt-elements-borderColor">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-bolt-elements-textSecondary">
|
||||
Last updated: {new Date(stats.lastUpdated).toLocaleString()}
|
||||
</span>
|
||||
{onRefresh && (
|
||||
<Button onClick={onRefresh} disabled={isRefreshing} variant="outline" size="sm" className="text-xs">
|
||||
{isRefreshing ? 'Refreshing...' : 'Refresh'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
export { default as GitLabConnection } from './GitLabConnection';
|
||||
export { RepositoryCard } from './RepositoryCard';
|
||||
export { RepositoryList } from './RepositoryList';
|
||||
export { StatsDisplay } from './StatsDisplay';
|
||||
@@ -1,99 +0,0 @@
|
||||
import type { MCPServer } from '~/lib/services/mcpService';
|
||||
import McpStatusBadge from '~/components/@settings/tabs/mcp/McpStatusBadge';
|
||||
import McpServerListItem from '~/components/@settings/tabs/mcp/McpServerListItem';
|
||||
|
||||
type McpServerListProps = {
|
||||
serverEntries: [string, MCPServer][];
|
||||
expandedServer: string | null;
|
||||
checkingServers: boolean;
|
||||
onlyShowAvailableServers?: boolean;
|
||||
toggleServerExpanded: (serverName: string) => void;
|
||||
};
|
||||
|
||||
export default function McpServerList({
|
||||
serverEntries,
|
||||
expandedServer,
|
||||
checkingServers,
|
||||
onlyShowAvailableServers = false,
|
||||
toggleServerExpanded,
|
||||
}: McpServerListProps) {
|
||||
if (serverEntries.length === 0) {
|
||||
return <p className="text-sm text-bolt-elements-textSecondary">No MCP servers configured</p>;
|
||||
}
|
||||
|
||||
const filteredEntries = onlyShowAvailableServers
|
||||
? serverEntries.filter(([, s]) => s.status === 'available')
|
||||
: serverEntries;
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{filteredEntries.map(([serverName, mcpServer]) => {
|
||||
const isAvailable = mcpServer.status === 'available';
|
||||
const isExpanded = expandedServer === serverName;
|
||||
const serverTools = isAvailable ? Object.entries(mcpServer.tools) : [];
|
||||
|
||||
return (
|
||||
<div key={serverName} className="flex flex-col p-2 rounded-md bg-bolt-elements-background-depth-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
<div
|
||||
onClick={() => toggleServerExpanded(serverName)}
|
||||
className="flex items-center gap-1.5 text-bolt-elements-textPrimary"
|
||||
aria-expanded={isExpanded}
|
||||
>
|
||||
<div
|
||||
className={`i-ph:${isExpanded ? 'caret-down' : 'caret-right'} w-3 h-3 transition-transform duration-150`}
|
||||
/>
|
||||
<span className="font-medium truncate text-left">{serverName}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0 truncate">
|
||||
{mcpServer.config.type === 'sse' || mcpServer.config.type === 'streamable-http' ? (
|
||||
<span className="text-xs text-bolt-elements-textSecondary truncate">{mcpServer.config.url}</span>
|
||||
) : (
|
||||
<span className="text-xs text-bolt-elements-textSecondary truncate">
|
||||
{mcpServer.config.command} {mcpServer.config.args?.join(' ')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ml-2 flex-shrink-0">
|
||||
{checkingServers ? (
|
||||
<McpStatusBadge status="checking" />
|
||||
) : (
|
||||
<McpStatusBadge status={isAvailable ? 'available' : 'unavailable'} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error message */}
|
||||
{!isAvailable && mcpServer.error && (
|
||||
<div className="mt-1.5 ml-6 text-xs text-red-600 dark:text-red-400">Error: {mcpServer.error}</div>
|
||||
)}
|
||||
|
||||
{/* Tool list */}
|
||||
{isExpanded && isAvailable && (
|
||||
<div className="mt-2">
|
||||
<div className="text-bolt-elements-textSecondary text-xs font-medium ml-1 mb-1.5">Available Tools:</div>
|
||||
{serverTools.length === 0 ? (
|
||||
<div className="ml-4 text-xs text-bolt-elements-textSecondary">No tools available</div>
|
||||
) : (
|
||||
<div className="mt-1 space-y-2">
|
||||
{serverTools.map(([toolName, toolSchema]) => (
|
||||
<McpServerListItem
|
||||
key={`${serverName}-${toolName}`}
|
||||
toolName={toolName}
|
||||
toolSchema={toolSchema}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import type { Tool } from 'ai';
|
||||
|
||||
type ParameterProperty = {
|
||||
type?: string;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
type ToolParameters = {
|
||||
jsonSchema: {
|
||||
properties?: Record<string, ParameterProperty>;
|
||||
required?: string[];
|
||||
};
|
||||
};
|
||||
|
||||
type McpToolProps = {
|
||||
toolName: string;
|
||||
toolSchema: Tool;
|
||||
};
|
||||
|
||||
export default function McpServerListItem({ toolName, toolSchema }: McpToolProps) {
|
||||
if (!toolSchema) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parameters = (toolSchema.parameters as ToolParameters)?.jsonSchema.properties || {};
|
||||
const requiredParams = (toolSchema.parameters as ToolParameters)?.jsonSchema.required || [];
|
||||
|
||||
return (
|
||||
<div className="mt-2 ml-4 p-3 rounded-md bg-bolt-elements-background-depth-2 text-xs">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<h3 className="text-bolt-elements-textPrimary font-semibold truncate" title={toolName}>
|
||||
{toolName}
|
||||
</h3>
|
||||
|
||||
<p className="text-bolt-elements-textSecondary">{toolSchema.description || 'No description available'}</p>
|
||||
|
||||
{Object.keys(parameters).length > 0 && (
|
||||
<div className="mt-2.5">
|
||||
<h4 className="text-bolt-elements-textSecondary font-semibold mb-1.5">Parameters:</h4>
|
||||
<ul className="ml-1 space-y-2">
|
||||
{Object.entries(parameters).map(([paramName, paramDetails]) => (
|
||||
<li key={paramName} className="break-words">
|
||||
<div className="flex items-start">
|
||||
<span className="font-medium text-bolt-elements-textPrimary">
|
||||
{paramName}
|
||||
{requiredParams.includes(paramName) && (
|
||||
<span className="text-red-600 dark:text-red-400 ml-1">*</span>
|
||||
)}
|
||||
</span>
|
||||
|
||||
<span className="mx-2 text-bolt-elements-textSecondary">•</span>
|
||||
|
||||
<div className="flex-1">
|
||||
{paramDetails.type && (
|
||||
<span className="text-bolt-elements-textSecondary italic">{paramDetails.type}</span>
|
||||
)}
|
||||
{paramDetails.description && (
|
||||
<div className="mt-0.5 text-bolt-elements-textSecondary">{paramDetails.description}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
|
||||
export default function McpStatusBadge({ status }: { status: 'checking' | 'available' | 'unavailable' }) {
|
||||
const { styles, label, icon, ariaLabel } = useMemo(() => {
|
||||
const base = 'px-2 py-0.5 rounded-full text-xs font-medium flex items-center gap-1 transition-colors';
|
||||
|
||||
const config = {
|
||||
checking: {
|
||||
styles: `${base} bg-blue-100 text-blue-800 dark:bg-blue-900/80 dark:text-blue-200`,
|
||||
label: 'Checking...',
|
||||
ariaLabel: 'Checking server status',
|
||||
icon: <span className="i-svg-spinners:90-ring-with-bg w-3 h-3 text-current animate-spin" aria-hidden="true" />,
|
||||
},
|
||||
available: {
|
||||
styles: `${base} bg-green-100 text-green-800 dark:bg-green-900/80 dark:text-green-200`,
|
||||
label: 'Available',
|
||||
ariaLabel: 'Server available',
|
||||
icon: <span className="i-ph:check-circle w-3 h-3 text-current" aria-hidden="true" />,
|
||||
},
|
||||
unavailable: {
|
||||
styles: `${base} bg-red-100 text-red-800 dark:bg-red-900/80 dark:text-red-200`,
|
||||
label: 'Unavailable',
|
||||
ariaLabel: 'Server unavailable',
|
||||
icon: <span className="i-ph:warning-circle w-3 h-3 text-current" aria-hidden="true" />,
|
||||
},
|
||||
};
|
||||
|
||||
return config[status];
|
||||
}, [status]);
|
||||
|
||||
return (
|
||||
<span className={styles} role="status" aria-live="polite" aria-label={ariaLabel}>
|
||||
{icon}
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import type { MCPConfig } from '~/lib/services/mcpService';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useMCPStore } from '~/lib/stores/mcp';
|
||||
import McpServerList from '~/components/@settings/tabs/mcp/McpServerList';
|
||||
|
||||
const EXAMPLE_MCP_CONFIG: MCPConfig = {
|
||||
mcpServers: {
|
||||
everything: {
|
||||
type: 'stdio',
|
||||
command: 'npx',
|
||||
args: ['-y', '@modelcontextprotocol/server-everything'],
|
||||
},
|
||||
deepwiki: {
|
||||
type: 'streamable-http',
|
||||
url: 'https://mcp.deepwiki.com/mcp',
|
||||
},
|
||||
'local-sse': {
|
||||
type: 'sse',
|
||||
url: 'http://localhost:8000/sse',
|
||||
headers: {
|
||||
Authorization: 'Bearer mytoken123',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default function McpTab() {
|
||||
const settings = useMCPStore((state) => state.settings);
|
||||
const isInitialized = useMCPStore((state) => state.isInitialized);
|
||||
const serverTools = useMCPStore((state) => state.serverTools);
|
||||
const initialize = useMCPStore((state) => state.initialize);
|
||||
const updateSettings = useMCPStore((state) => state.updateSettings);
|
||||
const checkServersAvailabilities = useMCPStore((state) => state.checkServersAvailabilities);
|
||||
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [mcpConfigText, setMCPConfigText] = useState('');
|
||||
const [maxLLMSteps, setMaxLLMSteps] = useState(1);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isCheckingServers, setIsCheckingServers] = useState(false);
|
||||
const [expandedServer, setExpandedServer] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isInitialized) {
|
||||
initialize().catch((err) => {
|
||||
setError(`Failed to initialize MCP settings: ${err instanceof Error ? err.message : String(err)}`);
|
||||
toast.error('Failed to load MCP configuration');
|
||||
});
|
||||
}
|
||||
}, [isInitialized]);
|
||||
|
||||
useEffect(() => {
|
||||
setMCPConfigText(JSON.stringify(settings.mcpConfig, null, 2));
|
||||
setMaxLLMSteps(settings.maxLLMSteps);
|
||||
setError(null);
|
||||
}, [settings]);
|
||||
|
||||
const parsedConfig = useMemo(() => {
|
||||
try {
|
||||
setError(null);
|
||||
return JSON.parse(mcpConfigText) as MCPConfig;
|
||||
} catch (e) {
|
||||
setError(`Invalid JSON format: ${e instanceof Error ? e.message : String(e)}`);
|
||||
return null;
|
||||
}
|
||||
}, [mcpConfigText]);
|
||||
|
||||
const handleMaxLLMCallChange = (value: string) => {
|
||||
setMaxLLMSteps(parseInt(value, 10));
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!parsedConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSaving(true);
|
||||
|
||||
try {
|
||||
await updateSettings({
|
||||
mcpConfig: parsedConfig,
|
||||
maxLLMSteps,
|
||||
});
|
||||
toast.success('MCP configuration saved');
|
||||
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to save configuration');
|
||||
toast.error('Failed to save MCP configuration');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLoadExample = () => {
|
||||
setMCPConfigText(JSON.stringify(EXAMPLE_MCP_CONFIG, null, 2));
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const checkServerAvailability = async () => {
|
||||
if (serverEntries.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCheckingServers(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await checkServersAvailabilities();
|
||||
} catch (e) {
|
||||
setError(`Failed to check server availability: ${e instanceof Error ? e.message : String(e)}`);
|
||||
} finally {
|
||||
setIsCheckingServers(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleServerExpanded = (serverName: string) => {
|
||||
setExpandedServer(expandedServer === serverName ? null : serverName);
|
||||
};
|
||||
|
||||
const serverEntries = useMemo(() => Object.entries(serverTools), [serverTools]);
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto space-y-6">
|
||||
<section aria-labelledby="server-status-heading">
|
||||
<div className="flex justify-between items-center mb-3">
|
||||
<h2 className="text-base font-medium text-bolt-elements-textPrimary">MCP Servers Configured</h2>{' '}
|
||||
<button
|
||||
onClick={checkServerAvailability}
|
||||
disabled={isCheckingServers || !parsedConfig || serverEntries.length === 0}
|
||||
className={classNames(
|
||||
'px-3 py-1.5 rounded-lg text-sm',
|
||||
'bg-bolt-elements-background-depth-3 hover:bg-bolt-elements-background-depth-4',
|
||||
'text-bolt-elements-textPrimary',
|
||||
'transition-all duration-200',
|
||||
'flex items-center gap-2',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
)}
|
||||
>
|
||||
{isCheckingServers ? (
|
||||
<div className="i-svg-spinners:90-ring-with-bg w-3 h-3 text-bolt-elements-loader-progress animate-spin" />
|
||||
) : (
|
||||
<div className="i-ph:arrow-counter-clockwise w-3 h-3" />
|
||||
)}
|
||||
Check availability
|
||||
</button>
|
||||
</div>
|
||||
<McpServerList
|
||||
checkingServers={isCheckingServers}
|
||||
expandedServer={expandedServer}
|
||||
serverEntries={serverEntries}
|
||||
toggleServerExpanded={toggleServerExpanded}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="config-section-heading">
|
||||
<h2 className="text-base font-medium text-bolt-elements-textPrimary mb-3">Configuration</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="mcp-config" className="block text-sm text-bolt-elements-textSecondary mb-2">
|
||||
Configuration JSON
|
||||
</label>
|
||||
<textarea
|
||||
id="mcp-config"
|
||||
value={mcpConfigText}
|
||||
onChange={(e) => setMCPConfigText(e.target.value)}
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm font-mono h-72',
|
||||
'bg-[#F8F8F8] dark:bg-[#1A1A1A]',
|
||||
'border',
|
||||
error ? 'border-bolt-elements-icon-error' : 'border-[#E5E5E5] dark:border-[#333333]',
|
||||
'text-bolt-elements-textPrimary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-focus',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div>{error && <p className="mt-2 mb-2 text-sm text-bolt-elements-icon-error">{error}</p>}</div>
|
||||
<div>
|
||||
<label htmlFor="max-llm-steps" className="block text-sm text-bolt-elements-textSecondary mb-2">
|
||||
Maximum number of sequential LLM calls (steps)
|
||||
</label>
|
||||
<input
|
||||
id="max-llm-steps"
|
||||
type="number"
|
||||
placeholder="Maximum number of sequential LLM calls"
|
||||
min="1"
|
||||
max="20"
|
||||
value={maxLLMSteps}
|
||||
onChange={(e) => handleMaxLLMCallChange(e.target.value)}
|
||||
className="w-full px-3 py-2 text-bolt-elements-textPrimary text-sm rounded-lg bg-white dark:bg-bolt-elements-background-depth-4 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
|
||||
The MCP configuration format is identical to the one used in Claude Desktop.
|
||||
<a
|
||||
href="https://modelcontextprotocol.io/examples"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-bolt-elements-link hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
View example servers
|
||||
<div className="i-ph:arrow-square-out w-4 h-4" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="flex flex-wrap justify-between gap-3 mt-6">
|
||||
<button
|
||||
onClick={handleLoadExample}
|
||||
className="px-4 py-2 rounded-lg text-sm border border-bolt-elements-borderColor
|
||||
bg-bolt-elements-background-depth-2 text-bolt-elements-textSecondary
|
||||
hover:bg-bolt-elements-background-depth-3"
|
||||
>
|
||||
Load Example
|
||||
</button>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={isSaving || !parsedConfig}
|
||||
aria-disabled={isSaving || !parsedConfig}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-bolt-elements-item-backgroundAccent text-bolt-elements-item-contentAccent',
|
||||
'hover:bg-bolt-elements-item-backgroundActive',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
)}
|
||||
>
|
||||
<div className="i-ph:floppy-disk w-4 h-4" />
|
||||
{isSaving ? 'Saving...' : 'Save Configuration'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,990 +0,0 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { netlifyConnection, updateNetlifyConnection, initializeNetlifyConnection } from '~/lib/stores/netlify';
|
||||
import type { NetlifySite, NetlifyDeploy, NetlifyBuild, NetlifyUser } from '~/types/netlify';
|
||||
import {
|
||||
CloudIcon,
|
||||
BuildingLibraryIcon,
|
||||
ClockIcon,
|
||||
CodeBracketIcon,
|
||||
CheckCircleIcon,
|
||||
XCircleIcon,
|
||||
TrashIcon,
|
||||
ArrowPathIcon,
|
||||
LockClosedIcon,
|
||||
LockOpenIcon,
|
||||
RocketLaunchIcon,
|
||||
ChartBarIcon,
|
||||
CogIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '~/components/ui/Collapsible';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
import { Badge } from '~/components/ui/Badge';
|
||||
|
||||
// Add the Netlify logo SVG component at the top of the file
|
||||
const NetlifyLogo = () => (
|
||||
<svg viewBox="0 0 40 40" className="w-5 h-5">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M28.589 14.135l-.014-.006c-.008-.003-.016-.006-.023-.013a.11.11 0 0 1-.028-.093l.773-4.726 3.625 3.626-3.77 1.604a.083.083 0 0 1-.033.006h-.015c-.005-.003-.01-.007-.02-.017a1.716 1.716 0 0 0-.495-.381zm5.258-.288l3.876 3.876c.805.806 1.208 1.208 1.674 1.355a2 2 0 0 1 1.206 0c.466-.148.869-.55 1.674-1.356L8.73 28.73l2.349-3.643c.011-.018.022-.034.04-.047.025-.018.061-.01.091 0a2.434 2.434 0 0 0 1.638-.083c.027-.01.054-.017.075.002a.19.19 0 0 1 .028.032L21.95 38.05zM7.863 27.863L5.8 25.8l4.074-1.738a.084.084 0 0 1 .033-.007c.034 0 .054.034.072.065a2.91 2.91 0 0 0 .13.184l.013.016c.012.017.004.034-.008.05l-2.25 3.493zm-2.976-2.976l-2.61-2.61c-.444-.444-.766-.766-.99-1.043l7.936 1.646a.84.84 0 0 0 .03.005c.049.008.103.017.103.063 0 .05-.059.073-.109.092l-.023.01-4.337 1.837zM.831 19.892a2 2 0 0 1 .09-.495c.148-.466.55-.868 1.356-1.674l3.34-3.34a2175.525 2175.525 0 0 0 4.626 6.687c.027.036.057.076.026.106-.146.161-.292.337-.395.528a.16.16 0 0 1-.05.062c-.013.008-.027.005-.042.002H9.78L.831 19.892zm5.68-6.403l4.491-4.491c.422.185 1.958.834 3.332 1.414 1.04.44 1.988.84 2.286.97.03.012.057.024.07.054.008.018.004.041 0 .06a2.003 2.003 0 0 0 .523 1.828c.03.03 0 .073-.026.11l-.014.021-4.56 7.063c-.012.02-.023.037-.043.05-.024.015-.058.008-.086.001a2.274 2.274 0 0 0-.543-.074c-.164 0-.342.03-.522.063h-.001c-.02.003-.038.007-.054-.005a.21.21 0 0 1-.045-.051l-4.808-7.013zm5.398-5.398l5.814-5.814c.805-.805 1.208-1.208 1.674-1.355a2 2 0 0 1 1.206 0c.466.147.869.55 1.674 1.355l1.26 1.26-4.135 6.404a.155.155 0 0 1-.041.048c-.025.017-.06.01-.09 0a2.097 2.097 0 0 0-1.92.37c-.027.028-.067.012-.101-.003-.54-.235-4.74-2.01-5.341-2.265zm12.506-3.676l3.818 3.818-.92 5.698v.015a.135.135 0 0 1-.008.038c-.01.02-.03.024-.05.03a1.83 1.83 0 0 0-.548.273.154.154 0 0 0-.02.017c-.011.012-.022.023-.04.025a.114.114 0 0 1-.043-.007l-5.818-2.472-.011-.005c-.037-.015-.081-.033-.081-.071a2.198 2.198 0 0 0-.31-.915c-.028-.046-.059-.094-.035-.141l4.066-6.303zm-3.932 8.606l5.454 2.31c.03.014.063.027.076.058a.106.106 0 0 1 0 .057c-.016.08-.03.171-.03.263v.153c0 .038-.039.054-.075.069l-.011.004c-.864.369-12.13 5.173-12.147 5.173-.017 0-.035 0-.052-.017-.03-.03 0-.072.027-.11a.76.76 0 0 0 .014-.02l4.482-6.94.008-.012c.026-.042.056-.089.104-.089l.045.007c.102.014.192.027.283.027.68 0 1.31-.331 1.69-.897a.16.16 0 0 1 .034-.04c.027-.02.067-.01.098.004zm-6.246 9.185l12.28-5.237s.018 0 .035.017c.067.067.124.112.179.154l.027.017c.025.014.05.03.052.056 0 .01 0 .016-.002.025L25.756 23.7l-.004.026c-.007.05-.014.107-.061.107a1.729 1.729 0 0 0-1.373.847l-.005.008c-.014.023-.027.045-.05.057-.021.01-.048.006-.07.001l-9.793-2.02c-.01-.002-.152-.519-.163-.52z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// Add new interface for site actions
|
||||
interface SiteAction {
|
||||
name: string;
|
||||
icon: React.ComponentType<any>;
|
||||
action: (siteId: string) => Promise<void>;
|
||||
requiresConfirmation?: boolean;
|
||||
variant?: 'default' | 'destructive' | 'outline';
|
||||
}
|
||||
|
||||
export default function NetlifyConnection() {
|
||||
console.log('NetlifyConnection component mounted');
|
||||
|
||||
const connection = useStore(netlifyConnection);
|
||||
const [tokenInput, setTokenInput] = useState('');
|
||||
const [fetchingStats, setFetchingStats] = useState(false);
|
||||
const [sites, setSites] = useState<NetlifySite[]>([]);
|
||||
const [deploys, setDeploys] = useState<NetlifyDeploy[]>([]);
|
||||
const [builds, setBuilds] = useState<NetlifyBuild[]>([]);
|
||||
|
||||
console.log('NetlifyConnection initial state:', {
|
||||
connection: {
|
||||
user: connection.user,
|
||||
token: connection.token ? '[TOKEN_EXISTS]' : '[NO_TOKEN]',
|
||||
},
|
||||
envToken: import.meta.env?.VITE_NETLIFY_ACCESS_TOKEN ? '[ENV_TOKEN_EXISTS]' : '[NO_ENV_TOKEN]',
|
||||
});
|
||||
|
||||
const [deploymentCount, setDeploymentCount] = useState(0);
|
||||
const [lastUpdated, setLastUpdated] = useState('');
|
||||
const [isStatsOpen, setIsStatsOpen] = useState(false);
|
||||
const [activeSiteIndex, setActiveSiteIndex] = useState(0);
|
||||
const [isActionLoading, setIsActionLoading] = useState(false);
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
|
||||
// Add site actions
|
||||
const siteActions: SiteAction[] = [
|
||||
{
|
||||
name: 'Clear Cache',
|
||||
icon: ArrowPathIcon,
|
||||
action: async (siteId: string) => {
|
||||
try {
|
||||
// Try to get site details first to check for build hooks
|
||||
const siteResponse = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!siteResponse.ok) {
|
||||
const errorText = await siteResponse.text();
|
||||
|
||||
if (siteResponse.status === 404) {
|
||||
toast.error('Site not found. This may be a free account limitation.');
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Failed to get site details: ${errorText}`);
|
||||
}
|
||||
|
||||
const siteData = (await siteResponse.json()) as any;
|
||||
|
||||
// Check if this looks like a free account (limited features)
|
||||
const isFreeAccount = !siteData.plan || siteData.plan === 'free' || siteData.plan === 'starter';
|
||||
|
||||
// If site has build hooks, try triggering a build instead
|
||||
if (siteData.build_settings && siteData.build_settings.repo_url) {
|
||||
// Try to trigger a build by making a POST to the site's build endpoint
|
||||
const buildResponse = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/builds`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
clear_cache: true,
|
||||
}),
|
||||
});
|
||||
|
||||
if (buildResponse.ok) {
|
||||
toast.success('Build triggered with cache clear');
|
||||
return;
|
||||
} else if (buildResponse.status === 422) {
|
||||
// Often indicates free account limitation
|
||||
toast.warning('Build trigger failed. This feature may not be available on free accounts.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Try the standard cache purge endpoint
|
||||
const cacheResponse = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/purge_cache`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!cacheResponse.ok) {
|
||||
if (cacheResponse.status === 404) {
|
||||
if (isFreeAccount) {
|
||||
toast.warning('Cache purge not available on free accounts. Try triggering a build instead.');
|
||||
} else {
|
||||
toast.error('Cache purge endpoint not found. This feature may not be available.');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const errorText = await cacheResponse.text();
|
||||
throw new Error(`Cache purge failed: ${errorText}`);
|
||||
}
|
||||
|
||||
toast.success('Site cache cleared successfully');
|
||||
} catch (err: unknown) {
|
||||
const error = err instanceof Error ? err.message : 'Unknown error';
|
||||
toast.error(`Failed to clear site cache: ${error}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Manage Environment',
|
||||
icon: CogIcon,
|
||||
action: async (siteId: string) => {
|
||||
try {
|
||||
// Get site info first to check account type
|
||||
const siteResponse = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!siteResponse.ok) {
|
||||
throw new Error('Failed to get site details');
|
||||
}
|
||||
|
||||
const siteData = (await siteResponse.json()) as any;
|
||||
const isFreeAccount = !siteData.plan || siteData.plan === 'free' || siteData.plan === 'starter';
|
||||
|
||||
// Get environment variables
|
||||
const envResponse = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/env`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (envResponse.ok) {
|
||||
const envVars = (await envResponse.json()) as any[];
|
||||
toast.success(`Environment variables loaded: ${envVars.length} variables`);
|
||||
} else if (envResponse.status === 404) {
|
||||
if (isFreeAccount) {
|
||||
toast.info('Environment variables management is limited on free accounts');
|
||||
} else {
|
||||
toast.info('Site has no environment variables configured');
|
||||
}
|
||||
} else {
|
||||
const errorText = await envResponse.text();
|
||||
toast.error(`Failed to load environment variables: ${errorText}`);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const error = err instanceof Error ? err.message : 'Unknown error';
|
||||
toast.error(`Failed to load environment variables: ${error}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Trigger Build',
|
||||
icon: RocketLaunchIcon,
|
||||
action: async (siteId: string) => {
|
||||
try {
|
||||
const buildResponse = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/builds`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!buildResponse.ok) {
|
||||
throw new Error('Failed to trigger build');
|
||||
}
|
||||
|
||||
const buildData = (await buildResponse.json()) as any;
|
||||
toast.success(`Build triggered successfully! ID: ${buildData.id}`);
|
||||
} catch (err: unknown) {
|
||||
const error = err instanceof Error ? err.message : 'Unknown error';
|
||||
toast.error(`Failed to trigger build: ${error}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'View Functions',
|
||||
icon: CodeBracketIcon,
|
||||
action: async (siteId: string) => {
|
||||
try {
|
||||
// Get site info first to check account type
|
||||
const siteResponse = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!siteResponse.ok) {
|
||||
throw new Error('Failed to get site details');
|
||||
}
|
||||
|
||||
const siteData = (await siteResponse.json()) as any;
|
||||
const isFreeAccount = !siteData.plan || siteData.plan === 'free' || siteData.plan === 'starter';
|
||||
|
||||
const functionsResponse = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/functions`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (functionsResponse.ok) {
|
||||
const functions = (await functionsResponse.json()) as any[];
|
||||
toast.success(`Site has ${functions.length} serverless functions`);
|
||||
} else if (functionsResponse.status === 404) {
|
||||
if (isFreeAccount) {
|
||||
toast.info('Functions may be limited or unavailable on free accounts');
|
||||
} else {
|
||||
toast.info('Site has no serverless functions');
|
||||
}
|
||||
} else {
|
||||
const errorText = await functionsResponse.text();
|
||||
toast.error(`Failed to load functions: ${errorText}`);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const error = err instanceof Error ? err.message : 'Unknown error';
|
||||
toast.error(`Failed to load functions: ${error}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Site Analytics',
|
||||
icon: ChartBarIcon,
|
||||
action: async (siteId: string) => {
|
||||
try {
|
||||
// Get site info first to check account type
|
||||
const siteResponse = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!siteResponse.ok) {
|
||||
throw new Error('Failed to get site details');
|
||||
}
|
||||
|
||||
const siteData = (await siteResponse.json()) as any;
|
||||
const isFreeAccount = !siteData.plan || siteData.plan === 'free' || siteData.plan === 'starter';
|
||||
|
||||
// Get site traffic data (if available)
|
||||
const analyticsResponse = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/traffic`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (analyticsResponse.ok) {
|
||||
await analyticsResponse.json(); // Analytics data received
|
||||
toast.success('Site analytics loaded successfully');
|
||||
} else if (analyticsResponse.status === 404) {
|
||||
if (isFreeAccount) {
|
||||
toast.info('Analytics not available on free accounts. Showing basic site info instead.');
|
||||
}
|
||||
|
||||
// Fallback to basic site info
|
||||
toast.info(`Site: ${siteData.name} - Status: ${siteData.state || 'Unknown'}`);
|
||||
} else {
|
||||
const errorText = await analyticsResponse.text();
|
||||
|
||||
if (isFreeAccount) {
|
||||
toast.info(
|
||||
'Analytics unavailable on free accounts. Site info: ' +
|
||||
`${siteData.name} (${siteData.state || 'Unknown'})`,
|
||||
);
|
||||
} else {
|
||||
toast.error(`Failed to load analytics: ${errorText}`);
|
||||
}
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const error = err instanceof Error ? err.message : 'Unknown error';
|
||||
toast.error(`Failed to load site analytics: ${error}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Delete Site',
|
||||
icon: TrashIcon,
|
||||
action: async (siteId: string) => {
|
||||
try {
|
||||
const response = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to delete site');
|
||||
}
|
||||
|
||||
toast.success('Site deleted successfully');
|
||||
fetchNetlifyStats(connection.token);
|
||||
} catch (err: unknown) {
|
||||
const error = err instanceof Error ? err.message : 'Unknown error';
|
||||
toast.error(`Failed to delete site: ${error}`);
|
||||
}
|
||||
},
|
||||
requiresConfirmation: true,
|
||||
variant: 'destructive',
|
||||
},
|
||||
];
|
||||
|
||||
// Add deploy management functions
|
||||
const handleDeploy = async (siteId: string, deployId: string, action: 'lock' | 'unlock' | 'publish') => {
|
||||
try {
|
||||
setIsActionLoading(true);
|
||||
|
||||
const endpoint =
|
||||
action === 'publish'
|
||||
? `https://api.netlify.com/api/v1/sites/${siteId}/deploys/${deployId}/restore`
|
||||
: `https://api.netlify.com/api/v1/deploys/${deployId}/${action}`;
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${connection.token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to ${action} deploy`);
|
||||
}
|
||||
|
||||
toast.success(`Deploy ${action}ed successfully`);
|
||||
fetchNetlifyStats(connection.token);
|
||||
} catch (err: unknown) {
|
||||
const error = err instanceof Error ? err.message : 'Unknown error';
|
||||
toast.error(`Failed to ${action} deploy: ${error}`);
|
||||
} finally {
|
||||
setIsActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
console.log('Netlify: Running initialization useEffect');
|
||||
|
||||
// Initialize connection with environment token if available
|
||||
initializeNetlifyConnection();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// Check if we have a connection with a token but no stats
|
||||
if (connection.user && connection.token && (!connection.stats || !connection.stats.sites)) {
|
||||
fetchNetlifyStats(connection.token);
|
||||
}
|
||||
|
||||
// Update local state from connection
|
||||
if (connection.stats) {
|
||||
setSites(connection.stats.sites || []);
|
||||
setDeploys(connection.stats.deploys || []);
|
||||
setBuilds(connection.stats.builds || []);
|
||||
setDeploymentCount(connection.stats.deploys?.length || 0);
|
||||
setLastUpdated(connection.stats.lastDeployTime || '');
|
||||
}
|
||||
}, [connection]);
|
||||
|
||||
const handleConnect = async () => {
|
||||
if (!tokenInput) {
|
||||
toast.error('Please enter a Netlify API token');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsConnecting(true);
|
||||
|
||||
try {
|
||||
const response = await fetch('https://api.netlify.com/api/v1/user', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokenInput}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
||||
}
|
||||
|
||||
const userData = (await response.json()) as NetlifyUser;
|
||||
|
||||
// Update the connection store
|
||||
updateNetlifyConnection({
|
||||
user: userData,
|
||||
token: tokenInput,
|
||||
});
|
||||
|
||||
toast.success('Connected to Netlify successfully');
|
||||
|
||||
// Fetch stats after successful connection
|
||||
fetchNetlifyStats(tokenInput);
|
||||
} catch (error) {
|
||||
console.error('Error connecting to Netlify:', error);
|
||||
toast.error(`Failed to connect to Netlify: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
setTokenInput('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDisconnect = () => {
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('netlify_connection');
|
||||
|
||||
// Remove cookies
|
||||
document.cookie = 'netlifyToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
|
||||
|
||||
// Update the store
|
||||
updateNetlifyConnection({ user: null, token: '' });
|
||||
toast.success('Disconnected from Netlify');
|
||||
};
|
||||
|
||||
const fetchNetlifyStats = async (token: string) => {
|
||||
setFetchingStats(true);
|
||||
|
||||
try {
|
||||
// Fetch sites
|
||||
const sitesResponse = await fetch('https://api.netlify.com/api/v1/sites', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!sitesResponse.ok) {
|
||||
throw new Error(`Failed to fetch sites: ${sitesResponse.statusText}`);
|
||||
}
|
||||
|
||||
const sitesData = (await sitesResponse.json()) as NetlifySite[];
|
||||
setSites(sitesData);
|
||||
|
||||
// Fetch recent deploys for the first site (if any)
|
||||
let deploysData: NetlifyDeploy[] = [];
|
||||
let buildsData: NetlifyBuild[] = [];
|
||||
let lastDeployTime = '';
|
||||
|
||||
if (sitesData && sitesData.length > 0) {
|
||||
const firstSite = sitesData[0];
|
||||
|
||||
// Fetch deploys
|
||||
const deploysResponse = await fetch(`https://api.netlify.com/api/v1/sites/${firstSite.id}/deploys`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (deploysResponse.ok) {
|
||||
deploysData = (await deploysResponse.json()) as NetlifyDeploy[];
|
||||
setDeploys(deploysData);
|
||||
setDeploymentCount(deploysData.length);
|
||||
|
||||
// Get the latest deploy time
|
||||
if (deploysData.length > 0) {
|
||||
lastDeployTime = deploysData[0].created_at;
|
||||
setLastUpdated(lastDeployTime);
|
||||
|
||||
// Fetch builds for the site
|
||||
const buildsResponse = await fetch(`https://api.netlify.com/api/v1/sites/${firstSite.id}/builds`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (buildsResponse.ok) {
|
||||
buildsData = (await buildsResponse.json()) as NetlifyBuild[];
|
||||
setBuilds(buildsData);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update the stats in the store
|
||||
updateNetlifyConnection({
|
||||
stats: {
|
||||
sites: sitesData,
|
||||
deploys: deploysData,
|
||||
builds: buildsData,
|
||||
lastDeployTime,
|
||||
totalSites: sitesData.length,
|
||||
},
|
||||
});
|
||||
|
||||
toast.success('Netlify stats updated');
|
||||
} catch (error) {
|
||||
console.error('Error fetching Netlify stats:', error);
|
||||
toast.error(`Failed to fetch Netlify stats: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
} finally {
|
||||
setFetchingStats(false);
|
||||
}
|
||||
};
|
||||
|
||||
const renderStats = () => {
|
||||
if (!connection.user || !connection.stats) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-6">
|
||||
<Collapsible open={isStatsOpen} onOpenChange={setIsStatsOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div className="flex items-center justify-between p-4 rounded-lg bg-bolt-elements-background dark:bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70 dark:hover:border-bolt-elements-borderColorActive/70 transition-all duration-200">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="i-ph:chart-bar w-4 h-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
<span className="text-sm font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
Netlify Stats
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
'i-ph:caret-down w-4 h-4 transform transition-transform duration-200 text-bolt-elements-textSecondary',
|
||||
isStatsOpen ? 'rotate-180' : '',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="overflow-hidden">
|
||||
<div className="space-y-4 mt-4">
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
|
||||
>
|
||||
<BuildingLibraryIcon className="h-4 w-4 text-bolt-elements-item-contentAccent" />
|
||||
<span>{connection.stats.totalSites} Sites</span>
|
||||
</Badge>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
|
||||
>
|
||||
<RocketLaunchIcon className="h-4 w-4 text-bolt-elements-item-contentAccent" />
|
||||
<span>{deploymentCount} Deployments</span>
|
||||
</Badge>
|
||||
{lastUpdated && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
|
||||
>
|
||||
<ClockIcon className="h-4 w-4 text-bolt-elements-item-contentAccent" />
|
||||
<span>Updated {formatDistanceToNow(new Date(lastUpdated))} ago</span>
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{sites.length > 0 && (
|
||||
<div className="mt-4 space-y-4">
|
||||
<div className="bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg p-4">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h4 className="text-sm font-medium flex items-center gap-2 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
<BuildingLibraryIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
Your Sites
|
||||
</h4>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => fetchNetlifyStats(connection.token)}
|
||||
disabled={fetchingStats}
|
||||
className="flex items-center gap-2 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary hover:bg-bolt-elements-item-backgroundActive/10"
|
||||
>
|
||||
<ArrowPathIcon
|
||||
className={classNames(
|
||||
'h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent',
|
||||
{ 'animate-spin': fetchingStats },
|
||||
)}
|
||||
/>
|
||||
{fetchingStats ? 'Refreshing...' : 'Refresh'}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{sites.map((site, index) => (
|
||||
<div
|
||||
key={site.id}
|
||||
className={classNames(
|
||||
'bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border rounded-lg p-4 transition-all',
|
||||
activeSiteIndex === index
|
||||
? 'border-bolt-elements-item-contentAccent bg-bolt-elements-item-backgroundActive/10'
|
||||
: 'border-bolt-elements-borderColor hover:border-bolt-elements-borderColorActive/70',
|
||||
)}
|
||||
onClick={() => {
|
||||
setActiveSiteIndex(index);
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<CloudIcon className="h-5 w-5 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
<span className="font-medium text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
{site.name}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant={site.published_deploy?.state === 'ready' ? 'default' : 'destructive'}
|
||||
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
|
||||
>
|
||||
{site.published_deploy?.state === 'ready' ? (
|
||||
<CheckCircleIcon className="h-4 w-4 text-green-500" />
|
||||
) : (
|
||||
<XCircleIcon className="h-4 w-4 text-red-500" />
|
||||
)}
|
||||
<span className="text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
{site.published_deploy?.state || 'Unknown'}
|
||||
</span>
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<a
|
||||
href={site.ssl_url || site.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm flex items-center gap-1 transition-colors text-bolt-elements-link-text hover:text-bolt-elements-link-textHover dark:text-white dark:hover:text-bolt-elements-link-textHover"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<CloudIcon className="h-3 w-3 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
<span className="underline decoration-1 underline-offset-2">
|
||||
{site.ssl_url || site.url}
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{activeSiteIndex === index && (
|
||||
<>
|
||||
<div className="mt-4 pt-3 border-t border-bolt-elements-borderColor">
|
||||
<div className="flex items-center gap-2">
|
||||
{siteActions.map((action) => (
|
||||
<Button
|
||||
key={action.name}
|
||||
variant={action.variant || 'outline'}
|
||||
size="sm"
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
|
||||
if (action.requiresConfirmation) {
|
||||
if (!confirm(`Are you sure you want to ${action.name.toLowerCase()}?`)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setIsActionLoading(true);
|
||||
await action.action(site.id);
|
||||
setIsActionLoading(false);
|
||||
}}
|
||||
disabled={isActionLoading}
|
||||
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
|
||||
>
|
||||
<action.icon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
{action.name}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{site.published_deploy && (
|
||||
<div className="mt-3 text-sm">
|
||||
<div className="flex items-center gap-1">
|
||||
<ClockIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
<span className="text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
|
||||
Published {formatDistanceToNow(new Date(site.published_deploy.published_at))} ago
|
||||
</span>
|
||||
</div>
|
||||
{site.published_deploy.branch && (
|
||||
<div className="flex items-center gap-1 mt-1">
|
||||
<CodeBracketIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
<span className="text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
|
||||
Branch: {site.published_deploy.branch}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{activeSiteIndex !== -1 && deploys.length > 0 && (
|
||||
<div className="bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h4 className="text-sm font-medium flex items-center gap-2 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
<BuildingLibraryIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
Recent Deployments
|
||||
</h4>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{deploys.map((deploy) => (
|
||||
<div
|
||||
key={deploy.id}
|
||||
className="bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg p-3"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant={
|
||||
deploy.state === 'ready'
|
||||
? 'default'
|
||||
: deploy.state === 'error'
|
||||
? 'destructive'
|
||||
: 'outline'
|
||||
}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
{deploy.state === 'ready' ? (
|
||||
<CheckCircleIcon className="h-4 w-4 text-green-500" />
|
||||
) : deploy.state === 'error' ? (
|
||||
<XCircleIcon className="h-4 w-4 text-red-500" />
|
||||
) : (
|
||||
<BuildingLibraryIcon className="h-4 w-4 text-bolt-elements-item-contentAccent" />
|
||||
)}
|
||||
<span className="text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
{deploy.state}
|
||||
</span>
|
||||
</Badge>
|
||||
</div>
|
||||
<span className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
|
||||
{formatDistanceToNow(new Date(deploy.created_at))} ago
|
||||
</span>
|
||||
</div>
|
||||
{deploy.branch && (
|
||||
<div className="mt-2 text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary flex items-center gap-1">
|
||||
<CodeBracketIcon className="h-3 w-3 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
<span className="text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
|
||||
Branch: {deploy.branch}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{deploy.deploy_url && (
|
||||
<div className="mt-2 text-xs">
|
||||
<a
|
||||
href={deploy.deploy_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-1 transition-colors text-bolt-elements-link-text hover:text-bolt-elements-link-textHover dark:text-white dark:hover:text-bolt-elements-link-textHover"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<CloudIcon className="h-3 w-3 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
<span className="underline decoration-1 underline-offset-2">{deploy.deploy_url}</span>
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDeploy(sites[activeSiteIndex].id, deploy.id, 'publish')}
|
||||
disabled={isActionLoading}
|
||||
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
|
||||
>
|
||||
<BuildingLibraryIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
Publish
|
||||
</Button>
|
||||
{deploy.state === 'ready' ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDeploy(sites[activeSiteIndex].id, deploy.id, 'lock')}
|
||||
disabled={isActionLoading}
|
||||
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
|
||||
>
|
||||
<LockClosedIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
Lock
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDeploy(sites[activeSiteIndex].id, deploy.id, 'unlock')}
|
||||
disabled={isActionLoading}
|
||||
className="flex items-center gap-1 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary"
|
||||
>
|
||||
<LockOpenIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
Unlock
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{activeSiteIndex !== -1 && builds.length > 0 && (
|
||||
<div className="bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h4 className="text-sm font-medium flex items-center gap-2 text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
<CodeBracketIcon className="h-4 w-4 text-bolt-elements-item-contentAccent dark:text-bolt-elements-item-contentAccent" />
|
||||
Recent Builds
|
||||
</h4>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{builds.map((build) => (
|
||||
<div
|
||||
key={build.id}
|
||||
className="bg-bolt-elements-background dark:bg-bolt-elements-background-depth-1 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg p-3"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant={
|
||||
build.done && !build.error ? 'default' : build.error ? 'destructive' : 'outline'
|
||||
}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
{build.done && !build.error ? (
|
||||
<CheckCircleIcon className="h-4 w-4" />
|
||||
) : build.error ? (
|
||||
<XCircleIcon className="h-4 w-4" />
|
||||
) : (
|
||||
<CodeBracketIcon className="h-4 w-4" />
|
||||
)}
|
||||
<span className="text-bolt-elements-textPrimary dark:text-bolt-elements-textPrimary">
|
||||
{build.done ? (build.error ? 'Failed' : 'Completed') : 'In Progress'}
|
||||
</span>
|
||||
</Badge>
|
||||
</div>
|
||||
<span className="text-xs text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary">
|
||||
{formatDistanceToNow(new Date(build.created_at))} ago
|
||||
</span>
|
||||
</div>
|
||||
{build.error && (
|
||||
<div className="mt-2 text-xs text-bolt-elements-textDestructive dark:text-bolt-elements-textDestructive flex items-center gap-1">
|
||||
<XCircleIcon className="h-3 w-3 text-bolt-elements-textDestructive dark:text-bolt-elements-textDestructive" />
|
||||
Error: {build.error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 bg-bolt-elements-background dark:bg-bolt-elements-background border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor rounded-lg">
|
||||
<div className="p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="text-[#00AD9F]">
|
||||
<NetlifyLogo />
|
||||
</div>
|
||||
<h2 className="text-lg font-medium text-bolt-elements-textPrimary">Netlify Connection</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!connection.user ? (
|
||||
<div className="mt-4">
|
||||
<label className="block text-sm text-bolt-elements-textSecondary dark:text-bolt-elements-textSecondary mb-2">
|
||||
API Token
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={tokenInput}
|
||||
onChange={(e) => setTokenInput(e.target.value)}
|
||||
placeholder="Enter your Netlify API token"
|
||||
className={classNames(
|
||||
'w-full px-3 py-2 rounded-lg text-sm',
|
||||
'bg-[#F8F8F8] dark:bg-[#1A1A1A]',
|
||||
'border border-[#E5E5E5] dark:border-[#333333]',
|
||||
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
|
||||
'focus:outline-none focus:ring-1 focus:ring-bolt-elements-borderColorActive',
|
||||
'disabled:opacity-50',
|
||||
)}
|
||||
/>
|
||||
<div className="mt-2 text-sm text-bolt-elements-textSecondary">
|
||||
<a
|
||||
href="https://app.netlify.com/user/applications#personal-access-tokens"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-bolt-elements-borderColorActive hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
Get your token
|
||||
<div className="i-ph:arrow-square-out w-4 h-4" />
|
||||
</a>
|
||||
</div>
|
||||
{/* Debug info - remove this later */}
|
||||
<div className="mt-2 text-xs text-gray-500">
|
||||
<p>Debug: Token present: {connection.token ? '✅' : '❌'}</p>
|
||||
<p>Debug: User present: {connection.user ? '✅' : '❌'}</p>
|
||||
<p>Debug: Env token: {import.meta.env?.VITE_NETLIFY_ACCESS_TOKEN ? '✅' : '❌'}</p>
|
||||
</div>
|
||||
<div className="flex gap-2 mt-4">
|
||||
<button
|
||||
onClick={handleConnect}
|
||||
disabled={isConnecting || !tokenInput}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-[#303030] text-white',
|
||||
'hover:bg-[#5E41D0] hover:text-white',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200',
|
||||
'transform active:scale-95',
|
||||
)}
|
||||
>
|
||||
{isConnecting ? (
|
||||
<>
|
||||
<div className="i-ph:spinner-gap animate-spin" />
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="i-ph:plug-charging w-4 h-4" />
|
||||
Connect
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Debug button - remove this later */}
|
||||
<button
|
||||
onClick={async () => {
|
||||
console.log('Manual Netlify auto-connect test');
|
||||
await initializeNetlifyConnection();
|
||||
}}
|
||||
className="px-3 py-2 rounded-lg text-xs bg-blue-500 text-white hover:bg-blue-600"
|
||||
>
|
||||
Test Auto-Connect
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col w-full gap-4 mt-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={handleDisconnect}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm flex items-center gap-2',
|
||||
'bg-red-500 text-white',
|
||||
'hover:bg-red-600',
|
||||
)}
|
||||
>
|
||||
<div className="i-ph:plug w-4 h-4" />
|
||||
Disconnect
|
||||
</button>
|
||||
<span className="text-sm text-bolt-elements-textSecondary flex items-center gap-1">
|
||||
<div className="i-ph:check-circle w-4 h-4 text-green-500" />
|
||||
Connected to Netlify
|
||||
</span>
|
||||
</div>
|
||||
{renderStats()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export { default as NetlifyConnection } from './NetlifyConnection';
|
||||
@@ -8,7 +8,7 @@ import { motion } from 'framer-motion';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { toast } from 'react-toastify';
|
||||
import { providerBaseUrlEnvKeys } from '~/utils/constants';
|
||||
import { SiAmazon, SiGoogle, SiGithub, SiHuggingface, SiPerplexity, SiOpenai } from 'react-icons/si';
|
||||
import { SiAmazon, SiGoogle, SiHuggingface, SiPerplexity, SiOpenai } from 'react-icons/si';
|
||||
import { BsRobot, BsCloud } from 'react-icons/bs';
|
||||
import { TbBrain, TbCloudComputing } from 'react-icons/tb';
|
||||
import { BiCodeBlock, BiChip } from 'react-icons/bi';
|
||||
@@ -21,7 +21,6 @@ type ProviderName =
|
||||
| 'Anthropic'
|
||||
| 'Cohere'
|
||||
| 'Deepseek'
|
||||
| 'Github'
|
||||
| 'Google'
|
||||
| 'Groq'
|
||||
| 'HuggingFace'
|
||||
@@ -39,7 +38,6 @@ const PROVIDER_ICONS: Record<ProviderName, IconType> = {
|
||||
Anthropic: FaBrain,
|
||||
Cohere: BiChip,
|
||||
Deepseek: BiCodeBlock,
|
||||
Github: SiGithub,
|
||||
Google: SiGoogle,
|
||||
Groq: BsCloud,
|
||||
HuggingFace: SiHuggingface,
|
||||
@@ -55,7 +53,6 @@ const PROVIDER_ICONS: Record<ProviderName, IconType> = {
|
||||
// Update PROVIDER_DESCRIPTIONS to use the same type
|
||||
const PROVIDER_DESCRIPTIONS: Partial<Record<ProviderName, string>> = {
|
||||
Anthropic: 'Access Claude and other Anthropic models',
|
||||
Github: 'Use OpenAI models hosted through GitHub infrastructure',
|
||||
OpenAI: 'Use GPT-4, GPT-3.5, and other OpenAI models',
|
||||
};
|
||||
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
import React, { Component } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
fallback?: ReactNode;
|
||||
onError?: (error: Error, errorInfo: React.ErrorInfo) => void;
|
||||
}
|
||||
|
||||
interface State {
|
||||
hasError: boolean;
|
||||
error?: Error;
|
||||
}
|
||||
|
||||
export default class ErrorBoundary extends Component<Props, State> {
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.state = { hasError: false };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: Error): State {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
|
||||
console.error('Local Providers Error Boundary caught an error:', error, errorInfo);
|
||||
this.props.onError?.(error, errorInfo);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
if (this.props.fallback) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={classNames('p-6 rounded-lg border border-red-500/20', 'bg-red-500/5 text-center')}>
|
||||
<AlertCircle className="w-12 h-12 mx-auto text-red-500 mb-4" />
|
||||
<h3 className="text-lg font-medium text-red-500 mb-2">Something went wrong</h3>
|
||||
<p className="text-sm text-red-400 mb-4">There was an error loading the local providers section.</p>
|
||||
<button
|
||||
onClick={() => this.setState({ hasError: false, error: undefined })}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg text-sm font-medium',
|
||||
'bg-red-500/10 text-red-500',
|
||||
'hover:bg-red-500/20',
|
||||
'transition-colors duration-200',
|
||||
)}
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
{process.env.NODE_ENV === 'development' && this.state.error && (
|
||||
<details className="mt-4 text-left">
|
||||
<summary className="cursor-pointer text-sm text-red-400 hover:text-red-300">Error Details</summary>
|
||||
<pre className="mt-2 p-2 bg-red-500/10 rounded text-xs text-red-300 overflow-auto">
|
||||
{this.state.error.stack}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import React from 'react';
|
||||
import { CheckCircle, XCircle, Loader2, AlertCircle } from 'lucide-react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
interface HealthStatusBadgeProps {
|
||||
status: 'healthy' | 'unhealthy' | 'checking' | 'unknown';
|
||||
responseTime?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function HealthStatusBadge({ status, responseTime, className }: HealthStatusBadgeProps) {
|
||||
const getStatusConfig = () => {
|
||||
switch (status) {
|
||||
case 'healthy':
|
||||
return {
|
||||
color: 'text-green-500',
|
||||
bgColor: 'bg-green-500/10 border-green-500/20',
|
||||
Icon: CheckCircle,
|
||||
label: 'Healthy',
|
||||
};
|
||||
case 'unhealthy':
|
||||
return {
|
||||
color: 'text-red-500',
|
||||
bgColor: 'bg-red-500/10 border-red-500/20',
|
||||
Icon: XCircle,
|
||||
label: 'Unhealthy',
|
||||
};
|
||||
case 'checking':
|
||||
return {
|
||||
color: 'text-blue-500',
|
||||
bgColor: 'bg-blue-500/10 border-blue-500/20',
|
||||
Icon: Loader2,
|
||||
label: 'Checking',
|
||||
};
|
||||
default:
|
||||
return {
|
||||
color: 'text-bolt-elements-textTertiary',
|
||||
bgColor: 'bg-bolt-elements-background-depth-3 border-bolt-elements-borderColor',
|
||||
Icon: AlertCircle,
|
||||
label: 'Unknown',
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const config = getStatusConfig();
|
||||
const Icon = config.Icon;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors',
|
||||
config.bgColor,
|
||||
config.color,
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<Icon className={classNames('w-3 h-3', { 'animate-spin': status === 'checking' })} />
|
||||
<span>{config.label}</span>
|
||||
{responseTime !== undefined && status === 'healthy' && <span className="opacity-75">({responseTime}ms)</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default HealthStatusBadge;
|
||||
@@ -1,107 +0,0 @@
|
||||
import React from 'react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
|
||||
interface LoadingSkeletonProps {
|
||||
className?: string;
|
||||
lines?: number;
|
||||
height?: string;
|
||||
}
|
||||
|
||||
export function LoadingSkeleton({ className, lines = 1, height = 'h-4' }: LoadingSkeletonProps) {
|
||||
return (
|
||||
<div className={classNames('space-y-2', className)}>
|
||||
{Array.from({ length: lines }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={classNames('bg-bolt-elements-background-depth-3 rounded', height, 'animate-pulse')}
|
||||
style={{ animationDelay: `${i * 0.1}s` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ModelCardSkeletonProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ModelCardSkeleton({ className }: ModelCardSkeletonProps) {
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'border rounded-lg p-4',
|
||||
'bg-bolt-elements-background-depth-2',
|
||||
'border-bolt-elements-borderColor',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3 flex-1">
|
||||
<div className="w-3 h-3 rounded-full bg-bolt-elements-textTertiary animate-pulse" />
|
||||
<div className="space-y-2 flex-1">
|
||||
<LoadingSkeleton height="h-5" lines={1} className="w-3/4" />
|
||||
<LoadingSkeleton height="h-3" lines={1} className="w-1/2" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-4 h-4 bg-bolt-elements-textTertiary rounded animate-pulse" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ProviderCardSkeletonProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ProviderCardSkeleton({ className }: ProviderCardSkeletonProps) {
|
||||
return (
|
||||
<div className={classNames('bg-bolt-elements-background-depth-2 rounded-xl p-5', className)}>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-start gap-4 flex-1">
|
||||
<div className="w-12 h-12 rounded-xl bg-bolt-elements-background-depth-3 animate-pulse" />
|
||||
<div className="space-y-3 flex-1">
|
||||
<div className="space-y-2">
|
||||
<LoadingSkeleton height="h-5" lines={1} className="w-1/3" />
|
||||
<LoadingSkeleton height="h-4" lines={1} className="w-2/3" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<LoadingSkeleton height="h-3" lines={1} className="w-1/4" />
|
||||
<LoadingSkeleton height="h-8" lines={1} className="w-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-10 h-6 bg-bolt-elements-background-depth-3 rounded-full animate-pulse" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ModelManagerSkeletonProps {
|
||||
className?: string;
|
||||
cardCount?: number;
|
||||
}
|
||||
|
||||
export function ModelManagerSkeleton({ className, cardCount = 3 }: ModelManagerSkeletonProps) {
|
||||
return (
|
||||
<div className={classNames('space-y-6', className)}>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-2">
|
||||
<LoadingSkeleton height="h-6" lines={1} className="w-48" />
|
||||
<LoadingSkeleton height="h-4" lines={1} className="w-64" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-24 h-8 bg-bolt-elements-background-depth-3 rounded-lg animate-pulse" />
|
||||
<div className="w-16 h-8 bg-bolt-elements-background-depth-3 rounded-lg animate-pulse" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Model Cards */}
|
||||
<div className="space-y-4">
|
||||
{Array.from({ length: cardCount }).map((_, i) => (
|
||||
<ModelCardSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,106 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Card, CardContent } from '~/components/ui/Card';
|
||||
import { Progress } from '~/components/ui/Progress';
|
||||
import { RotateCw, Trash2, Code, Database, Package, Loader2 } from 'lucide-react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import type { OllamaModel } from './types';
|
||||
|
||||
// Model Card Component
|
||||
interface ModelCardProps {
|
||||
model: OllamaModel;
|
||||
onUpdate: () => void;
|
||||
onDelete: () => void;
|
||||
}
|
||||
|
||||
function ModelCard({ model, onUpdate, onDelete }: ModelCardProps) {
|
||||
return (
|
||||
<Card className="bg-bolt-elements-background-depth-3 hover:bg-bolt-elements-background-depth-4 transition-all duration-200 shadow-sm hover:shadow-md border border-bolt-elements-borderColor hover:border-purple-500/20">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-medium text-bolt-elements-textPrimary font-mono">{model.name}</h4>
|
||||
{model.status && model.status !== 'idle' && (
|
||||
<span
|
||||
className={classNames('px-2 py-0.5 rounded-full text-xs font-medium', {
|
||||
'bg-yellow-500/10 text-yellow-500': model.status === 'updating',
|
||||
'bg-green-500/10 text-green-500': model.status === 'updated',
|
||||
'bg-red-500/10 text-red-500': model.status === 'error',
|
||||
})}
|
||||
>
|
||||
{model.status === 'updating' && 'Updating'}
|
||||
{model.status === 'updated' && 'Updated'}
|
||||
{model.status === 'error' && 'Error'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-xs text-bolt-elements-textSecondary">
|
||||
<div className="flex items-center gap-1">
|
||||
<Code className="w-3 h-3" />
|
||||
<span>{model.digest.substring(0, 8)}</span>
|
||||
</div>
|
||||
{model.details && (
|
||||
<>
|
||||
<div className="flex items-center gap-1">
|
||||
<Database className="w-3 h-3" />
|
||||
<span>{model.details.parameter_size}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Package className="w-3 h-3" />
|
||||
<span>{model.details.quantization_level}</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={onUpdate}
|
||||
disabled={model.status === 'updating'}
|
||||
className={classNames(
|
||||
'flex items-center gap-2 px-3 py-2 text-xs rounded-lg transition-all duration-200',
|
||||
'bg-purple-500/10 text-purple-500 hover:bg-purple-500/20 hover:shadow-sm',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-purple-500/10',
|
||||
)}
|
||||
>
|
||||
{model.status === 'updating' ? (
|
||||
<>
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
Updating
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<RotateCw className="w-3 h-3" />
|
||||
Update
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={onDelete}
|
||||
disabled={model.status === 'updating'}
|
||||
className={classNames(
|
||||
'flex items-center gap-2 px-3 py-2 text-xs rounded-lg transition-all duration-200',
|
||||
'bg-red-500/10 text-red-500 hover:bg-red-500/20 hover:shadow-sm',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-red-500/10',
|
||||
)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{model.progress && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<div className="flex justify-between text-xs text-bolt-elements-textSecondary">
|
||||
<span>{model.progress.status}</span>
|
||||
<span>{Math.round((model.progress.current / model.progress.total) * 100)}%</span>
|
||||
</div>
|
||||
<Progress value={Math.round((model.progress.current / model.progress.total) * 100)} className="h-1" />
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default ModelCard;
|
||||
@@ -0,0 +1,603 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import { Progress } from '~/components/ui/Progress';
|
||||
import { useToast } from '~/components/ui/use-toast';
|
||||
import { useSettings } from '~/lib/hooks/useSettings';
|
||||
|
||||
interface OllamaModelInstallerProps {
|
||||
onModelInstalled: () => void;
|
||||
}
|
||||
|
||||
interface InstallProgress {
|
||||
status: string;
|
||||
progress: number;
|
||||
downloadedSize?: string;
|
||||
totalSize?: string;
|
||||
speed?: string;
|
||||
}
|
||||
|
||||
interface ModelInfo {
|
||||
name: string;
|
||||
desc: string;
|
||||
size: string;
|
||||
tags: string[];
|
||||
installedVersion?: string;
|
||||
latestVersion?: string;
|
||||
needsUpdate?: boolean;
|
||||
status?: 'idle' | 'installing' | 'updating' | 'updated' | 'error';
|
||||
details?: {
|
||||
family: string;
|
||||
parameter_size: string;
|
||||
quantization_level: string;
|
||||
};
|
||||
}
|
||||
|
||||
const POPULAR_MODELS: ModelInfo[] = [
|
||||
{
|
||||
name: 'deepseek-coder:6.7b',
|
||||
desc: "DeepSeek's code generation model",
|
||||
size: '4.1GB',
|
||||
tags: ['coding', 'popular'],
|
||||
},
|
||||
{
|
||||
name: 'llama2:7b',
|
||||
desc: "Meta's Llama 2 (7B parameters)",
|
||||
size: '3.8GB',
|
||||
tags: ['general', 'popular'],
|
||||
},
|
||||
{
|
||||
name: 'mistral:7b',
|
||||
desc: "Mistral's 7B model",
|
||||
size: '4.1GB',
|
||||
tags: ['general', 'popular'],
|
||||
},
|
||||
{
|
||||
name: 'gemma:7b',
|
||||
desc: "Google's Gemma model",
|
||||
size: '4.0GB',
|
||||
tags: ['general', 'new'],
|
||||
},
|
||||
{
|
||||
name: 'codellama:7b',
|
||||
desc: "Meta's Code Llama model",
|
||||
size: '4.1GB',
|
||||
tags: ['coding', 'popular'],
|
||||
},
|
||||
{
|
||||
name: 'neural-chat:7b',
|
||||
desc: "Intel's Neural Chat model",
|
||||
size: '4.1GB',
|
||||
tags: ['chat', 'popular'],
|
||||
},
|
||||
{
|
||||
name: 'phi:latest',
|
||||
desc: "Microsoft's Phi-2 model",
|
||||
size: '2.7GB',
|
||||
tags: ['small', 'fast'],
|
||||
},
|
||||
{
|
||||
name: 'qwen:7b',
|
||||
desc: "Alibaba's Qwen model",
|
||||
size: '4.1GB',
|
||||
tags: ['general'],
|
||||
},
|
||||
{
|
||||
name: 'solar:10.7b',
|
||||
desc: "Upstage's Solar model",
|
||||
size: '6.1GB',
|
||||
tags: ['large', 'powerful'],
|
||||
},
|
||||
{
|
||||
name: 'openchat:7b',
|
||||
desc: 'Open-source chat model',
|
||||
size: '4.1GB',
|
||||
tags: ['chat', 'popular'],
|
||||
},
|
||||
{
|
||||
name: 'dolphin-phi:2.7b',
|
||||
desc: 'Lightweight chat model',
|
||||
size: '1.6GB',
|
||||
tags: ['small', 'fast'],
|
||||
},
|
||||
{
|
||||
name: 'stable-code:3b',
|
||||
desc: 'Lightweight coding model',
|
||||
size: '1.8GB',
|
||||
tags: ['coding', 'small'],
|
||||
},
|
||||
];
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) {
|
||||
return '0 B';
|
||||
}
|
||||
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
|
||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
|
||||
}
|
||||
|
||||
function formatSpeed(bytesPerSecond: number): string {
|
||||
return `${formatBytes(bytesPerSecond)}/s`;
|
||||
}
|
||||
|
||||
// Add Ollama Icon SVG component
|
||||
function OllamaIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 1024 1024" className={className} fill="currentColor">
|
||||
<path d="M684.3 322.2H339.8c-9.5.1-17.7 6.8-19.6 16.1-8.2 41.4-12.4 83.5-12.4 125.7 0 42.2 4.2 84.3 12.4 125.7 1.9 9.3 10.1 16 19.6 16.1h344.5c9.5-.1 17.7-6.8 19.6-16.1 8.2-41.4 12.4-83.5 12.4-125.7 0-42.2-4.2-84.3-12.4-125.7-1.9-9.3-10.1-16-19.6-16.1zM512 640c-176.7 0-320-143.3-320-320S335.3 0 512 0s320 143.3 320 320-143.3 320-320 320z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default function OllamaModelInstaller({ onModelInstalled }: OllamaModelInstallerProps) {
|
||||
const [modelString, setModelString] = useState('');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [isInstalling, setIsInstalling] = useState(false);
|
||||
const [isChecking, setIsChecking] = useState(false);
|
||||
const [installProgress, setInstallProgress] = useState<InstallProgress | null>(null);
|
||||
const [selectedTags, setSelectedTags] = useState<string[]>([]);
|
||||
const [models, setModels] = useState<ModelInfo[]>(POPULAR_MODELS);
|
||||
const { toast } = useToast();
|
||||
const { providers } = useSettings();
|
||||
|
||||
// Get base URL from provider settings
|
||||
const baseUrl = providers?.Ollama?.settings?.baseUrl || 'http://127.0.0.1:11434';
|
||||
|
||||
// Function to check installed models and their versions
|
||||
const checkInstalledModels = async () => {
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/api/tags`, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch installed models');
|
||||
}
|
||||
|
||||
const data = (await response.json()) as { models: Array<{ name: string; digest: string; latest: string }> };
|
||||
const installedModels = data.models || [];
|
||||
|
||||
// Update models with installed versions
|
||||
setModels((prevModels) =>
|
||||
prevModels.map((model) => {
|
||||
const installed = installedModels.find((m) => m.name.toLowerCase() === model.name.toLowerCase());
|
||||
|
||||
if (installed) {
|
||||
return {
|
||||
...model,
|
||||
installedVersion: installed.digest.substring(0, 8),
|
||||
needsUpdate: installed.digest !== installed.latest,
|
||||
latestVersion: installed.latest?.substring(0, 8),
|
||||
};
|
||||
}
|
||||
|
||||
return model;
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error checking installed models:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Check installed models on mount and after installation
|
||||
useEffect(() => {
|
||||
checkInstalledModels();
|
||||
}, [baseUrl]);
|
||||
|
||||
const handleCheckUpdates = async () => {
|
||||
setIsChecking(true);
|
||||
|
||||
try {
|
||||
await checkInstalledModels();
|
||||
toast('Model versions checked');
|
||||
} catch (err) {
|
||||
console.error('Failed to check model versions:', err);
|
||||
toast('Failed to check model versions');
|
||||
} finally {
|
||||
setIsChecking(false);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredModels = models.filter((model) => {
|
||||
const matchesSearch =
|
||||
searchQuery === '' ||
|
||||
model.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
model.desc.toLowerCase().includes(searchQuery.toLowerCase());
|
||||
const matchesTags = selectedTags.length === 0 || selectedTags.some((tag) => model.tags.includes(tag));
|
||||
|
||||
return matchesSearch && matchesTags;
|
||||
});
|
||||
|
||||
const handleInstallModel = async (modelToInstall: string) => {
|
||||
if (!modelToInstall) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsInstalling(true);
|
||||
setInstallProgress({
|
||||
status: 'Starting download...',
|
||||
progress: 0,
|
||||
downloadedSize: '0 B',
|
||||
totalSize: 'Calculating...',
|
||||
speed: '0 B/s',
|
||||
});
|
||||
setModelString('');
|
||||
setSearchQuery('');
|
||||
|
||||
const response = await fetch(`${baseUrl}/api/pull`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ name: modelToInstall }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
|
||||
if (!reader) {
|
||||
throw new Error('Failed to get response reader');
|
||||
}
|
||||
|
||||
let lastTime = Date.now();
|
||||
let lastBytes = 0;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
const text = new TextDecoder().decode(value);
|
||||
const lines = text.split('\n').filter(Boolean);
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const data = JSON.parse(line);
|
||||
|
||||
if ('status' in data) {
|
||||
const currentTime = Date.now();
|
||||
const timeDiff = (currentTime - lastTime) / 1000; // Convert to seconds
|
||||
const bytesDiff = (data.completed || 0) - lastBytes;
|
||||
const speed = bytesDiff / timeDiff;
|
||||
|
||||
setInstallProgress({
|
||||
status: data.status,
|
||||
progress: data.completed && data.total ? (data.completed / data.total) * 100 : 0,
|
||||
downloadedSize: formatBytes(data.completed || 0),
|
||||
totalSize: data.total ? formatBytes(data.total) : 'Calculating...',
|
||||
speed: formatSpeed(speed),
|
||||
});
|
||||
|
||||
lastTime = currentTime;
|
||||
lastBytes = data.completed || 0;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error parsing progress:', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
toast('Successfully installed ' + modelToInstall + '. The model list will refresh automatically.');
|
||||
|
||||
// Ensure we call onModelInstalled after successful installation
|
||||
setTimeout(() => {
|
||||
onModelInstalled();
|
||||
}, 1000);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
|
||||
console.error(`Error installing ${modelToInstall}:`, errorMessage);
|
||||
toast(`Failed to install ${modelToInstall}. ${errorMessage}`);
|
||||
} finally {
|
||||
setIsInstalling(false);
|
||||
setInstallProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateModel = async (modelToUpdate: string) => {
|
||||
try {
|
||||
setModels((prev) => prev.map((m) => (m.name === modelToUpdate ? { ...m, status: 'updating' } : m)));
|
||||
|
||||
const response = await fetch(`${baseUrl}/api/pull`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ name: modelToUpdate }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
|
||||
if (!reader) {
|
||||
throw new Error('Failed to get response reader');
|
||||
}
|
||||
|
||||
let lastTime = Date.now();
|
||||
let lastBytes = 0;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
const text = new TextDecoder().decode(value);
|
||||
const lines = text.split('\n').filter(Boolean);
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const data = JSON.parse(line);
|
||||
|
||||
if ('status' in data) {
|
||||
const currentTime = Date.now();
|
||||
const timeDiff = (currentTime - lastTime) / 1000;
|
||||
const bytesDiff = (data.completed || 0) - lastBytes;
|
||||
const speed = bytesDiff / timeDiff;
|
||||
|
||||
setInstallProgress({
|
||||
status: data.status,
|
||||
progress: data.completed && data.total ? (data.completed / data.total) * 100 : 0,
|
||||
downloadedSize: formatBytes(data.completed || 0),
|
||||
totalSize: data.total ? formatBytes(data.total) : 'Calculating...',
|
||||
speed: formatSpeed(speed),
|
||||
});
|
||||
|
||||
lastTime = currentTime;
|
||||
lastBytes = data.completed || 0;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error parsing progress:', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
toast('Successfully updated ' + modelToUpdate);
|
||||
|
||||
// Refresh model list after update
|
||||
await checkInstalledModels();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
|
||||
console.error(`Error updating ${modelToUpdate}:`, errorMessage);
|
||||
toast(`Failed to update ${modelToUpdate}. ${errorMessage}`);
|
||||
setModels((prev) => prev.map((m) => (m.name === modelToUpdate ? { ...m, status: 'error' } : m)));
|
||||
} finally {
|
||||
setInstallProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
const allTags = Array.from(new Set(POPULAR_MODELS.flatMap((model) => model.tags)));
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between pt-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<OllamaIcon className="w-8 h-8 text-purple-500" />
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-bolt-elements-textPrimary">Ollama Models</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary mt-1">Install and manage your Ollama models</p>
|
||||
</div>
|
||||
</div>
|
||||
<motion.button
|
||||
onClick={handleCheckUpdates}
|
||||
disabled={isChecking}
|
||||
className={classNames(
|
||||
'px-4 py-2 rounded-lg',
|
||||
'bg-purple-500/10 text-purple-500',
|
||||
'hover:bg-purple-500/20',
|
||||
'transition-all duration-200',
|
||||
'flex items-center gap-2',
|
||||
)}
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
{isChecking ? (
|
||||
<div className="i-ph:spinner-gap-bold animate-spin" />
|
||||
) : (
|
||||
<div className="i-ph:arrows-clockwise" />
|
||||
)}
|
||||
Check Updates
|
||||
</motion.button>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4">
|
||||
<div className="flex-1">
|
||||
<div className="space-y-1">
|
||||
<input
|
||||
type="text"
|
||||
className={classNames(
|
||||
'w-full px-4 py-3 rounded-xl',
|
||||
'bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor',
|
||||
'text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary',
|
||||
'focus:outline-none focus:ring-2 focus:ring-purple-500/30',
|
||||
'transition-all duration-200',
|
||||
)}
|
||||
placeholder="Search models or enter custom model name..."
|
||||
value={searchQuery || modelString}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setSearchQuery(value);
|
||||
setModelString(value);
|
||||
}}
|
||||
disabled={isInstalling}
|
||||
/>
|
||||
<p className="text-sm text-bolt-elements-textSecondary px-1">
|
||||
Browse models at{' '}
|
||||
<a
|
||||
href="https://ollama.com/library"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-purple-500 hover:underline inline-flex items-center gap-1 text-base font-medium"
|
||||
>
|
||||
ollama.com/library
|
||||
<div className="i-ph:arrow-square-out text-sm" />
|
||||
</a>{' '}
|
||||
and copy model names to install
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<motion.button
|
||||
onClick={() => handleInstallModel(modelString)}
|
||||
disabled={!modelString || isInstalling}
|
||||
className={classNames(
|
||||
'rounded-lg px-4 py-2',
|
||||
'bg-purple-500 text-white text-sm',
|
||||
'hover:bg-purple-600',
|
||||
'transition-all duration-200',
|
||||
'flex items-center gap-2',
|
||||
{ 'opacity-50 cursor-not-allowed': !modelString || isInstalling },
|
||||
)}
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
{isInstalling ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="i-ph:spinner-gap-bold animate-spin w-4 h-4" />
|
||||
<span>Installing...</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<OllamaIcon className="w-4 h-4" />
|
||||
<span>Install Model</span>
|
||||
</div>
|
||||
)}
|
||||
</motion.button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{allTags.map((tag) => (
|
||||
<button
|
||||
key={tag}
|
||||
onClick={() => {
|
||||
setSelectedTags((prev) => (prev.includes(tag) ? prev.filter((t) => t !== tag) : [...prev, tag]));
|
||||
}}
|
||||
className={classNames(
|
||||
'px-3 py-1 rounded-full text-xs font-medium transition-all duration-200',
|
||||
selectedTags.includes(tag)
|
||||
? 'bg-purple-500 text-white'
|
||||
: 'bg-bolt-elements-background-depth-3 text-bolt-elements-textSecondary hover:bg-bolt-elements-background-depth-4',
|
||||
)}
|
||||
>
|
||||
{tag}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
{filteredModels.map((model) => (
|
||||
<motion.div
|
||||
key={model.name}
|
||||
className={classNames(
|
||||
'flex items-start gap-2 p-3 rounded-lg',
|
||||
'bg-bolt-elements-background-depth-3',
|
||||
'hover:bg-bolt-elements-background-depth-4',
|
||||
'transition-all duration-200',
|
||||
'relative group',
|
||||
)}
|
||||
>
|
||||
<OllamaIcon className="w-5 h-5 text-purple-500 mt-0.5 flex-shrink-0" />
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<p className="text-bolt-elements-textPrimary font-mono text-sm">{model.name}</p>
|
||||
<p className="text-xs text-bolt-elements-textSecondary mt-0.5">{model.desc}</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<span className="text-xs text-bolt-elements-textTertiary">{model.size}</span>
|
||||
{model.installedVersion && (
|
||||
<div className="mt-0.5 flex flex-col items-end gap-0.5">
|
||||
<span className="text-xs text-bolt-elements-textTertiary">v{model.installedVersion}</span>
|
||||
{model.needsUpdate && model.latestVersion && (
|
||||
<span className="text-xs text-purple-500">v{model.latestVersion} available</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{model.tags.map((tag) => (
|
||||
<span
|
||||
key={tag}
|
||||
className="px-1.5 py-0.5 rounded-full text-[10px] bg-bolt-elements-background-depth-4 text-bolt-elements-textTertiary"
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{model.installedVersion ? (
|
||||
model.needsUpdate ? (
|
||||
<motion.button
|
||||
onClick={() => handleUpdateModel(model.name)}
|
||||
className={classNames(
|
||||
'px-2 py-0.5 rounded-lg text-xs',
|
||||
'bg-purple-500 text-white',
|
||||
'hover:bg-purple-600',
|
||||
'transition-all duration-200',
|
||||
'flex items-center gap-1',
|
||||
)}
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
<div className="i-ph:arrows-clockwise text-xs" />
|
||||
Update
|
||||
</motion.button>
|
||||
) : (
|
||||
<span className="px-2 py-0.5 rounded-lg text-xs text-green-500 bg-green-500/10">Up to date</span>
|
||||
)
|
||||
) : (
|
||||
<motion.button
|
||||
onClick={() => handleInstallModel(model.name)}
|
||||
className={classNames(
|
||||
'px-2 py-0.5 rounded-lg text-xs',
|
||||
'bg-purple-500 text-white',
|
||||
'hover:bg-purple-600',
|
||||
'transition-all duration-200',
|
||||
'flex items-center gap-1',
|
||||
)}
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
>
|
||||
<div className="i-ph:download text-xs" />
|
||||
Install
|
||||
</motion.button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{installProgress && (
|
||||
<motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-bolt-elements-textSecondary">{installProgress.status}</span>
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-bolt-elements-textTertiary">
|
||||
{installProgress.downloadedSize} / {installProgress.totalSize}
|
||||
</span>
|
||||
<span className="text-bolt-elements-textTertiary">{installProgress.speed}</span>
|
||||
<span className="text-bolt-elements-textSecondary">{Math.round(installProgress.progress)}%</span>
|
||||
</div>
|
||||
</div>
|
||||
<Progress value={installProgress.progress} className="h-1" />
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Switch } from '~/components/ui/Switch';
|
||||
import { Card, CardContent } from '~/components/ui/Card';
|
||||
import { Link, Server, Monitor, Globe } from 'lucide-react';
|
||||
import { classNames } from '~/utils/classNames';
|
||||
import type { IProviderConfig } from '~/types/model';
|
||||
import { PROVIDER_DESCRIPTIONS } from './types';
|
||||
|
||||
// Provider Card Component
|
||||
interface ProviderCardProps {
|
||||
provider: IProviderConfig;
|
||||
onToggle: (enabled: boolean) => void;
|
||||
onUpdateBaseUrl: (url: string) => void;
|
||||
isEditing: boolean;
|
||||
onStartEditing: () => void;
|
||||
onStopEditing: () => void;
|
||||
}
|
||||
|
||||
function ProviderCard({
|
||||
provider,
|
||||
onToggle,
|
||||
onUpdateBaseUrl,
|
||||
isEditing,
|
||||
onStartEditing,
|
||||
onStopEditing,
|
||||
}: ProviderCardProps) {
|
||||
const getIcon = (providerName: string) => {
|
||||
switch (providerName) {
|
||||
case 'Ollama':
|
||||
return Server;
|
||||
case 'LMStudio':
|
||||
return Monitor;
|
||||
case 'OpenAILike':
|
||||
return Globe;
|
||||
default:
|
||||
return Server;
|
||||
}
|
||||
};
|
||||
|
||||
const Icon = getIcon(provider.name);
|
||||
|
||||
return (
|
||||
<Card className="bg-bolt-elements-background-depth-2 hover:bg-bolt-elements-background-depth-3 transition-all duration-300 shadow-sm hover:shadow-md border border-bolt-elements-borderColor hover:border-purple-500/30">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-start gap-4 flex-1">
|
||||
<div
|
||||
className={classNames(
|
||||
'w-12 h-12 rounded-xl flex items-center justify-center transition-all duration-300',
|
||||
provider.settings.enabled
|
||||
? 'bg-gradient-to-br from-purple-500/20 to-purple-600/20 ring-1 ring-purple-500/30'
|
||||
: 'bg-bolt-elements-background-depth-3',
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
className={classNames(
|
||||
'w-6 h-6 transition-all duration-300',
|
||||
provider.settings.enabled ? 'text-purple-500' : 'text-bolt-elements-textTertiary',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<h3 className="text-lg font-semibold text-bolt-elements-textPrimary">{provider.name}</h3>
|
||||
<span className="px-2 py-1 text-xs rounded-full bg-green-500/10 text-green-500 font-medium">Local</span>
|
||||
</div>
|
||||
<p className="text-sm text-bolt-elements-textSecondary mb-4">
|
||||
{PROVIDER_DESCRIPTIONS[provider.name as keyof typeof PROVIDER_DESCRIPTIONS]}
|
||||
</p>
|
||||
|
||||
{provider.settings.enabled && (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-bolt-elements-textPrimary">API Endpoint</label>
|
||||
{isEditing ? (
|
||||
<input
|
||||
type="text"
|
||||
defaultValue={provider.settings.baseUrl}
|
||||
placeholder={`Enter ${provider.name} base URL`}
|
||||
className="w-full px-4 py-3 rounded-lg text-sm bg-bolt-elements-background-depth-4 border border-purple-500/30 text-bolt-elements-textPrimary placeholder-bolt-elements-textTertiary focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 transition-all duration-200 shadow-sm"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
onUpdateBaseUrl(e.currentTarget.value);
|
||||
onStopEditing();
|
||||
} else if (e.key === 'Escape') {
|
||||
onStopEditing();
|
||||
}
|
||||
}}
|
||||
onBlur={(e) => {
|
||||
onUpdateBaseUrl(e.target.value);
|
||||
onStopEditing();
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
onClick={onStartEditing}
|
||||
className="w-full px-4 py-3 rounded-lg text-sm bg-bolt-elements-background-depth-3 border border-bolt-elements-borderColor hover:border-purple-500/30 hover:bg-bolt-elements-background-depth-4 hover:shadow-sm transition-all duration-200 text-left group"
|
||||
>
|
||||
<div className="flex items-center gap-3 text-bolt-elements-textSecondary group-hover:text-bolt-elements-textPrimary">
|
||||
<Link className="w-4 h-4 group-hover:text-purple-500 transition-colors" />
|
||||
<span className="font-mono">{provider.settings.baseUrl || 'Click to set base URL'}</span>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<Switch
|
||||
checked={provider.settings.enabled}
|
||||
onCheckedChange={onToggle}
|
||||
aria-label={`Toggle ${provider.name} provider`}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default ProviderCard;
|
||||
@@ -1,671 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { Card, CardContent, CardHeader } from '~/components/ui/Card';
|
||||
import {
|
||||
Cpu,
|
||||
Server,
|
||||
Settings,
|
||||
ExternalLink,
|
||||
Package,
|
||||
Code,
|
||||
Database,
|
||||
CheckCircle,
|
||||
AlertCircle,
|
||||
Activity,
|
||||
Cable,
|
||||
ArrowLeft,
|
||||
Download,
|
||||
Shield,
|
||||
Globe,
|
||||
Terminal,
|
||||
Monitor,
|
||||
Wifi,
|
||||
} from 'lucide-react';
|
||||
|
||||
// Setup Guide Component
|
||||
function SetupGuide({ onBack }: { onBack: () => void }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header with Back Button */}
|
||||
<div className="flex items-center gap-4 mb-6">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
className="bg-transparent hover:bg-transparent text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-all duration-200 p-2"
|
||||
aria-label="Back to Dashboard"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</Button>
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold text-bolt-elements-textPrimary">Local Provider Setup Guide</h2>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">
|
||||
Complete setup instructions for running AI models locally
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Hardware Requirements Overview */}
|
||||
<Card className="bg-gradient-to-r from-blue-500/10 to-purple-500/10 border border-blue-500/20 shadow-sm">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center">
|
||||
<Shield className="w-5 h-5 text-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-bolt-elements-textPrimary">System Requirements</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">Recommended hardware for optimal performance</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-3 gap-4 text-sm">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Cpu className="w-4 h-4 text-green-500" />
|
||||
<span className="font-medium text-bolt-elements-textPrimary">CPU</span>
|
||||
</div>
|
||||
<p className="text-bolt-elements-textSecondary">8+ cores, modern architecture</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="w-4 h-4 text-blue-500" />
|
||||
<span className="font-medium text-bolt-elements-textPrimary">RAM</span>
|
||||
</div>
|
||||
<p className="text-bolt-elements-textSecondary">16GB minimum, 32GB+ recommended</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Monitor className="w-4 h-4 text-purple-500" />
|
||||
<span className="font-medium text-bolt-elements-textPrimary">GPU</span>
|
||||
</div>
|
||||
<p className="text-bolt-elements-textSecondary">NVIDIA RTX 30xx+ or AMD RX 6000+</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Ollama Setup Section */}
|
||||
<Card className="bg-bolt-elements-background-depth-2 shadow-sm">
|
||||
<CardHeader className="pb-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-12 h-12 rounded-xl bg-gradient-to-br from-purple-500/20 to-purple-600/20 flex items-center justify-center ring-1 ring-purple-500/30">
|
||||
<Server className="w-6 h-6 text-purple-500" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-xl font-semibold text-bolt-elements-textPrimary">Ollama Setup</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">
|
||||
Most popular choice for running open-source models locally with desktop app
|
||||
</p>
|
||||
</div>
|
||||
<span className="px-3 py-1 bg-purple-500/10 text-purple-500 text-xs font-medium rounded-full">
|
||||
Recommended
|
||||
</span>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Installation Options */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary flex items-center gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
1. Choose Installation Method
|
||||
</h4>
|
||||
|
||||
{/* Desktop App - New and Recommended */}
|
||||
<div className="p-4 rounded-lg bg-green-500/5 border border-green-500/20">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Monitor className="w-5 h-5 text-green-500" />
|
||||
<h5 className="font-medium text-green-500">🆕 Desktop App (Recommended)</h5>
|
||||
</div>
|
||||
<p className="text-sm text-bolt-elements-textSecondary mb-3">
|
||||
New user-friendly desktop application with built-in model management and web interface.
|
||||
</p>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="p-3 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Monitor className="w-4 h-4 text-bolt-elements-textPrimary" />
|
||||
<strong className="text-bolt-elements-textPrimary">macOS</strong>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full bg-gradient-to-r from-purple-500/10 to-purple-600/10 hover:from-purple-500/20 hover:to-purple-600/20 border-purple-500/30 hover:border-purple-500/50 transition-all duration-300 gap-2 group shadow-sm hover:shadow-lg hover:shadow-purple-500/20 font-medium"
|
||||
_asChild
|
||||
>
|
||||
<a
|
||||
href="https://ollama.com/download/mac"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center justify-center gap-2"
|
||||
>
|
||||
<Download className="w-4 h-4 group-hover:scale-110 group-hover:rotate-12 transition-all duration-300 flex-shrink-0" />
|
||||
<span className="flex-1 text-center font-medium">Download Desktop App</span>
|
||||
<ExternalLink className="w-3 h-3 group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition-all duration-300 flex-shrink-0" />
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="p-3 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Monitor className="w-4 h-4 text-bolt-elements-textPrimary" />
|
||||
<strong className="text-bolt-elements-textPrimary">Windows</strong>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full bg-gradient-to-r from-purple-500/10 to-purple-600/10 hover:from-purple-500/20 hover:to-purple-600/20 border-purple-500/30 hover:border-purple-500/50 transition-all duration-300 gap-2 group shadow-sm hover:shadow-lg hover:shadow-purple-500/20 font-medium"
|
||||
_asChild
|
||||
>
|
||||
<a
|
||||
href="https://ollama.com/download/windows"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center justify-center gap-2"
|
||||
>
|
||||
<Download className="w-4 h-4 group-hover:scale-110 group-hover:rotate-12 transition-all duration-300 flex-shrink-0" />
|
||||
<span className="flex-1 text-center font-medium">Download Desktop App</span>
|
||||
<ExternalLink className="w-3 h-3 group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition-all duration-300 flex-shrink-0" />
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 p-3 rounded-lg bg-blue-500/5 border border-blue-500/20">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Globe className="w-4 h-4 text-blue-500" />
|
||||
<span className="font-medium text-blue-500 text-sm">Built-in Web Interface</span>
|
||||
</div>
|
||||
<p className="text-xs text-bolt-elements-textSecondary">
|
||||
Desktop app includes a web interface at{' '}
|
||||
<code className="bg-bolt-elements-background-depth-4 px-1 rounded">http://localhost:11434</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* CLI Installation */}
|
||||
<div className="p-4 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Terminal className="w-5 h-5 text-bolt-elements-textPrimary" />
|
||||
<h5 className="font-medium text-bolt-elements-textPrimary">Command Line (Advanced)</h5>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div className="p-3 rounded-lg bg-bolt-elements-background-depth-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Monitor className="w-4 h-4 text-bolt-elements-textPrimary" />
|
||||
<strong className="text-bolt-elements-textPrimary">Windows</strong>
|
||||
</div>
|
||||
<div className="text-xs bg-bolt-elements-background-depth-4 p-2 rounded font-mono text-bolt-elements-textPrimary">
|
||||
winget install Ollama.Ollama
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 rounded-lg bg-bolt-elements-background-depth-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Monitor className="w-4 h-4 text-bolt-elements-textPrimary" />
|
||||
<strong className="text-bolt-elements-textPrimary">macOS</strong>
|
||||
</div>
|
||||
<div className="text-xs bg-bolt-elements-background-depth-4 p-2 rounded font-mono text-bolt-elements-textPrimary">
|
||||
brew install ollama
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 rounded-lg bg-bolt-elements-background-depth-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Terminal className="w-4 h-4 text-bolt-elements-textPrimary" />
|
||||
<strong className="text-bolt-elements-textPrimary">Linux</strong>
|
||||
</div>
|
||||
<div className="text-xs bg-bolt-elements-background-depth-4 p-2 rounded font-mono text-bolt-elements-textPrimary">
|
||||
curl -fsSL https://ollama.com/install.sh | sh
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Latest Model Recommendations */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary flex items-center gap-2">
|
||||
<Package className="w-4 h-4" />
|
||||
2. Download Latest Models
|
||||
</h4>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="p-4 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<h5 className="font-medium text-bolt-elements-textPrimary mb-3 flex items-center gap-2">
|
||||
<Code className="w-4 h-4 text-green-500" />
|
||||
Code & Development
|
||||
</h5>
|
||||
<div className="space-y-2 text-xs bg-bolt-elements-background-depth-4 p-3 rounded font-mono text-bolt-elements-textPrimary">
|
||||
<div># Latest Llama 3.2 for coding</div>
|
||||
<div>ollama pull llama3.2:3b</div>
|
||||
<div>ollama pull codellama:13b</div>
|
||||
<div>ollama pull deepseek-coder-v2</div>
|
||||
<div>ollama pull qwen2.5-coder:7b</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<h5 className="font-medium text-bolt-elements-textPrimary mb-3 flex items-center gap-2">
|
||||
<Terminal className="w-4 h-4 text-blue-500" />
|
||||
General Purpose & Chat
|
||||
</h5>
|
||||
<div className="space-y-2 text-xs bg-bolt-elements-background-depth-4 p-3 rounded font-mono text-bolt-elements-textPrimary">
|
||||
<div># Latest general models</div>
|
||||
<div>ollama pull llama3.2:3b</div>
|
||||
<div>ollama pull mistral:7b</div>
|
||||
<div>ollama pull phi3.5:3.8b</div>
|
||||
<div>ollama pull qwen2.5:7b</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="p-4 rounded-lg bg-purple-500/5 border border-purple-500/20">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Activity className="w-4 h-4 text-purple-500" />
|
||||
<span className="font-medium text-purple-500">Performance Optimized</span>
|
||||
</div>
|
||||
<ul className="text-xs text-bolt-elements-textSecondary space-y-1">
|
||||
<li>• Llama 3.2: 3B - Fastest, 8GB RAM</li>
|
||||
<li>• Phi-3.5: 3.8B - Great balance</li>
|
||||
<li>• Qwen2.5: 7B - Excellent quality</li>
|
||||
<li>• Mistral: 7B - Popular choice</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div className="p-4 rounded-lg bg-yellow-500/10 border border-yellow-500/20">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<AlertCircle className="w-4 h-4 text-yellow-500" />
|
||||
<span className="font-medium text-yellow-500">Pro Tips</span>
|
||||
</div>
|
||||
<ul className="text-xs text-bolt-elements-textSecondary space-y-1">
|
||||
<li>• Start with 3B-7B models for best performance</li>
|
||||
<li>• Use quantized versions for faster loading</li>
|
||||
<li>• Desktop app auto-manages model storage</li>
|
||||
<li>• Web UI available at localhost:11434</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Desktop App Features */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary flex items-center gap-2">
|
||||
<Monitor className="w-4 h-4" />
|
||||
3. Desktop App Features
|
||||
</h4>
|
||||
<div className="p-4 rounded-lg bg-blue-500/5 border border-blue-500/20">
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<h5 className="font-medium text-blue-500 mb-3">🖥️ User Interface</h5>
|
||||
<ul className="text-sm text-bolt-elements-textSecondary space-y-1">
|
||||
<li>• Model library browser</li>
|
||||
<li>• One-click model downloads</li>
|
||||
<li>• Built-in chat interface</li>
|
||||
<li>• System resource monitoring</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h5 className="font-medium text-blue-500 mb-3">🔧 Management Tools</h5>
|
||||
<ul className="text-sm text-bolt-elements-textSecondary space-y-1">
|
||||
<li>• Automatic updates</li>
|
||||
<li>• Model size optimization</li>
|
||||
<li>• GPU acceleration detection</li>
|
||||
<li>• Cross-platform compatibility</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Troubleshooting */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary flex items-center gap-2">
|
||||
<Settings className="w-4 h-4" />
|
||||
4. Troubleshooting & Commands
|
||||
</h4>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="p-4 rounded-lg bg-red-500/5 border border-red-500/20">
|
||||
<h5 className="font-medium text-red-500 mb-2">Common Issues</h5>
|
||||
<ul className="text-xs text-bolt-elements-textSecondary space-y-1">
|
||||
<li>• Desktop app not starting: Restart system</li>
|
||||
<li>• GPU not detected: Update drivers</li>
|
||||
<li>• Port 11434 blocked: Change port in settings</li>
|
||||
<li>• Models not loading: Check available disk space</li>
|
||||
<li>• Slow performance: Use smaller models or enable GPU</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div className="p-4 rounded-lg bg-green-500/5 border border-green-500/20">
|
||||
<h5 className="font-medium text-green-500 mb-2">Useful Commands</h5>
|
||||
<div className="text-xs bg-bolt-elements-background-depth-4 p-3 rounded font-mono text-bolt-elements-textPrimary space-y-1">
|
||||
<div># Check installed models</div>
|
||||
<div>ollama list</div>
|
||||
<div></div>
|
||||
<div># Remove unused models</div>
|
||||
<div>ollama rm model_name</div>
|
||||
<div></div>
|
||||
<div># Check GPU usage</div>
|
||||
<div>ollama ps</div>
|
||||
<div></div>
|
||||
<div># View logs</div>
|
||||
<div>ollama logs</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* LM Studio Setup Section */}
|
||||
<Card className="bg-bolt-elements-background-depth-2 shadow-sm">
|
||||
<CardHeader className="pb-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-12 h-12 rounded-xl bg-gradient-to-br from-blue-500/20 to-blue-600/20 flex items-center justify-center ring-1 ring-blue-500/30">
|
||||
<Monitor className="w-6 h-6 text-blue-500" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-xl font-semibold text-bolt-elements-textPrimary">LM Studio Setup</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">
|
||||
User-friendly GUI for running local models with excellent model management
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Installation */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary flex items-center gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
1. Download & Install
|
||||
</h4>
|
||||
<div className="p-4 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<p className="text-sm text-bolt-elements-textSecondary mb-3">
|
||||
Download LM Studio for Windows, macOS, or Linux from the official website.
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="bg-gradient-to-r from-blue-500/10 to-blue-600/10 hover:from-blue-500/20 hover:to-blue-600/20 border-blue-500/30 hover:border-blue-500/50 transition-all duration-300 gap-2 group shadow-sm hover:shadow-lg hover:shadow-blue-500/20 font-medium"
|
||||
_asChild
|
||||
>
|
||||
<a
|
||||
href="https://lmstudio.ai/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center justify-center gap-2"
|
||||
>
|
||||
<Download className="w-4 h-4 group-hover:scale-110 group-hover:rotate-12 transition-all duration-300 flex-shrink-0" />
|
||||
<span className="flex-1 text-center font-medium">Download LM Studio</span>
|
||||
<ExternalLink className="w-3 h-3 group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition-all duration-300 flex-shrink-0" />
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Configuration */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary flex items-center gap-2">
|
||||
<Settings className="w-4 h-4" />
|
||||
2. Configure Local Server
|
||||
</h4>
|
||||
<div className="space-y-3">
|
||||
<div className="p-4 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<h5 className="font-medium text-bolt-elements-textPrimary mb-2">Start Local Server</h5>
|
||||
<ol className="text-xs text-bolt-elements-textSecondary space-y-1 list-decimal list-inside">
|
||||
<li>Download a model from the "My Models" tab</li>
|
||||
<li>Go to "Local Server" tab</li>
|
||||
<li>Select your downloaded model</li>
|
||||
<li>Set port to 1234 (default)</li>
|
||||
<li>Click "Start Server"</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<div className="p-4 rounded-lg bg-red-500/10 border border-red-500/20">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<AlertCircle className="w-4 h-4 text-red-500" />
|
||||
<span className="font-medium text-red-500">Critical: Enable CORS</span>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs text-bolt-elements-textSecondary">
|
||||
To work with Bolt DIY, you MUST enable CORS in LM Studio:
|
||||
</p>
|
||||
<ol className="text-xs text-bolt-elements-textSecondary space-y-1 list-decimal list-inside ml-2">
|
||||
<li>In Server Settings, check "Enable CORS"</li>
|
||||
<li>Set Network Interface to "0.0.0.0" for external access</li>
|
||||
<li>
|
||||
Alternatively, use CLI:{' '}
|
||||
<code className="bg-bolt-elements-background-depth-4 px-1 rounded">lms server start --cors</code>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Advantages */}
|
||||
<div className="p-4 rounded-lg bg-blue-500/10 border border-blue-500/20">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<CheckCircle className="w-4 h-4 text-blue-500" />
|
||||
<span className="font-medium text-blue-500">LM Studio Advantages</span>
|
||||
</div>
|
||||
<ul className="text-xs text-bolt-elements-textSecondary space-y-1 list-disc list-inside">
|
||||
<li>Built-in model downloader with search</li>
|
||||
<li>Easy model switching and management</li>
|
||||
<li>Built-in chat interface for testing</li>
|
||||
<li>GGUF format support (most compatible)</li>
|
||||
<li>Regular updates with new features</li>
|
||||
</ul>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* LocalAI Setup Section */}
|
||||
<Card className="bg-bolt-elements-background-depth-2 shadow-sm">
|
||||
<CardHeader className="pb-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-12 h-12 rounded-xl bg-gradient-to-br from-green-500/20 to-green-600/20 flex items-center justify-center ring-1 ring-green-500/30">
|
||||
<Globe className="w-6 h-6 text-green-500" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-xl font-semibold text-bolt-elements-textPrimary">LocalAI Setup</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">
|
||||
Self-hosted OpenAI-compatible API server with extensive model support
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Installation */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary flex items-center gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
Installation Options
|
||||
</h4>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="p-4 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<h5 className="font-medium text-bolt-elements-textPrimary mb-2">Quick Install</h5>
|
||||
<div className="text-xs bg-bolt-elements-background-depth-4 p-3 rounded font-mono text-bolt-elements-textPrimary space-y-1">
|
||||
<div># One-line install</div>
|
||||
<div>curl https://localai.io/install.sh | sh</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<h5 className="font-medium text-bolt-elements-textPrimary mb-2">Docker (Recommended)</h5>
|
||||
<div className="text-xs bg-bolt-elements-background-depth-4 p-3 rounded font-mono text-bolt-elements-textPrimary space-y-1">
|
||||
<div>docker run -p 8080:8080</div>
|
||||
<div>quay.io/go-skynet/local-ai:latest</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Configuration */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary flex items-center gap-2">
|
||||
<Settings className="w-4 h-4" />
|
||||
Configuration
|
||||
</h4>
|
||||
<div className="p-4 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<p className="text-sm text-bolt-elements-textSecondary mb-3">
|
||||
LocalAI supports many model formats and provides a full OpenAI-compatible API.
|
||||
</p>
|
||||
<div className="text-xs bg-bolt-elements-background-depth-4 p-3 rounded font-mono text-bolt-elements-textPrimary space-y-1">
|
||||
<div># Example configuration</div>
|
||||
<div>models:</div>
|
||||
<div>- name: llama3.1</div>
|
||||
<div>backend: llama</div>
|
||||
<div>parameters:</div>
|
||||
<div>model: llama3.1.gguf</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Advantages */}
|
||||
<div className="p-4 rounded-lg bg-green-500/10 border border-green-500/20">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<CheckCircle className="w-4 h-4 text-green-500" />
|
||||
<span className="font-medium text-green-500">LocalAI Advantages</span>
|
||||
</div>
|
||||
<ul className="text-xs text-bolt-elements-textSecondary space-y-1 list-disc list-inside">
|
||||
<li>Full OpenAI API compatibility</li>
|
||||
<li>Supports multiple model formats</li>
|
||||
<li>Docker deployment option</li>
|
||||
<li>Built-in model gallery</li>
|
||||
<li>REST API for model management</li>
|
||||
</ul>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Performance Optimization */}
|
||||
<Card className="bg-gradient-to-r from-purple-500/10 to-pink-500/10 border border-purple-500/20 shadow-sm">
|
||||
<CardHeader className="pb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-lg bg-purple-500/20 flex items-center justify-center">
|
||||
<Activity className="w-5 h-5 text-purple-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-bolt-elements-textPrimary">Performance Optimization</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">Tips to improve local AI performance</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-3">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary">Hardware Optimizations</h4>
|
||||
<ul className="text-sm text-bolt-elements-textSecondary space-y-2">
|
||||
<li className="flex items-start gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
|
||||
<span>Use NVIDIA GPU with CUDA for 5-10x speedup</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
|
||||
<span>Increase RAM for larger context windows</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
|
||||
<span>Use SSD storage for faster model loading</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
|
||||
<span>Close other applications to free up RAM</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary">Software Optimizations</h4>
|
||||
<ul className="text-sm text-bolt-elements-textSecondary space-y-2">
|
||||
<li className="flex items-start gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-blue-500 mt-0.5 flex-shrink-0" />
|
||||
<span>Use smaller models for faster responses</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-blue-500 mt-0.5 flex-shrink-0" />
|
||||
<span>Enable quantization (4-bit, 8-bit models)</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-blue-500 mt-0.5 flex-shrink-0" />
|
||||
<span>Reduce context length for chat applications</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-blue-500 mt-0.5 flex-shrink-0" />
|
||||
<span>Use streaming responses for better UX</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Alternative Options */}
|
||||
<Card className="bg-bolt-elements-background-depth-2 shadow-sm">
|
||||
<CardHeader className="pb-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-12 h-12 rounded-xl bg-gradient-to-br from-orange-500/20 to-red-500/20 flex items-center justify-center ring-1 ring-orange-500/30">
|
||||
<Wifi className="w-6 h-6 text-orange-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold text-bolt-elements-textPrimary">Alternative Options</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">
|
||||
Other local AI solutions and cloud alternatives
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<div className="space-y-4">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary">Other Local Solutions</h4>
|
||||
<div className="space-y-3">
|
||||
<div className="p-3 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Package className="w-4 h-4 text-blue-500" />
|
||||
<span className="font-medium text-bolt-elements-textPrimary">Jan.ai</span>
|
||||
</div>
|
||||
<p className="text-xs text-bolt-elements-textSecondary">
|
||||
Modern interface with built-in model marketplace
|
||||
</p>
|
||||
</div>
|
||||
<div className="p-3 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Terminal className="w-4 h-4 text-green-500" />
|
||||
<span className="font-medium text-bolt-elements-textPrimary">Oobabooga</span>
|
||||
</div>
|
||||
<p className="text-xs text-bolt-elements-textSecondary">
|
||||
Advanced text generation web UI with extensions
|
||||
</p>
|
||||
</div>
|
||||
<div className="p-3 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Cable className="w-4 h-4 text-purple-500" />
|
||||
<span className="font-medium text-bolt-elements-textPrimary">KoboldAI</span>
|
||||
</div>
|
||||
<p className="text-xs text-bolt-elements-textSecondary">Focus on creative writing and storytelling</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<h4 className="font-medium text-bolt-elements-textPrimary">Cloud Alternatives</h4>
|
||||
<div className="space-y-3">
|
||||
<div className="p-3 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Globe className="w-4 h-4 text-orange-500" />
|
||||
<span className="font-medium text-bolt-elements-textPrimary">OpenRouter</span>
|
||||
</div>
|
||||
<p className="text-xs text-bolt-elements-textSecondary">Access to 100+ models through unified API</p>
|
||||
</div>
|
||||
<div className="p-3 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Server className="w-4 h-4 text-red-500" />
|
||||
<span className="font-medium text-bolt-elements-textPrimary">Together AI</span>
|
||||
</div>
|
||||
<p className="text-xs text-bolt-elements-textSecondary">Fast inference with open-source models</p>
|
||||
</div>
|
||||
<div className="p-3 rounded-lg bg-bolt-elements-background-depth-3">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Activity className="w-4 h-4 text-pink-500" />
|
||||
<span className="font-medium text-bolt-elements-textPrimary">Groq</span>
|
||||
</div>
|
||||
<p className="text-xs text-bolt-elements-textSecondary">Ultra-fast LPU inference for Llama models</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SetupGuide;
|
||||
@@ -1,91 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { Card, CardContent } from '~/components/ui/Card';
|
||||
import { Cable, Server, ArrowLeft } from 'lucide-react';
|
||||
import { useLocalModelHealth } from '~/lib/hooks/useLocalModelHealth';
|
||||
import HealthStatusBadge from './HealthStatusBadge';
|
||||
import { PROVIDER_ICONS } from './types';
|
||||
|
||||
// Status Dashboard Component
|
||||
function StatusDashboard({ onBack }: { onBack: () => void }) {
|
||||
const { healthStatuses } = useLocalModelHealth();
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header with Back Button */}
|
||||
<div className="flex items-center gap-4 mb-6">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
className="bg-transparent hover:bg-transparent text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary transition-all duration-200 p-2"
|
||||
aria-label="Back to Dashboard"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</Button>
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold text-bolt-elements-textPrimary">Provider Status</h2>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">Monitor the health of your local AI providers</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{healthStatuses.length === 0 ? (
|
||||
<Card className="bg-bolt-elements-background-depth-2">
|
||||
<CardContent className="p-8 text-center">
|
||||
<Cable className="w-16 h-16 mx-auto text-bolt-elements-textTertiary mb-4" />
|
||||
<h3 className="text-lg font-medium text-bolt-elements-textPrimary mb-2">No Endpoints Configured</h3>
|
||||
<p className="text-sm text-bolt-elements-textSecondary">
|
||||
Configure and enable local providers to see their endpoint status here.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{healthStatuses.map((status) => (
|
||||
<Card key={`${status.provider}-${status.baseUrl}`} className="bg-bolt-elements-background-depth-2">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-lg bg-bolt-elements-background-depth-3 flex items-center justify-center">
|
||||
{React.createElement(PROVIDER_ICONS[status.provider as keyof typeof PROVIDER_ICONS] || Server, {
|
||||
className: 'w-5 h-5 text-bolt-elements-textPrimary',
|
||||
})}
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-bolt-elements-textPrimary">{status.provider}</h3>
|
||||
<p className="text-xs text-bolt-elements-textSecondary font-mono">{status.baseUrl}</p>
|
||||
</div>
|
||||
</div>
|
||||
<HealthStatusBadge status={status.status} responseTime={status.responseTime} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4 text-sm">
|
||||
<div className="text-center">
|
||||
<div className="text-bolt-elements-textSecondary">Models</div>
|
||||
<div className="text-lg font-semibold text-bolt-elements-textPrimary">
|
||||
{status.availableModels?.length || 0}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-bolt-elements-textSecondary">Version</div>
|
||||
<div className="text-lg font-semibold text-bolt-elements-textPrimary">
|
||||
{status.version || 'Unknown'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-bolt-elements-textSecondary">Last Check</div>
|
||||
<div className="text-lg font-semibold text-bolt-elements-textPrimary">
|
||||
{status.lastChecked ? new Date(status.lastChecked).toLocaleTimeString() : 'Never'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default StatusDashboard;
|
||||
@@ -1,44 +0,0 @@
|
||||
// Type definitions
|
||||
export type ProviderName = 'Ollama' | 'LMStudio' | 'OpenAILike';
|
||||
|
||||
export interface OllamaModel {
|
||||
name: string;
|
||||
digest: string;
|
||||
size: number;
|
||||
modified_at: string;
|
||||
details?: {
|
||||
family: string;
|
||||
parameter_size: string;
|
||||
quantization_level: string;
|
||||
};
|
||||
status?: 'idle' | 'updating' | 'updated' | 'error' | 'checking';
|
||||
error?: string;
|
||||
newDigest?: string;
|
||||
progress?: {
|
||||
current: number;
|
||||
total: number;
|
||||
status: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface LMStudioModel {
|
||||
id: string;
|
||||
object: 'model';
|
||||
owned_by: string;
|
||||
created?: number;
|
||||
}
|
||||
|
||||
// Constants
|
||||
export const OLLAMA_API_URL = 'http://127.0.0.1:11434';
|
||||
|
||||
export const PROVIDER_ICONS = {
|
||||
Ollama: 'Server',
|
||||
LMStudio: 'Monitor',
|
||||
OpenAILike: 'Globe',
|
||||
} as const;
|
||||
|
||||
export const PROVIDER_DESCRIPTIONS = {
|
||||
Ollama: 'Run open-source models locally on your machine',
|
||||
LMStudio: 'Local model inference with LM Studio',
|
||||
OpenAILike: 'Connect to OpenAI-compatible API endpoints',
|
||||
} as const;
|
||||
@@ -0,0 +1,135 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import type { ServiceStatus } from './types';
|
||||
import { ProviderStatusCheckerFactory } from './provider-factory';
|
||||
|
||||
export default function ServiceStatusTab() {
|
||||
const [serviceStatuses, setServiceStatuses] = useState<ServiceStatus[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAllProviders = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const providers = ProviderStatusCheckerFactory.getProviderNames();
|
||||
const statuses: ServiceStatus[] = [];
|
||||
|
||||
for (const provider of providers) {
|
||||
try {
|
||||
const checker = ProviderStatusCheckerFactory.getChecker(provider);
|
||||
const result = await checker.checkStatus();
|
||||
|
||||
statuses.push({
|
||||
provider,
|
||||
...result,
|
||||
lastChecked: new Date().toISOString(),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(`Error checking ${provider} status:`, err);
|
||||
statuses.push({
|
||||
provider,
|
||||
status: 'degraded',
|
||||
message: 'Unable to check service status',
|
||||
incidents: ['Error checking service status'],
|
||||
lastChecked: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
setServiceStatuses(statuses);
|
||||
} catch (err) {
|
||||
console.error('Error checking provider statuses:', err);
|
||||
setError('Failed to check service statuses');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkAllProviders();
|
||||
|
||||
// Set up periodic checks every 5 minutes
|
||||
const interval = setInterval(checkAllProviders, 5 * 60 * 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const getStatusColor = (status: ServiceStatus['status']) => {
|
||||
switch (status) {
|
||||
case 'operational':
|
||||
return 'text-green-500 dark:text-green-400';
|
||||
case 'degraded':
|
||||
return 'text-yellow-500 dark:text-yellow-400';
|
||||
case 'down':
|
||||
return 'text-red-500 dark:text-red-400';
|
||||
default:
|
||||
return 'text-gray-500 dark:text-gray-400';
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusIcon = (status: ServiceStatus['status']) => {
|
||||
switch (status) {
|
||||
case 'operational':
|
||||
return 'i-ph:check-circle';
|
||||
case 'degraded':
|
||||
return 'i-ph:warning';
|
||||
case 'down':
|
||||
return 'i-ph:x-circle';
|
||||
default:
|
||||
return 'i-ph:question';
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="animate-spin i-ph:circle-notch w-8 h-8 text-purple-500" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-full text-red-500 dark:text-red-400">
|
||||
<div className="i-ph:warning w-8 h-8 mb-2" />
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
{serviceStatuses.map((service) => (
|
||||
<div
|
||||
key={service.provider}
|
||||
className="p-4 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700"
|
||||
>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">{service.provider}</h3>
|
||||
<div className={`flex items-center ${getStatusColor(service.status)}`}>
|
||||
<div className={`${getStatusIcon(service.status)} w-5 h-5 mr-2`} />
|
||||
<span className="capitalize">{service.status}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-gray-600 dark:text-gray-300 mb-2">{service.message}</p>
|
||||
{service.incidents && service.incidents.length > 0 && (
|
||||
<div className="mt-2">
|
||||
<h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-1">Recent Incidents:</h4>
|
||||
<ul className="text-sm text-gray-600 dark:text-gray-400 space-y-1">
|
||||
{service.incidents.map((incident, index) => (
|
||||
<li key={index}>{incident}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-2 text-xs text-gray-500 dark:text-gray-400">
|
||||
Last checked: {new Date(service.lastChecked).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { ProviderConfig, StatusCheckResult, ApiResponse } from './types';
|
||||
|
||||
export abstract class BaseProviderChecker {
|
||||
protected config: ProviderConfig;
|
||||
|
||||
constructor(config: ProviderConfig) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
protected async checkApiEndpoint(
|
||||
url: string,
|
||||
headers?: Record<string, string>,
|
||||
testModel?: string,
|
||||
): Promise<{ ok: boolean; status: number | string; message?: string; responseTime: number }> {
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 10000);
|
||||
|
||||
const startTime = performance.now();
|
||||
|
||||
// Add common headers
|
||||
const processedHeaders = {
|
||||
'Content-Type': 'application/json',
|
||||
...headers,
|
||||
};
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: processedHeaders,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
const endTime = performance.now();
|
||||
const responseTime = endTime - startTime;
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
const data = (await response.json()) as ApiResponse;
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = `API returned status: ${response.status}`;
|
||||
|
||||
if (data.error?.message) {
|
||||
errorMessage = data.error.message;
|
||||
} else if (data.message) {
|
||||
errorMessage = data.message;
|
||||
}
|
||||
|
||||
return {
|
||||
ok: false,
|
||||
status: response.status,
|
||||
message: errorMessage,
|
||||
responseTime,
|
||||
};
|
||||
}
|
||||
|
||||
// Different providers have different model list formats
|
||||
let models: string[] = [];
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
models = data.map((model: { id?: string; name?: string }) => model.id || model.name || '');
|
||||
} else if (data.data && Array.isArray(data.data)) {
|
||||
models = data.data.map((model) => model.id || model.name || '');
|
||||
} else if (data.models && Array.isArray(data.models)) {
|
||||
models = data.models.map((model) => model.id || model.name || '');
|
||||
} else if (data.model) {
|
||||
models = [data.model];
|
||||
}
|
||||
|
||||
if (!testModel || models.length > 0) {
|
||||
return {
|
||||
ok: true,
|
||||
status: response.status,
|
||||
responseTime,
|
||||
message: 'API key is valid',
|
||||
};
|
||||
}
|
||||
|
||||
if (testModel && !models.includes(testModel)) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 'model_not_found',
|
||||
message: `API key is valid (test model ${testModel} not found in ${models.length} available models)`,
|
||||
responseTime,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
status: response.status,
|
||||
message: 'API key is valid',
|
||||
responseTime,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`Error checking API endpoint ${url}:`, error);
|
||||
return {
|
||||
ok: false,
|
||||
status: error instanceof Error ? error.message : 'Unknown error',
|
||||
message: error instanceof Error ? `Connection failed: ${error.message}` : 'Connection failed',
|
||||
responseTime: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
protected async checkEndpoint(url: string): Promise<'reachable' | 'unreachable'> {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
mode: 'no-cors',
|
||||
headers: {
|
||||
Accept: 'text/html',
|
||||
},
|
||||
});
|
||||
return response.type === 'opaque' ? 'reachable' : 'unreachable';
|
||||
} catch (error) {
|
||||
console.error(`Error checking ${url}:`, error);
|
||||
return 'unreachable';
|
||||
}
|
||||
}
|
||||
|
||||
abstract checkStatus(): Promise<StatusCheckResult>;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import type { ProviderName, ProviderConfig, StatusCheckResult } from './types';
|
||||
import { BaseProviderChecker } from './base-provider';
|
||||
|
||||
import { AmazonBedrockStatusChecker } from './providers/amazon-bedrock';
|
||||
import { CohereStatusChecker } from './providers/cohere';
|
||||
import { DeepseekStatusChecker } from './providers/deepseek';
|
||||
import { GoogleStatusChecker } from './providers/google';
|
||||
import { GroqStatusChecker } from './providers/groq';
|
||||
import { HuggingFaceStatusChecker } from './providers/huggingface';
|
||||
import { HyperbolicStatusChecker } from './providers/hyperbolic';
|
||||
import { MistralStatusChecker } from './providers/mistral';
|
||||
import { OpenRouterStatusChecker } from './providers/openrouter';
|
||||
import { PerplexityStatusChecker } from './providers/perplexity';
|
||||
import { TogetherStatusChecker } from './providers/together';
|
||||
import { XAIStatusChecker } from './providers/xai';
|
||||
|
||||
export class ProviderStatusCheckerFactory {
|
||||
private static _providerConfigs: Record<ProviderName, ProviderConfig> = {
|
||||
AmazonBedrock: {
|
||||
statusUrl: 'https://health.aws.amazon.com/health/status',
|
||||
apiUrl: 'https://bedrock.us-east-1.amazonaws.com/models',
|
||||
headers: {},
|
||||
testModel: 'anthropic.claude-3-sonnet-20240229-v1:0',
|
||||
},
|
||||
Cohere: {
|
||||
statusUrl: 'https://status.cohere.com/',
|
||||
apiUrl: 'https://api.cohere.ai/v1/models',
|
||||
headers: {},
|
||||
testModel: 'command',
|
||||
},
|
||||
Deepseek: {
|
||||
statusUrl: 'https://status.deepseek.com/',
|
||||
apiUrl: 'https://api.deepseek.com/v1/models',
|
||||
headers: {},
|
||||
testModel: 'deepseek-chat',
|
||||
},
|
||||
Google: {
|
||||
statusUrl: 'https://status.cloud.google.com/',
|
||||
apiUrl: 'https://generativelanguage.googleapis.com/v1/models',
|
||||
headers: {},
|
||||
testModel: 'gemini-pro',
|
||||
},
|
||||
Groq: {
|
||||
statusUrl: 'https://groqstatus.com/',
|
||||
apiUrl: 'https://api.groq.com/v1/models',
|
||||
headers: {},
|
||||
testModel: 'mixtral-8x7b-32768',
|
||||
},
|
||||
HuggingFace: {
|
||||
statusUrl: 'https://status.huggingface.co/',
|
||||
apiUrl: 'https://api-inference.huggingface.co/models',
|
||||
headers: {},
|
||||
testModel: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
|
||||
},
|
||||
Hyperbolic: {
|
||||
statusUrl: 'https://status.hyperbolic.ai/',
|
||||
apiUrl: 'https://api.hyperbolic.ai/v1/models',
|
||||
headers: {},
|
||||
testModel: 'hyperbolic-1',
|
||||
},
|
||||
Mistral: {
|
||||
statusUrl: 'https://status.mistral.ai/',
|
||||
apiUrl: 'https://api.mistral.ai/v1/models',
|
||||
headers: {},
|
||||
testModel: 'mistral-tiny',
|
||||
},
|
||||
OpenRouter: {
|
||||
statusUrl: 'https://status.openrouter.ai/',
|
||||
apiUrl: 'https://openrouter.ai/api/v1/models',
|
||||
headers: {},
|
||||
testModel: 'anthropic/claude-3-sonnet',
|
||||
},
|
||||
Perplexity: {
|
||||
statusUrl: 'https://status.perplexity.com/',
|
||||
apiUrl: 'https://api.perplexity.ai/v1/models',
|
||||
headers: {},
|
||||
testModel: 'pplx-7b-chat',
|
||||
},
|
||||
Together: {
|
||||
statusUrl: 'https://status.together.ai/',
|
||||
apiUrl: 'https://api.together.xyz/v1/models',
|
||||
headers: {},
|
||||
testModel: 'mistralai/Mixtral-8x7B-Instruct-v0.1',
|
||||
},
|
||||
XAI: {
|
||||
statusUrl: 'https://status.x.ai/',
|
||||
apiUrl: 'https://api.x.ai/v1/models',
|
||||
headers: {},
|
||||
testModel: 'grok-1',
|
||||
},
|
||||
};
|
||||
|
||||
static getChecker(provider: ProviderName): BaseProviderChecker {
|
||||
const config = this._providerConfigs[provider];
|
||||
|
||||
if (!config) {
|
||||
throw new Error(`No configuration found for provider: ${provider}`);
|
||||
}
|
||||
|
||||
switch (provider) {
|
||||
case 'AmazonBedrock':
|
||||
return new AmazonBedrockStatusChecker(config);
|
||||
case 'Cohere':
|
||||
return new CohereStatusChecker(config);
|
||||
case 'Deepseek':
|
||||
return new DeepseekStatusChecker(config);
|
||||
case 'Google':
|
||||
return new GoogleStatusChecker(config);
|
||||
case 'Groq':
|
||||
return new GroqStatusChecker(config);
|
||||
case 'HuggingFace':
|
||||
return new HuggingFaceStatusChecker(config);
|
||||
case 'Hyperbolic':
|
||||
return new HyperbolicStatusChecker(config);
|
||||
case 'Mistral':
|
||||
return new MistralStatusChecker(config);
|
||||
case 'OpenRouter':
|
||||
return new OpenRouterStatusChecker(config);
|
||||
case 'Perplexity':
|
||||
return new PerplexityStatusChecker(config);
|
||||
case 'Together':
|
||||
return new TogetherStatusChecker(config);
|
||||
case 'XAI':
|
||||
return new XAIStatusChecker(config);
|
||||
default:
|
||||
return new (class extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
const endpointStatus = await this.checkEndpoint(this.config.statusUrl);
|
||||
const apiStatus = await this.checkEndpoint(this.config.apiUrl);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
})(config);
|
||||
}
|
||||
}
|
||||
|
||||
static getProviderNames(): ProviderName[] {
|
||||
return Object.keys(this._providerConfigs) as ProviderName[];
|
||||
}
|
||||
|
||||
static getProviderConfig(provider: ProviderName): ProviderConfig {
|
||||
const config = this._providerConfigs[provider];
|
||||
|
||||
if (!config) {
|
||||
throw new Error(`Unknown provider: ${provider}`);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class AmazonBedrockStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
// Check AWS health status page
|
||||
const statusPageResponse = await fetch('https://health.aws.amazon.com/health/status');
|
||||
const text = await statusPageResponse.text();
|
||||
|
||||
// Check for Bedrock and general AWS status
|
||||
const hasBedrockIssues =
|
||||
text.includes('Amazon Bedrock') &&
|
||||
(text.includes('Service is experiencing elevated error rates') ||
|
||||
text.includes('Service disruption') ||
|
||||
text.includes('Degraded Service'));
|
||||
|
||||
const hasGeneralIssues = text.includes('Service disruption') || text.includes('Multiple services affected');
|
||||
|
||||
// Extract incidents
|
||||
const incidents: string[] = [];
|
||||
const incidentMatches = text.matchAll(/(\d{4}-\d{2}-\d{2})\s+(.*?)\s+Impact:(.*?)(?=\n|$)/g);
|
||||
|
||||
for (const match of incidentMatches) {
|
||||
const [, date, title, impact] = match;
|
||||
|
||||
if (title.includes('Bedrock') || title.includes('AWS')) {
|
||||
incidents.push(`${date}: ${title.trim()} - Impact: ${impact.trim()}`);
|
||||
}
|
||||
}
|
||||
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
let message = 'All services operational';
|
||||
|
||||
if (hasBedrockIssues) {
|
||||
status = 'degraded';
|
||||
message = 'Amazon Bedrock service issues reported';
|
||||
} else if (hasGeneralIssues) {
|
||||
status = 'degraded';
|
||||
message = 'AWS experiencing general issues';
|
||||
}
|
||||
|
||||
// If status page check fails, fallback to endpoint check
|
||||
if (!statusPageResponse.ok) {
|
||||
const endpointStatus = await this.checkEndpoint('https://health.aws.amazon.com/health/status');
|
||||
const apiEndpoint = 'https://bedrock.us-east-1.amazonaws.com/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
incidents: incidents.slice(0, 5),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking Amazon Bedrock status:', error);
|
||||
|
||||
// Fallback to basic endpoint check
|
||||
const endpointStatus = await this.checkEndpoint('https://health.aws.amazon.com/health/status');
|
||||
const apiEndpoint = 'https://bedrock.us-east-1.amazonaws.com/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class AnthropicStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
// Check status page
|
||||
const statusPageResponse = await fetch('https://status.anthropic.com/');
|
||||
const text = await statusPageResponse.text();
|
||||
|
||||
// Check for specific Anthropic status indicators
|
||||
const isOperational = text.includes('All Systems Operational');
|
||||
const hasDegradedPerformance = text.includes('Degraded Performance');
|
||||
const hasPartialOutage = text.includes('Partial Outage');
|
||||
const hasMajorOutage = text.includes('Major Outage');
|
||||
|
||||
// Extract incidents
|
||||
const incidents: string[] = [];
|
||||
const incidentSection = text.match(/Past Incidents(.*?)(?=\n\n)/s);
|
||||
|
||||
if (incidentSection) {
|
||||
const incidentLines = incidentSection[1]
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && line.includes('202')); // Only get dated incidents
|
||||
|
||||
incidents.push(...incidentLines.slice(0, 5));
|
||||
}
|
||||
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
let message = 'All systems operational';
|
||||
|
||||
if (hasMajorOutage) {
|
||||
status = 'down';
|
||||
message = 'Major service outage';
|
||||
} else if (hasPartialOutage) {
|
||||
status = 'down';
|
||||
message = 'Partial service outage';
|
||||
} else if (hasDegradedPerformance) {
|
||||
status = 'degraded';
|
||||
message = 'Service experiencing degraded performance';
|
||||
} else if (!isOperational) {
|
||||
status = 'degraded';
|
||||
message = 'Service status unknown';
|
||||
}
|
||||
|
||||
// If status page check fails, fallback to endpoint check
|
||||
if (!statusPageResponse.ok) {
|
||||
const endpointStatus = await this.checkEndpoint('https://status.anthropic.com/');
|
||||
const apiEndpoint = 'https://api.anthropic.com/v1/messages';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
incidents,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking Anthropic status:', error);
|
||||
|
||||
// Fallback to basic endpoint check
|
||||
const endpointStatus = await this.checkEndpoint('https://status.anthropic.com/');
|
||||
const apiEndpoint = 'https://api.anthropic.com/v1/messages';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class CohereStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
// Check status page
|
||||
const statusPageResponse = await fetch('https://status.cohere.com/');
|
||||
const text = await statusPageResponse.text();
|
||||
|
||||
// Check for specific Cohere status indicators
|
||||
const isOperational = text.includes('All Systems Operational');
|
||||
const hasIncidents = text.includes('Active Incidents');
|
||||
const hasDegradation = text.includes('Degraded Performance');
|
||||
const hasOutage = text.includes('Service Outage');
|
||||
|
||||
// Extract incidents
|
||||
const incidents: string[] = [];
|
||||
const incidentSection = text.match(/Past Incidents(.*?)(?=\n\n)/s);
|
||||
|
||||
if (incidentSection) {
|
||||
const incidentLines = incidentSection[1]
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && line.includes('202')); // Only get dated incidents
|
||||
|
||||
incidents.push(...incidentLines.slice(0, 5));
|
||||
}
|
||||
|
||||
// Check specific services
|
||||
const services = {
|
||||
api: {
|
||||
operational: text.includes('API Service') && text.includes('Operational'),
|
||||
degraded: text.includes('API Service') && text.includes('Degraded Performance'),
|
||||
outage: text.includes('API Service') && text.includes('Service Outage'),
|
||||
},
|
||||
generation: {
|
||||
operational: text.includes('Generation Service') && text.includes('Operational'),
|
||||
degraded: text.includes('Generation Service') && text.includes('Degraded Performance'),
|
||||
outage: text.includes('Generation Service') && text.includes('Service Outage'),
|
||||
},
|
||||
};
|
||||
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
let message = 'All systems operational';
|
||||
|
||||
if (services.api.outage || services.generation.outage || hasOutage) {
|
||||
status = 'down';
|
||||
message = 'Service outage detected';
|
||||
} else if (services.api.degraded || services.generation.degraded || hasDegradation || hasIncidents) {
|
||||
status = 'degraded';
|
||||
message = 'Service experiencing issues';
|
||||
} else if (!isOperational) {
|
||||
status = 'degraded';
|
||||
message = 'Service status unknown';
|
||||
}
|
||||
|
||||
// If status page check fails, fallback to endpoint check
|
||||
if (!statusPageResponse.ok) {
|
||||
const endpointStatus = await this.checkEndpoint('https://status.cohere.com/');
|
||||
const apiEndpoint = 'https://api.cohere.ai/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
incidents,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking Cohere status:', error);
|
||||
|
||||
// Fallback to basic endpoint check
|
||||
const endpointStatus = await this.checkEndpoint('https://status.cohere.com/');
|
||||
const apiEndpoint = 'https://api.cohere.ai/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class DeepseekStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
/*
|
||||
* Check status page - Note: Deepseek doesn't have a public status page yet
|
||||
* so we'll check their API endpoint directly
|
||||
*/
|
||||
const apiEndpoint = 'https://api.deepseek.com/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
// Check their website as a secondary indicator
|
||||
const websiteStatus = await this.checkEndpoint('https://deepseek.com');
|
||||
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
let message = 'All systems operational';
|
||||
|
||||
if (apiStatus !== 'reachable' || websiteStatus !== 'reachable') {
|
||||
status = apiStatus !== 'reachable' ? 'down' : 'degraded';
|
||||
message = apiStatus !== 'reachable' ? 'API appears to be down' : 'Service may be experiencing issues';
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
incidents: [], // No public incident tracking available yet
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking Deepseek status:', error);
|
||||
|
||||
return {
|
||||
status: 'degraded',
|
||||
message: 'Unable to determine service status',
|
||||
incidents: ['Note: Limited status information available'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class GoogleStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
// Check status page
|
||||
const statusPageResponse = await fetch('https://status.cloud.google.com/');
|
||||
const text = await statusPageResponse.text();
|
||||
|
||||
// Check for Vertex AI and general cloud status
|
||||
const hasVertexAIIssues =
|
||||
text.includes('Vertex AI') &&
|
||||
(text.includes('Incident') ||
|
||||
text.includes('Disruption') ||
|
||||
text.includes('Outage') ||
|
||||
text.includes('degraded'));
|
||||
|
||||
const hasGeneralIssues = text.includes('Major Incidents') || text.includes('Service Disruption');
|
||||
|
||||
// Extract incidents
|
||||
const incidents: string[] = [];
|
||||
const incidentMatches = text.matchAll(/(\d{4}-\d{2}-\d{2})\s+(.*?)\s+Impact:(.*?)(?=\n|$)/g);
|
||||
|
||||
for (const match of incidentMatches) {
|
||||
const [, date, title, impact] = match;
|
||||
|
||||
if (title.includes('Vertex AI') || title.includes('Cloud')) {
|
||||
incidents.push(`${date}: ${title.trim()} - Impact: ${impact.trim()}`);
|
||||
}
|
||||
}
|
||||
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
let message = 'All services operational';
|
||||
|
||||
if (hasVertexAIIssues) {
|
||||
status = 'degraded';
|
||||
message = 'Vertex AI service issues reported';
|
||||
} else if (hasGeneralIssues) {
|
||||
status = 'degraded';
|
||||
message = 'Google Cloud experiencing issues';
|
||||
}
|
||||
|
||||
// If status page check fails, fallback to endpoint check
|
||||
if (!statusPageResponse.ok) {
|
||||
const endpointStatus = await this.checkEndpoint('https://status.cloud.google.com/');
|
||||
const apiEndpoint = 'https://generativelanguage.googleapis.com/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
incidents: incidents.slice(0, 5),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking Google status:', error);
|
||||
|
||||
// Fallback to basic endpoint check
|
||||
const endpointStatus = await this.checkEndpoint('https://status.cloud.google.com/');
|
||||
const apiEndpoint = 'https://generativelanguage.googleapis.com/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class GroqStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
// Check status page
|
||||
const statusPageResponse = await fetch('https://groqstatus.com/');
|
||||
const text = await statusPageResponse.text();
|
||||
|
||||
const isOperational = text.includes('All Systems Operational');
|
||||
const hasIncidents = text.includes('Active Incidents');
|
||||
const hasDegradation = text.includes('Degraded Performance');
|
||||
const hasOutage = text.includes('Service Outage');
|
||||
|
||||
// Extract incidents
|
||||
const incidents: string[] = [];
|
||||
const incidentMatches = text.matchAll(/(\d{4}-\d{2}-\d{2})\s+(.*?)\s+Status:(.*?)(?=\n|$)/g);
|
||||
|
||||
for (const match of incidentMatches) {
|
||||
const [, date, title, status] = match;
|
||||
incidents.push(`${date}: ${title.trim()} - ${status.trim()}`);
|
||||
}
|
||||
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
let message = 'All systems operational';
|
||||
|
||||
if (hasOutage) {
|
||||
status = 'down';
|
||||
message = 'Service outage detected';
|
||||
} else if (hasDegradation || hasIncidents) {
|
||||
status = 'degraded';
|
||||
message = 'Service experiencing issues';
|
||||
} else if (!isOperational) {
|
||||
status = 'degraded';
|
||||
message = 'Service status unknown';
|
||||
}
|
||||
|
||||
// If status page check fails, fallback to endpoint check
|
||||
if (!statusPageResponse.ok) {
|
||||
const endpointStatus = await this.checkEndpoint('https://groqstatus.com/');
|
||||
const apiEndpoint = 'https://api.groq.com/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
incidents: incidents.slice(0, 5),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking Groq status:', error);
|
||||
|
||||
// Fallback to basic endpoint check
|
||||
const endpointStatus = await this.checkEndpoint('https://groqstatus.com/');
|
||||
const apiEndpoint = 'https://api.groq.com/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class HuggingFaceStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
// Check status page
|
||||
const statusPageResponse = await fetch('https://status.huggingface.co/');
|
||||
const text = await statusPageResponse.text();
|
||||
|
||||
// Check for "All services are online" message
|
||||
const allServicesOnline = text.includes('All services are online');
|
||||
|
||||
// Get last update time
|
||||
const lastUpdateMatch = text.match(/Last updated on (.*?)(EST|PST|GMT)/);
|
||||
const lastUpdate = lastUpdateMatch ? `${lastUpdateMatch[1]}${lastUpdateMatch[2]}` : '';
|
||||
|
||||
// Check individual services and their uptime percentages
|
||||
const services = {
|
||||
'Huggingface Hub': {
|
||||
operational: text.includes('Huggingface Hub') && text.includes('Operational'),
|
||||
uptime: text.match(/Huggingface Hub[\s\S]*?(\d+\.\d+)%\s*uptime/)?.[1],
|
||||
},
|
||||
'Git Hosting and Serving': {
|
||||
operational: text.includes('Git Hosting and Serving') && text.includes('Operational'),
|
||||
uptime: text.match(/Git Hosting and Serving[\s\S]*?(\d+\.\d+)%\s*uptime/)?.[1],
|
||||
},
|
||||
'Inference API': {
|
||||
operational: text.includes('Inference API') && text.includes('Operational'),
|
||||
uptime: text.match(/Inference API[\s\S]*?(\d+\.\d+)%\s*uptime/)?.[1],
|
||||
},
|
||||
'HF Endpoints': {
|
||||
operational: text.includes('HF Endpoints') && text.includes('Operational'),
|
||||
uptime: text.match(/HF Endpoints[\s\S]*?(\d+\.\d+)%\s*uptime/)?.[1],
|
||||
},
|
||||
Spaces: {
|
||||
operational: text.includes('Spaces') && text.includes('Operational'),
|
||||
uptime: text.match(/Spaces[\s\S]*?(\d+\.\d+)%\s*uptime/)?.[1],
|
||||
},
|
||||
};
|
||||
|
||||
// Create service status messages with uptime
|
||||
const serviceMessages = Object.entries(services).map(([name, info]) => {
|
||||
if (info.uptime) {
|
||||
return `${name}: ${info.uptime}% uptime`;
|
||||
}
|
||||
|
||||
return `${name}: ${info.operational ? 'Operational' : 'Issues detected'}`;
|
||||
});
|
||||
|
||||
// Determine overall status
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
let message = allServicesOnline
|
||||
? `All services are online (Last updated on ${lastUpdate})`
|
||||
: 'Checking individual services';
|
||||
|
||||
// Only mark as degraded if we explicitly detect issues
|
||||
const hasIssues = Object.values(services).some((service) => !service.operational);
|
||||
|
||||
if (hasIssues) {
|
||||
status = 'degraded';
|
||||
message = `Service issues detected (Last updated on ${lastUpdate})`;
|
||||
}
|
||||
|
||||
// If status page check fails, fallback to endpoint check
|
||||
if (!statusPageResponse.ok) {
|
||||
const endpointStatus = await this.checkEndpoint('https://status.huggingface.co/');
|
||||
const apiEndpoint = 'https://api-inference.huggingface.co/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
incidents: serviceMessages,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking HuggingFace status:', error);
|
||||
|
||||
// Fallback to basic endpoint check
|
||||
const endpointStatus = await this.checkEndpoint('https://status.huggingface.co/');
|
||||
const apiEndpoint = 'https://api-inference.huggingface.co/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class HyperbolicStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
/*
|
||||
* Check API endpoint directly since Hyperbolic is a newer provider
|
||||
* and may not have a public status page yet
|
||||
*/
|
||||
const apiEndpoint = 'https://api.hyperbolic.ai/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
// Check their website as a secondary indicator
|
||||
const websiteStatus = await this.checkEndpoint('https://hyperbolic.ai');
|
||||
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
let message = 'All systems operational';
|
||||
|
||||
if (apiStatus !== 'reachable' || websiteStatus !== 'reachable') {
|
||||
status = apiStatus !== 'reachable' ? 'down' : 'degraded';
|
||||
message = apiStatus !== 'reachable' ? 'API appears to be down' : 'Service may be experiencing issues';
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
incidents: [], // No public incident tracking available yet
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking Hyperbolic status:', error);
|
||||
|
||||
return {
|
||||
status: 'degraded',
|
||||
message: 'Unable to determine service status',
|
||||
incidents: ['Note: Limited status information available'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class MistralStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
// Check status page
|
||||
const statusPageResponse = await fetch('https://status.mistral.ai/');
|
||||
const text = await statusPageResponse.text();
|
||||
|
||||
const isOperational = text.includes('All Systems Operational');
|
||||
const hasIncidents = text.includes('Active Incidents');
|
||||
const hasDegradation = text.includes('Degraded Performance');
|
||||
const hasOutage = text.includes('Service Outage');
|
||||
|
||||
// Extract incidents
|
||||
const incidents: string[] = [];
|
||||
const incidentSection = text.match(/Recent Events(.*?)(?=\n\n)/s);
|
||||
|
||||
if (incidentSection) {
|
||||
const incidentLines = incidentSection[1]
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && !line.includes('No incidents'));
|
||||
|
||||
incidents.push(...incidentLines.slice(0, 5));
|
||||
}
|
||||
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
let message = 'All systems operational';
|
||||
|
||||
if (hasOutage) {
|
||||
status = 'down';
|
||||
message = 'Service outage detected';
|
||||
} else if (hasDegradation || hasIncidents) {
|
||||
status = 'degraded';
|
||||
message = 'Service experiencing issues';
|
||||
} else if (!isOperational) {
|
||||
status = 'degraded';
|
||||
message = 'Service status unknown';
|
||||
}
|
||||
|
||||
// If status page check fails, fallback to endpoint check
|
||||
if (!statusPageResponse.ok) {
|
||||
const endpointStatus = await this.checkEndpoint('https://status.mistral.ai/');
|
||||
const apiEndpoint = 'https://api.mistral.ai/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
incidents,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking Mistral status:', error);
|
||||
|
||||
// Fallback to basic endpoint check
|
||||
const endpointStatus = await this.checkEndpoint('https://status.mistral.ai/');
|
||||
const apiEndpoint = 'https://api.mistral.ai/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class OpenAIStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
// Check status page
|
||||
const statusPageResponse = await fetch('https://status.openai.com/');
|
||||
const text = await statusPageResponse.text();
|
||||
|
||||
// Check individual services
|
||||
const services = {
|
||||
api: {
|
||||
operational: text.includes('API ? Operational'),
|
||||
degraded: text.includes('API ? Degraded Performance'),
|
||||
outage: text.includes('API ? Major Outage') || text.includes('API ? Partial Outage'),
|
||||
},
|
||||
chat: {
|
||||
operational: text.includes('ChatGPT ? Operational'),
|
||||
degraded: text.includes('ChatGPT ? Degraded Performance'),
|
||||
outage: text.includes('ChatGPT ? Major Outage') || text.includes('ChatGPT ? Partial Outage'),
|
||||
},
|
||||
};
|
||||
|
||||
// Extract recent incidents
|
||||
const incidents: string[] = [];
|
||||
const incidentMatches = text.match(/Past Incidents(.*?)(?=\w+ \d+, \d{4})/s);
|
||||
|
||||
if (incidentMatches) {
|
||||
const recentIncidents = incidentMatches[1]
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && line.includes('202')); // Get only dated incidents
|
||||
|
||||
incidents.push(...recentIncidents.slice(0, 5));
|
||||
}
|
||||
|
||||
// Determine overall status
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
const messages: string[] = [];
|
||||
|
||||
if (services.api.outage || services.chat.outage) {
|
||||
status = 'down';
|
||||
|
||||
if (services.api.outage) {
|
||||
messages.push('API: Major Outage');
|
||||
}
|
||||
|
||||
if (services.chat.outage) {
|
||||
messages.push('ChatGPT: Major Outage');
|
||||
}
|
||||
} else if (services.api.degraded || services.chat.degraded) {
|
||||
status = 'degraded';
|
||||
|
||||
if (services.api.degraded) {
|
||||
messages.push('API: Degraded Performance');
|
||||
}
|
||||
|
||||
if (services.chat.degraded) {
|
||||
messages.push('ChatGPT: Degraded Performance');
|
||||
}
|
||||
} else if (services.api.operational) {
|
||||
messages.push('API: Operational');
|
||||
}
|
||||
|
||||
// If status page check fails, fallback to endpoint check
|
||||
if (!statusPageResponse.ok) {
|
||||
const endpointStatus = await this.checkEndpoint('https://status.openai.com/');
|
||||
const apiEndpoint = 'https://api.openai.com/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message: messages.join(', ') || 'Status unknown',
|
||||
incidents,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking OpenAI status:', error);
|
||||
|
||||
// Fallback to basic endpoint check
|
||||
const endpointStatus = await this.checkEndpoint('https://status.openai.com/');
|
||||
const apiEndpoint = 'https://api.openai.com/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class OpenRouterStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
// Check status page
|
||||
const statusPageResponse = await fetch('https://status.openrouter.ai/');
|
||||
const text = await statusPageResponse.text();
|
||||
|
||||
// Check for specific OpenRouter status indicators
|
||||
const isOperational = text.includes('All Systems Operational');
|
||||
const hasIncidents = text.includes('Active Incidents');
|
||||
const hasDegradation = text.includes('Degraded Performance');
|
||||
const hasOutage = text.includes('Service Outage');
|
||||
|
||||
// Extract incidents
|
||||
const incidents: string[] = [];
|
||||
const incidentSection = text.match(/Past Incidents(.*?)(?=\n\n)/s);
|
||||
|
||||
if (incidentSection) {
|
||||
const incidentLines = incidentSection[1]
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && line.includes('202')); // Only get dated incidents
|
||||
|
||||
incidents.push(...incidentLines.slice(0, 5));
|
||||
}
|
||||
|
||||
// Check specific services
|
||||
const services = {
|
||||
api: {
|
||||
operational: text.includes('API Service') && text.includes('Operational'),
|
||||
degraded: text.includes('API Service') && text.includes('Degraded Performance'),
|
||||
outage: text.includes('API Service') && text.includes('Service Outage'),
|
||||
},
|
||||
routing: {
|
||||
operational: text.includes('Routing Service') && text.includes('Operational'),
|
||||
degraded: text.includes('Routing Service') && text.includes('Degraded Performance'),
|
||||
outage: text.includes('Routing Service') && text.includes('Service Outage'),
|
||||
},
|
||||
};
|
||||
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
let message = 'All systems operational';
|
||||
|
||||
if (services.api.outage || services.routing.outage || hasOutage) {
|
||||
status = 'down';
|
||||
message = 'Service outage detected';
|
||||
} else if (services.api.degraded || services.routing.degraded || hasDegradation || hasIncidents) {
|
||||
status = 'degraded';
|
||||
message = 'Service experiencing issues';
|
||||
} else if (!isOperational) {
|
||||
status = 'degraded';
|
||||
message = 'Service status unknown';
|
||||
}
|
||||
|
||||
// If status page check fails, fallback to endpoint check
|
||||
if (!statusPageResponse.ok) {
|
||||
const endpointStatus = await this.checkEndpoint('https://status.openrouter.ai/');
|
||||
const apiEndpoint = 'https://openrouter.ai/api/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
incidents,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking OpenRouter status:', error);
|
||||
|
||||
// Fallback to basic endpoint check
|
||||
const endpointStatus = await this.checkEndpoint('https://status.openrouter.ai/');
|
||||
const apiEndpoint = 'https://openrouter.ai/api/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { BaseProviderChecker } from '~/components/@settings/tabs/providers/service-status/base-provider';
|
||||
import type { StatusCheckResult } from '~/components/@settings/tabs/providers/service-status/types';
|
||||
|
||||
export class PerplexityStatusChecker extends BaseProviderChecker {
|
||||
async checkStatus(): Promise<StatusCheckResult> {
|
||||
try {
|
||||
// Check status page
|
||||
const statusPageResponse = await fetch('https://status.perplexity.ai/');
|
||||
const text = await statusPageResponse.text();
|
||||
|
||||
// Check for specific Perplexity status indicators
|
||||
const isOperational = text.includes('All Systems Operational');
|
||||
const hasIncidents = text.includes('Active Incidents');
|
||||
const hasDegradation = text.includes('Degraded Performance');
|
||||
const hasOutage = text.includes('Service Outage');
|
||||
|
||||
// Extract incidents
|
||||
const incidents: string[] = [];
|
||||
const incidentSection = text.match(/Past Incidents(.*?)(?=\n\n)/s);
|
||||
|
||||
if (incidentSection) {
|
||||
const incidentLines = incidentSection[1]
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && line.includes('202')); // Only get dated incidents
|
||||
|
||||
incidents.push(...incidentLines.slice(0, 5));
|
||||
}
|
||||
|
||||
// Check specific services
|
||||
const services = {
|
||||
api: {
|
||||
operational: text.includes('API Service') && text.includes('Operational'),
|
||||
degraded: text.includes('API Service') && text.includes('Degraded Performance'),
|
||||
outage: text.includes('API Service') && text.includes('Service Outage'),
|
||||
},
|
||||
inference: {
|
||||
operational: text.includes('Inference Service') && text.includes('Operational'),
|
||||
degraded: text.includes('Inference Service') && text.includes('Degraded Performance'),
|
||||
outage: text.includes('Inference Service') && text.includes('Service Outage'),
|
||||
},
|
||||
};
|
||||
|
||||
let status: StatusCheckResult['status'] = 'operational';
|
||||
let message = 'All systems operational';
|
||||
|
||||
if (services.api.outage || services.inference.outage || hasOutage) {
|
||||
status = 'down';
|
||||
message = 'Service outage detected';
|
||||
} else if (services.api.degraded || services.inference.degraded || hasDegradation || hasIncidents) {
|
||||
status = 'degraded';
|
||||
message = 'Service experiencing issues';
|
||||
} else if (!isOperational) {
|
||||
status = 'degraded';
|
||||
message = 'Service status unknown';
|
||||
}
|
||||
|
||||
// If status page check fails, fallback to endpoint check
|
||||
if (!statusPageResponse.ok) {
|
||||
const endpointStatus = await this.checkEndpoint('https://status.perplexity.ai/');
|
||||
const apiEndpoint = 'https://api.perplexity.ai/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
message,
|
||||
incidents,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking Perplexity status:', error);
|
||||
|
||||
// Fallback to basic endpoint check
|
||||
const endpointStatus = await this.checkEndpoint('https://status.perplexity.ai/');
|
||||
const apiEndpoint = 'https://api.perplexity.ai/v1/models';
|
||||
const apiStatus = await this.checkEndpoint(apiEndpoint);
|
||||
|
||||
return {
|
||||
status: endpointStatus === 'reachable' && apiStatus === 'reachable' ? 'operational' : 'degraded',
|
||||
message: `Status page: ${endpointStatus}, API: ${apiStatus}`,
|
||||
incidents: ['Note: Limited status information due to CORS restrictions'],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user