> ## Documentation Index
> Fetch the complete documentation index at: https://docs.airys.chat/llms.txt
> Use this file to discover all available pages before exploring further.

# Erros Comuns e Soluções

> Guia de solução de problemas para erros comuns durante a configuração de desenvolvimento do AirysChat

# Erros Comuns e Soluções

Este guia aborda os erros mais comuns encontrados durante a configuração de desenvolvimento do AirysChat e suas soluções. Use isso como uma referência rápida ao solucionar problemas.

## Erros de Instalação e Configuração

### Problemas com Ruby e Bundler

<Accordion title="O bundle install falha com erros de extensão nativa">
  **Mensagem de Erro**:

  ```
  An error occurred while installing pg (1.5.4), and Bundler cannot continue.
  Make sure that `gem install pg -v '1.5.4'` succeeds before bundling.
  ```

  **Causa**: Cabeçalhos de desenvolvimento do PostgreSQL ausentes ou caminho do pg\_config incorreto.

  **Soluções**:

  <Tabs>
    <Tab title="macOS">
      ```bash theme={null}
      # Install PostgreSQL with Homebrew
      brew install postgresql

      # Configure bundle to use correct pg_config
      bundle config build.pg --with-pg-config=/opt/homebrew/bin/pg_config

      # For Intel Macs
      bundle config build.pg --with-pg-config=/usr/local/bin/pg_config

      # Retry bundle install
      bundle install
      ```
    </Tab>

    <Tab title="Ubuntu/Debian">
      ```bash theme={null}
      # Install PostgreSQL development headers
      sudo apt-get update
      sudo apt-get install libpq-dev postgresql-client

      # Install build essentials
      sudo apt-get install build-essential

      # Retry bundle install
      bundle install
      ```
    </Tab>

    <Tab title="CentOS/RHEL">
      ```bash theme={null}
      # Install PostgreSQL development packages
      sudo yum install postgresql-devel

      # Install development tools
      sudo yum groupinstall "Development Tools"

      # Retry bundle install
      bundle install
      ```
    </Tab>
  </Tabs>
</Accordion>

<Accordion title="Incompatibilidade de versão do Ruby">
  **Mensagem de Erro**:

  ```
  Your Ruby version is 3.1.0, but your Gemfile specified 3.3.3
  ```

  **Causa**: Versão incorreta do Ruby instalada.

  **Soluções**:

  <Tabs>
    <Tab title="rbenv">
      ```bash theme={null}
      # Install correct Ruby version
      rbenv install 3.3.3

      # Set as global version
      rbenv global 3.3.3

      # Verify version
      ruby --version

      # Rehash to update shims
      rbenv rehash
      ```
    </Tab>

    <Tab title="RVM">
      ```bash theme={null}
      # Install correct Ruby version
      rvm install 3.3.3

      # Use the version
      rvm use 3.3.3 --default

      # Verify version
      ruby --version
      ```
    </Tab>

    <Tab title="asdf">
      ```bash theme={null}
      # Install correct Ruby version
      asdf install ruby 3.3.3

      # Set as global version
      asdf global ruby 3.3.3

      # Verify version
      ruby --version
      ```
    </Tab>
  </Tabs>
</Accordion>

<Accordion title="Conflitos de versão do Bundler">
  **Mensagem de Erro**:

  ```
  Bundler could not find compatible versions for gem "bundler"
  ```

  **Causa**: Versão incompatível do Bundler.

  **Solução**:

  ```bash theme={null}
  # Check current Bundler version
  bundler --version

  # Install specific Bundler version (check Gemfile.lock)
  gem install bundler:2.4.22

  # Update Bundler
  gem update bundler

  # Clean bundle cache
  bundle clean --force

  # Retry installation
  bundle install
  ```
</Accordion>

### Problemas com Node.js e Gerenciador de Pacotes

<Accordion title="Incompatibilidade de versão do Node.js">
  **Mensagem de Erro**:

  ```
  error @airyschat/airyschat@1.0.0: The engine "node" is incompatible with this module.
  ```

  **Causa**: Versão incorreta do Node.js.

  **Soluções**:

  <Tabs>
    <Tab title="nvm">
      ```bash theme={null}
      # Install correct Node.js version
      nvm install 20

      # Use the version
      nvm use 20

      # Set as default
      nvm alias default 20

      # Verify version
      node --version
      ```
    </Tab>

    <Tab title="n">
      ```bash theme={null}
      # Install correct Node.js version
      n 20

      # Verify version
      node --version
      ```
    </Tab>

    <Tab title="asdf">
      ```bash theme={null}
      # Install correct Node.js version
      asdf install nodejs 20.10.0

      # Set as global version
      asdf global nodejs 20.10.0

      # Verify version
      node --version
      ```
    </Tab>
  </Tabs>
</Accordion>

<Accordion title="Problemas na instalação do pnpm">
  **Mensagem de Erro**:

  ```
  pnpm: command not found
  ```

  **Causa**: pnpm não está instalado.

  **Soluções**:

  ```bash theme={null}
  # Install pnpm globally
  npm install -g pnpm

  # Or using corepack (Node.js 16.10+)
  corepack enable
  corepack prepare pnpm@latest --activate

  # Or using Homebrew (macOS)
  brew install pnpm

  # Verify installation
  pnpm --version
  ```
</Accordion>

<Accordion title="Falhas na instalação de pacotes">
  **Mensagem de Erro**:

  ```
  ERR_PNPM_PEER_DEP_ISSUES  Unmet peer dependencies
  ```

  **Causa**: Conflitos de dependência de peer ou cache corrompido.

  **Soluções**:

  ```bash theme={null}
  # Clear pnpm cache
  pnpm store prune

  # Remove node_modules and lock file
  rm -rf node_modules pnpm-lock.yaml

  # Reinstall with legacy peer deps
  pnpm install --legacy-peer-deps

  # Or force installation
  pnpm install --force

  # Alternative: use npm
  npm install
  ```
</Accordion>

## Erros de Banco de Dados

### Problemas de Conexão com PostgreSQL

<Accordion title="Conexão de banco de dados recusada">
  **Mensagem de Erro**:

  ```
  PG::ConnectionBad: could not connect to server: Connection refused
  ```

  **Causa**: O serviço PostgreSQL não está em execução ou parâmetros de conexão incorretos.

  **Soluções**:

  <Tabs>
    <Tab title="macOS">
      ```bash theme={null}
      # Check if PostgreSQL is running
      brew services list | grep postgresql

      # Start PostgreSQL
      brew services start postgresql

      # Check connection
      psql postgres -c "SELECT 1;"

      # If user doesn't exist, create it
      createuser -s airyschat
      ```
    </Tab>

    <Tab title="Ubuntu/Debian">
      ```bash theme={null}
      # Check PostgreSQL status
      sudo systemctl status postgresql

      # Start PostgreSQL
      sudo systemctl start postgresql
      sudo systemctl enable postgresql

      # Switch to postgres user and create airyschat user
      sudo -u postgres createuser -s airyschat

      # Set password for airyschat user
      sudo -u postgres psql -c "ALTER USER airyschat PASSWORD 'password';"
      ```
    </Tab>

    <Tab title="Docker">
      ```bash theme={null}
      # Start PostgreSQL container
      docker run --name postgres-airyschat \
        -e POSTGRES_USER=airyschat \
        -e POSTGRES_PASSWORD=password \
        -e POSTGRES_DB=airyschat_development \
        -p 5432:5432 \
        -d postgres:15

      # Check if container is running
      docker ps | grep postgres
      ```
    </Tab>
  </Tabs>
</Accordion>

<Accordion title="O banco de dados não existe">
  **Mensagem de Erro**:

  ```
  ActiveRecord::NoDatabaseError: FATAL: database "airyschat_development" does not exist
  ```

  **Causa**: O banco de dados não foi criado.

  **Solução**:

  ```bash theme={null}
  # Create databases
  bundle exec rails db:create

  # If that fails, create manually
  createdb airyschat_development
  createdb airyschat_test

  # Or using psql
  psql postgres -c "CREATE DATABASE airyschat_development;"
  psql postgres -c "CREATE DATABASE airyschat_test;"
  ```
</Accordion>

<Accordion title="Erros de migração">
  **Mensagem de Erro**:

  ```
  ActiveRecord::PendingMigrationError: Migrations are pending
  ```

  **Causa**: O esquema do banco de dados não está atualizado.

  **Soluções**:

  ```bash theme={null}
  # Run pending migrations
  bundle exec rails db:migrate

  # If migrations fail, check status
  bundle exec rails db:migrate:status

  # Reset database (WARNING: destroys data)
  bundle exec rails db:drop db:create db:migrate db:seed

  # For specific migration issues
  bundle exec rails db:migrate:up VERSION=20231201000000
  ```
</Accordion>

### Problemas de Conexão com Redis

<Accordion title="Conexão Redis recusada">
  **Mensagem de Erro**:

  ```
  Redis::CannotConnectError: Error connecting to Redis on localhost:6379
  ```

  **Causa**: O serviço Redis não está em execução.

  **Soluções**:

  <Tabs>
    <Tab title="macOS">
      ```bash theme={null}
      # Check if Redis is running
      brew services list | grep redis

      # Start Redis
      brew services start redis

      # Test connection
      redis-cli ping
      ```
    </Tab>

    <Tab title="Ubuntu/Debian">
      ```bash theme={null}
      # Check Redis status
      sudo systemctl status redis

      # Start Redis
      sudo systemctl start redis
      sudo systemctl enable redis

      # Test connection
      redis-cli ping
      ```
    </Tab>

    <Tab title="Docker">
      ```bash theme={null}
      # Start Redis container
      docker run --name redis-airyschat \
        -p 6379:6379 \
        -d redis:7-alpine

      # Test connection
      docker exec redis-airyschat redis-cli ping
      ```
    </Tab>
  </Tabs>
</Accordion>

## Erros de Tempo de Execução do Aplicativo

### Problemas com o Servidor Rails

<Accordion title="Porta já em uso">
  **Mensagem de Erro**:

  ```
  Address already in use - bind(2) for "127.0.0.1" port 3000
  ```

  **Causa**: Outro processo está usando a porta 3000.

  **Soluções**:

  ```bash theme={null}
  # Find process using port 3000
  lsof -ti:3000

  # Kill the process
  kill -9 $(lsof -ti:3000)

  # Or use a different port
  bundle exec rails server -p 3001

  # Check what's running on the port
  netstat -tulpn | grep :3000
  ```
</Accordion>

<Accordion title="A base da chave secreta está ausente">
  **Mensagem de Erro**:

  ```
  ArgumentError: Missing `secret_key_base` for 'development' environment
  ```

  **Causa**: SECRET\_KEY\_BASE não está definida no ambiente.

  **Solução**:

  ```bash theme={null}
  # Generate a new secret key
  bundle exec rails secret

  # Add to .env file
  echo "SECRET_KEY_BASE=$(bundle exec rails secret)" >> .env

  # Or set temporarily
  export SECRET_KEY_BASE=$(bundle exec rails secret)
  bundle exec rails server
  ```
</Accordion>

<Accordion title="Erros de compilação do Webpacker">
  **Mensagem de Erro**:

  ```
  Webpacker::Manifest::MissingEntryError: Webpacker can't find application.js
  ```

  **Causa**: Assets do Webpack não compilados ou falha na compilação.

  **Soluções**:

  ```bash theme={null}
  # Check if webpack dev server is running
  ps aux | grep webpack

  # Start webpack dev server
  pnpm run dev

  # Or compile assets manually
  bundle exec rails assets:precompile

  # Clear webpack cache
  rm -rf tmp/cache/webpacker
  rm -rf public/packs

  # Reinstall node modules
  rm -rf node_modules
  pnpm install
  ```
</Accordion>

### Problemas com Sidekiq Worker

<Accordion title="Sidekiq não está processando trabalhos">
  **Mensagem de Erro**:

  ```
  Jobs are queued but not being processed
  ```

  **Causa**: O Sidekiq worker não está em execução.

  **Soluções**:

  ```bash theme={null}
  # Check if Sidekiq is running
  ps aux | grep sidekiq

  # Start Sidekiq
  bundle exec sidekiq

  # Check Sidekiq web interface
  open http://localhost:3000/sidekiq

  # Clear failed jobs
  bundle exec rails runner "Sidekiq::Queue.new.clear"
  ```
</Accordion>

<Accordion title="Problemas de memória do Redis">
  **Mensagem de Erro**:

  ```
  Redis::CommandError: OOM command not allowed when used memory > 'maxmemory'
  ```

  **Causa**: O Redis está ficando sem memória.

  **Soluções**:

  ```bash theme={null}
  # Check Redis memory usage
  redis-cli info memory

  # Clear Redis cache
  redis-cli flushall

  # Increase Redis memory limit (redis.conf)
  # maxmemory 256mb

  # Or restart Redis
  brew services restart redis  # macOS
  sudo systemctl restart redis  # Linux
  ```
</Accordion>

## Erros de Teste

### Falhas de Teste RSpec

<Accordion title="Banco de dados não preparado para testes">
  **Mensagem de Erro**:

  ```
  ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "users" does not exist
  ```

  **Causa**: O banco de dados de teste não foi configurado corretamente.

  **Solução**:

  ```bash theme={null}
  # Prepare test database
  RAILS_ENV=test bundle exec rails db:create
  RAILS_ENV=test bundle exec rails db:migrate

  # Or use the combined command
  bundle exec rails db:test:prepare

  # Reset test database if needed
  RAILS_ENV=test bundle exec rails db:drop db:create db:migrate
  ```
</Accordion>

<Accordion title="Erros de Factory Bot">
  **Mensagem de Erro**:

  ```
  FactoryBot::DuplicateDefinitionError: Factory already registered
  ```

  **Causa**: Definições de factory carregadas várias vezes.

  **Solução**:

  ```bash theme={null}
  # Clear Spring cache
  bundle exec spring stop

  # Restart test suite
  bundle exec rspec

  # Check for duplicate factory definitions
  grep -r "FactoryBot.define" spec/
  ```
</Accordion>

<Accordion title="Erros de Capybara/Selenium">
  **Mensagem de Erro**:

  ```
  Selenium::WebDriver::Error::WebDriverError: unable to connect to chromedriver
  ```

  **Causa**: ChromeDriver não instalado ou versão incompatível.

  **Soluções**:

  ```bash theme={null}
  # Install ChromeDriver
  # macOS
  brew install chromedriver

  # Ubuntu/Debian
  sudo apt-get install chromium-chromedriver

  # Or use webdrivers gem (should be automatic)
  bundle exec rails runner "Webdrivers::Chromedriver.update"

  # Run tests in headless mode
  HEADLESS=true bundle exec rspec spec/system/
  ```
</Accordion>

## Problemas de Ambiente de Desenvolvimento

### Problemas com IDE e Editor

<Accordion title="A extensão Ruby do VS Code não está funcionando">
  **Erro**: Ruby IntelliSense não está funcionando, sem destaque de sintaxe.

  **Soluções**:

  ```bash theme={null}
  # Install Ruby LSP
  gem install ruby-lsp

  # Or add to Gemfile
  echo 'gem "ruby-lsp", group: :development' >> Gemfile
  bundle install

  # Restart VS Code
  # Install recommended extensions:
  # - Ruby LSP
  # - Ruby Solargraph
  # - Ruby Test Explorer
  ```
</Accordion>

<Accordion title="O Solargraph não está funcionando">
  **Erro**: A documentação e o preenchimento automático do Ruby não estão funcionando.

  **Soluções**:

  ```bash theme={null}
  # Install Solargraph
  gem install solargraph

  # Generate documentation
  bundle exec yard gems
  bundle exec solargraph bundle

  # Create .solargraph.yml config
  solargraph config

  # Restart your editor
  ```
</Accordion>

### Problemas de Git e Controle de Versão

<Accordion title="Ganchos pre-commit falhando">
  **Erro**: O commit do Git foi rejeitado devido a erros de linting.

  **Soluções**:

  ```bash theme={null}
  # Fix RuboCop issues
  bundle exec rubocop -a

  # Fix ESLint issues
  pnpm run lint:fix

  # Format code
  pnpm run format

  # Skip hooks temporarily (not recommended)
  git commit --no-verify -m "Your commit message"

  # Update pre-commit hooks
  pre-commit autoupdate
  ```
</Accordion>

<Accordion title="Erros de arquivo grande">
  **Erro**: Git LFS ou avisos de arquivo grande.

  **Soluções**:

  ```bash theme={null}
  # Install Git LFS
  git lfs install

  # Track large files
  git lfs track "*.png"
  git lfs track "*.jpg"
  git lfs track "*.pdf"

  # Add .gitattributes
  git add .gitattributes

  # Check LFS status
  git lfs status
  ```
</Accordion>

## Problemas de Desempenho

### Inicialização Lenta do Aplicativo

<Accordion title="O servidor Rails demora muito para iniciar">
  **Causa**: Base de código grande, banco de dados lento ou problemas de memória.

  **Soluções**:

  ```bash theme={null}
  # Use Spring for faster Rails commands
  bundle exec spring binstub --all

  # Check Spring status
  bundle exec spring status

  # Restart Spring if needed
  bundle exec spring stop

  # Increase memory if needed
  export RUBY_GC_HEAP_INIT_SLOTS=10000
  export RUBY_GC_HEAP_FREE_SLOTS=10000

  # Profile startup time
  time bundle exec rails runner "puts 'Rails loaded'"
  ```
</Accordion>

<Accordion title="Suite de testes lenta">
  **Causa**: Configuração do banco de dados, criação de factory ou testes ineficientes.

  **Soluções**:

  ```bash theme={null}
  # Use parallel testing
  bundle exec rspec --parallel

  # Profile slow tests
  bundle exec rspec --profile

  # Use database cleaner strategies
  # Add to spec/rails_helper.rb:
  # config.use_transactional_fixtures = true

  # Optimize factories
  # Use build_stubbed instead of create when possible
  ```
</Accordion>

## Problemas de E-mail e Comunicação

### Problemas de Entrega de E-mail

<Accordion title="E-mails não estão sendo enviados em desenvolvimento">
  **Causa**: Configuração de SMTP ou problemas no serviço de e-mail.

  **Soluções**:

  <Tabs>
    <Tab title="MailHog">
      ```bash theme={null}
      # Install and start MailHog
      brew install mailhog  # macOS
      mailhog

      # Configure .env
      MAILER_SENDER_EMAIL=dev@airyschat.local
      SMTP_ADDRESS=localhost
      SMTP_PORT=1025

      # Check web interface
      open http://localhost:8025
      ```
    </Tab>

    <Tab title="Letter Opener">
      ```bash theme={null}
      # Add to Gemfile
      echo 'gem "letter_opener", group: :development' >> Gemfile
      bundle install

      # Configure in development.rb
      # config.action_mailer.delivery_method = :letter_opener

      # Emails will open in browser
      ```
    </Tab>

    <Tab title="Gmail SMTP">
      ```bash theme={null}
      # Use app password, not regular password
      MAILER_SENDER_EMAIL=your-email@gmail.com
      SMTP_ADDRESS=smtp.gmail.com
      SMTP_PORT=587
      SMTP_USERNAME=your-email@gmail.com
      SMTP_PASSWORD=your-app-password
      SMTP_DOMAIN=gmail.com
      SMTP_ENABLE_STARTTLS_AUTO=true
      ```
    </Tab>
  </Tabs>
</Accordion>

### Problemas de Conexão WebSocket

<Accordion title="O ActionCable não está funcionando">
  **Erro**: Os recursos em tempo real não estão funcionando, a conexão WebSocket falhou.

  **Soluções**:

  ```bash theme={null}
  # Check if ActionCable is mounted
  grep -r "mount ActionCable" config/routes.rb

  # Check Redis connection
  redis-cli ping

  # Configure ActionCable for development
  # In config/environments/development.rb:
  # config.action_cable.url = "ws://localhost:3000/cable"
  # config.action_cable.allowed_request_origins = ["http://localhost:3000"]

  # Test WebSocket connection
  # Open browser console and check for WebSocket errors
  ```
</Accordion>

## Problemas de Depuração e Registro

### Problemas com Arquivo de Log

<Accordion title="Arquivos de log muito grandes ou não rodando">
  **Causa**: Registro excessivo em desenvolvimento.

  **Soluções**:

  ```bash theme={null}
  # Clear log files
  > log/development.log
  > log/test.log

  # Configure log rotation in development.rb
  # config.logger = ActiveSupport::Logger.new("log/development.log", 5, 10.megabytes)

  # Reduce log level
  # config.log_level = :info

  # Use logrotate (Linux)
  sudo logrotate -f /etc/logrotate.conf
  ```
</Accordion>

### Problemas de Ferramenta de Depuração

<Accordion title="O Pry ou o byebug não param a execução">
  **Causa**: O depurador não está configurado corretamente ou está em execução no contexto incorreto.

  **Soluções**:

  ```bash theme={null}
  # Make sure gems are in Gemfile
  echo 'gem "pry-rails", group: [:development, :test]' >> Gemfile
  echo 'gem "pry-byebug", group: [:development, :test]' >> Gemfile
  bundle install

  # Use correct debugger syntax
  # binding.pry  # for Pry
  # debugger     # for built-in debugger
  # byebug       # for byebug

  # Check if running in correct environment
  puts Rails.env
  ```
</Accordion>

## Comandos Rápidos de Diagnóstico

### Verificação de Saúde do Sistema

```bash theme={null}
#!/bin/bash
# health_check.sh - Quick system diagnostic

echo "=== AirysChat Development Health Check ==="

# Check Ruby version
echo "Ruby version: $(ruby --version)"

# Check Node.js version
echo "Node.js version: $(node --version)"

# Check database connection
if bundle exec rails runner "ActiveRecord::Base.connection.execute('SELECT 1')" > /dev/null 2>&1; then
  echo "✅ Database connection: OK"
else
  echo "❌ Database connection: FAILED"
fi

# Check Redis connection
if redis-cli ping > /dev/null 2>&1; then
  echo "✅ Redis connection: OK"
else
  echo "❌ Redis connection: FAILED"
fi

# Check if services are running
echo "Running processes:"
ps aux | grep -E "(rails|sidekiq|webpack|mailhog)" | grep -v grep

# Check ports
echo "Port usage:"
lsof -i :3000,3035,6379,5432,8025 2>/dev/null || echo "No processes found on common ports"

echo "=== Health Check Complete ==="
```

### Validação do Ambiente

```bash theme={null}
#!/bin/bash
# validate_env.sh - Validate development environment

required_vars=(
  "RAILS_ENV"
  "DATABASE_URL"
  "REDIS_URL"
  "SECRET_KEY_BASE"
  "FRONTEND_URL"
)

echo "=== Environment Variable Check ==="
for var in "${required_vars[@]}"; do
  if [ -z "${!var}" ]; then
    echo "❌ Missing: $var"
  else
    echo "✅ Set: $var"
  fi
done

echo "=== Dependency Check ==="
commands=("ruby" "node" "psql" "redis-cli" "git")
for cmd in "${commands[@]}"; do
  if command -v $cmd > /dev/null 2>&1; then
    echo "✅ $cmd: $(command -v $cmd)"
  else
    echo "❌ $cmd: Not found"
  fi
done
```

## Obtendo Ajuda Adicional

Se você ainda estiver enfrentando problemas após tentar essas soluções:

1. **Pesquisar Problemas no GitHub**: Verifique se outras pessoas relataram problemas semelhantes
2. **Verificar Logs**: Olhe para o `log/development.log` para mensagens de erro detalhadas
3. **Comunidade no Discord**: Entre no Discord do AirysChat para obter ajuda em tempo real
4. **Documentação**: Reveja a documentação oficial
5. **Criar uma Issue**: Se for um bug, crie uma issue detalhada no GitHub

### Criando um Bom Relatório de Bug

Ao relatar problemas, inclua:

```markdown theme={null}
## Environment
- OS: [e.g., macOS 13.0, Ubuntu 22.04]
- Ruby version: [e.g., 3.3.3]
- Node.js version: [e.g., 20.10.0]
- Database: [e.g., PostgreSQL 15.0]

## Steps to Reproduce
1. Step one
2. Step two
3. Step three

## Expected Behavior
What you expected to happen

## Actual Behavior
What actually happened

## Error Messages
Full error message and stack trace

## Additional Context
Any other relevant information
```

***

Este guia cobre a maioria dos problemas comuns de desenvolvimento. Para problemas de implantação de produção, consulte a [Documentação Self-hosted](/self-hosted/).
