diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000..2f8f89bc3d --- /dev/null +++ b/.dockerignore @@ -0,0 +1,26 @@ +# Ignore Git and GitHub files +.git +.github/ + +# Ignore Husky configuration files +.husky/ + +# Ignore documentation and metadata files +CONTRIBUTING.md +LICENSE +README.md + +# Ignore environment examples and sensitive info +.env +*.local +*.example + +# Ignore node modules, logs and cache files +**/*.log +**/node_modules +**/dist +**/build +**/.cache +logs +dist-ssr +.DS_Store diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000..3c7840a9b4 --- /dev/null +++ b/.env.example @@ -0,0 +1,122 @@ +# 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 +#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= + +# 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 +# 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= + +# Include this environment variable if you want more logging for debugging locally +VITE_LOG_LEVEL=debug + +# 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=classic + +# 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= diff --git a/.env.production b/.env.production new file mode 100644 index 0000000000..8fe4367a0e --- /dev/null +++ b/.env.production @@ -0,0 +1,115 @@ +# 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= + +# Netlify Authentication +VITE_NETLIFY_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= \ No newline at end of file diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000000..3f4eb97dd2 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,15 @@ +{ + "env": { + "browser": true, + "es2021": true + }, + "extends": [ + "eslint:recommended", + "plugin:prettier/recommended" + ], + "rules": { + // example: turn off console warnings + "no-console": "off" + } + } + \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index a594bc8724..5c8c6ad70d 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,4 +1,4 @@ -name: "Bug report" +name: 'Bug report' description: Create a report to help us improve body: - type: markdown @@ -6,8 +6,8 @@ body: value: | Thank you for reporting an issue :pray:. - This issue tracker is for bugs and issues found with [Bolt.new](https://bolt.new). - If you experience issues related to WebContainer, please file an issue in our [WebContainer repo](https://github.com/stackblitz/webcontainer-core), or file an issue in our [StackBlitz core repo](https://github.com/stackblitz/core) for issues with StackBlitz. + This issue tracker is for bugs and issues found with [Bolt.diy](https://bolt.diy). + If you experience issues related to WebContainer, please file an issue in the official [StackBlitz WebContainer repo](https://github.com/stackblitz/webcontainer-core). The more information you fill in, the better we can help you. - type: textarea @@ -56,6 +56,16 @@ body: - OS: [e.g. macOS, Windows, Linux] - Browser: [e.g. Chrome, Safari, Firefox] - Version: [e.g. 91.1] + - type: input + id: provider + attributes: + label: Provider Used + description: Tell us the provider you are using. + - type: input + id: model + attributes: + label: Model Used + description: Tell us the model you are using. - type: textarea id: additional attributes: diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000..1fbea24a6b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Bolt.new related issues + url: https://github.com/stackblitz/bolt.new/issues/new/choose + about: Report issues related to Bolt.new (not Bolt.diy) + - name: Chat + url: https://thinktank.ottomator.ai + about: Ask questions and discuss with other Bolt.diy users. diff --git a/.github/ISSUE_TEMPLATE/epic.md b/.github/ISSUE_TEMPLATE/epic.md new file mode 100644 index 0000000000..e75eca0113 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/epic.md @@ -0,0 +1,23 @@ +--- +name: Epic +about: Epics define long-term vision and capabilities of the software. They will never be finished but serve as umbrella for features. +title: '' +labels: + - epic +assignees: '' +--- + +# Strategic Impact + + + +# Target Audience + + + +# Capabilities + + diff --git a/.github/ISSUE_TEMPLATE/feature.md b/.github/ISSUE_TEMPLATE/feature.md new file mode 100644 index 0000000000..3869b4d330 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.md @@ -0,0 +1,28 @@ +--- +name: Feature +about: A pretty vague description of how a capability of our software can be added or improved. +title: '' +labels: + - feature +assignees: '' +--- + +# Motivation + + + +# Scope + + + +# Options + + + +# Related + + diff --git a/.github/scripts/generate-changelog.sh b/.github/scripts/generate-changelog.sh new file mode 100755 index 0000000000..e6300128b0 --- /dev/null +++ b/.github/scripts/generate-changelog.sh @@ -0,0 +1,261 @@ +#!/usr/bin/env bash + +# Ensure we're running in bash +if [ -z "$BASH_VERSION" ]; then + echo "This script requires bash. Please run with: bash $0" >&2 + exit 1 +fi + +# Ensure we're using bash 4.0 or later for associative arrays +if ((BASH_VERSINFO[0] < 4)); then + echo "This script requires bash version 4 or later" >&2 + echo "Current bash version: $BASH_VERSION" >&2 + exit 1 +fi + +# Set default values for required environment variables if not in GitHub Actions +if [ -z "$GITHUB_ACTIONS" ]; then + : "${GITHUB_SERVER_URL:=https://github.com}" + : "${GITHUB_REPOSITORY:=stackblitz-labs/bolt.diy}" + : "${GITHUB_OUTPUT:=/tmp/github_output}" + touch "$GITHUB_OUTPUT" + + # Running locally + echo "Running locally - checking for upstream remote..." + MAIN_REMOTE="origin" + if git remote -v | grep -q "upstream"; then + MAIN_REMOTE="upstream" + fi + MAIN_BRANCH="main" # or "master" depending on your repository + + # Ensure we have latest tags + git fetch ${MAIN_REMOTE} --tags + + # Use the remote reference for git log + GITLOG_REF="${MAIN_REMOTE}/${MAIN_BRANCH}" +else + # Running in GitHub Actions + GITLOG_REF="HEAD" +fi + +# Get the latest tag +LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "") + +# Start changelog file +echo "# πŸš€ Release v${NEW_VERSION}" > changelog.md +echo "" >> changelog.md +echo "## What's Changed 🌟" >> changelog.md +echo "" >> changelog.md + +if [ -z "$LATEST_TAG" ]; then + echo "### πŸŽ‰ First Release" >> changelog.md + echo "" >> changelog.md + echo "Exciting times! This marks our first release. Thanks to everyone who contributed! πŸ™Œ" >> changelog.md + echo "" >> changelog.md + COMPARE_BASE="$(git rev-list --max-parents=0 HEAD)" +else + echo "### πŸ”„ Changes since $LATEST_TAG" >> changelog.md + echo "" >> changelog.md + COMPARE_BASE="$LATEST_TAG" +fi + +# Function to extract conventional commit type and associated emoji +get_commit_type() { + local msg="$1" + if [[ $msg =~ ^feat(\(.+\))?:|^feature(\(.+\))?: ]]; then echo "✨ Features" + elif [[ $msg =~ ^fix(\(.+\))?: ]]; then echo "πŸ› Bug Fixes" + elif [[ $msg =~ ^docs(\(.+\))?: ]]; then echo "πŸ“š Documentation" + elif [[ $msg =~ ^style(\(.+\))?: ]]; then echo "πŸ’Ž Styles" + elif [[ $msg =~ ^refactor(\(.+\))?: ]]; then echo "♻️ Code Refactoring" + elif [[ $msg =~ ^perf(\(.+\))?: ]]; then echo "⚑ Performance Improvements" + elif [[ $msg =~ ^test(\(.+\))?: ]]; then echo "πŸ§ͺ Tests" + elif [[ $msg =~ ^build(\(.+\))?: ]]; then echo "πŸ› οΈ Build System" + elif [[ $msg =~ ^ci(\(.+\))?: ]]; then echo "βš™οΈ CI" + elif [[ $msg =~ ^chore(\(.+\))?: ]]; then echo "" # Skip chore commits + else echo "πŸ” Other Changes" # Default category with emoji + fi +} + +# Initialize associative arrays +declare -A CATEGORIES +declare -A COMMITS_BY_CATEGORY +declare -A ALL_AUTHORS +declare -A NEW_CONTRIBUTORS + +# Get all historical authors before the compare base +while IFS= read -r author; do + ALL_AUTHORS["$author"]=1 +done < <(git log "${COMPARE_BASE}" --pretty=format:"%ae" | sort -u) + +# Process all commits since last tag +while IFS= read -r commit_line; do + if [[ ! $commit_line =~ ^[a-f0-9]+\| ]]; then + echo "WARNING: Skipping invalid commit line format: $commit_line" >&2 + continue + fi + + HASH=$(echo "$commit_line" | cut -d'|' -f1) + COMMIT_MSG=$(echo "$commit_line" | cut -d'|' -f2) + BODY=$(echo "$commit_line" | cut -d'|' -f3) + # Skip if hash doesn't match the expected format + if [[ ! $HASH =~ ^[a-f0-9]{40}$ ]]; then + continue + fi + + HASH=$(echo "$commit_line" | cut -d'|' -f1) + COMMIT_MSG=$(echo "$commit_line" | cut -d'|' -f2) + BODY=$(echo "$commit_line" | cut -d'|' -f3) + + + # Validate hash format + if [[ ! $HASH =~ ^[a-f0-9]{40}$ ]]; then + echo "WARNING: Invalid commit hash format: $HASH" >&2 + continue + fi + + # Check if it's a merge commit + if [[ $COMMIT_MSG =~ Merge\ pull\ request\ #([0-9]+) ]]; then + # echo "Processing as merge commit" >&2 + PR_NUM="${BASH_REMATCH[1]}" + + # Extract the PR title from the merge commit body + PR_TITLE=$(echo "$BODY" | grep -v "^Merge pull request" | head -n 1) + + # Only process if it follows conventional commit format + CATEGORY=$(get_commit_type "$PR_TITLE") + + if [ -n "$CATEGORY" ]; then # Only process if it's a conventional commit + # Get PR author's GitHub username + GITHUB_USERNAME=$(gh pr view "$PR_NUM" --json author --jq '.author.login') + + if [ -n "$GITHUB_USERNAME" ]; then + # Check if this is a first-time contributor + AUTHOR_EMAIL=$(git show -s --format='%ae' "$HASH") + if [ -z "${ALL_AUTHORS[$AUTHOR_EMAIL]}" ]; then + NEW_CONTRIBUTORS["$GITHUB_USERNAME"]=1 + ALL_AUTHORS["$AUTHOR_EMAIL"]=1 + fi + + CATEGORIES["$CATEGORY"]=1 + COMMITS_BY_CATEGORY["$CATEGORY"]+="* ${PR_TITLE#*: } ([#$PR_NUM](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/$PR_NUM)) by @$GITHUB_USERNAME"$'\n' + else + COMMITS_BY_CATEGORY["$CATEGORY"]+="* ${PR_TITLE#*: } ([#$PR_NUM](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/$PR_NUM))"$'\n' + fi + fi + # Check if it's a squash merge by looking for (#NUMBER) pattern + elif [[ $COMMIT_MSG =~ \(#([0-9]+)\) ]]; then + # echo "Processing as squash commit" >&2 + PR_NUM="${BASH_REMATCH[1]}" + + # Only process if it follows conventional commit format + CATEGORY=$(get_commit_type "$COMMIT_MSG") + + if [ -n "$CATEGORY" ]; then # Only process if it's a conventional commit + # Get PR author's GitHub username + GITHUB_USERNAME=$(gh pr view "$PR_NUM" --json author --jq '.author.login') + + if [ -n "$GITHUB_USERNAME" ]; then + # Check if this is a first-time contributor + AUTHOR_EMAIL=$(git show -s --format='%ae' "$HASH") + if [ -z "${ALL_AUTHORS[$AUTHOR_EMAIL]}" ]; then + NEW_CONTRIBUTORS["$GITHUB_USERNAME"]=1 + ALL_AUTHORS["$AUTHOR_EMAIL"]=1 + fi + + CATEGORIES["$CATEGORY"]=1 + COMMIT_TITLE=${COMMIT_MSG%% (#*} # Remove the PR number suffix + COMMIT_TITLE=${COMMIT_TITLE#*: } # Remove the type prefix + COMMITS_BY_CATEGORY["$CATEGORY"]+="* $COMMIT_TITLE ([#$PR_NUM](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/$PR_NUM)) by @$GITHUB_USERNAME"$'\n' + else + COMMIT_TITLE=${COMMIT_MSG%% (#*} # Remove the PR number suffix + COMMIT_TITLE=${COMMIT_TITLE#*: } # Remove the type prefix + COMMITS_BY_CATEGORY["$CATEGORY"]+="* $COMMIT_TITLE ([#$PR_NUM](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/$PR_NUM))"$'\n' + fi + fi + + else + # echo "Processing as regular commit" >&2 + # Process conventional commits without PR numbers + CATEGORY=$(get_commit_type "$COMMIT_MSG") + + if [ -n "$CATEGORY" ]; then # Only process if it's a conventional commit + # Get commit author info + AUTHOR_EMAIL=$(git show -s --format='%ae' "$HASH") + + # Try to get GitHub username using gh api + if [ -n "$GITHUB_ACTIONS" ] || command -v gh >/dev/null 2>&1; then + GITHUB_USERNAME=$(gh api "/repos/${GITHUB_REPOSITORY}/commits/${HASH}" --jq '.author.login' 2>/dev/null) + fi + + if [ -n "$GITHUB_USERNAME" ]; then + # If we got GitHub username, use it + if [ -z "${ALL_AUTHORS[$AUTHOR_EMAIL]}" ]; then + NEW_CONTRIBUTORS["$GITHUB_USERNAME"]=1 + ALL_AUTHORS["$AUTHOR_EMAIL"]=1 + fi + + CATEGORIES["$CATEGORY"]=1 + COMMIT_TITLE=${COMMIT_MSG#*: } # Remove the type prefix + COMMITS_BY_CATEGORY["$CATEGORY"]+="* $COMMIT_TITLE (${HASH:0:7}) by @$GITHUB_USERNAME"$'\n' + else + # Fallback to git author name if no GitHub username found + AUTHOR_NAME=$(git show -s --format='%an' "$HASH") + + if [ -z "${ALL_AUTHORS[$AUTHOR_EMAIL]}" ]; then + NEW_CONTRIBUTORS["$AUTHOR_NAME"]=1 + ALL_AUTHORS["$AUTHOR_EMAIL"]=1 + fi + + CATEGORIES["$CATEGORY"]=1 + COMMIT_TITLE=${COMMIT_MSG#*: } # Remove the type prefix + COMMITS_BY_CATEGORY["$CATEGORY"]+="* $COMMIT_TITLE (${HASH:0:7}) by $AUTHOR_NAME"$'\n' + fi + fi + fi + +done < <(git log "${COMPARE_BASE}..${GITLOG_REF}" --pretty=format:"%H|%s|%b" --reverse --first-parent) + +# Write categorized commits to changelog with their emojis +for category in "✨ Features" "πŸ› Bug Fixes" "πŸ“š Documentation" "πŸ’Ž Styles" "♻️ Code Refactoring" "⚑ Performance Improvements" "πŸ§ͺ Tests" "πŸ› οΈ Build System" "βš™οΈ CI" "πŸ” Other Changes"; do + if [ -n "${COMMITS_BY_CATEGORY[$category]}" ]; then + echo "### $category" >> changelog.md + echo "" >> changelog.md + echo "${COMMITS_BY_CATEGORY[$category]}" >> changelog.md + echo "" >> changelog.md + fi +done + +# Add first-time contributors section if there are any +if [ ${#NEW_CONTRIBUTORS[@]} -gt 0 ]; then + echo "## ✨ First-time Contributors" >> changelog.md + echo "" >> changelog.md + echo "A huge thank you to our amazing new contributors! Your first contribution marks the start of an exciting journey! 🌟" >> changelog.md + echo "" >> changelog.md + # Use readarray to sort the keys + readarray -t sorted_contributors < <(printf '%s\n' "${!NEW_CONTRIBUTORS[@]}" | sort) + for github_username in "${sorted_contributors[@]}"; do + echo "* 🌟 [@$github_username](https://github.com/$github_username)" >> changelog.md + done + echo "" >> changelog.md +fi + +# Add compare link if not first release +if [ -n "$LATEST_TAG" ]; then + echo "## πŸ“ˆ Stats" >> changelog.md + echo "" >> changelog.md + echo "**Full Changelog**: [\`$LATEST_TAG..v${NEW_VERSION}\`](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/compare/$LATEST_TAG...v${NEW_VERSION})" >> changelog.md +fi + +# Output the changelog content +CHANGELOG_CONTENT=$(cat changelog.md) +{ + echo "content<> "$GITHUB_OUTPUT" + +# Also print to stdout for local testing +echo "Generated changelog:" +echo "===================" +cat changelog.md +echo "===================" \ No newline at end of file diff --git a/.github/workflows/docker.yaml b/.github/workflows/docker.yaml new file mode 100644 index 0000000000..a038e02f15 --- /dev/null +++ b/.github/workflows/docker.yaml @@ -0,0 +1,62 @@ +name: Docker Publish + +on: + push: + branches: [main, stable] + tags: ['v*', '*.*.*'] + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + packages: write + contents: read + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + docker-build-publish: + runs-on: ubuntu-latest + # timeout-minutes: 30 + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata for Docker image + id: meta + uses: docker/metadata-action@v4 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_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 + uses: docker/build-push-action@v6 + with: + context: . + platforms: linux/amd64,linux/arm64 + target: bolt-ai-production + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + + - name: Check manifest + run: docker buildx imagetools inspect ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} \ No newline at end of file diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml new file mode 100644 index 0000000000..c0f117b760 --- /dev/null +++ b/.github/workflows/docs.yaml @@ -0,0 +1,35 @@ +name: Docs CI/CD + +on: + push: + branches: + - main + paths: + - 'docs/**' # This will only trigger the workflow when files in docs directory change +permissions: + contents: write +jobs: + build_docs: + runs-on: ubuntu-latest + defaults: + run: + working-directory: ./docs + steps: + - uses: actions/checkout@v4 + - name: Configure Git Credentials + run: | + git config user.name github-actions[bot] + git config user.email 41898282+github-actions[bot]@users.noreply.github.com + - uses: actions/setup-python@v5 + with: + python-version: 3.x + - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV + - uses: actions/cache@v4 + with: + key: mkdocs-material-${{ env.cache_id }} + path: .cache + restore-keys: | + mkdocs-material- + + - run: pip install mkdocs-material + - run: mkdocs gh-deploy --force diff --git a/.github/workflows/electron.yml b/.github/workflows/electron.yml new file mode 100644 index 0000000000..d877a9a463 --- /dev/null +++ b/.github/workflows/electron.yml @@ -0,0 +1,98 @@ +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: [18.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@v3 + 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 ", 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 }} \ No newline at end of file diff --git a/.github/workflows/pr-release-validation.yaml b/.github/workflows/pr-release-validation.yaml new file mode 100644 index 0000000000..9c5787e2d9 --- /dev/null +++ b/.github/workflows/pr-release-validation.yaml @@ -0,0 +1,31 @@ +name: PR Validation + +on: + pull_request: + types: [opened, synchronize, reopened, labeled, unlabeled] + branches: + - main + +jobs: + validate: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Validate PR Labels + run: | + if [[ "${{ contains(github.event.pull_request.labels.*.name, 'stable-release') }}" == "true" ]]; then + echo "βœ“ PR has stable-release label" + + # Check version bump labels + if [[ "${{ contains(github.event.pull_request.labels.*.name, 'major') }}" == "true" ]]; then + echo "βœ“ Major version bump requested" + elif [[ "${{ contains(github.event.pull_request.labels.*.name, 'minor') }}" == "true" ]]; then + echo "βœ“ Minor version bump requested" + else + echo "βœ“ Patch version bump will be applied" + fi + else + echo "This PR doesn't have the stable-release label. No release will be created." + fi diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000000..4b6fc78cff --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,25 @@ +name: Mark Stale Issues and Pull Requests + +on: + schedule: + - cron: '0 2 * * *' # Runs daily at 2:00 AM UTC + workflow_dispatch: # Allows manual triggering of the workflow + +jobs: + stale: + runs-on: ubuntu-latest + + steps: + - name: Mark stale issues and pull requests + uses: actions/stale@v8 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-issue-message: 'This issue has been marked as stale due to inactivity. If no further activity occurs, it will be closed in 7 days.' + stale-pr-message: 'This pull request has been marked as stale due to inactivity. If no further activity occurs, it will be closed in 7 days.' + days-before-stale: 10 # Number of days before marking an issue or PR as stale + days-before-close: 4 # Number of days after being marked stale before closing + stale-issue-label: 'stale' # Label to apply to stale issues + stale-pr-label: 'stale' # Label to apply to stale pull requests + exempt-issue-labels: 'pinned,important' # Issues with these labels won't be marked stale + exempt-pr-labels: 'pinned,important' # PRs with these labels won't be marked stale + operations-per-run: 75 # Limits the number of actions per run to avoid API rate limits diff --git a/.github/workflows/update-stable.yml b/.github/workflows/update-stable.yml new file mode 100644 index 0000000000..f990968a7e --- /dev/null +++ b/.github/workflows/update-stable.yml @@ -0,0 +1,127 @@ +name: Update Stable Branch + +on: + push: + branches: + - main + +permissions: + contents: write + +jobs: + prepare-release: + if: contains(github.event.head_commit.message, '#release') + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Configure Git + run: | + git config --global user.name 'github-actions[bot]' + git config --global user.email 'github-actions[bot]@users.noreply.github.com' + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Install pnpm + uses: pnpm/action-setup@v2 + with: + version: latest + run_install: false + + - name: Get pnpm store directory + id: pnpm-cache + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT + + - name: Setup pnpm cache + uses: actions/cache@v4 + with: + path: ${{ steps.pnpm-cache.outputs.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + + - name: Get Current Version + id: current_version + run: | + CURRENT_VERSION=$(node -p "require('./package.json').version") + echo "version=$CURRENT_VERSION" >> $GITHUB_OUTPUT + + - name: Install semver + run: pnpm add -g semver + + - name: Determine Version Bump + id: version_bump + run: | + COMMIT_MSG="${{ github.event.head_commit.message }}" + if [[ $COMMIT_MSG =~ "#release:major" ]]; then + echo "bump=major" >> $GITHUB_OUTPUT + elif [[ $COMMIT_MSG =~ "#release:minor" ]]; then + echo "bump=minor" >> $GITHUB_OUTPUT + else + echo "bump=patch" >> $GITHUB_OUTPUT + fi + + - name: Bump Version + id: bump_version + run: | + NEW_VERSION=$(semver -i ${{ steps.version_bump.outputs.bump }} ${{ steps.current_version.outputs.version }}) + echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT + + - name: Update Package.json + run: | + NEW_VERSION=${{ steps.bump_version.outputs.new_version }} + pnpm version $NEW_VERSION --no-git-tag-version --allow-same-version + + - name: Prepare changelog script + run: chmod +x .github/scripts/generate-changelog.sh + + - name: Generate Changelog + id: changelog + env: + NEW_VERSION: ${{ steps.bump_version.outputs.new_version }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + run: .github/scripts/generate-changelog.sh + + - name: Get the latest commit hash and version tag + run: | + echo "COMMIT_HASH=$(git rev-parse HEAD)" >> $GITHUB_ENV + echo "NEW_VERSION=${{ steps.bump_version.outputs.new_version }}" >> $GITHUB_ENV + + - name: Commit and Tag Release + run: | + git pull + git add package.json pnpm-lock.yaml changelog.md + git commit -m "chore: release version ${{ steps.bump_version.outputs.new_version }}" + git tag "v${{ steps.bump_version.outputs.new_version }}" + git push + git push --tags + + - name: Update Stable Branch + run: | + if ! git checkout stable 2>/dev/null; then + echo "Creating new stable branch..." + git checkout -b stable + fi + git merge main --no-ff -m "chore: release version ${{ steps.bump_version.outputs.new_version }}" + git push --set-upstream origin stable --force + + - name: Create GitHub Release + env: + 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 \ + --target stable diff --git a/.gitignore b/.gitignore index 965ef504ae..4bc03e175d 100644 --- a/.gitignore +++ b/.gitignore @@ -12,7 +12,7 @@ dist-ssr *.local .vscode/* -!.vscode/launch.json +.vscode/launch.json !.vscode/extensions.json .idea .DS_Store @@ -22,9 +22,27 @@ dist-ssr *.sln *.sw? +/.history /.cache /build -.env* +functions/build/ +.env.local +.env +.dev.vars *.vars .wrangler _worker.bundle + +Modelfile +modelfiles + +# docs ignore +site + +# commit file ignore +app/commit.json +changelogUI.md +docs/instructions/Roadmap.md +.cursorrules +*.md +.qodo diff --git a/.husky/commit-msg b/.husky/commit-msg deleted file mode 100644 index d821bbc58d..0000000000 --- a/.husky/commit-msg +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env sh - -. "$(dirname "$0")/_/husky.sh" - -npx commitlint --edit $1 - -exit 0 diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 0000000000..5f5c2b9ed7 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,32 @@ +#!/bin/sh + +echo "πŸ” Running pre-commit hook to check the code looks good... πŸ”" + +# Load NVM if available (useful for managing Node.js versions) +export NVM_DIR="$HOME/.nvm" +[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" + +# Ensure `pnpm` is available +echo "Checking if pnpm is available..." +if ! command -v pnpm >/dev/null 2>&1; then + echo "❌ pnpm not found! Please ensure pnpm is installed and available in PATH." + exit 1 +fi + +# Run typecheck +echo "Running typecheck..." +if ! pnpm typecheck; then + echo "❌ Type checking failed! Please review TypeScript types." + echo "Once you're done, don't forget to add your changes to the commit! πŸš€" + exit 1 +fi + +# Run lint +echo "Running lint..." +if ! pnpm lint; then + echo "❌ Linting failed! Run 'pnpm lint:fix' to fix the easy issues." + echo "Once you're done, don't forget to add your beautification to the commit! 🀩" + exit 1 +fi + +echo "πŸ‘ All checks passed! Committing changes..." diff --git a/.tool-versions b/.tool-versions deleted file mode 100644 index 427253d38b..0000000000 --- a/.tool-versions +++ /dev/null @@ -1,2 +0,0 @@ -nodejs 20.15.1 -pnpm 9.4.0 diff --git a/CHANGES.md b/CHANGES.md new file mode 100644 index 0000000000..0b70664039 --- /dev/null +++ b/CHANGES.md @@ -0,0 +1,92 @@ +# 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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ef4141cd85..400bb32aa8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,110 +1,242 @@ -[![Bolt Open Source Codebase](./public/social_preview_index.jpg)](https://bolt.new) +# Contribution Guidelines -> Welcome to the **Bolt** open-source codebase! This repo contains a simple example app using the core components from bolt.new to help you get started building **AI-powered software development tools** powered by StackBlitz’s **WebContainer API**. +Welcome! This guide provides all the details you need to contribute effectively to the project. Thank you for helping us make **bolt.diy** a better tool for developers worldwide. πŸ’‘ -### Why Build with Bolt + WebContainer API +--- -By building with the Bolt + WebContainer API you can create browser-based applications that let users **prompt, run, edit, and deploy** full-stack web apps directly in the browser, without the need for virtual machines. With WebContainer API, you can build apps that give AI direct access and full control over a **Node.js server**, **filesystem**, **package manager** and **dev terminal** inside your users browser tab. This powerful combination allows you to create a new class of development tools that support all major JavaScript libraries and Node packages right out of the box, all without remote environments or local installs. +## πŸ“‹ Table of Contents -### What’s the Difference Between Bolt (This Repo) and [Bolt.new](https://bolt.new)? +1. [Code of Conduct](#code-of-conduct) +2. [How Can I Contribute?](#how-can-i-contribute) +3. [Pull Request Guidelines](#pull-request-guidelines) +4. [Coding Standards](#coding-standards) +5. [Development Setup](#development-setup) +6. [Testing](#testing) +7. [Deployment](#deployment) +8. [Docker Deployment](#docker-deployment) +9. [VS Code Dev Containers Integration](#vs-code-dev-containers-integration) -- **Bolt.new**: This is the **commercial product** from StackBlitzβ€”a hosted, browser-based AI development tool that enables users to prompt, run, edit, and deploy full-stack web applications directly in the browser. Built on top of the [Bolt open-source repo](https://github.com/stackblitz/bolt.new) and powered by the StackBlitz **WebContainer API**. +--- -- **Bolt (This Repo)**: This open-source repository provides the core components used to make **Bolt.new**. This repo contains the UI interface for Bolt as well as the server components, built using [Remix Run](https://remix.run/). By leveraging this repo and StackBlitz’s **WebContainer API**, you can create your own AI-powered development tools and full-stack applications that run entirely in the browser. +## πŸ›‘οΈ Code of Conduct -# Get Started Building with Bolt +This project is governed by our **Code of Conduct**. By participating, you agree to uphold this code. Report unacceptable behavior to the project maintainers. -Bolt combines the capabilities of AI with sandboxed development environments to create a collaborative experience where code can be developed by the assistant and the programmer together. Bolt combines [WebContainer API](https://webcontainers.io/api) with [Claude Sonnet 3.5](https://www.anthropic.com/news/claude-3-5-sonnet) using [Remix](https://remix.run/) and the [AI SDK](https://sdk.vercel.ai/). +--- -### WebContainer API +## πŸ› οΈ How Can I Contribute? -Bolt uses [WebContainers](https://webcontainers.io/) to run generated code in the browser. WebContainers provide Bolt with a full-stack sandbox environment using [WebContainer API](https://webcontainers.io/api). WebContainers run full-stack applications directly in the browser without the cost and security concerns of cloud hosted AI agents. WebContainers are interactive and editable, and enables Bolt's AI to run code and understand any changes from the user. +### 1️⃣ Reporting Bugs or Feature Requests -The [WebContainer API](https://webcontainers.io) is free for personal and open source usage. If you're building an application for commercial usage, you can learn more about our [WebContainer API commercial usage pricing here](https://stackblitz.com/pricing#webcontainer-api). +- Check the [issue tracker](#) to avoid duplicates. +- Use issue templates (if available). +- Provide detailed, relevant information and steps to reproduce bugs. -### Remix App +### 2️⃣ Code Contributions -Bolt is built with [Remix](https://remix.run/) and -deployed using [CloudFlare Pages](https://pages.cloudflare.com/) and -[CloudFlare Workers](https://workers.cloudflare.com/). +1. Fork the repository. +2. Create a feature or fix branch. +3. Write and test your code. +4. Submit a pull request (PR). -### AI SDK Integration +### 3️⃣ Join as a Core Contributor -Bolt uses the [AI SDK](https://github.com/vercel/ai) to integrate with AI -models. At this time, Bolt supports using Anthropic's Claude Sonnet 3.5. -You can get an API key from the [Anthropic API Console](https://console.anthropic.com/) to use with Bolt. -Take a look at how [Bolt uses the AI SDK](https://github.com/stackblitz/bolt.new/tree/main/app/lib/.server/llm) +Interested in maintaining and growing the project? Fill out our [Contributor Application Form](https://forms.gle/TBSteXSDCtBDwr5m7). -## Prerequisites +--- -Before you begin, ensure you have the following installed: +## βœ… Pull Request Guidelines -- Node.js (v20.15.1) -- pnpm (v9.4.0) +### PR Checklist -## Setup +- Branch from the **main** branch. +- Update documentation, if needed. +- Test all functionality manually. +- Focus on one feature/bug per PR. -1. Clone the repository (if you haven't already): +### Review Process + +1. Manual testing by reviewers. +2. At least one maintainer review required. +3. Address review comments. +4. Maintain a clean commit history. + +--- + +## πŸ“ Coding Standards + +### General Guidelines + +- Follow existing code style. +- Comment complex logic. +- Keep functions small and focused. +- Use meaningful variable names. + +--- + +## πŸ–₯️ Development Setup + +### 1️⃣ Initial Setup + +- Clone the repository: + ```bash + git clone https://github.com/stackblitz-labs/bolt.diy.git + ``` +- Install dependencies: + ```bash + pnpm install + ``` +- Set up environment variables: + 1. Rename `.env.example` to `.env.local`. + 2. Add your API keys: + ```bash + GROQ_API_KEY=XXX + HuggingFace_API_KEY=XXX + OPENAI_API_KEY=XXX + ... + ``` + 3. Optionally set: + - Debug level: `VITE_LOG_LEVEL=debug` + - Context size: `DEFAULT_NUM_CTX=32768` + +**Note**: Never commit your `.env.local` file to version control. It’s already in `.gitignore`. + +### 2️⃣ Run Development Server ```bash -git clone https://github.com/stackblitz/bolt.new.git +pnpm run dev ``` -2. Install dependencies: +**Tip**: Use **Google Chrome Canary** for local testing. + +--- + +## πŸ§ͺ Testing + +Run the test suite with: ```bash -pnpm install +pnpm test ``` -3. Create a `.env.local` file in the root directory and add your Anthropic API key: +--- + +## πŸš€ Deployment +### Deploy to Cloudflare Pages + +```bash +pnpm run deploy ``` -ANTHROPIC_API_KEY=XXX + +Ensure you have required permissions and that Wrangler is configured. + +--- + +## 🐳 Docker Deployment + +This section outlines the methods for deploying the application using Docker. The processes for **Development** and **Production** are provided separately for clarity. + +--- + +### πŸ§‘β€πŸ’» Development Environment + +#### Build Options + +**Option 1: Helper Scripts** + +```bash +# Development build +npm run dockerbuild ``` -Optionally, you can set the debug level: +**Option 2: Direct Docker Build Command** +```bash +docker build . --target bolt-ai-development ``` -VITE_LOG_LEVEL=debug + +**Option 3: Docker Compose Profile** + +```bash +docker compose --profile development up ``` -**Important**: Never commit your `.env.local` file to version control. It's already included in .gitignore. +#### Running the Development Container -## Available Scripts +```bash +docker run -p 5173:5173 --env-file .env.local bolt-ai:development +``` -- `pnpm run dev`: Starts the development server. -- `pnpm run build`: Builds the project. -- `pnpm run start`: Runs the built application locally using Wrangler Pages. This script uses `bindings.sh` to set up necessary bindings so you don't have to duplicate environment variables. -- `pnpm run preview`: Builds the project and then starts it locally, useful for testing the production build. Note, HTTP streaming currently doesn't work as expected with `wrangler pages dev`. -- `pnpm test`: Runs the test suite using Vitest. -- `pnpm run typecheck`: Runs TypeScript type checking. -- `pnpm run typegen`: Generates TypeScript types using Wrangler. -- `pnpm run deploy`: Builds the project and deploys it to Cloudflare Pages. +--- -## Development +### 🏭 Production Environment -To start the development server: +#### Build Options + +**Option 1: Helper Scripts** ```bash -pnpm run dev +# Production build +npm run dockerbuild:prod ``` -This will start the Remix Vite development server. +**Option 2: Direct Docker Build Command** -## Testing +```bash +docker build . --target bolt-ai-production +``` -Run the test suite with: +**Option 3: Docker Compose Profile** ```bash -pnpm test +docker compose --profile production up ``` -## Deployment - -To deploy the application to Cloudflare Pages: +#### Running the Production Container ```bash -pnpm run deploy +docker run -p 5173:5173 --env-file .env.local bolt-ai:production ``` -Make sure you have the necessary permissions and Wrangler is correctly configured for your Cloudflare account. +--- + +### Coolify Deployment + +For an easy deployment process, use [Coolify](https://github.com/coollabsio/coolify): + +1. Import your Git repository into Coolify. +2. Choose **Docker Compose** as the build pack. +3. Configure environment variables (e.g., API keys). +4. Set the start command: + ```bash + docker compose --profile production up + ``` + +--- + +## πŸ› οΈ VS Code Dev Containers Integration + +The `docker-compose.yaml` configuration is compatible with **VS Code Dev Containers**, making it easy to set up a development environment directly in Visual Studio Code. + +### Steps to Use Dev Containers + +1. Open the command palette in VS Code (`Ctrl+Shift+P` or `Cmd+Shift+P` on macOS). +2. Select **Dev Containers: Reopen in Container**. +3. Choose the **development** profile when prompted. +4. VS Code will rebuild the container and open it with the pre-configured environment. + +--- + +## πŸ”‘ Environment Variables + +Ensure `.env.local` is configured correctly with: + +- API keys. +- Context-specific configurations. + +Example for the `DEFAULT_NUM_CTX` variable: + +```bash +DEFAULT_NUM_CTX=24576 # Uses 32GB VRAM +``` diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000..1cd3f0bfca --- /dev/null +++ b/Dockerfile @@ -0,0 +1,95 @@ +ARG BASE=node:20.18.0 +FROM ${BASE} AS base + +WORKDIR /app + +# Install dependencies (this step is cached as long as the dependencies don't change) +COPY package.json pnpm-lock.yaml ./ + +#RUN npm install -g corepack@latest + +#RUN corepack enable pnpm && pnpm install +RUN npm install -g pnpm && pnpm install + +# Copy the rest of your app's source code +COPY . . + +# Expose the port the app runs on +EXPOSE 5173 + +# Production image +FROM base AS bolt-ai-production + +# 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 + +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}\ + RUNNING_IN_DOCKER=true + +# Pre-configure wrangler to disable metrics +RUN mkdir -p /root/.config/.wrangler && \ + echo '{"enabled":false}' > /root/.config/.wrangler/metrics.json + +RUN pnpm run build + +CMD [ "pnpm", "run", "dockerstart"] + +# Development image +FROM base AS bolt-ai-development + +# 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 + +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 + +RUN mkdir -p ${WORKDIR}/run +CMD pnpm run dev --host diff --git a/FAQ.md b/FAQ.md new file mode 100644 index 0000000000..cf00f54672 --- /dev/null +++ b/FAQ.md @@ -0,0 +1,105 @@ +# Frequently Asked Questions (FAQ) + +
+What are the best models for bolt.diy? + +For the best experience with bolt.diy, we recommend using the following models: + +- **Claude 3.5 Sonnet (old)**: Best overall coder, providing excellent results across all use cases +- **Gemini 2.0 Flash**: Exceptional speed while maintaining good performance +- **GPT-4o**: Strong alternative to Claude 3.5 Sonnet with comparable capabilities +- **DeepSeekCoder V2 236b**: Best open source model (available through OpenRouter, DeepSeek API, or self-hosted) +- **Qwen 2.5 Coder 32b**: Best model for self-hosting with reasonable hardware requirements + +**Note**: Models with less than 7b parameters typically lack the capability to properly interact with bolt! + +
+ +
+How do I get the best results with bolt.diy? + +- **Be specific about your stack**: + Mention the frameworks or libraries you want to use (e.g., Astro, Tailwind, ShadCN) in your initial prompt. This ensures that bolt.diy scaffolds the project according to your preferences. + +- **Use the enhance prompt icon**: + Before sending your prompt, click the _enhance_ icon to let the AI refine your prompt. You can edit the suggested improvements before submitting. + +- **Scaffold the basics first, then add features**: + Ensure the foundational structure of your application is in place before introducing advanced functionality. This helps bolt.diy establish a solid base to build on. + +- **Batch simple instructions**: + Combine simple tasks into a single prompt to save time and reduce API credit consumption. For example: + _"Change the color scheme, add mobile responsiveness, and restart the dev server."_ +
+ +
+How do I contribute to bolt.diy? + +Check out our [Contribution Guide](CONTRIBUTING.md) for more details on how to get involved! + +
+ +
+What are the future plans for bolt.diy? + +Visit our [Roadmap](https://roadmap.sh/r/ottodev-roadmap-2ovzo) for the latest updates. +New features and improvements are on the way! + +
+ +
+Why are there so many open issues/pull requests? + +bolt.diy began as a small showcase project on @ColeMedin's YouTube channel to explore editing open-source projects with local LLMs. However, it quickly grew into a massive community effort! + +We're forming a team of maintainers to manage demand and streamline issue resolution. The maintainers are rockstars, and we're also exploring partnerships to help the project thrive. + +
+ +
+How do local LLMs compare to larger models like Claude 3.5 Sonnet for bolt.diy? + +While local LLMs are improving rapidly, larger models like GPT-4o, Claude 3.5 Sonnet, and DeepSeek Coder V2 236b still offer the best results for complex applications. Our ongoing focus is to improve prompts, agents, and the platform to better support smaller local LLMs. + +
+ +
+Common Errors and Troubleshooting + +### **"There was an error processing this request"** + +This generic error message means something went wrong. Check both: + +- The terminal (if you started the app with Docker or `pnpm`). +- The developer console in your browser (press `F12` or right-click > _Inspect_, then go to the _Console_ tab). + +### **"x-api-key header missing"** + +This error is sometimes resolved by restarting the Docker container. +If that doesn't work, try switching from Docker to `pnpm` or vice versa. We're actively investigating this issue. + +### **Blank preview when running the app** + +A blank preview often occurs due to hallucinated bad code or incorrect commands. +To troubleshoot: + +- Check the developer console for errors. +- Remember, previews are core functionality, so the app isn't broken! We're working on making these errors more transparent. + +### **"Everything works, but the results are bad"** + +Local LLMs like Qwen-2.5-Coder are powerful for small applications but still experimental for larger projects. For better results, consider using larger models like GPT-4o, Claude 3.5 Sonnet, or DeepSeek Coder V2 236b. + +### **"Received structured exception #0xc0000005: access violation"** + +If you are getting this, you are probably on Windows. The fix is generally to update the [Visual C++ Redistributable](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170) + +### **"Miniflare or Wrangler errors in Windows"** + +You will need to make sure you have the latest version of Visual Studio C++ installed (14.40.33816), more information here https://github.com/stackblitz-labs/bolt.diy/issues/19. + +
+ +--- + +Got more questions? Feel free to reach out or open an issue in our GitHub repo! diff --git a/LICENSE b/LICENSE index 79290241f9..8fb312e947 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2024 StackBlitz, Inc. +Copyright (c) 2024 StackBlitz, Inc. and bolt.diy contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/PROJECT.md b/PROJECT.md new file mode 100644 index 0000000000..58d470891d --- /dev/null +++ b/PROJECT.md @@ -0,0 +1,57 @@ +# Project management of bolt.diy + +First off: this sounds funny, we know. "Project management" comes from a world of enterprise stuff and this project is +far from being enterprisy- it's still anarchy all over the place πŸ˜‰ + +But we need to organize ourselves somehow, right? + +> tl;dr: We've got a project board with epics and features. We use PRs as change log and as materialized features. Find it [here](https://github.com/orgs/stackblitz-labs/projects/4). + +Here's how we structure long-term vision, mid-term capabilities of the software and short term improvements. + +## Strategic epics (long-term) + +Strategic epics define areas in which the product evolves. Usually, these epics don’t overlap. They shall allow the core +team to define what they believe is most important and should be worked on with the highest priority. + +You can find the [epics as issues](https://github.com/stackblitz-labs/bolt.diy/labels/epic) which are probably never +going to be closed. + +What's the benefit / purpose of epics? + +1. Prioritization + +E. g. we could say β€œmanaging files is currently more important that quality”. Then, we could thing about which features +would bring β€œmanaging files” forward. It may be different features, such as β€œupload local files”, β€œimport from a repo” +or also undo/redo/commit. + +In a more-or-less regular meeting dedicated for that, the core team discusses which epics matter most, sketch features +and then check who can work on them. After the meeting, they update the roadmap (at least for the next development turn) +and this way communicate where the focus currently is. + +2. Grouping of features + +By linking features with epics, we can keep them together and document _why_ we invest work into a particular thing. + +## Features (mid-term) + +We all know probably a dozen of methodologies following which features are being described (User story, business +function, you name it). + +However, we intentionally describe features in a more vague manner. Why? Everybody loves crisp, well-defined +acceptance-criteria, no? Well, every product owner loves it. because he knows what he’ll get once it’s done. + +But: **here is no owner of this product**. Therefore, we grant _maximum flexibility to the developer contributing a feature_ – so that he can bring in his ideas and have most fun implementing it. + +The feature therefore tries to describe _what_ should be improved but not in detail _how_. + +## PRs as materialized features (short-term) + +Once a developer starts working on a feature, a draft-PR _can_ be opened asap to share, describe and discuss, how the feature shall be implemented. But: this is not a must. It just helps to get early feedback and get other developers involved. Sometimes, the developer just wants to get started and then open a PR later. + +In a loosely organized project, it may as well happen that multiple PRs are opened for the same feature. This is no real issue: Usually, peoply being passionate about a solution are willing to join forces and get it done together. And if a second developer was just faster getting the same feature realized: Be happy that it's been done, close the PR and look out for the next feature to implement πŸ€“ + +## PRs as change log + +Once a PR is merged, a squashed commit contains the whole PR description which allows for a good change log. +All authors of commits in the PR are mentioned in the squashed commit message and become contributors πŸ™Œ diff --git a/README.md b/README.md index d3745298ff..cbcd8a4c6b 100644 --- a/README.md +++ b/README.md @@ -1,54 +1,368 @@ -[![Bolt.new: AI-Powered Full-Stack Web Development in the Browser](./public/social_preview_index.jpg)](https://bolt.new) +# bolt.diy -# Bolt.new: AI-Powered Full-Stack Web Development in the Browser +[![bolt.diy: AI-Powered Full-Stack Web Development in the Browser](./public/social_preview_index.jpg)](https://bolt.diy) -Bolt.new is an AI-powered web development agent that allows you to prompt, run, edit, and deploy full-stack applications directly from your browserβ€”no local setup required. If you're here to build your own AI-powered web dev agent using the Bolt open source codebase, [click here to get started!](./CONTRIBUTING.md) +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, 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. -## What Makes Bolt.new Different +----- +Check the [bolt.diy Docs](https://stackblitz-labs.github.io/bolt.diy/) for more offical installation instructions and more informations. -Claude, v0, etc are incredible- but you can't install packages, run backends or edit code. That’s where Bolt.new stands out: +----- +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! -- **Full-Stack in the Browser**: Bolt.new integrates cutting-edge AI models with an in-browser development environment powered by **StackBlitz’s WebContainers**. This allows you to: - - Install and run npm tools and libraries (like Vite, Next.js, and more) - - Run Node.js servers - - Interact with third-party APIs - - Deploy to production from chat - - Share your work via a URL +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/). -- **AI with Environment Control**: Unlike traditional dev environments where the AI can only assist in code generation, Bolt.new gives AI models **complete control** over the entire environment including the filesystem, node server, package manager, terminal, and browser console. This empowers AI agents to handle the entire app lifecycleβ€”from creation to deployment. +bolt.diy was originally started by [Cole Medin](https://www.youtube.com/@ColeMedin) but has quickly grown into a massive community effort to build the BEST open source AI coding assistant! -Whether you’re an experienced developer, a PM or designer, Bolt.new allows you to build production-grade full-stack applications with ease. +## Table of Contents -For developers interested in building their own AI-powered development tools with WebContainers, check out the open-source Bolt codebase in this repo! +- [Join the Community](#join-the-community) +- [Requested Additions](#requested-additions) +- [Features](#features) +- [Setup](#setup) +- [Run the Application](#run-the-application) +- [Available Scripts](#available-scripts) +- [Contributing](#contributing) +- [Roadmap](#roadmap) +- [FAQ](#faq) -## Tips and Tricks +## Join the community -Here are some tips to get the most out of Bolt.new: +[Join the bolt.diy community here, in the oTTomator Think Tank!](https://thinktank.ottomator.ai) -- **Be specific about your stack**: If you want to use specific frameworks or libraries (like Astro, Tailwind, ShadCN, or any other popular JavaScript framework), mention them in your initial prompt to ensure Bolt scaffolds the project accordingly. +## Project management -- **Use the enhance prompt icon**: Before sending your prompt, try clicking the 'enhance' icon to have the AI model help you refine your prompt, then edit the results before submitting. +Bolt.diy is a community effort! Still, the core team of contributors aims at organizing the project in way that allows +you to understand where the current areas of focus are. -- **Scaffold the basics first, then add features**: Make sure the basic structure of your application is in place before diving into more advanced functionality. This helps Bolt understand the foundation of your project and ensure everything is wired up right before building out more advanced functionality. +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. -- **Batch simple instructions**: Save time by combining simple instructions into one message. For example, you can ask Bolt to change the color scheme, add mobile responsiveness, and restart the dev server, all in one go saving you time and reducing API credit consumption significantly. +## Requested Additions -## FAQs +- βœ… 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) +- βœ… Add a "Diff View" to see the changes (@toddyclipsgg) +- ⬜ **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 Netlify (@xKevIsDev) +- βœ… Supabase Integration (@xKevIsDev) +- ⬜ 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) -**Where do I sign up for a paid plan?** -Bolt.new is free to get started. If you need more AI tokens or want private projects, you can purchase a paid subscription in your [Bolt.new](https://bolt.new) settings, in the lower-left hand corner of the application. +## Features -**What happens if I hit the free usage limit?** -Once your free daily token limit is reached, AI interactions are paused until the next day or until you upgrade your plan. +- **AI-powered full-stack web development** for **NodeJS based applications** directly in your browser. +- **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 Sync to a folder on the host. +- **Integration-ready Docker support** for a hassle-free setup. +- **Deploy** directly to **Netlify** -**Is Bolt in beta?** -Yes, Bolt.new is in beta, and we are actively improving it based on feedback. +## Setup -**How can I report Bolt.new issues?** -Check out the [Issues section](https://github.com/stackblitz/bolt.new/issues) to report an issue or request a new feature. Please use the search feature to check if someone else has already submitted the same issue/request. +If you're new to installing software from GitHub, don't worry! If you encounter any issues, feel free to submit an "issue" using the provided links or improve this documentation by forking the repository, editing the instructions, and submitting a pull request. The following instruction will help you get the stable branch up and running on your local machine in no time. -**What frameworks/libraries currently work on Bolt?** -Bolt.new supports most popular JavaScript frameworks and libraries. If it runs on StackBlitz, it will run on Bolt.new as well. +Let's get you up and running with the stable version of Bolt.DIY! -**How can I add make sure my framework/project works well in bolt?** -We are excited to work with the JavaScript ecosystem to improve functionality in Bolt. Reach out to us via [hello@stackblitz.com](mailto:hello@stackblitz.com) to discuss how we can partner! +## Quick Download + +[![Download Latest Release](https://img.shields.io/github/v/release/stackblitz-labs/bolt.diy?label=Download%20Bolt&sort=semver)](https://github.com/stackblitz-labs/bolt.diy/releases/latest) ← Click here to go the the latest release version! + +- Next **click source.zip** + +## Prerequisites + +Before you begin, you'll need to install two important pieces of software: + +### Install Node.js + +Node.js is required to run the application. + +1. Visit the [Node.js Download Page](https://nodejs.org/en/download/) +2. Download the "LTS" (Long Term Support) version for your operating system +3. Run the installer, accepting the default settings +4. Verify Node.js is properly installed: + - **For Windows Users**: + 1. Press `Windows + R` + 2. Type "sysdm.cpl" and press Enter + 3. Go to "Advanced" tab β†’ "Environment Variables" + 4. Check if `Node.js` appears in the "Path" variable + - **For Mac/Linux Users**: + 1. Open Terminal + 2. Type this command: + ```bash + echo $PATH + ``` + 3. Look for `/usr/local/bin` in the output + +## Running the Application + +You have two options for running Bolt.DIY: directly on your machine or using Docker. + +### Option 1: Direct Installation (Recommended for Beginners) + +1. **Install Package Manager (pnpm)**: + + ```bash + npm install -g pnpm + ``` + +2. **Install Project Dependencies**: + + ```bash + pnpm install + ``` + +3. **Start the Application**: + + ```bash + pnpm run dev + ``` + +### Option 2: Using Docker + +This option requires some familiarity with Docker but provides a more isolated environment. + +#### Additional Prerequisite + +- Install Docker: [Download Docker](https://www.docker.com/) + +#### Steps: + +1. **Build the Docker Image**: + + ```bash + # Using npm script: + npm run dockerbuild + + # OR using direct Docker command: + docker build . --target bolt-ai-development + ``` + +2. **Run the Container**: + ```bash + docker compose --profile development up + ``` + +## Configuring API Keys and Providers + +### Adding Your API Keys + +Setting up your API keys in Bolt.DIY is straightforward: + +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 + +![API Key Configuration Interface](./docs/images/api-key-ui-section.png) + +### Configuring Custom Base URLs + +For providers that support custom base URLs (such as Ollama or LM Studio), follow these steps: + +1. Click the settings icon in the sidebar to open the settings menu + ![Settings Button Location](./docs/images/bolt-settings-button.png) + +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 + ![Provider Base URL Configuration](./docs/images/provider-base-url.png) + +> **Note**: Custom base URLs are particularly useful when running local instances of AI models or using custom API endpoints. + +### Supported Providers + +- Ollama +- LM Studio +- OpenAILike + +## Setup Using Git (For Developers only) + +This method is recommended for developers who want to: + +- Contribute to the project +- Stay updated with the latest changes +- Switch between different versions +- Create custom modifications + +#### Prerequisites + +1. Install Git: [Download Git](https://git-scm.com/downloads) + +#### Initial Setup + +1. **Clone the Repository**: + + ```bash + git clone -b stable https://github.com/stackblitz-labs/bolt.diy.git + ``` + +2. **Navigate to Project Directory**: + + ```bash + 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: + ```bash + git checkout main + pnpm install + 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)** +> - Beginngers: +> - 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 + +To get the latest changes from the repository: + +1. **Save Your Local Changes** (if any): + + ```bash + git stash + ``` + +2. **Pull Latest Updates**: + + ```bash + git pull + ``` + +3. **Update Dependencies**: + + ```bash + pnpm install + ``` + +4. **Restore Your Local Changes** (if any): + ```bash + git stash pop + ``` + +#### Troubleshooting Git Setup + +If you encounter issues: + +1. **Clean Installation**: + + ```bash + # Remove node modules and lock files + rm -rf node_modules pnpm-lock.yaml + + # Clear pnpm cache + pnpm store prune + + # Reinstall dependencies + pnpm install + ``` + +2. **Reset Local Changes**: + ```bash + # Discard all local changes + git reset --hard origin/main + ``` + +Remember to always commit your local changes or stash them before pulling updates to avoid conflicts. + +--- + +## Available Scripts + +- **`pnpm run dev`**: Starts the development server. +- **`pnpm run build`**: Builds the project. +- **`pnpm run start`**: Runs the built application locally using Wrangler Pages. +- **`pnpm run preview`**: Builds and runs the production build locally. +- **`pnpm test`**: Runs the test suite using Vitest. +- **`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:fix`**: Automatically fixes linting issues. + +--- + +## Contributing + +We welcome contributions! Check out our [Contributing Guide](CONTRIBUTING.md) to get started. + +--- + +## Roadmap + +Explore upcoming features and priorities on our [Roadmap](https://roadmap.sh/r/ottodev-roadmap-2ovzo). + +--- + +## 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. diff --git a/app/components/@settings/core/AvatarDropdown.tsx b/app/components/@settings/core/AvatarDropdown.tsx new file mode 100644 index 0000000000..c6c1845567 --- /dev/null +++ b/app/components/@settings/core/AvatarDropdown.tsx @@ -0,0 +1,140 @@ +import * as DropdownMenu from '@radix-ui/react-dropdown-menu'; +import { motion } from 'framer-motion'; +import { useStore } from '@nanostores/react'; +import { classNames } from '~/utils/classNames'; +import { profileStore } from '~/lib/stores/profile'; +import type { TabType, Profile } from './types'; + +const BetaLabel = () => ( + + BETA + +); + +interface AvatarDropdownProps { + onSelectTab: (tab: TabType) => void; +} + +export const AvatarDropdown = ({ onSelectTab }: AvatarDropdownProps) => { + const profile = useStore(profileStore) as Profile; + + return ( + + + + {profile?.avatar ? ( + {profile?.username + ) : ( +
+
+
+ )} + + + + + +
+
+ {profile?.avatar ? ( + {profile?.username + ) : ( +
+
+
+ )} +
+
+
+ {profile?.username || 'Guest User'} +
+ {profile?.bio &&
{profile.bio}
} +
+
+ + onSelectTab('profile')} + > +
+ Edit Profile + + + onSelectTab('settings')} + > +
+ Settings + + +
+ onSelectTab('service-status')} + > +
+ Service Status + + + + + + ); +}; diff --git a/app/components/@settings/core/ControlPanel.tsx b/app/components/@settings/core/ControlPanel.tsx new file mode 100644 index 0000000000..7292f5668d --- /dev/null +++ b/app/components/@settings/core/ControlPanel.tsx @@ -0,0 +1,323 @@ +import { useState, useEffect, useMemo } from 'react'; +import { useStore } from '@nanostores/react'; +import * as RadixDialog from '@radix-ui/react-dialog'; +import { classNames } from '~/utils/classNames'; +import { TabTile } from '~/components/@settings/shared/components/TabTile'; +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 { profileStore } from '~/lib/stores/profile'; +import type { TabType, Profile } from './types'; +import { TAB_LABELS, DEFAULT_TAB_CONFIG, TAB_DESCRIPTIONS } from './constants'; +import { DialogTitle } from '~/components/ui/Dialog'; +import { AvatarDropdown } from './AvatarDropdown'; +import BackgroundRays from '~/components/ui/BackgroundRays'; + +// Import all tab components +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 { EventLogsTab } from '~/components/@settings/tabs/event-logs/EventLogsTab'; +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'; + +interface ControlPanelProps { + open: boolean; + onClose: () => void; +} + +// Beta status for experimental features +const BETA_TABS = new Set(['service-status', 'local-providers', 'mcp']); + +const BetaLabel = () => ( +
+ BETA +
+); + +export const ControlPanel = ({ open, onClose }: ControlPanelProps) => { + // State + const [activeTab, setActiveTab] = useState(null); + const [loadingTab, setLoadingTab] = useState(null); + const [showTabManagement, setShowTabManagement] = useState(false); + + // Store values + const tabConfiguration = useStore(tabConfigurationStore); + const profile = useStore(profileStore) as Profile; + + // Status hooks + const { hasNewFeatures, unviewedFeatures, acknowledgeAllFeatures } = useFeatures(); + const { hasUnreadNotifications, unreadNotifications, markAllAsRead } = useNotifications(); + const { hasConnectionIssues, currentIssue, acknowledgeIssue } = useConnectionStatus(); + + // Memoize the base tab configurations to avoid recalculation + const baseTabConfig = useMemo(() => { + return new Map(DEFAULT_TAB_CONFIG.map((tab) => [tab.id, tab])); + }, []); + + // Add visibleTabs logic using useMemo with optimized calculations + const visibleTabs = useMemo(() => { + if (!tabConfiguration?.userTabs || !Array.isArray(tabConfiguration.userTabs)) { + console.warn('Invalid tab configuration, resetting to defaults'); + resetTabConfiguration(); + + return []; + } + + const notificationsDisabled = profile?.preferences?.notifications === false; + + // Optimize user mode tab filtering + return tabConfiguration.userTabs + .filter((tab) => { + if (!tab?.id) { + return false; + } + + if (tab.id === 'notifications' && notificationsDisabled) { + return false; + } + + return tab.visible && tab.window === 'user'; + }) + .sort((a, b) => a.order - b.order); + }, [tabConfiguration, profile?.preferences?.notifications, baseTabConfig]); + + // Reset to default view when modal opens/closes + useEffect(() => { + if (!open) { + // Reset when closing + setActiveTab(null); + setLoadingTab(null); + setShowTabManagement(false); + } else { + // When opening, set to null to show the main view + setActiveTab(null); + } + }, [open]); + + // Handle closing + const handleClose = () => { + setActiveTab(null); + setLoadingTab(null); + setShowTabManagement(false); + onClose(); + }; + + // Handlers + const handleBack = () => { + if (showTabManagement) { + setShowTabManagement(false); + } else if (activeTab) { + setActiveTab(null); + } + }; + + const getTabComponent = (tabId: TabType) => { + switch (tabId) { + case 'profile': + return ; + case 'settings': + return ; + case 'notifications': + return ; + case 'features': + return ; + case 'data': + return ; + case 'cloud-providers': + return ; + case 'local-providers': + return ; + case 'connection': + return ; + case 'event-logs': + return ; + case 'service-status': + return ; + case 'mcp': + return ; + default: + return null; + } + }; + + const getTabUpdateStatus = (tabId: TabType): boolean => { + switch (tabId) { + case 'features': + return hasNewFeatures; + case 'notifications': + return hasUnreadNotifications; + case 'connection': + return hasConnectionIssues; + default: + return false; + } + }; + + const getStatusMessage = (tabId: TabType): string => { + switch (tabId) { + 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 'connection': + return currentIssue === 'disconnected' + ? 'Connection lost' + : currentIssue === 'high-latency' + ? 'High latency detected' + : 'Connection issues detected'; + default: + return ''; + } + }; + + const handleTabClick = (tabId: TabType) => { + setLoadingTab(tabId); + setActiveTab(tabId); + setShowTabManagement(false); + + // Acknowledge notifications based on tab + switch (tabId) { + case 'features': + acknowledgeAllFeatures(); + break; + case 'notifications': + markAllAsRead(); + break; + case 'connection': + acknowledgeIssue(); + break; + } + + // Clear loading state after a delay + setTimeout(() => setLoadingTab(null), 500); + }; + + return ( + + +
+ + + +
+
+ +
+
+ {/* Header */} +
+
+ {(activeTab || showTabManagement) && ( + + )} + + {showTabManagement ? 'Tab Management' : activeTab ? TAB_LABELS[activeTab] : 'Control Panel'} + +
+ +
+ {/* Avatar and Dropdown */} +
+ +
+ + {/* Close Button */} + +
+
+ + {/* Content */} +
+
+ {activeTab ? ( + getTabComponent(activeTab) + ) : ( +
+ {visibleTabs.map((tab, index) => ( +
+ 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) && } + +
+ ))} +
+ )} +
+
+
+
+
+
+
+
+ ); +}; diff --git a/app/components/@settings/core/constants.ts b/app/components/@settings/core/constants.ts new file mode 100644 index 0000000000..8901a8f016 --- /dev/null +++ b/app/components/@settings/core/constants.ts @@ -0,0 +1,60 @@ +import type { TabType } from './types'; + +export const TAB_ICONS: Record = { + profile: 'i-ph:user-circle', + settings: 'i-ph:gear-six', + notifications: 'i-ph:bell', + features: 'i-ph:star', + data: 'i-ph:database', + 'cloud-providers': 'i-ph:cloud', + 'local-providers': 'i-ph:laptop', + 'service-status': 'i-ph:activity-bold', + connection: 'i-ph:wifi-high', + 'event-logs': 'i-ph:list-bullets', + mcp: 'i-ph:wrench', +}; + +export const TAB_LABELS: Record = { + 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', + 'event-logs': 'Event Logs', + mcp: 'MCP Servers', +}; + +export const TAB_DESCRIPTIONS: Record = { + 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', + '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: '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 }, + { id: 'mcp', visible: true, window: 'user' as const, order: 7 }, + { id: 'profile', visible: true, window: 'user' as const, order: 8 }, + { id: 'service-status', visible: true, window: 'user' as const, order: 9 }, + { id: 'settings', visible: true, window: 'user' as const, order: 10 }, + + // User Window Tabs (In dropdown, initially hidden) +]; diff --git a/app/components/@settings/core/types.ts b/app/components/@settings/core/types.ts new file mode 100644 index 0000000000..d4a518f4b5 --- /dev/null +++ b/app/components/@settings/core/types.ts @@ -0,0 +1,107 @@ +import type { ReactNode } from 'react'; + +export type SettingCategory = 'profile' | 'file_sharing' | 'connectivity' | 'system' | 'services' | 'preferences'; + +export type TabType = + | 'profile' + | 'settings' + | 'notifications' + | 'features' + | 'data' + | 'cloud-providers' + | 'local-providers' + | 'service-status' + | 'connection' + | 'event-logs' + | 'mcp'; + +export type WindowType = 'user' | 'developer'; + +export interface UserProfile { + nickname: any; + name: string; + email: string; + avatar?: string; + theme: 'light' | 'dark' | 'system'; + notifications: boolean; + password?: string; + bio?: string; + language: string; + timezone: string; +} + +export interface SettingItem { + id: TabType; + label: string; + icon: string; + category: SettingCategory; + description?: string; + component: () => ReactNode; + badge?: string; + keywords?: string[]; +} + +export interface TabVisibilityConfig { + id: TabType; + visible: boolean; + window: WindowType; + order: number; + isExtraDevTab?: boolean; + locked?: boolean; +} + +export interface DevTabConfig extends TabVisibilityConfig { + window: 'developer'; +} + +export interface UserTabConfig extends TabVisibilityConfig { + window: 'user'; +} + +export interface TabWindowConfig { + userTabs: UserTabConfig[]; +} + +export const TAB_LABELS: Record = { + profile: 'Profile', + settings: 'Settings', + notifications: 'Notifications', + features: 'Features', + data: 'Data Management', + 'cloud-providers': 'Cloud Providers', + 'local-providers': 'Local Providers', + 'service-status': 'Service Status', + connection: 'Connections', + 'event-logs': 'Event Logs', + mcp: 'MCP Servers', +}; + +export const categoryLabels: Record = { + profile: 'Profile & Account', + file_sharing: 'File Sharing', + connectivity: 'Connectivity', + system: 'System', + services: 'Services', + preferences: 'Preferences', +}; + +export const categoryIcons: Record = { + 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 { + username?: string; + bio?: string; + avatar?: string; + preferences?: { + notifications?: boolean; + theme?: 'light' | 'dark' | 'system'; + language?: string; + timezone?: string; + }; +} diff --git a/app/components/@settings/index.ts b/app/components/@settings/index.ts new file mode 100644 index 0000000000..94b3de94c7 --- /dev/null +++ b/app/components/@settings/index.ts @@ -0,0 +1,12 @@ +// Core exports +export { ControlPanel } from './core/ControlPanel'; +export type { TabType, TabVisibilityConfig } from './core/types'; + +// Constants +export { TAB_LABELS, TAB_DESCRIPTIONS, DEFAULT_TAB_CONFIG } from './core/constants'; + +// Shared components +export { TabTile } from './shared/components/TabTile'; + +// Utils +export { getVisibleTabs, reorderTabs, resetToDefaultConfig } from './utils/tab-helpers'; diff --git a/app/components/@settings/shared/components/DraggableTabList.tsx b/app/components/@settings/shared/components/DraggableTabList.tsx new file mode 100644 index 0000000000..a8681835dc --- /dev/null +++ b/app/components/@settings/shared/components/DraggableTabList.tsx @@ -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 ( + +
+
+
+
+
+
{TAB_LABELS[tab.id]}
+ {showControls && ( +
+ Order: {tab.order}, Window: {tab.window} +
+ )} +
+
+ {showControls && !tab.locked && ( +
+
+ onVisibilityChange?.(tab, checked)} + className="data-[state=checked]:bg-purple-500" + aria-label={`Toggle ${TAB_LABELS[tab.id]} visibility`} + /> + +
+
+ + onWindowChange?.(tab, checked ? 'developer' : 'user')} + className="data-[state=checked]:bg-purple-500" + aria-label={`Toggle ${TAB_LABELS[tab.id]} window assignment`} + /> + +
+
+ )} + + ); +}; + +export const DraggableTabList = ({ + tabs, + onReorder, + onWindowChange, + onVisibilityChange, + showControls = false, +}: DraggableTabListProps) => { + const moveTab = (dragIndex: number, hoverIndex: number) => { + const items = Array.from(tabs); + const [reorderedItem] = items.splice(dragIndex, 1); + items.splice(hoverIndex, 0, reorderedItem); + + // Update order numbers based on position + const reorderedTabs = items.map((tab, index) => ({ + ...tab, + order: index + 1, + })); + + onReorder(reorderedTabs); + }; + + return ( +
+ {tabs.map((tab, index) => ( + + ))} +
+ ); +}; diff --git a/app/components/@settings/shared/components/TabTile.tsx b/app/components/@settings/shared/components/TabTile.tsx new file mode 100644 index 0000000000..ebc0b19c59 --- /dev/null +++ b/app/components/@settings/shared/components/TabTile.tsx @@ -0,0 +1,147 @@ +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; + onClick?: () => void; + isActive?: boolean; + hasUpdate?: boolean; + statusMessage?: string; + description?: string; + isLoading?: boolean; + className?: string; + children?: React.ReactNode; +} + +export const TabTile: React.FC = ({ + tab, + onClick, + isActive, + hasUpdate, + statusMessage, + description, + isLoading, + className, + children, +}: TabTileProps) => { + return ( + + + +
+
+ +
+ {/* Icon */} +
+
+
+ + {/* Label and Description */} +
+

+ {TAB_LABELS[tab.id]} +

+ {description && ( +

+ {description} +

+ )} +
+ + {/* Update Indicator with Tooltip */} + {hasUpdate && ( + <> +
+ + + {statusMessage} + + + + + )} + + {/* Children (e.g. Beta Label) */} + {children} +
+
+
+ + + + ); +}; diff --git a/app/components/@settings/tabs/connections/ConnectionDiagnostics.tsx b/app/components/@settings/tabs/connections/ConnectionDiagnostics.tsx new file mode 100644 index 0000000000..c14d4f9621 --- /dev/null +++ b/app/components/@settings/tabs/connections/ConnectionDiagnostics.tsx @@ -0,0 +1,595 @@ +import React, { useState } from 'react'; +import { toast } from 'react-toastify'; +import { Button } from '~/components/ui/Button'; +import { Badge } from '~/components/ui/Badge'; +import { classNames } from '~/utils/classNames'; +import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '~/components/ui/Collapsible'; +import { CodeBracketIcon, ChevronDownIcon } from '@heroicons/react/24/outline'; + +// Helper function to safely parse JSON +const safeJsonParse = (item: string | null) => { + if (!item) { + return null; + } + + try { + return JSON.parse(item); + } catch (e) { + console.error('Failed to parse JSON from localStorage:', e); + return null; + } +}; + +/** + * A diagnostics component to help troubleshoot connection issues + */ +export default function ConnectionDiagnostics() { + const [diagnosticResults, setDiagnosticResults] = useState(null); + const [isRunning, setIsRunning] = useState(false); + const [showDetails, setShowDetails] = useState(false); + + // Run diagnostics when requested + const runDiagnostics = async () => { + try { + setIsRunning(true); + setDiagnosticResults(null); + + // Check browser-side storage + const localStorageChecks = { + githubConnection: localStorage.getItem('github_connection'), + netlifyConnection: localStorage.getItem('netlify_connection'), + vercelConnection: localStorage.getItem('vercel_connection'), + supabaseConnection: localStorage.getItem('supabase_connection'), + }; + + // Get diagnostic data from server + const response = await fetch('/api/system/diagnostics'); + + if (!response.ok) { + throw new Error(`Diagnostics API error: ${response.status}`); + } + + const serverDiagnostics = await response.json(); + + // === GitHub Checks === + const githubConnectionParsed = safeJsonParse(localStorageChecks.githubConnection); + const githubToken = githubConnectionParsed?.token; + const githubAuthHeaders = { + ...(githubToken ? { Authorization: `Bearer ${githubToken}` } : {}), + 'Content-Type': 'application/json', + }; + console.log('Testing GitHub endpoints with token:', githubToken ? 'present' : 'missing'); + + const githubEndpoints = [ + { name: 'User', url: '/api/system/git-info?action=getUser' }, + { name: 'Repos', url: '/api/system/git-info?action=getRepos' }, + { name: 'Default', url: '/api/system/git-info' }, + ]; + const githubResults = await Promise.all( + githubEndpoints.map(async (endpoint) => { + try { + const resp = await fetch(endpoint.url, { headers: githubAuthHeaders }); + return { endpoint: endpoint.name, status: resp.status, ok: resp.ok }; + } catch (error) { + return { + endpoint: endpoint.name, + error: error instanceof Error ? error.message : String(error), + ok: false, + }; + } + }), + ); + + // === Netlify Checks === + const netlifyConnectionParsed = safeJsonParse(localStorageChecks.netlifyConnection); + const netlifyToken = netlifyConnectionParsed?.token; + let netlifyUserCheck = null; + + if (netlifyToken) { + try { + const netlifyResp = await fetch('https://api.netlify.com/api/v1/user', { + headers: { Authorization: `Bearer ${netlifyToken}` }, + }); + netlifyUserCheck = { status: netlifyResp.status, ok: netlifyResp.ok }; + } catch (error) { + netlifyUserCheck = { + error: error instanceof Error ? error.message : String(error), + ok: false, + }; + } + } + + // === Vercel Checks === + const vercelConnectionParsed = safeJsonParse(localStorageChecks.vercelConnection); + const vercelToken = vercelConnectionParsed?.token; + let vercelUserCheck = null; + + if (vercelToken) { + try { + const vercelResp = await fetch('https://api.vercel.com/v2/user', { + headers: { Authorization: `Bearer ${vercelToken}` }, + }); + vercelUserCheck = { status: vercelResp.status, ok: vercelResp.ok }; + } catch (error) { + vercelUserCheck = { + error: error instanceof Error ? error.message : String(error), + ok: false, + }; + } + } + + // === Supabase Checks === + const supabaseConnectionParsed = safeJsonParse(localStorageChecks.supabaseConnection); + const supabaseUrl = supabaseConnectionParsed?.projectUrl; + const supabaseAnonKey = supabaseConnectionParsed?.anonKey; + let supabaseCheck = null; + + if (supabaseUrl && supabaseAnonKey) { + supabaseCheck = { ok: true, status: 200, message: 'URL and Key present in localStorage' }; + } else { + supabaseCheck = { ok: false, message: 'URL or Key missing in localStorage' }; + } + + // Compile results + const results = { + timestamp: new Date().toISOString(), + localStorage: { + hasGithubConnection: Boolean(localStorageChecks.githubConnection), + hasNetlifyConnection: Boolean(localStorageChecks.netlifyConnection), + hasVercelConnection: Boolean(localStorageChecks.vercelConnection), + hasSupabaseConnection: Boolean(localStorageChecks.supabaseConnection), + githubConnectionParsed, + netlifyConnectionParsed, + vercelConnectionParsed, + supabaseConnectionParsed, + }, + apiEndpoints: { + github: githubResults, + netlify: netlifyUserCheck, + vercel: vercelUserCheck, + supabase: supabaseCheck, + }, + serverDiagnostics, + }; + + setDiagnosticResults(results); + + // Display simple results + if (results.localStorage.hasGithubConnection && results.apiEndpoints.github.some((r: { ok: boolean }) => !r.ok)) { + toast.error('GitHub API connections are failing. Try reconnecting.'); + } + + if (results.localStorage.hasNetlifyConnection && netlifyUserCheck && !netlifyUserCheck.ok) { + toast.error('Netlify API connection is failing. Try reconnecting.'); + } + + if (results.localStorage.hasVercelConnection && vercelUserCheck && !vercelUserCheck.ok) { + toast.error('Vercel API connection is failing. Try reconnecting.'); + } + + if (results.localStorage.hasSupabaseConnection && supabaseCheck && !supabaseCheck.ok) { + toast.warning('Supabase connection check failed or missing details. Verify settings.'); + } + + if ( + !results.localStorage.hasGithubConnection && + !results.localStorage.hasNetlifyConnection && + !results.localStorage.hasVercelConnection && + !results.localStorage.hasSupabaseConnection + ) { + toast.info('No connection data found in browser storage.'); + } + } catch (error) { + console.error('Diagnostics error:', error); + toast.error('Error running diagnostics'); + setDiagnosticResults({ error: error instanceof Error ? error.message : String(error) }); + } finally { + setIsRunning(false); + } + }; + + // Helper to reset GitHub connection + const resetGitHubConnection = () => { + try { + localStorage.removeItem('github_connection'); + document.cookie = 'githubToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; + document.cookie = 'githubUsername=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; + document.cookie = 'git:github.com=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; + toast.success('GitHub connection data cleared. Please refresh the page and reconnect.'); + setDiagnosticResults(null); + } catch (error) { + console.error('Error clearing GitHub data:', error); + toast.error('Failed to clear GitHub connection data'); + } + }; + + // Helper to reset Netlify connection + const resetNetlifyConnection = () => { + try { + localStorage.removeItem('netlify_connection'); + document.cookie = 'netlifyToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; + toast.success('Netlify connection data cleared. Please refresh the page and reconnect.'); + setDiagnosticResults(null); + } catch (error) { + console.error('Error clearing Netlify data:', error); + toast.error('Failed to clear Netlify connection data'); + } + }; + + // Helper to reset Vercel connection + const resetVercelConnection = () => { + try { + localStorage.removeItem('vercel_connection'); + toast.success('Vercel connection data cleared. Please refresh the page and reconnect.'); + setDiagnosticResults(null); + } catch (error) { + console.error('Error clearing Vercel data:', error); + toast.error('Failed to clear Vercel connection data'); + } + }; + + // Helper to reset Supabase connection + const resetSupabaseConnection = () => { + try { + localStorage.removeItem('supabase_connection'); + toast.success('Supabase connection data cleared. Please refresh the page and reconnect.'); + setDiagnosticResults(null); + } catch (error) { + console.error('Error clearing Supabase data:', error); + toast.error('Failed to clear Supabase connection data'); + } + }; + + return ( +
+ {/* Connection Status Cards */} +
+ {/* GitHub Connection Card */} +
+
+
+
+ GitHub Connection +
+
+ {diagnosticResults ? ( + <> +
+ + {diagnosticResults.localStorage.hasGithubConnection ? 'Connected' : 'Not Connected'} + +
+ {diagnosticResults.localStorage.hasGithubConnection && ( + <> +
+
+ User: {diagnosticResults.localStorage.githubConnectionParsed?.user?.login || 'N/A'} +
+
+
+ API Status:{' '} + r.ok) + ? 'default' + : 'destructive' + } + className="ml-1" + > + {diagnosticResults.apiEndpoints.github.every((r: { ok: boolean }) => r.ok) ? 'OK' : 'Failed'} + +
+ + )} + {!diagnosticResults.localStorage.hasGithubConnection && ( + + )} + + ) : ( +
+
+
+ Run diagnostics to check connection status +
+
+ )} +
+ + {/* Netlify Connection Card */} +
+
+
+
+ Netlify Connection +
+
+ {diagnosticResults ? ( + <> +
+ + {diagnosticResults.localStorage.hasNetlifyConnection ? 'Connected' : 'Not Connected'} + +
+ {diagnosticResults.localStorage.hasNetlifyConnection && ( + <> +
+
+ User:{' '} + {diagnosticResults.localStorage.netlifyConnectionParsed?.user?.full_name || + diagnosticResults.localStorage.netlifyConnectionParsed?.user?.email || + 'N/A'} +
+
+
+ API Status:{' '} + + {diagnosticResults.apiEndpoints.netlify?.ok ? 'OK' : 'Failed'} + +
+ + )} + {!diagnosticResults.localStorage.hasNetlifyConnection && ( + + )} + + ) : ( +
+
+
+ Run diagnostics to check connection status +
+
+ )} +
+ + {/* Vercel Connection Card */} +
+
+
+
+ Vercel Connection +
+
+ {diagnosticResults ? ( + <> +
+ + {diagnosticResults.localStorage.hasVercelConnection ? 'Connected' : 'Not Connected'} + +
+ {diagnosticResults.localStorage.hasVercelConnection && ( + <> +
+
+ User:{' '} + {diagnosticResults.localStorage.vercelConnectionParsed?.user?.username || + diagnosticResults.localStorage.vercelConnectionParsed?.user?.user?.username || + 'N/A'} +
+
+
+ API Status:{' '} + + {diagnosticResults.apiEndpoints.vercel?.ok ? 'OK' : 'Failed'} + +
+ + )} + {!diagnosticResults.localStorage.hasVercelConnection && ( + + )} + + ) : ( +
+
+
+ Run diagnostics to check connection status +
+
+ )} +
+ + {/* Supabase Connection Card */} +
+
+
+
+ Supabase Connection +
+
+ {diagnosticResults ? ( + <> +
+ + {diagnosticResults.localStorage.hasSupabaseConnection ? 'Configured' : 'Not Configured'} + +
+ {diagnosticResults.localStorage.hasSupabaseConnection && ( + <> +
+
+ Project URL: {diagnosticResults.localStorage.supabaseConnectionParsed?.projectUrl || 'N/A'} +
+
+
+ Config Status:{' '} + + {diagnosticResults.apiEndpoints.supabase?.ok ? 'OK' : 'Check Failed'} + +
+ + )} + {!diagnosticResults.localStorage.hasSupabaseConnection && ( + + )} + + ) : ( +
+
+
+ Run diagnostics to check connection status +
+
+ )} +
+
+ + {/* Action Buttons */} +
+ + + + + + + + + +
+ + {/* Details Panel */} + {diagnosticResults && ( +
+ + +
+
+ + + Diagnostic Details + +
+ +
+
+ +
+
+                  {JSON.stringify(diagnosticResults, null, 2)}
+                
+
+
+
+
+ )} +
+ ); +} diff --git a/app/components/@settings/tabs/connections/ConnectionsTab.tsx b/app/components/@settings/tabs/connections/ConnectionsTab.tsx new file mode 100644 index 0000000000..d61b6fdc1a --- /dev/null +++ b/app/components/@settings/tabs/connections/ConnectionsTab.tsx @@ -0,0 +1,184 @@ +import { motion } from 'framer-motion'; +import React, { Suspense, useState } from 'react'; +import { classNames } from '~/utils/classNames'; +import ConnectionDiagnostics from './ConnectionDiagnostics'; +import { Button } from '~/components/ui/Button'; +import VercelConnection from './VercelConnection'; + +// Use React.lazy for dynamic imports +const GitHubConnection = React.lazy(() => import('./GithubConnection')); +const NetlifyConnection = React.lazy(() => import('./NetlifyConnection')); + +// Loading fallback component +const LoadingFallback = () => ( +
+
+
+ Loading connection... +
+
+); + +export default function ConnectionsTab() { + const [isEnvVarsExpanded, setIsEnvVarsExpanded] = useState(false); + const [showDiagnostics, setShowDiagnostics] = useState(false); + + return ( +
+ {/* Header */} + +
+
+

+ Connection Settings +

+
+ + +

+ Manage your external service connections and integrations +

+ + {/* Diagnostics Tool - Conditionally rendered */} + {showDiagnostics && } + + {/* Environment Variables Info - Collapsible */} + +
+ + + {isEnvVarsExpanded && ( +
+

+ You can configure connections using environment variables in your{' '} + + .env.local + {' '} + file: +

+
+
+ # GitHub Authentication +
+
+ VITE_GITHUB_ACCESS_TOKEN=your_token_here +
+
+ # Optional: Specify token type (defaults to 'classic' if not specified) +
+
+ VITE_GITHUB_TOKEN_TYPE=classic|fine-grained +
+
+ # Netlify Authentication +
+
+ VITE_NETLIFY_ACCESS_TOKEN=your_token_here +
+
+
+

+ Token types: +

+
    +
  • + classic - Personal Access Token with{' '} + + repo, read:org, read:user + {' '} + scopes +
  • +
  • + fine-grained - Fine-grained token with Repository and + Organization access +
  • +
+

+ When set, these variables will be used automatically without requiring manual connection. +

+
+
+ )} +
+
+ +
+ }> + + + }> + + + }> + + +
+ + {/* Additional help text */} +
+

+ + Troubleshooting Tip: +

+

+ If you're having trouble with connections, try using the troubleshooting tool at the top of this page. It can + help diagnose and fix common connection issues. +

+

For persistent issues:

+
    +
  1. Check your browser console for errors
  2. +
  3. Verify that your tokens have the correct permissions
  4. +
  5. Try clearing your browser cache and cookies
  6. +
  7. Ensure your browser allows third-party cookies if using integrations
  8. +
+
+
+ ); +} diff --git a/app/components/@settings/tabs/connections/GithubConnection.tsx b/app/components/@settings/tabs/connections/GithubConnection.tsx new file mode 100644 index 0000000000..f57c4d16bf --- /dev/null +++ b/app/components/@settings/tabs/connections/GithubConnection.tsx @@ -0,0 +1,980 @@ +import React, { useState, useEffect } from 'react'; +import { motion } from 'framer-motion'; +import { toast } from 'react-toastify'; +import { logStore } from '~/lib/stores/logs'; +import { classNames } from '~/utils/classNames'; +import Cookies from 'js-cookie'; +import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '~/components/ui/Collapsible'; +import { Button } from '~/components/ui/Button'; + +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[]; + recentActivity: GitHubEvent[]; + languages: GitHubLanguageStats; + totalGists: number; + publicRepos: number; + privateRepos: number; + stars: number; + forks: number; + followers: number; + publicGists: number; + privateGists: number; + lastUpdated: string; + + // Keep these for backward compatibility + totalStars?: number; + totalForks?: number; + organizations?: GitHubOrganization[]; +} + +interface GitHubConnection { + user: GitHubUserResponse | null; + token: string; + tokenType: 'classic' | 'fine-grained'; + stats?: GitHubStats; + rateLimit?: { + limit: number; + remaining: number; + reset: number; + }; +} + +// Add the GitHub logo SVG component +const GithubLogo = () => ( + + + +); + +export default function GitHubConnection() { + const [connection, setConnection] = useState({ + user: null, + token: '', + tokenType: 'classic', + }); + const [isLoading, setIsLoading] = useState(true); + const [isConnecting, setIsConnecting] = useState(false); + const [isFetchingStats, setIsFetchingStats] = useState(false); + const [isStatsExpanded, setIsStatsExpanded] = useState(false); + const tokenTypeRef = React.useRef<'classic' | 'fine-grained'>('classic'); + + const fetchGithubUser = async (token: string) => { + try { + console.log('Fetching GitHub user with token:', token.substring(0, 5) + '...'); + + // Use server-side API endpoint instead of direct GitHub API call + const response = await fetch(`/api/system/git-info?action=getUser`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, // Include token in headers for validation + }, + }); + + if (!response.ok) { + console.error('Error fetching GitHub user. Status:', response.status); + throw new Error(`Error: ${response.status}`); + } + + // Get rate limit information from headers + const rateLimit = { + limit: parseInt(response.headers.get('x-ratelimit-limit') || '0'), + remaining: parseInt(response.headers.get('x-ratelimit-remaining') || '0'), + reset: parseInt(response.headers.get('x-ratelimit-reset') || '0'), + }; + + const data = await response.json(); + console.log('GitHub user API response:', data); + + const { user } = data as { user: GitHubUserResponse }; + + // Validate that we received a user object + if (!user || !user.login) { + console.error('Invalid user data received:', user); + throw new Error('Invalid user data received'); + } + + // Use the response data + setConnection((prev) => ({ + ...prev, + user, + token, + tokenType: tokenTypeRef.current, + rateLimit, + })); + + // Set cookies for client-side access + Cookies.set('githubUsername', user.login); + Cookies.set('githubToken', token); + Cookies.set('git:github.com', JSON.stringify({ username: token, password: 'x-oauth-basic' })); + + // Store connection details in localStorage + localStorage.setItem( + 'github_connection', + JSON.stringify({ + user, + token, + tokenType: tokenTypeRef.current, + }), + ); + + logStore.logInfo('Connected to GitHub', { + type: 'system', + message: `Connected to GitHub as ${user.login}`, + }); + + // Fetch additional GitHub stats + fetchGitHubStats(token); + } catch (error) { + console.error('Failed to fetch GitHub user:', error); + logStore.logError(`GitHub authentication failed: ${error instanceof Error ? error.message : 'Unknown error'}`, { + type: 'system', + message: 'GitHub authentication failed', + }); + + toast.error(`Authentication failed: ${error instanceof Error ? error.message : 'Unknown error'}`); + throw error; // Rethrow to allow handling in the calling function + } + }; + + const fetchGitHubStats = async (token: string) => { + setIsFetchingStats(true); + + try { + // Get the current user first to ensure we have the latest value + const userResponse = await fetch('https://api.github.com/user', { + headers: { + Authorization: `${connection.tokenType === 'classic' ? 'token' : 'Bearer'} ${token}`, + }, + }); + + if (!userResponse.ok) { + if (userResponse.status === 401) { + toast.error('Your GitHub token has expired. Please reconnect your account.'); + handleDisconnect(); + + return; + } + + throw new Error(`Failed to fetch user data: ${userResponse.statusText}`); + } + + const userData = (await userResponse.json()) as any; + + // Fetch repositories with pagination + let allRepos: any[] = []; + let page = 1; + let hasMore = true; + + while (hasMore) { + const reposResponse = await fetch(`https://api.github.com/user/repos?per_page=100&page=${page}`, { + headers: { + Authorization: `${connection.tokenType === 'classic' ? 'token' : 'Bearer'} ${token}`, + }, + }); + + if (!reposResponse.ok) { + throw new Error(`Failed to fetch repositories: ${reposResponse.statusText}`); + } + + const repos = (await reposResponse.json()) as any[]; + allRepos = [...allRepos, ...repos]; + + // Check if there are more pages + const linkHeader = reposResponse.headers.get('Link'); + hasMore = linkHeader?.includes('rel="next"') ?? false; + page++; + } + + // Calculate stats + const repoStats = calculateRepoStats(allRepos); + + // Fetch recent activity + const eventsResponse = await fetch(`https://api.github.com/users/${userData.login}/events?per_page=10`, { + headers: { + Authorization: `${connection.tokenType === 'classic' ? 'token' : 'Bearer'} ${token}`, + }, + }); + + if (!eventsResponse.ok) { + throw new Error(`Failed to fetch events: ${eventsResponse.statusText}`); + } + + const events = (await eventsResponse.json()) as any[]; + const recentActivity = events.slice(0, 5).map((event: any) => ({ + id: event.id, + type: event.type, + repo: event.repo.name, + created_at: event.created_at, + })); + + // Calculate total stars and forks + const totalStars = allRepos.reduce((sum: number, repo: any) => sum + repo.stargazers_count, 0); + const totalForks = allRepos.reduce((sum: number, repo: any) => sum + repo.forks_count, 0); + const privateRepos = allRepos.filter((repo: any) => repo.private).length; + + // Update the stats in the store + const stats: GitHubStats = { + repos: repoStats.repos, + recentActivity, + languages: repoStats.languages || {}, + totalGists: repoStats.totalGists || 0, + publicRepos: userData.public_repos || 0, + privateRepos: privateRepos || 0, + stars: totalStars || 0, + forks: totalForks || 0, + followers: userData.followers || 0, + publicGists: userData.public_gists || 0, + privateGists: userData.private_gists || 0, + lastUpdated: new Date().toISOString(), + + // For backward compatibility + totalStars: totalStars || 0, + totalForks: totalForks || 0, + organizations: [], + }; + + // Get the current user first to ensure we have the latest value + const currentConnection = JSON.parse(localStorage.getItem('github_connection') || '{}'); + const currentUser = currentConnection.user || connection.user; + + // Update connection with stats + const updatedConnection: GitHubConnection = { + user: currentUser, + token, + tokenType: connection.tokenType, + stats, + rateLimit: connection.rateLimit, + }; + + // Update localStorage + localStorage.setItem('github_connection', JSON.stringify(updatedConnection)); + + // Update state + setConnection(updatedConnection); + + toast.success('GitHub stats refreshed'); + } catch (error) { + console.error('Error fetching GitHub stats:', error); + toast.error(`Failed to fetch GitHub stats: ${error instanceof Error ? error.message : 'Unknown error'}`); + } finally { + setIsFetchingStats(false); + } + }; + + const calculateRepoStats = (repos: any[]) => { + const repoStats = { + repos: repos.map((repo: any) => ({ + name: repo.name, + full_name: repo.full_name, + html_url: repo.html_url, + description: repo.description, + stargazers_count: repo.stargazers_count, + forks_count: repo.forks_count, + default_branch: repo.default_branch, + updated_at: repo.updated_at, + languages_url: repo.languages_url, + })), + + languages: {} as Record, + totalGists: 0, + }; + + repos.forEach((repo: any) => { + fetch(repo.languages_url) + .then((response) => response.json()) + .then((languages: any) => { + const typedLanguages = languages as Record; + Object.keys(typedLanguages).forEach((language) => { + if (!repoStats.languages[language]) { + repoStats.languages[language] = 0; + } + + repoStats.languages[language] += 1; + }); + }); + }); + + return repoStats; + }; + + useEffect(() => { + const loadSavedConnection = async () => { + setIsLoading(true); + + const savedConnection = localStorage.getItem('github_connection'); + + if (savedConnection) { + try { + const parsed = JSON.parse(savedConnection); + + if (!parsed.tokenType) { + parsed.tokenType = 'classic'; + } + + // Update the ref with the parsed token type + tokenTypeRef.current = parsed.tokenType; + + // Set the connection + setConnection(parsed); + + // If we have a token but no stats or incomplete stats, fetch them + if ( + parsed.user && + parsed.token && + (!parsed.stats || !parsed.stats.repos || parsed.stats.repos.length === 0) + ) { + console.log('Fetching missing GitHub stats for saved connection'); + await fetchGitHubStats(parsed.token); + } + } catch (error) { + console.error('Error parsing saved GitHub connection:', error); + localStorage.removeItem('github_connection'); + } + } else { + // Check for environment variable token + const envToken = import.meta.env.VITE_GITHUB_ACCESS_TOKEN; + + if (envToken) { + // Check if token type is specified in environment variables + const envTokenType = import.meta.env.VITE_GITHUB_TOKEN_TYPE; + console.log('Environment token type:', envTokenType); + + const tokenType = + envTokenType === 'classic' || envTokenType === 'fine-grained' + ? (envTokenType as 'classic' | 'fine-grained') + : 'classic'; + + console.log('Using token type:', tokenType); + + // Update both the state and the ref + tokenTypeRef.current = tokenType; + setConnection((prev) => ({ + ...prev, + tokenType, + })); + + try { + // Fetch user data with the environment token + await fetchGithubUser(envToken); + } catch (error) { + console.error('Failed to connect with environment token:', error); + } + } + } + + setIsLoading(false); + }; + + loadSavedConnection(); + }, []); + + // Ensure cookies are updated when connection changes + useEffect(() => { + if (!connection) { + return; + } + + const token = connection.token; + const data = connection.user; + + if (token) { + Cookies.set('githubToken', token); + Cookies.set('git:github.com', JSON.stringify({ username: token, password: 'x-oauth-basic' })); + } + + if (data) { + Cookies.set('githubUsername', data.login); + } + }, [connection]); + + // Add function to update rate limits + const updateRateLimits = async (token: string) => { + try { + const response = await fetch('https://api.github.com/rate_limit', { + headers: { + Authorization: `Bearer ${token}`, + Accept: 'application/vnd.github.v3+json', + }, + }); + + if (response.ok) { + const rateLimit = { + limit: parseInt(response.headers.get('x-ratelimit-limit') || '0'), + remaining: parseInt(response.headers.get('x-ratelimit-remaining') || '0'), + reset: parseInt(response.headers.get('x-ratelimit-reset') || '0'), + }; + + setConnection((prev) => ({ + ...prev, + rateLimit, + })); + } + } catch (error) { + console.error('Failed to fetch rate limits:', error); + } + }; + + // Add effect to update rate limits periodically + useEffect(() => { + let interval: NodeJS.Timeout; + + if (connection.token && connection.user) { + updateRateLimits(connection.token); + interval = setInterval(() => updateRateLimits(connection.token), 60000); // Update every minute + } + + return () => { + if (interval) { + clearInterval(interval); + } + }; + }, [connection.token, connection.user]); + + if (isLoading || isConnecting || isFetchingStats) { + return ; + } + + const handleConnect = async (event: React.FormEvent) => { + event.preventDefault(); + setIsConnecting(true); + + try { + // Update the ref with the current state value before connecting + tokenTypeRef.current = connection.tokenType; + + /* + * Save token type to localStorage even before connecting + * This ensures the token type is persisted even if connection fails + */ + localStorage.setItem( + 'github_connection', + JSON.stringify({ + user: null, + token: connection.token, + tokenType: connection.tokenType, + }), + ); + + // Attempt to fetch the user info which validates the token + await fetchGithubUser(connection.token); + + toast.success('Connected to GitHub successfully'); + } catch (error) { + console.error('Failed to connect to GitHub:', error); + + // Reset connection state on failure + setConnection({ user: null, token: connection.token, tokenType: connection.tokenType }); + + toast.error(`Failed to connect to GitHub: ${error instanceof Error ? error.message : 'Unknown error'}`); + } finally { + setIsConnecting(false); + } + }; + + const handleDisconnect = () => { + localStorage.removeItem('github_connection'); + + // Remove all GitHub-related cookies + Cookies.remove('githubToken'); + Cookies.remove('githubUsername'); + Cookies.remove('git:github.com'); + + // Reset the token type ref + tokenTypeRef.current = 'classic'; + setConnection({ user: null, token: '', tokenType: 'classic' }); + toast.success('Disconnected from GitHub'); + }; + + return ( + +
+
+
+ +

+ GitHub Connection +

+
+
+ + {!connection.user && ( +
+

+ + Tip: You can also set the{' '} + + VITE_GITHUB_ACCESS_TOKEN + {' '} + environment variable to connect automatically. +

+

+ For fine-grained tokens, also set{' '} + + VITE_GITHUB_TOKEN_TYPE=fine-grained + +

+
+ )} +
+
+ + +
+ +
+ + 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-bolt-elements-borderColorActive', + 'disabled:opacity-50', + )} + /> +
+ + Get your token +
+ + β€’ + + Required scopes:{' '} + {connection.tokenType === 'classic' + ? 'repo, read:org, read:user' + : 'Repository access, Organization access'} + +
+
+
+ +
+ {!connection.user ? ( + + ) : ( + <> +
+
+ + +
+ Connected to GitHub + +
+
+ + +
+
+ + )} +
+ + {connection.user && connection.stats && ( +
+
+ {connection.user.login} +
+

+ {connection.user.name || connection.user.login} +

+

+ {connection.user.login} +

+
+
+ + + +
+
+
+ GitHub Stats +
+
+
+ + +
+ {/* Languages Section */} +
+

Top Languages

+
+ {Object.entries(connection.stats.languages) + .sort(([, a], [, b]) => b - a) + .slice(0, 5) + .map(([language]) => ( + + {language} + + ))} +
+
+ + {/* Additional Stats */} +
+ {[ + { + label: 'Member Since', + value: new Date(connection.user.created_at).toLocaleDateString(), + }, + { + label: 'Public Gists', + value: connection.stats.publicGists, + }, + { + label: 'Organizations', + value: connection.stats.organizations ? connection.stats.organizations.length : 0, + }, + { + label: 'Languages', + value: Object.keys(connection.stats.languages).length, + }, + ].map((stat, index) => ( +
+ {stat.label} + {stat.value} +
+ ))} +
+ + {/* Repository Stats */} +
+
+
+
Repository Stats
+
+ {[ + { + label: 'Public Repos', + value: connection.stats.publicRepos, + }, + { + label: 'Private Repos', + value: connection.stats.privateRepos, + }, + ].map((stat, index) => ( +
+ {stat.label} + {stat.value} +
+ ))} +
+
+ +
+
Contribution Stats
+
+ {[ + { + label: 'Stars', + value: connection.stats.stars || 0, + icon: 'i-ph:star', + iconColor: 'text-bolt-elements-icon-warning', + }, + { + label: 'Forks', + value: connection.stats.forks || 0, + icon: 'i-ph:git-fork', + iconColor: 'text-bolt-elements-icon-info', + }, + { + label: 'Followers', + value: connection.stats.followers || 0, + icon: 'i-ph:users', + iconColor: 'text-bolt-elements-icon-success', + }, + ].map((stat, index) => ( +
+ {stat.label} + +
+ {stat.value} + +
+ ))} +
+
+ +
+
Gists
+
+ {[ + { + label: 'Public', + value: connection.stats.publicGists, + }, + { + label: 'Private', + value: connection.stats.privateGists || 0, + }, + ].map((stat, index) => ( +
+ {stat.label} + {stat.value} +
+ ))} +
+
+ +
+ + Last updated: {new Date(connection.stats.lastUpdated).toLocaleString()} + +
+
+
+ + {/* Repositories Section */} +
+

Recent Repositories

+
+ {connection.stats.repos.map((repo) => ( + +
+ + + ); +} + +function LoadingSpinner() { + return ( +
+
+
+ Loading... +
+
+ ); +} diff --git a/app/components/@settings/tabs/connections/NetlifyConnection.tsx b/app/components/@settings/tabs/connections/NetlifyConnection.tsx new file mode 100644 index 0000000000..2bd95f4fd2 --- /dev/null +++ b/app/components/@settings/tabs/connections/NetlifyConnection.tsx @@ -0,0 +1,731 @@ +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, +} 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 = () => ( + + + +); + +// Add new interface for site actions +interface SiteAction { + name: string; + icon: React.ComponentType; + action: (siteId: string) => Promise; + requiresConfirmation?: boolean; + variant?: 'default' | 'destructive' | 'outline'; +} + +export default function NetlifyConnection() { + const connection = useStore(netlifyConnection); + const [tokenInput, setTokenInput] = useState(''); + const [fetchingStats, setFetchingStats] = useState(false); + const [sites, setSites] = useState([]); + const [deploys, setDeploys] = useState([]); + const [builds, setBuilds] = useState([]); + 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 { + const response = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/cache`, { + method: 'POST', + headers: { + Authorization: `Bearer ${connection.token}`, + }, + }); + + if (!response.ok) { + throw new Error('Failed to clear cache'); + } + + 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: '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(() => { + // 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 ( +
+ + +
+
+
+ + Netlify Stats + +
+
+
+ + +
+
+ + + {connection.stats.totalSites} Sites + + + + {deploymentCount} Deployments + + {lastUpdated && ( + + + Updated {formatDistanceToNow(new Date(lastUpdated))} ago + + )} +
+ {sites.length > 0 && ( +
+
+
+

+ + Your Sites +

+ +
+
+ {sites.map((site, index) => ( +
{ + setActiveSiteIndex(index); + }} + > +
+
+ + + {site.name} + +
+
+ + {site.published_deploy?.state === 'ready' ? ( + + ) : ( + + )} + + {site.published_deploy?.state || 'Unknown'} + + +
+
+ + + + {activeSiteIndex === index && ( + <> +
+
+ {siteActions.map((action) => ( + + ))} +
+
+ {site.published_deploy && ( +
+
+ + + Published {formatDistanceToNow(new Date(site.published_deploy.published_at))} ago + +
+ {site.published_deploy.branch && ( +
+ + + Branch: {site.published_deploy.branch} + +
+ )} +
+ )} + + )} +
+ ))} +
+
+ {activeSiteIndex !== -1 && deploys.length > 0 && ( +
+
+

+ + Recent Deployments +

+
+
+ {deploys.map((deploy) => ( +
+
+
+ + {deploy.state === 'ready' ? ( + + ) : deploy.state === 'error' ? ( + + ) : ( + + )} + + {deploy.state} + + +
+ + {formatDistanceToNow(new Date(deploy.created_at))} ago + +
+ {deploy.branch && ( +
+ + + Branch: {deploy.branch} + +
+ )} + {deploy.deploy_url && ( + + )} +
+ + {deploy.state === 'ready' ? ( + + ) : ( + + )} +
+
+ ))} +
+
+ )} + {activeSiteIndex !== -1 && builds.length > 0 && ( +
+
+

+ + Recent Builds +

+
+
+ {builds.map((build) => ( +
+
+
+ + {build.done && !build.error ? ( + + ) : build.error ? ( + + ) : ( + + )} + + {build.done ? (build.error ? 'Failed' : 'Completed') : 'In Progress'} + + +
+ + {formatDistanceToNow(new Date(build.created_at))} ago + +
+ {build.error && ( +
+ + Error: {build.error} +
+ )} +
+ ))} +
+
+ )} +
+ )} +
+
+ +
+ ); + }; + + return ( +
+
+
+
+
+ +
+

Netlify Connection

+
+
+ + {!connection.user ? ( +
+ + 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', + )} + /> +
+ + Get your token +
+ +
+
+ +
+
+ ) : ( +
+
+ + +
+ Connected to Netlify + +
+ {renderStats()} +
+ )} +
+
+ ); +} diff --git a/app/components/@settings/tabs/connections/VercelConnection.tsx b/app/components/@settings/tabs/connections/VercelConnection.tsx new file mode 100644 index 0000000000..852782232f --- /dev/null +++ b/app/components/@settings/tabs/connections/VercelConnection.tsx @@ -0,0 +1,290 @@ +import React, { useEffect, useState } from 'react'; +import { motion } from 'framer-motion'; +import { toast } from 'react-toastify'; +import { useStore } from '@nanostores/react'; +import { logStore } from '~/lib/stores/logs'; +import { classNames } from '~/utils/classNames'; +import { + vercelConnection, + isConnecting, + isFetchingStats, + updateVercelConnection, + fetchVercelStats, +} from '~/lib/stores/vercel'; + +export default function VercelConnection() { + const connection = useStore(vercelConnection); + const connecting = useStore(isConnecting); + const fetchingStats = useStore(isFetchingStats); + const [isProjectsExpanded, setIsProjectsExpanded] = useState(false); + + useEffect(() => { + const fetchProjects = async () => { + if (connection.user && connection.token) { + await fetchVercelStats(connection.token); + } + }; + fetchProjects(); + }, [connection.user, connection.token]); + + const handleConnect = async (event: React.FormEvent) => { + event.preventDefault(); + isConnecting.set(true); + + try { + const response = await fetch('https://api.vercel.com/v2/user', { + headers: { + Authorization: `Bearer ${connection.token}`, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error('Invalid token or unauthorized'); + } + + const userData = (await response.json()) as any; + updateVercelConnection({ + user: userData.user || userData, // Handle both possible structures + token: connection.token, + }); + + await fetchVercelStats(connection.token); + toast.success('Successfully connected to Vercel'); + } catch (error) { + console.error('Auth error:', error); + logStore.logError('Failed to authenticate with Vercel', { error }); + toast.error('Failed to connect to Vercel'); + updateVercelConnection({ user: null, token: '' }); + } finally { + isConnecting.set(false); + } + }; + + const handleDisconnect = () => { + updateVercelConnection({ user: null, token: '' }); + toast.success('Disconnected from Vercel'); + }; + + console.log('connection', connection); + + return ( + +
+
+
+ +

Vercel Connection

+
+
+ + {!connection.user ? ( +
+
+ + updateVercelConnection({ ...connection, token: e.target.value })} + disabled={connecting} + placeholder="Enter your Vercel personal access 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', + )} + /> + + + +
+ ) : ( +
+
+
+ + +
+ Connected to Vercel + +
+
+ +
+ {/* Debug output */} +
{JSON.stringify(connection.user, null, 2)}
+ + User Avatar +
+

+ {connection.user?.username || connection.user?.user?.username || 'Vercel User'} +

+

+ {connection.user?.email || connection.user?.user?.email || 'No email available'} +

+
+
+ + {fetchingStats ? ( +
+
+ Fetching Vercel projects... +
+ ) : ( +
+ + {isProjectsExpanded && connection.stats?.projects?.length ? ( +
+ {connection.stats.projects.map((project) => ( + +
+
+
+
+ {project.name} +
+
+ {project.targets?.production?.alias && project.targets.production.alias.length > 0 ? ( + <> + a.endsWith('.vercel.app') && !a.includes('-projects.vercel.app')) || project.targets.production.alias[0]}`} + target="_blank" + rel="noopener noreferrer" + className="hover:text-bolt-elements-borderColorActive" + > + {project.targets.production.alias.find( + (a: string) => a.endsWith('.vercel.app') && !a.includes('-projects.vercel.app'), + ) || project.targets.production.alias[0]} + + β€’ + +
+ {new Date(project.createdAt).toLocaleDateString()} + + + ) : project.latestDeployments && project.latestDeployments.length > 0 ? ( + <> + + {project.latestDeployments[0].url} + + β€’ + +
+ {new Date(project.latestDeployments[0].created).toLocaleDateString()} + + + ) : null} +
+
+ {project.framework && ( +
+ +
+ {project.framework} + +
+ )} +
+ + ))} +
+ ) : isProjectsExpanded ? ( +
+
+ No projects found in your Vercel account +
+ ) : null} +
+ )} +
+ )} +
+ + ); +} diff --git a/app/components/@settings/tabs/connections/components/ConnectionForm.tsx b/app/components/@settings/tabs/connections/components/ConnectionForm.tsx new file mode 100644 index 0000000000..2c9876b6ea --- /dev/null +++ b/app/components/@settings/tabs/connections/components/ConnectionForm.tsx @@ -0,0 +1,183 @@ +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>; + 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) || Cookies.get('githubToken') || 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, + }, + })); + + // Ensure the token is also saved with the correct key for API requests + Cookies.set('githubToken', savedToken); + } + }, []); + + return ( +
+
+
+
+
+
+
+
+

Connection Settings

+

Configure your GitHub connection

+
+
+
+ +
+
+ + 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" + /> +
+ +
+
+ + + Generate new token +
+ +
+ + 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" + /> +
+ +
+
+ {!authState.isConnected ? ( + + ) : ( + <> + + +
+ Connected + + + )} +
+ {authState.rateLimits && ( +
+
+ Rate limit resets at {authState.rateLimits.reset.toLocaleTimeString()} +
+ )} +
+ +
+
+ ); +} diff --git a/app/components/@settings/tabs/connections/components/CreateBranchDialog.tsx b/app/components/@settings/tabs/connections/components/CreateBranchDialog.tsx new file mode 100644 index 0000000000..3fd32ff275 --- /dev/null +++ b/app/components/@settings/tabs/connections/components/CreateBranchDialog.tsx @@ -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 ( + + + + + + Create New Branch + + +
+
+
+ + 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 + /> +
+ +
+ + +
+ +
+

Branch Overview

+
    +
  • + + Repository: {repository.name} +
  • + {branchName && ( +
  • +
    + New branch will be created as: {branchName} +
  • + )} +
  • +
    + Based on: {sourceBranch} +
  • +
+
+
+ +
+ + +
+
+
+
+
+ ); +} diff --git a/app/components/@settings/tabs/connections/components/GitHubAuthDialog.tsx b/app/components/@settings/tabs/connections/components/GitHubAuthDialog.tsx new file mode 100644 index 0000000000..b53a64d4cd --- /dev/null +++ b/app/components/@settings/tabs/connections/components/GitHubAuthDialog.tsx @@ -0,0 +1,190 @@ +import React, { useState } from 'react'; +import * as Dialog from '@radix-ui/react-dialog'; +import { motion } from 'framer-motion'; +import { toast } from 'react-toastify'; +import Cookies from 'js-cookie'; +import type { GitHubUserResponse } from '~/types/GitHub'; + +interface GitHubAuthDialogProps { + isOpen: boolean; + onClose: () => void; +} + +export function GitHubAuthDialog({ isOpen, onClose }: GitHubAuthDialogProps) { + const [token, setToken] = useState(''); + const [isSubmitting, setIsSubmitting] = useState(false); + const [tokenType, setTokenType] = useState<'classic' | 'fine-grained'>('classic'); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + + if (!token.trim()) { + return; + } + + setIsSubmitting(true); + + try { + const response = await fetch('https://api.github.com/user', { + headers: { + Accept: 'application/vnd.github.v3+json', + Authorization: `Bearer ${token}`, + }, + }); + + if (response.ok) { + const userData = (await response.json()) as GitHubUserResponse; + + // Save connection data + const connectionData = { + token, + tokenType, + user: { + login: userData.login, + avatar_url: userData.avatar_url, + name: userData.name || userData.login, + }, + connected_at: new Date().toISOString(), + }; + + localStorage.setItem('github_connection', JSON.stringify(connectionData)); + + // Set cookies for API requests + Cookies.set('githubToken', token); + Cookies.set('githubUsername', userData.login); + Cookies.set('git:github.com', JSON.stringify({ username: token, password: 'x-oauth-basic' })); + + toast.success(`Successfully connected as ${userData.login}`); + setToken(''); + onClose(); + } else { + if (response.status === 401) { + toast.error('Invalid GitHub token. Please check and try again.'); + } else { + toast.error(`GitHub API error: ${response.status} ${response.statusText}`); + } + } + } catch (error) { + console.error('Error connecting to GitHub:', error); + toast.error('Failed to connect to GitHub. Please try again.'); + } finally { + setIsSubmitting(false); + } + }; + + return ( + !open && onClose()}> + + +
+ + +
+

Access Private Repositories

+ +

+ To access private repositories, you need to connect your GitHub account by providing a personal access + token. +

+ +
+

Connect with GitHub Token

+ +
+
+ + setToken(e.target.value)} + placeholder="ghp_xxxxxxxxxxxxxxxxxxxx" + className="w-full px-3 py-1.5 rounded-lg border border-[#E5E5E5] dark:border-[#333333] bg-white dark:bg-[#1A1A1A] text-[#111111] dark:text-white placeholder-[#999999] text-sm" + /> +
+ Get your token at{' '} + + github.com/settings/tokens + +
+
+ +
+ +
+ + +
+
+ + +
+
+ +
+

+ + Accessing Private Repositories +

+

+ Important things to know about accessing private repositories: +

+
    +
  • You must be granted access to the repository by its owner
  • +
  • Your GitHub token must have the 'repo' scope
  • +
  • For organization repositories, you may need additional permissions
  • +
  • No token can give you access to repositories you don't have permission for
  • +
+
+
+ +
+ + + +
+
+
+
+
+
+ ); +} diff --git a/app/components/@settings/tabs/connections/components/PushToGitHubDialog.tsx b/app/components/@settings/tabs/connections/components/PushToGitHubDialog.tsx new file mode 100644 index 0000000000..1f8adb9527 --- /dev/null +++ b/app/components/@settings/tabs/connections/components/PushToGitHubDialog.tsx @@ -0,0 +1,717 @@ +import * as Dialog from '@radix-ui/react-dialog'; +import { useState, useEffect, useCallback } from 'react'; +import { toast } from 'react-toastify'; +import { motion } from 'framer-motion'; +import { Octokit } from '@octokit/rest'; + +// Internal imports +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'; + +// UI Components +import { Badge, EmptyState, StatusIndicator, SearchInput } from '~/components/ui'; + +interface PushToGitHubDialogProps { + isOpen: boolean; + onClose: () => void; + onPush: (repoName: string, username?: string, token?: string, isPrivate?: boolean) => Promise; +} + +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(null); + const [recentRepos, setRecentRepos] = useState([]); + const [filteredRepos, setFilteredRepos] = useState([]); + const [repoSearchQuery, setRepoSearchQuery] = useState(''); + 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]); + + /* + * Filter repositories based on search query + * const debouncedSetRepoSearchQuery = useDebouncedCallback((value: string) => setRepoSearchQuery(value), 300); + */ + + useEffect(() => { + if (recentRepos.length === 0) { + setFilteredRepos([]); + return; + } + + if (!repoSearchQuery.trim()) { + setFilteredRepos(recentRepos); + return; + } + + const query = repoSearchQuery.toLowerCase().trim(); + const filtered = recentRepos.filter( + (repo) => + repo.name.toLowerCase().includes(query) || + (repo.description && repo.description.toLowerCase().includes(query)) || + (repo.language && repo.language.toLowerCase().includes(query)), + ); + + setFilteredRepos(filtered); + }, [recentRepos, repoSearchQuery]); + + const fetchRecentRepos = useCallback(async (token: string) => { + if (!token) { + logStore.logError('No GitHub token available'); + toast.error('GitHub authentication required'); + + return; + } + + try { + setIsFetchingRepos(true); + console.log('Fetching GitHub repositories with token:', token.substring(0, 5) + '...'); + + // Fetch ALL repos by paginating through all pages + let allRepos: GitHubRepo[] = []; + let page = 1; + let hasMore = true; + + while (hasMore) { + const requestUrl = `https://api.github.com/user/repos?sort=updated&per_page=100&page=${page}&affiliation=owner,organization_member`; + const response = await fetch(requestUrl, { + headers: { + Accept: 'application/vnd.github.v3+json', + Authorization: `Bearer ${token.trim()}`, + }, + }); + + if (!response.ok) { + let errorData: { message?: string } = {}; + + try { + errorData = await response.json(); + console.error('Error response data:', errorData); + } catch (e) { + errorData = { message: 'Could not parse error response' }; + console.error('Could not parse error response:', e); + } + + 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 if (response.status === 403 && response.headers.get('x-ratelimit-remaining') === '0') { + // Rate limit exceeded + const resetTime = response.headers.get('x-ratelimit-reset'); + const resetDate = resetTime ? new Date(parseInt(resetTime) * 1000).toLocaleTimeString() : 'soon'; + toast.error(`GitHub API rate limit exceeded. Limit resets at ${resetDate}`); + } else { + logStore.logError('Failed to fetch GitHub repositories', { + status: response.status, + statusText: response.statusText, + error: errorData, + }); + toast.error(`Failed to fetch repositories: ${errorData.message || response.statusText}`); + } + + return; + } + + try { + const repos = (await response.json()) as GitHubRepo[]; + allRepos = allRepos.concat(repos); + + if (repos.length < 100) { + hasMore = false; + } else { + page += 1; + } + } catch (parseError) { + console.error('Error parsing JSON response:', parseError); + logStore.logError('Failed to parse GitHub repositories response', { parseError }); + toast.error('Failed to parse repository data'); + setRecentRepos([]); + + return; + } + } + setRecentRepos(allRepos); + } catch (error) { + console.error('Exception while fetching GitHub repositories:', error); + logStore.logError('Failed to fetch GitHub repositories', { error }); + toast.error('Failed to fetch recent repositories'); + } finally { + setIsFetchingRepos(false); + } + }, []); + + async function handleSubmit(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 { + const { data: existingRepo } = await octokit.repos.get({ + owner: connection.user.login, + repo: repoName, + }); + + // If we get here, the repo exists + let confirmMessage = `Repository "${repoName}" already exists. Do you want to update it? This will add or modify files in the repository.`; + + // Add visibility change warning if needed + if (existingRepo.private !== isPrivate) { + const visibilityChange = isPrivate + ? 'This will also change the repository from public to private.' + : 'This will also change the repository from private to public.'; + + confirmMessage += `\n\n${visibilityChange}`; + } + + const confirmOverwrite = window.confirm(confirmMessage); + + 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 ( + !open && handleClose()}> + + +
+ + +
+
+
+
+
+
+
+

+ Successfully pushed to GitHub +

+

+ Your code is now available on GitHub +

+
+
+ + + +
+ +
+

+ + Repository URL +

+
+ + {createdRepoUrl} + + { + 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 bg-bolt-elements-background-depth-1 dark:bg-bolt-elements-background-depth-4 rounded-lg border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark" + whileHover={{ scale: 1.05 }} + whileTap={{ scale: 0.95 }} + > +
+ +
+
+ +
+

+ + Pushed Files ({pushedFiles.length}) +

+
+ {pushedFiles.map((file) => ( +
+ {file.path} + + {formatSize(file.size)} + +
+ ))} +
+
+ +
+ +
+ View Repository + + { + navigator.clipboard.writeText(createdRepoUrl); + toast.success('URL copied to clipboard'); + }} + 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 inline-flex items-center gap-2 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark" + whileHover={{ scale: 1.02 }} + whileTap={{ scale: 0.98 }} + > +
+ Copy URL + + + Close + +
+
+ + +
+ + + ); + } + + if (!user) { + return ( + !open && handleClose()}> + + +
+ + +
+ + + + +
+ +

+ GitHub Connection Required +

+

+ To push your code to GitHub, you need to connect your GitHub account in Settings {'>'} Connections + first. +

+
+ + Close + + +
+ Go to Settings + +
+
+ + +
+ + + ); + } + + return ( + !open && handleClose()}> + + +
+ + +
+
+ +
+ +
+ + Push to GitHub + +

+ Push your code to a new or existing GitHub repository +

+
+ + + +
+ +
+
+ {user.login} +
+
+
+
+
+

+ {user.name || user.login} +

+

+ @{user.login} +

+
+
+ +
+
+ +
+
+ +
+ setRepoName(e.target.value)} + placeholder="my-awesome-project" + className="w-full pl-10 px-4 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 placeholder-bolt-elements-textTertiary dark:placeholder-bolt-elements-textTertiary-dark focus:outline-none focus:ring-2 focus:ring-purple-500" + required + /> +
+
+ +
+
+ + + {filteredRepos.length} of {recentRepos.length} + +
+ +
+ setRepoSearchQuery(e.target.value)} + onClear={() => setRepoSearchQuery('')} + className="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-sm" + /> +
+ + {recentRepos.length === 0 && !isFetchingRepos ? ( + + ) : ( +
+ {filteredRepos.length === 0 && repoSearchQuery.trim() !== '' ? ( + + ) : ( + filteredRepos.map((repo) => ( + 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 border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark hover:border-purple-500/30" + whileHover={{ scale: 1.01 }} + whileTap={{ scale: 0.99 }} + > +
+
+
+ + {repo.name} + +
+ {repo.private && ( + + Private + + )} +
+ {repo.description && ( +

+ {repo.description} +

+ )} +
+ {repo.language && ( + + {repo.language} + + )} + + {repo.stargazers_count.toLocaleString()} + + + {repo.forks_count.toLocaleString()} + + + {new Date(repo.updated_at).toLocaleDateString()} + +
+ + )) + )} +
+ )} +
+ + {isFetchingRepos && ( +
+ +
+ )} +
+
+ setIsPrivate(e.target.checked)} + className="rounded border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark text-purple-500 focus:ring-purple-500 dark:bg-bolt-elements-background-depth-3" + /> + +
+

+ Private repositories are only visible to you and people you share them with +

+
+ +
+ + Cancel + + + {isLoading ? ( + <> +
+ Pushing... + + ) : ( + <> +
+ Push to GitHub + + )} + +
+ +
+ + +
+ + + ); +} diff --git a/app/components/@settings/tabs/connections/components/RepositoryCard.tsx b/app/components/@settings/tabs/connections/components/RepositoryCard.tsx new file mode 100644 index 0000000000..0d63277cd3 --- /dev/null +++ b/app/components/@settings/tabs/connections/components/RepositoryCard.tsx @@ -0,0 +1,146 @@ +import React from 'react'; +import { motion } from 'framer-motion'; +import type { GitHubRepoInfo } from '~/types/GitHub'; + +interface RepositoryCardProps { + repo: GitHubRepoInfo; + onSelect: () => void; +} + +import { useMemo } from 'react'; + +export function RepositoryCard({ repo, onSelect }: RepositoryCardProps) { + // Use a consistent styling for all repository cards + const getCardStyle = () => { + return 'from-bolt-elements-background-depth-1 to-bolt-elements-background-depth-1 dark:from-bolt-elements-background-depth-2-dark dark:to-bolt-elements-background-depth-2-dark'; + }; + + // Format the date in a more readable format + const formatDate = (dateString: string) => { + const date = new Date(dateString); + const now = new Date(); + const diffTime = Math.abs(now.getTime() - date.getTime()); + const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); + + if (diffDays <= 1) { + return 'Today'; + } + + if (diffDays <= 2) { + return 'Yesterday'; + } + + if (diffDays <= 7) { + return `${diffDays} days ago`; + } + + if (diffDays <= 30) { + return `${Math.floor(diffDays / 7)} weeks ago`; + } + + return date.toLocaleDateString(undefined, { + year: 'numeric', + month: 'short', + day: 'numeric', + }); + }; + + const cardStyle = useMemo(() => getCardStyle(), []); + + // const formattedDate = useMemo(() => formatDate(repo.updated_at), [repo.updated_at]); + + return ( + +
+
+
+ +
+
+

+ {repo.name} +

+

+ + {repo.full_name.split('/')[0]} +

+
+
+ + + Import + +
+ + {repo.description && ( +
+

+ {repo.description} +

+
+ )} + +
+ {repo.private && ( + + + Private + + )} + {repo.language && ( + + + {repo.language} + + )} + + + {repo.stargazers_count.toLocaleString()} + + {repo.forks_count > 0 && ( + + + {repo.forks_count.toLocaleString()} + + )} +
+ +
+ + + Updated {formatDate(repo.updated_at)} + + + {repo.topics && repo.topics.length > 0 && ( + + {repo.topics.slice(0, 1).map((topic) => ( + + {topic} + + ))} + {repo.topics.length > 1 && +{repo.topics.length - 1}} + + )} +
+
+ ); +} diff --git a/app/components/@settings/tabs/connections/components/RepositoryDialogContext.tsx b/app/components/@settings/tabs/connections/components/RepositoryDialogContext.tsx new file mode 100644 index 0000000000..8a0490e2f5 --- /dev/null +++ b/app/components/@settings/tabs/connections/components/RepositoryDialogContext.tsx @@ -0,0 +1,14 @@ +import { createContext } from 'react'; + +// Create a context to share the setShowAuthDialog function with child components +export interface RepositoryDialogContextType { + setShowAuthDialog: React.Dispatch>; +} + +// Default context value with a no-op function +export const RepositoryDialogContext = createContext({ + // This is intentionally empty as it will be overridden by the provider + setShowAuthDialog: () => { + // No operation + }, +}); diff --git a/app/components/@settings/tabs/connections/components/RepositoryList.tsx b/app/components/@settings/tabs/connections/components/RepositoryList.tsx new file mode 100644 index 0000000000..d6f0abdae4 --- /dev/null +++ b/app/components/@settings/tabs/connections/components/RepositoryList.tsx @@ -0,0 +1,58 @@ +import React, { useContext } from 'react'; +import type { GitHubRepoInfo } from '~/types/GitHub'; +import { EmptyState, StatusIndicator } from '~/components/ui'; +import { RepositoryCard } from './RepositoryCard'; +import { RepositoryDialogContext } from './RepositoryDialogContext'; + +interface RepositoryListProps { + repos: GitHubRepoInfo[]; + isLoading: boolean; + onSelect: (repo: GitHubRepoInfo) => void; + activeTab: string; +} + +export function RepositoryList({ repos, isLoading, onSelect, activeTab }: RepositoryListProps) { + // Access the parent component's setShowAuthDialog function + const { setShowAuthDialog } = useContext(RepositoryDialogContext); + + if (isLoading) { + return ( +
+ +

+ This may take a moment +

+
+ ); + } + + if (repos.length === 0) { + if (activeTab === 'my-repos') { + return ( + setShowAuthDialog(true)} + /> + ); + } else { + return ( + + ); + } + } + + return ( +
+ {repos.map((repo) => ( + onSelect(repo)} /> + ))} +
+ ); +} diff --git a/app/components/@settings/tabs/connections/components/RepositorySelectionDialog.tsx b/app/components/@settings/tabs/connections/components/RepositorySelectionDialog.tsx new file mode 100644 index 0000000000..82e1fbc483 --- /dev/null +++ b/app/components/@settings/tabs/connections/components/RepositorySelectionDialog.tsx @@ -0,0 +1,993 @@ +import type { GitHubRepoInfo, GitHubContent, RepositoryStats, GitHubUserResponse } 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, AnimatePresence } from 'framer-motion'; +import Cookies from 'js-cookie'; + +// Import UI components +import { Input, SearchInput, Badge, FilterChip } from '~/components/ui'; + +// Import the components we've extracted +import { RepositoryList } from './RepositoryList'; +import { StatsDialog } from './StatsDialog'; +import { GitHubAuthDialog } from './GitHubAuthDialog'; +import { RepositoryDialogContext } from './RepositoryDialogContext'; + +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; +} + +export function RepositorySelectionDialog({ isOpen, onClose, onSelect }: RepositorySelectionDialogProps) { + const [selectedRepository, setSelectedRepository] = useState(null); + const [isLoading, setIsLoading] = useState(false); + const [repositories, setRepositories] = useState([]); + const [searchQuery, setSearchQuery] = useState(''); + const [searchResults, setSearchResults] = useState([]); + 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({}); + const [showStatsDialog, setShowStatsDialog] = useState(false); + const [currentStats, setCurrentStats] = useState(null); + const [pendingGitUrl, setPendingGitUrl] = useState(''); + const [showAuthDialog, setShowAuthDialog] = useState(false); + + // Handle GitHub auth dialog close and refresh repositories + const handleAuthDialogClose = () => { + setShowAuthDialog(false); + + // If we're on the my-repos tab, refresh the repository list + if (activeTab === 'my-repos') { + fetchUserRepos(); + } + }; + + // Initialize GitHub connection and fetch repositories + useEffect(() => { + const savedConnection = getLocalStorage('github_connection'); + + // If no connection exists but environment variables are set, create a connection + if (!savedConnection && import.meta.env.VITE_GITHUB_ACCESS_TOKEN) { + const token = import.meta.env.VITE_GITHUB_ACCESS_TOKEN; + const tokenType = import.meta.env.VITE_GITHUB_TOKEN_TYPE === 'fine-grained' ? 'fine-grained' : 'classic'; + + // Fetch GitHub user info to initialize the connection + fetch('https://api.github.com/user', { + headers: { + Accept: 'application/vnd.github.v3+json', + Authorization: `Bearer ${token}`, + }, + }) + .then((response) => { + if (!response.ok) { + throw new Error('Invalid token or unauthorized'); + } + + return response.json(); + }) + .then((data: unknown) => { + const userData = data as GitHubUserResponse; + + // Save connection to local storage + const newConnection = { + token, + tokenType, + user: { + login: userData.login, + avatar_url: userData.avatar_url, + name: userData.name || userData.login, + }, + connected_at: new Date().toISOString(), + }; + + localStorage.setItem('github_connection', JSON.stringify(newConnection)); + + // Also save as cookies for API requests + Cookies.set('githubToken', token); + Cookies.set('githubUsername', userData.login); + Cookies.set('git:github.com', JSON.stringify({ username: token, password: 'x-oauth-basic' })); + + // Refresh repositories after connection is established + if (isOpen && activeTab === 'my-repos') { + fetchUserRepos(); + } + }) + .catch((error) => { + console.error('Failed to initialize GitHub connection from environment variables:', error); + }); + } + }, [isOpen]); + + // Fetch repositories when dialog opens or tab changes + 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: { + Accept: 'application/vnd.github.v3+json', + 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 connection = getLocalStorage('github_connection'); + const headers: HeadersInit = connection?.token + ? { + Accept: 'application/vnd.github.v3+json', + Authorization: `Bearer ${connection.token}`, + } + : {}; + const response = await fetch(`https://api.github.com/repos/${repo.full_name}/branches`, { + headers, + }); + + 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 => { + try { + // Extract branch from URL if present (format: url#branch) + let branch: string | null = null; + let cleanUrl = repoUrl; + + if (repoUrl.includes('#')) { + const parts = repoUrl.split('#'); + cleanUrl = parts[0]; + branch = parts[1]; + } + + const [owner, repo] = cleanUrl + .replace(/\.git$/, '') + .split('/') + .slice(-2); + + // Try to get token from local storage first + const connection = getLocalStorage('github_connection'); + + // If no connection in local storage, check environment variables + let headers: HeadersInit = {}; + + if (connection?.token) { + headers = { + Accept: 'application/vnd.github.v3+json', + Authorization: `Bearer ${connection.token}`, + }; + } else if (import.meta.env.VITE_GITHUB_ACCESS_TOKEN) { + // Use token from environment variables + headers = { + Accept: 'application/vnd.github.v3+json', + Authorization: `Bearer ${import.meta.env.VITE_GITHUB_ACCESS_TOKEN}`, + }; + } + + // First, get the repository info to determine the default branch + const repoInfoResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}`, { + headers, + }); + + if (!repoInfoResponse.ok) { + if (repoInfoResponse.status === 401 || repoInfoResponse.status === 403) { + throw new Error( + `Authentication failed (${repoInfoResponse.status}). Your GitHub token may be invalid or missing the required permissions.`, + ); + } else if (repoInfoResponse.status === 404) { + throw new Error( + `Repository not found or is private (${repoInfoResponse.status}). To access private repositories, you need to connect your GitHub account or provide a valid token with appropriate permissions.`, + ); + } else { + throw new Error( + `Failed to fetch repository information: ${repoInfoResponse.statusText} (${repoInfoResponse.status})`, + ); + } + } + + const repoInfo = (await repoInfoResponse.json()) as { default_branch: string }; + let defaultBranch = repoInfo.default_branch || 'main'; + + // If a branch was specified in the URL, use that instead of the default + if (branch) { + defaultBranch = branch; + } + + // Try to fetch the repository tree using the selected branch + let treeResponse = await fetch( + `https://api.github.com/repos/${owner}/${repo}/git/trees/${defaultBranch}?recursive=1`, + { + headers, + }, + ); + + // If the selected branch doesn't work, try common branch names + if (!treeResponse.ok) { + // Try 'master' branch if default branch failed + treeResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}/git/trees/master?recursive=1`, { + headers, + }); + + // If master also fails, try 'main' branch + if (!treeResponse.ok) { + treeResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}/git/trees/main?recursive=1`, { + headers, + }); + } + + // If all common branches fail, throw an error + if (!treeResponse.ok) { + throw new Error( + 'Failed to fetch repository structure. Please check the repository URL and your access permissions.', + ); + } + } + + 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, + }; + + return stats; + } catch (error) { + console.error('Error verifying repository:', error); + + // Check if it's an authentication error and show the auth dialog + const errorMessage = error instanceof Error ? error.message : 'Failed to verify repository'; + + if ( + errorMessage.includes('Authentication failed') || + errorMessage.includes('may be private') || + errorMessage.includes('Repository not found or is private') || + errorMessage.includes('Unauthorized') || + errorMessage.includes('401') || + errorMessage.includes('403') || + errorMessage.includes('404') || + errorMessage.includes('access permissions') + ) { + setShowAuthDialog(true); + } + + toast.error(errorMessage); + + 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); + + // Check if it's an authentication error + const errorMessage = error instanceof Error ? error.message : 'Failed to prepare repository. Please try again.'; + + // Show the GitHub auth dialog for any authentication or permission errors + if ( + errorMessage.includes('Authentication failed') || + errorMessage.includes('may be private') || + errorMessage.includes('Repository not found or is private') || + errorMessage.includes('Unauthorized') || + errorMessage.includes('401') || + errorMessage.includes('403') || + errorMessage.includes('404') || + errorMessage.includes('access permissions') + ) { + // Directly show the auth dialog instead of just showing a toast + setShowAuthDialog(true); + + toast.error( +
+

{errorMessage}

+ +
, + { autoClose: 10000 }, // Keep the toast visible longer + ); + } else { + toast.error(errorMessage); + } + } + }; + + 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 ( + + { + if (!open) { + handleClose(); + } + }} + > + + + + {/* Header */} +
+
+
+ +
+
+ + Import GitHub Repository + +

+ Clone a repository from GitHub to your workspace +

+
+
+ + +
+ + {/* Auth Info Banner */} +
+
+ + + Need to access private repositories? + +
+ setShowAuthDialog(true)} + className="px-3 py-1.5 rounded-lg bg-purple-500 hover:bg-purple-600 text-white text-sm transition-colors flex items-center gap-1.5 shadow-sm" + whileHover={{ scale: 1.02, boxShadow: '0 4px 8px rgba(124, 58, 237, 0.2)' }} + whileTap={{ scale: 0.98 }} + > + + Connect GitHub Account + +
+ + {/* Content */} +
+ {/* Tabs */} +
+
+
+ + + +
+
+
+ + {activeTab === 'url' ? ( +
+
+

+ + Repository URL +

+ +
+
+ +
+ setCustomUrl(e.target.value)} + className="w-full pl-10 py-3 border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark focus:ring-2 focus:ring-purple-500 focus:border-transparent" + /> +
+ +
+

+ + + You can paste any GitHub repository URL, including specific branches or tags. +
+ + Example: https://github.com/username/repository/tree/branch-name + +
+

+
+
+ +
+
+ Ready to import? +
+
+ + + + Import Repository + +
+ ) : ( + <> + {activeTab === 'search' && ( +
+
+

+ + Search GitHub +

+ +
+
+ { + setSearchQuery(e.target.value); + + if (e.target.value.length > 2) { + handleSearch(e.target.value); + } + }} + onKeyDown={(e) => { + if (e.key === 'Enter' && searchQuery.length > 2) { + handleSearch(searchQuery); + } + }} + onClear={() => { + setSearchQuery(''); + setSearchResults([]); + }} + iconClassName="text-blue-500" + className="py-3 bg-white dark:bg-bolt-elements-background-depth-4 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-blue-500 shadow-sm" + loading={isLoading} + /> +
+ setFilters({})} + className="px-3 py-2 rounded-lg bg-white dark:bg-bolt-elements-background-depth-4 text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary border border-bolt-elements-borderColor dark:border-bolt-elements-borderColor-dark shadow-sm" + whileHover={{ scale: 1.05 }} + whileTap={{ scale: 0.95 }} + title="Clear filters" + > + + +
+ +
+
+ Filters +
+ + {/* Active filters */} + {(filters.language || filters.stars || filters.forks) && ( +
+ + {filters.language && ( + { + const newFilters = { ...filters }; + delete newFilters.language; + setFilters(newFilters); + + if (searchQuery.length > 2) { + handleSearch(searchQuery); + } + }} + /> + )} + {filters.stars && ( + ${filters.stars}`} + icon="i-ph:star" + active + onRemove={() => { + const newFilters = { ...filters }; + delete newFilters.stars; + setFilters(newFilters); + + if (searchQuery.length > 2) { + handleSearch(searchQuery); + } + }} + /> + )} + {filters.forks && ( + ${filters.forks}`} + icon="i-ph:git-fork" + active + onRemove={() => { + const newFilters = { ...filters }; + delete newFilters.forks; + setFilters(newFilters); + + if (searchQuery.length > 2) { + handleSearch(searchQuery); + } + }} + /> + )} + +
+ )} + +
+
+
+ +
+ { + setFilters({ ...filters, language: e.target.value }); + + if (searchQuery.length > 2) { + handleSearch(searchQuery); + } + }} + className="w-full pl-8 px-3 py-2 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" + /> +
+
+
+ +
+ handleFilterChange('stars', e.target.value)} + className="w-full pl-8 px-3 py-2 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" + /> +
+
+
+ +
+ handleFilterChange('forks', e.target.value)} + className="w-full pl-8 px-3 py-2 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" + /> +
+
+
+ +
+

+ + + Search for repositories by name, description, or topics. Use filters to narrow down + results. + +

+
+
+
+ )} + +
+ {selectedRepository ? ( +
+
+
+ setSelectedRepository(null)} + className="p-2 rounded-lg hover:bg-white dark:hover:bg-bolt-elements-background-depth-4 text-bolt-elements-textSecondary hover:text-bolt-elements-textPrimary shadow-sm" + whileHover={{ scale: 1.1 }} + whileTap={{ scale: 0.9 }} + > + + +
+

+ {selectedRepository.name} +

+

+ + {selectedRepository.full_name.split('/')[0]} +

+
+
+ + {selectedRepository.private && ( + + Private + + )} +
+ + {selectedRepository.description && ( +
+

+ {selectedRepository.description} +

+
+ )} + +
+ {selectedRepository.language && ( + + {selectedRepository.language} + + )} + + {selectedRepository.stargazers_count.toLocaleString()} + + {selectedRepository.forks_count > 0 && ( + + {selectedRepository.forks_count.toLocaleString()} + + )} +
+ +
+
+ + +
+ +
+ +
+
+ Ready to import? +
+
+ + + + Import {selectedRepository.name} + +
+ ) : ( + + )} +
+ + )} +
+
+
+ + {/* GitHub Auth Dialog */} + + + {/* Repository Stats Dialog */} + {currentStats && ( + setShowStatsDialog(false)} + onConfirm={handleStatsConfirm} + stats={currentStats} + isLargeRepo={currentStats.totalSize > 50 * 1024 * 1024} + /> + )} +
+
+ ); +} diff --git a/app/components/@settings/tabs/connections/components/StatsDialog.tsx b/app/components/@settings/tabs/connections/components/StatsDialog.tsx new file mode 100644 index 0000000000..933ae2254a --- /dev/null +++ b/app/components/@settings/tabs/connections/components/StatsDialog.tsx @@ -0,0 +1,83 @@ +import React from 'react'; +import * as Dialog from '@radix-ui/react-dialog'; +import { motion } from 'framer-motion'; +import type { RepositoryStats } from '~/types/GitHub'; +import { formatSize } from '~/utils/formatSize'; +import { RepositoryStats as RepoStats } from '~/components/ui'; + +interface StatsDialogProps { + isOpen: boolean; + onClose: () => void; + onConfirm: () => void; + stats: RepositoryStats; + isLargeRepo?: boolean; +} + +export function StatsDialog({ isOpen, onClose, onConfirm, stats, isLargeRepo }: StatsDialogProps) { + return ( + !open && onClose()}> + + +
+ + +
+
+
+ +
+
+

+ Repository Overview +

+

+ Review repository details before importing +

+
+
+ +
+ +
+ + {isLargeRepo && ( +
+ +
+ This repository is quite large ({formatSize(stats.totalSize)}). Importing it might take a while + and could impact performance. +
+
+ )} +
+
+ + Cancel + + + Import Repository + +
+
+
+
+
+
+ ); +} diff --git a/app/components/@settings/tabs/connections/types/GitHub.ts b/app/components/@settings/tabs/connections/types/GitHub.ts new file mode 100644 index 0000000000..f2f1af6bca --- /dev/null +++ b/app/components/@settings/tabs/connections/types/GitHub.ts @@ -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; +} diff --git a/app/components/@settings/tabs/data/DataTab.tsx b/app/components/@settings/tabs/data/DataTab.tsx new file mode 100644 index 0000000000..df42c1daf9 --- /dev/null +++ b/app/components/@settings/tabs/data/DataTab.tsx @@ -0,0 +1,721 @@ +import { useState, useRef, useCallback, useEffect } from 'react'; +import { Button } from '~/components/ui/Button'; +import { ConfirmationDialog, SelectionDialog } from '~/components/ui/Dialog'; +import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '~/components/ui/Card'; +import { motion } from 'framer-motion'; +import { useDataOperations } from '~/lib/hooks/useDataOperations'; +import { openDatabase } from '~/lib/persistence/db'; +import { getAllChats, type Chat } from '~/lib/persistence/chats'; +import { DataVisualization } from './DataVisualization'; +import { classNames } from '~/utils/classNames'; +import { toast } from 'react-toastify'; + +// Create a custom hook to connect to the boltHistory database +function useBoltHistoryDB() { + const [db, setDb] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + const initDB = async () => { + try { + setIsLoading(true); + + const database = await openDatabase(); + setDb(database || null); + setIsLoading(false); + } catch (err) { + setError(err instanceof Error ? err : new Error('Unknown error initializing database')); + setIsLoading(false); + } + }; + + initDB(); + + return () => { + if (db) { + db.close(); + } + }; + }, []); + + return { db, isLoading, error }; +} + +// Extend the Chat interface to include the missing properties +interface ExtendedChat extends Chat { + title?: string; + updatedAt?: number; +} + +// Helper function to create a chat label and description +function createChatItem(chat: Chat): ChatItem { + return { + id: chat.id, + + // Use description as title if available, or format a short ID + label: (chat as ExtendedChat).title || chat.description || `Chat ${chat.id.slice(0, 8)}`, + + // Format the description with message count and timestamp + description: `${chat.messages.length} messages - Last updated: ${new Date((chat as ExtendedChat).updatedAt || Date.parse(chat.timestamp)).toLocaleString()}`, + }; +} + +interface SettingsCategory { + id: string; + label: string; + description: string; +} + +interface ChatItem { + id: string; + label: string; + description: string; +} + +export function DataTab() { + // Use our custom hook for the boltHistory database + const { db, isLoading: dbLoading } = useBoltHistoryDB(); + const fileInputRef = useRef(null); + const apiKeyFileInputRef = useRef(null); + const chatFileInputRef = useRef(null); + + // State for confirmation dialogs + const [showResetInlineConfirm, setShowResetInlineConfirm] = useState(false); + const [showDeleteInlineConfirm, setShowDeleteInlineConfirm] = useState(false); + const [showSettingsSelection, setShowSettingsSelection] = useState(false); + const [showChatsSelection, setShowChatsSelection] = useState(false); + + // State for settings categories and available chats + const [settingsCategories] = useState([ + { id: 'core', label: 'Core Settings', description: 'User profile and main settings' }, + { id: 'providers', label: 'Providers', description: 'API keys and provider configurations' }, + { id: 'features', label: 'Features', description: 'Feature flags and settings' }, + { id: 'ui', label: 'UI', description: 'UI configuration and preferences' }, + { id: 'connections', label: 'Connections', description: 'External service connections' }, + { id: 'debug', label: 'Debug', description: 'Debug settings and logs' }, + { id: 'updates', label: 'Updates', description: 'Update settings and notifications' }, + ]); + + const [availableChats, setAvailableChats] = useState([]); + const [chatItems, setChatItems] = useState([]); + + // Data operations hook with boltHistory database + const { + isExporting, + isImporting, + isResetting, + isDownloadingTemplate, + handleExportSettings, + handleExportSelectedSettings, + handleExportAllChats, + handleExportSelectedChats, + handleImportSettings, + handleImportChats, + handleResetSettings, + handleResetChats, + handleDownloadTemplate, + handleImportAPIKeys, + } = useDataOperations({ + customDb: db || undefined, // Pass the boltHistory database, converting null to undefined + onReloadSettings: () => window.location.reload(), + onReloadChats: () => { + // Reload chats after reset + if (db) { + getAllChats(db).then((chats) => { + // Cast to ExtendedChat to handle additional properties + const extendedChats = chats as ExtendedChat[]; + setAvailableChats(extendedChats); + setChatItems(extendedChats.map((chat) => createChatItem(chat))); + }); + } + }, + onResetSettings: () => setShowResetInlineConfirm(false), + onResetChats: () => setShowDeleteInlineConfirm(false), + }); + + // Loading states for operations not provided by the hook + const [isDeleting, setIsDeleting] = useState(false); + const [isImportingKeys, setIsImportingKeys] = useState(false); + + // Load available chats + useEffect(() => { + if (db) { + console.log('Loading chats from boltHistory database', { + name: db.name, + version: db.version, + objectStoreNames: Array.from(db.objectStoreNames), + }); + + getAllChats(db) + .then((chats) => { + console.log('Found chats:', chats.length); + + // Cast to ExtendedChat to handle additional properties + const extendedChats = chats as ExtendedChat[]; + setAvailableChats(extendedChats); + + // Create ChatItems for selection dialog + setChatItems(extendedChats.map((chat) => createChatItem(chat))); + }) + .catch((error) => { + console.error('Error loading chats:', error); + toast.error('Failed to load chats: ' + (error instanceof Error ? error.message : 'Unknown error')); + }); + } + }, [db]); + + // Handle file input changes + const handleFileInputChange = useCallback( + (event: React.ChangeEvent) => { + const file = event.target.files?.[0]; + + if (file) { + handleImportSettings(file); + } + }, + [handleImportSettings], + ); + + const handleAPIKeyFileInputChange = useCallback( + (event: React.ChangeEvent) => { + const file = event.target.files?.[0]; + + if (file) { + setIsImportingKeys(true); + handleImportAPIKeys(file).finally(() => setIsImportingKeys(false)); + } + }, + [handleImportAPIKeys], + ); + + const handleChatFileInputChange = useCallback( + (event: React.ChangeEvent) => { + const file = event.target.files?.[0]; + + if (file) { + handleImportChats(file); + } + }, + [handleImportChats], + ); + + // Wrapper for reset chats to handle loading state + const handleResetChatsWithState = useCallback(() => { + setIsDeleting(true); + handleResetChats().finally(() => setIsDeleting(false)); + }, [handleResetChats]); + + return ( +
+ {/* Hidden file inputs */} + + + + + {/* Reset Settings Confirmation Dialog */} + setShowResetInlineConfirm(false)} + title="Reset All Settings?" + description="This will reset all your settings to their default values. This action cannot be undone." + confirmLabel="Reset Settings" + cancelLabel="Cancel" + variant="destructive" + isLoading={isResetting} + onConfirm={handleResetSettings} + /> + + {/* Delete Chats Confirmation Dialog */} + setShowDeleteInlineConfirm(false)} + title="Delete All Chats?" + description="This will permanently delete all your chat history. This action cannot be undone." + confirmLabel="Delete All" + cancelLabel="Cancel" + variant="destructive" + isLoading={isDeleting} + onConfirm={handleResetChatsWithState} + /> + + {/* Settings Selection Dialog */} + setShowSettingsSelection(false)} + title="Select Settings to Export" + items={settingsCategories} + onConfirm={(selectedIds) => { + handleExportSelectedSettings(selectedIds); + setShowSettingsSelection(false); + }} + confirmLabel="Export Selected" + /> + + {/* Chats Selection Dialog */} + setShowChatsSelection(false)} + title="Select Chats to Export" + items={chatItems} + onConfirm={(selectedIds) => { + handleExportSelectedChats(selectedIds); + setShowChatsSelection(false); + }} + confirmLabel="Export Selected" + /> + + {/* Chats Section */} +
+

Chats

+ {dbLoading ? ( +
+
+ Loading chats database... +
+ ) : ( +
+ + +
+ +
+ + + Export All Chats + +
+ Export all your chats to a JSON file. + + + + + + + + + + +
+ +
+ + + Export Selected Chats + +
+ Choose specific chats to export. + + + + + + + + + + +
+ +
+ + + Import Chats + +
+ Import chats from a JSON file. + + + + + + + + + + +
+ +
+ + + Delete All Chats + +
+ Delete all your chat history. + + + + + + + +
+ )} +
+ + {/* Settings Section */} +
+

Settings

+
+ + +
+ +
+ + + Export All Settings + +
+ Export all your settings to a JSON file. + + + + + + + + + + +
+ +
+ + + Export Selected Settings + +
+ Choose specific settings to export. + + + + + + + + + + +
+ +
+ + + Import Settings + +
+ Import settings from a JSON file. + + + + + + + + + + +
+ +
+ + + Reset All Settings + +
+ Reset all settings to their default values. + + + + + + + +
+
+ + {/* API Keys Section */} +
+

API Keys

+
+ + +
+ +
+ + + Download Template + +
+ Download a template file for your API keys. + + + + + + + + + + +
+ +
+ + + Import API Keys + +
+ Import API keys from a JSON file. + + + + + + + +
+
+ + {/* Data Visualization */} +
+

Data Usage

+ + + + + +
+
+ ); +} diff --git a/app/components/@settings/tabs/data/DataVisualization.tsx b/app/components/@settings/tabs/data/DataVisualization.tsx new file mode 100644 index 0000000000..27d2738834 --- /dev/null +++ b/app/components/@settings/tabs/data/DataVisualization.tsx @@ -0,0 +1,384 @@ +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>({}); + const [messagesByRole, setMessagesByRole] = useState>({}); + const [apiKeyUsage, setApiKeyUsage] = useState>([]); + const [averageMessagesPerChat, setAverageMessagesPerChat] = useState(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 = {}; + const roleCounts: Record = {}; + const apiUsage: Record = {}; + 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 = {}; + 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 ( +
+
+

No Data Available

+

+ Start creating chats to see your usage statistics and data visualization. +

+
+ ); + } + + 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 ( +
+
+
+

Total Chats

+
+
+ {chats.length} +
+
+ +
+

Total Messages

+
+
+ {Object.values(messagesByRole).reduce((sum, count) => sum + count, 0)} +
+
+ +
+

Avg. Messages/Chat

+
+
+ {averageMessagesPerChat.toFixed(1)} +
+
+
+ +
+
+

Chat History

+
+ +
+
+ +
+

Message Distribution

+
+ +
+
+
+ + {apiKeyUsage.length > 0 && ( +
+

API Usage by Provider

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

No Logs Found

+

Try adjusting your search or filters

+
+
+ ) : ( + filteredLogs.map((log) => ( + + )) + )} +
+
+ ); +} diff --git a/app/components/@settings/tabs/features/FeaturesTab.tsx b/app/components/@settings/tabs/features/FeaturesTab.tsx new file mode 100644 index 0000000000..3b14a7565d --- /dev/null +++ b/app/components/@settings/tabs/features/FeaturesTab.tsx @@ -0,0 +1,295 @@ +// Remove unused imports +import React, { memo, useCallback } from 'react'; +import { motion } from 'framer-motion'; +import { Switch } from '~/components/ui/Switch'; +import { useSettings } from '~/lib/hooks/useSettings'; +import { classNames } from '~/utils/classNames'; +import { toast } from 'react-toastify'; +import { PromptLibrary } from '~/lib/common/prompt-library'; + +interface FeatureToggle { + id: string; + title: string; + description: string; + icon: string; + enabled: boolean; + beta?: boolean; + experimental?: boolean; + tooltip?: string; +} + +const FeatureCard = memo( + ({ + feature, + index, + onToggle, + }: { + feature: FeatureToggle; + index: number; + onToggle: (id: string, enabled: boolean) => void; + }) => ( + +
+
+
+
+
+

{feature.title}

+ {feature.beta && ( + Beta + )} + {feature.experimental && ( + + Experimental + + )} +
+
+ onToggle(feature.id, checked)} /> +
+

{feature.description}

+ {feature.tooltip &&

{feature.tooltip}

} +
+ + ), +); + +const FeatureSection = memo( + ({ + title, + features, + icon, + description, + onToggleFeature, + }: { + title: string; + features: FeatureToggle[]; + icon: string; + description: string; + onToggleFeature: (id: string, enabled: boolean) => void; + }) => ( + +
+
+
+

{title}

+

{description}

+
+
+ +
+ {features.map((feature, index) => ( + + ))} +
+ + ), +); + +export default function FeaturesTab() { + const { + autoSelectTemplate, + isLatestBranch, + contextOptimizationEnabled, + eventLogs, + setAutoSelectTemplate, + enableLatestBranch, + enableContextOptimization, + setEventLogs, + setPromptId, + promptId, + } = useSettings(); + + // Enable features by default on first load + React.useEffect(() => { + // Only set defaults if values are undefined + if (isLatestBranch === undefined) { + enableLatestBranch(false); // Default: OFF - Don't auto-update from main branch + } + + if (contextOptimizationEnabled === undefined) { + enableContextOptimization(true); // Default: ON - Enable context optimization + } + + if (autoSelectTemplate === undefined) { + setAutoSelectTemplate(true); // Default: ON - Enable auto-select templates + } + + if (promptId === undefined) { + setPromptId('default'); // Default: 'default' + } + + if (eventLogs === undefined) { + setEventLogs(true); // Default: ON - Enable event logging + } + }, []); // Only run once on component mount + + const handleToggleFeature = useCallback( + (id: string, enabled: boolean) => { + switch (id) { + case 'latestBranch': { + enableLatestBranch(enabled); + toast.success(`Main branch updates ${enabled ? 'enabled' : 'disabled'}`); + break; + } + + case 'autoSelectTemplate': { + setAutoSelectTemplate(enabled); + toast.success(`Auto select template ${enabled ? 'enabled' : 'disabled'}`); + break; + } + + case 'contextOptimization': { + enableContextOptimization(enabled); + toast.success(`Context optimization ${enabled ? 'enabled' : 'disabled'}`); + break; + } + + case 'eventLogs': { + setEventLogs(enabled); + toast.success(`Event logging ${enabled ? 'enabled' : 'disabled'}`); + break; + } + + default: + break; + } + }, + [enableLatestBranch, setAutoSelectTemplate, enableContextOptimization, setEventLogs], + ); + + const features = { + stable: [ + { + id: 'latestBranch', + title: 'Main Branch Updates', + description: 'Get the latest updates from the main branch', + icon: 'i-ph:git-branch', + enabled: isLatestBranch, + tooltip: 'Enabled by default to receive updates from the main development branch', + }, + { + id: 'autoSelectTemplate', + title: 'Auto Select Template', + description: 'Automatically select starter template', + icon: 'i-ph:selection', + enabled: autoSelectTemplate, + tooltip: 'Enabled by default to automatically select the most appropriate starter template', + }, + { + id: 'contextOptimization', + title: 'Context Optimization', + description: 'Optimize context for better responses', + icon: 'i-ph:brain', + enabled: contextOptimizationEnabled, + tooltip: 'Enabled by default for improved AI responses', + }, + { + id: 'eventLogs', + title: 'Event Logging', + description: 'Enable detailed event logging and history', + icon: 'i-ph:list-bullets', + enabled: eventLogs, + tooltip: 'Enabled by default to record detailed logs of system events and user actions', + }, + ], + beta: [], + }; + + return ( +
+ + + {features.beta.length > 0 && ( + + )} + + +
+
+
+
+
+

+ Prompt Library +

+

+ Choose a prompt from the library to use as the system prompt +

+
+ +
+ +
+ ); +} diff --git a/app/components/@settings/tabs/mcp/McpServerList.tsx b/app/components/@settings/tabs/mcp/McpServerList.tsx new file mode 100644 index 0000000000..6e15fa9ed0 --- /dev/null +++ b/app/components/@settings/tabs/mcp/McpServerList.tsx @@ -0,0 +1,99 @@ +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

No MCP servers configured

; + } + + const filteredEntries = onlyShowAvailableServers + ? serverEntries.filter(([, s]) => s.status === 'available') + : serverEntries; + + return ( +
+ {filteredEntries.map(([serverName, mcpServer]) => { + const isAvailable = mcpServer.status === 'available'; + const isExpanded = expandedServer === serverName; + const serverTools = isAvailable ? Object.entries(mcpServer.tools) : []; + + return ( +
+
+
+
toggleServerExpanded(serverName)} + className="flex items-center gap-1.5 text-bolt-elements-textPrimary" + aria-expanded={isExpanded} + > +
+ {serverName} +
+ +
+ {mcpServer.config.type === 'sse' || mcpServer.config.type === 'streamable-http' ? ( + {mcpServer.config.url} + ) : ( + + {mcpServer.config.command} {mcpServer.config.args?.join(' ')} + + )} +
+
+ +
+ {checkingServers ? ( + + ) : ( + + )} +
+
+ + {/* Error message */} + {!isAvailable && mcpServer.error && ( +
Error: {mcpServer.error}
+ )} + + {/* Tool list */} + {isExpanded && isAvailable && ( +
+
Available Tools:
+ {serverTools.length === 0 ? ( +
No tools available
+ ) : ( +
+ {serverTools.map(([toolName, toolSchema]) => ( + + ))} +
+ )} +
+ )} +
+ ); + })} +
+ ); +} diff --git a/app/components/@settings/tabs/mcp/McpServerListItem.tsx b/app/components/@settings/tabs/mcp/McpServerListItem.tsx new file mode 100644 index 0000000000..7013ddeedc --- /dev/null +++ b/app/components/@settings/tabs/mcp/McpServerListItem.tsx @@ -0,0 +1,70 @@ +import type { Tool } from 'ai'; + +type ParameterProperty = { + type?: string; + description?: string; +}; + +type ToolParameters = { + jsonSchema: { + properties?: Record; + 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 ( +
+
+

+ {toolName} +

+ +

{toolSchema.description || 'No description available'}

+ + {Object.keys(parameters).length > 0 && ( +
+

Parameters:

+
    + {Object.entries(parameters).map(([paramName, paramDetails]) => ( +
  • +
    + + {paramName} + {requiredParams.includes(paramName) && ( + * + )} + + + β€’ + +
    + {paramDetails.type && ( + {paramDetails.type} + )} + {paramDetails.description && ( +
    {paramDetails.description}
    + )} +
    +
    +
  • + ))} +
+
+ )} +
+
+ ); +} diff --git a/app/components/@settings/tabs/mcp/McpStatusBadge.tsx b/app/components/@settings/tabs/mcp/McpStatusBadge.tsx new file mode 100644 index 0000000000..3cbbb1f1f4 --- /dev/null +++ b/app/components/@settings/tabs/mcp/McpStatusBadge.tsx @@ -0,0 +1,37 @@ +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: