Skip to content

Troubleshooting

Dragon edited this page Dec 22, 2025 · 1 revision

🔧 Troubleshooting Guide for NaviDuck

Comprehensive solutions to common problems, error messages, and performance issues. Get NaviDuck working perfectly with these troubleshooting tips.

Last updated: 12/22/2025

📋 Quick Navigation


🔍 Common Issues Quick Fixes

Top 5 Most Common Problems

Problem Quick Fix Detailed Solution
App won't start pip install requests then restart Installation Issues
No search results Try search brave test or enable Tor Search Engine Issues
CAPTCHA blocking Use tor start then search CAPTCHA Solutions
Slow performance Clear history with settings option 4 Performance Tips
Command not working Check help for correct syntax Command Reference

Emergency Solutions

If NaviDuck freezes or hangs:

  1. Press Ctrl+X - Immediate quit (works even during operations)
  2. Windows: Ctrl+C in command prompt
  3. Mac/Linux: Ctrl+Z then kill %1

If you see no icons/colors:

# Terminal doesn't support colors/Unicode
# 1. Switch to emoji mode:
settings  # Then option 3
# 2. Or use a better terminal:
# Windows: Windows Terminal
# Mac: iTerm2
# Linux: Terminator

🚨 Startup & Installation Problems

"requests library not installed" Error

Full Error Message:

❌ requests library not installed!
Install with: pip install requests

Solutions:

1. Basic Installation:

# Install required package
pip install requests

# Or install all recommended packages
pip install requests beautifulsoup4 colorama

2. If pip is not found:

# Windows:
python -m pip install requests
# or
py -m pip install requests

# Linux/Mac:
pip3 install requests
# or
python3 -m pip install requests

3. Virtual Environment (Recommended):

# Create virtual environment
python -m venv naviduck_env

# Activate it:
# Windows:
naviduck_env\Scripts\activate
# Mac/Linux:
source naviduck_env/bin/activate

# Install dependencies
pip install requests beautifulsoup4 colorama

4. Global Python Issues:

# Check Python installation
python --version  # Should be 3.6+
python -m ensurepip  # Ensure pip is installed

# If using Anaconda:
conda install -c anaconda requests

"Python not found" or Command Not Recognized

Windows Solutions:

# 1. Add Python to PATH during installation
# Re-run Python installer, check "Add Python to PATH"

# 2. Manually add to PATH:
# Press Win+X → System → Advanced System Settings
# Environment Variables → Path → Add Python path
# Typical paths: C:\Python39\ or C:\Users\YourName\AppData\Local\Programs\Python\Python39\

# 3. Use Python launcher:
py naviduck.py
# or
python3 naviduck.py

Mac Solutions:

# 1. Install Python via Homebrew:
brew install python

# 2. Check Python 3 specifically:
python3 naviduck.py

# 3. Fix symlinks if needed:
ln -s /usr/local/bin/python3 /usr/local/bin/python

Linux Solutions:

# 1. Install Python 3:
sudo apt-get install python3 python3-pip  # Debian/Ubuntu
sudo yum install python3 python3-pip      # RedHat/Fedora

# 2. Make script executable:
chmod +x naviduck.py

# 3. Use shebang line (already in script):
./naviduck.py

Script Runs but Immediately Closes

Diagnosis Steps:

  1. Open terminal first, then run script:

    cd /path/to/naviduck
    python naviduck.py
  2. Check for errors (Windows):

    python naviduck.py
    pause
  3. Create batch file:

    @echo off
    python naviduck.py
    pause
  4. Enable logging:

    # Add to start of script:
    import logging
    logging.basicConfig(level=logging.DEBUG, filename='naviduck.log')

ModuleNotFoundError for Other Packages

Common missing packages:

# Install commonly required packages
pip install beautifulsoup4 lxml html5lib colorama

# For enhanced features (optional):
pip install rich prompt_toolkit PyInquirer

If you see "No module named 'bs4'":

# BeautifulSoup is optional for NaviDuck
# The app works without it using regex parsing
# But you can install it for better parsing:
pip install beautifulsoup4

# Or disable BS4 dependency by modifying code:
# Comment out any bs4 imports (not needed in current version)

🌐 Search Engine Issues

No Search Results Showing

Diagnosis Checklist:

# Test each engine individually:
1. search brave test  # Should work
2. search google test
3. search ddg test
4. search wikipedia test
5. search ddg_api test

Engine-Specific Solutions:

1. DuckDuckGo Issues:

# If ddg doesn't work, try ddg_api:
search ddg_api [query]

# Or switch to HTML version manually:
# In code, change line 119 from:
# "url": "https://lite.duckduckgo.com/lite/",
# To:
# "url": "https://html.duckduckgo.com/html/",

2. Google Issues:

# Google often blocks automated requests:
# Solution 1: Use Tor
tor start
search google [query]

# Solution 2: Use alternative engine
search brave [query]

# Solution 3: Modify user agent in code
# In NetworkManager.__init__, change user-agent

3. Brave Search Issues:

# Brave is the default for a reason - it works best
# If Brave fails, check:
# 1. Internet connection
# 2. DNS settings (try 8.8.8.8)
# 3. Temporary outage (check brave.com)

4. Wikipedia API Issues:

# If Wikipedia returns no results:
# 1. Check API status: https://en.wikipedia.org/wiki/Special:ApiSandbox
# 2. Use direct search:
open https://en.wikipedia.org/wiki/Special:Search?search=[query]

CAPTCHA Issues

Symptoms:

  • "CAPTCHA detected" message
  • Search returns blank or "complete verification"
  • Redirects to verification page

Immediate Solutions:

1. Enable Tor (Most Effective):

tor start
# Wait for "Tor started successfully"
search [query]  # Will use Tor automatically

2. Switch Search Engine:

# Different engines have different CAPTCHA rates:
# Low CAPTCHA: Brave, DuckDuckGo API
# Medium: Google, Wikipedia  
# High: DuckDuckGo HTML
search brave [query]  # Least likely to trigger CAPTCHA

3. Add Delays Between Searches:

# Rapid searches trigger CAPTCHA
# NaviDuck already has random delays (0.5-2 seconds)
# You can increase delays in code:
# In NetworkManager.get(), change:
time.sleep(random.uniform(1.0, 3.0))  # Increase from 0.5-2.0

4. Use Different Network:

# CAPTCHA often triggered by:
# 1. School/work networks
# 2. Public WiFi
# 3. VPN/Proxy users
# Try: Mobile hotspot or home network

Long-term CAPTCHA Solutions:

1. Rotate User Agents:

# In NetworkManager.__init__, add rotation:
user_agents = [
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15...',
    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36...'
]
self.session.headers.update({'User-Agent': random.choice(user_agents)})

2. Implement Cookie Handling:

# Some sites use cookies to track
self.session = requests.Session()
# Session maintains cookies between requests

3. Use Residential Proxies (Advanced):

# In NetworkManager.get():
proxies = {
    'http': 'http://user:pass@residential-proxy:8080',
    'https': 'http://user:pass@residential-proxy:8080',
}
response = self.session.get(url, proxies=proxies, timeout=10)

"All search engines failed" Error

Complete Troubleshooting:

# Step-by-step diagnosis:

# 1. Test internet connectivity:
ping 8.8.8.8

# 2. Test direct HTTP request:
python -c "import requests; print(requests.get('https://httpbin.org/ip').text)"

# 3. Check if Python can make requests:
python -c "import requests; r=requests.get('https://google.com'); print(r.status_code)"

# 4. Check DNS resolution:
nslookup duckduckgo.com

# 5. Test with curl (bypass Python):
curl https://duckduckgo.com/?q=test

If All Engines Fail:

1. Firewall/Antivirus Blocking:

# Temporarily disable to test:
# Windows Defender: Add python.exe to exclusions
# Third-party AV: Add exception for Python
# Firewall: Allow Python through firewall

2. Corporate/Network Restrictions:

# Common in schools/workplaces:
# Solution: Use Tor
tor start
# Tor bypasses most network restrictions

3. Python SSL Certificate Issues:

# Update certificates:
# Windows: Update Python or install certifi
pip install --upgrade certifi

# Linux:
sudo update-ca-certificates

# Or disable SSL verification (not recommended):
# In NetworkManager.get(), add:
verify=False  # Only for testing!

4. IPv6 Issues:

# Some networks have IPv6 problems:
# Disable IPv6 temporarily or force IPv4:
# In code, add to requests:
import socket
socket.setdefaulttimeout(10)
# Or modify /etc/gai.conf to prefer IPv4

Slow Search Results

Performance Optimization:

1. Enable Faster Engines:

# Engine speed comparison (fastest to slowest):
# 1. ddg_api (JSON API, fastest)
# 2. wikipedia (API, fast)
# 3. brave (HTML, medium)
# 4. google (HTML, slow due to blocks)
# 5. ddg (HTML, slowest due to CAPTCHA)

# Set fastest as default:
settings  # Then option 1 → select ddg_api

2. Implement Caching:

# Add to SearchManager:
import hashlib
import pickle
import os

def search(self, query, engine=None):
    cache_key = hashlib.md5(f"{query}_{engine}".encode()).hexdigest()
    cache_file = f"cache/{cache_key}.pkl"
    
    if os.path.exists(cache_file):
        # Load from cache (1 hour TTL)
        if time.time() - os.path.getmtime(cache_file) < 3600:
            with open(cache_file, 'rb') as f:
                return pickle.load(f)

3. Parallel Searches (Advanced):

# Search multiple engines simultaneously
import threading

def parallel_search(query, engines=['brave', 'ddg_api']):
    results = {}
    threads = []
    
    def search_engine(engine):
        results[engine] = self.search(query, engine)
    
    for engine in engines:
        t = threading.Thread(target=search_engine, args=(engine,))
        threads.append(t)
        t.start()
    
    for t in threads:
        t.join()
    
    return results

Incorrect or Poor Quality Results

Improving Result Quality:

1. Better Query Formulation:

# NaviDuck uses exact query
# Try these formats:
search "exact phrase in quotes"
search site:example.com keyword
search filetype:pdf topic
search -exclude unwanted

2. Engine-Specific Syntax:

# Each engine has different advanced syntax:
# Google: search google "python tutorial" site:github.com
# DuckDuckGo: search ddg !w python  # Bang syntax
# Wikipedia: search wikipedia "Python (programming language)"

3. Custom Result Parsing:

# If an engine returns poor results, improve parsing:
# In SearchManager.parse_results(), add better patterns

# Example for better HTML parsing:
elif engine == "brave":
    # Try multiple patterns
    patterns = [
        r'<a[^>]+data-testid="[^"]*result-title[^"]*"[^>]+href="([^"]+)"[^>]*>(.*?)</a>',
        r'<a[^>]+class="[^"]*result-header[^"]*"[^>]+href="([^"]+)"[^>]*>(.*?)</a>',
        r'<h3[^>]*><a[^>]+href="([^"]+)"[^>]*>(.*?)</a></h3>',
    ]

4. Result Filtering:

# Filter out low-quality results
def filter_results(results, min_title_length=10, required_domains=None):
    filtered = []
    for result in results:
        # Filter by title length
        if len(result['title']) < min_title_length:
            continue
        
        # Filter by domain
        if required_domains:
            domain = urlparse(result['url']).netloc
            if not any(req in domain for req in required_domains):
                continue
        
        filtered.append(result)
    return filtered

🤖 AI Feature Problems

NavAI Not Responding

Symptoms:

  • "AI Error" messages
  • No response or empty answers
  • "No answer found" for everything

Solutions:

1. Check Internet Connection for AI:

# NavAI needs internet for web searches
# Test if AI can access DuckDuckGo API:
python -c "
import requests
r = requests.get('https://api.duckduckgo.com/?q=python&format=json&no_html=1')
print('Status:', r.status_code)
print('Response length:', len(r.text))
"

2. DuckDuckGo API Issues:

# If DuckDuckGo API is down:
# 1. NavAI will still handle simple queries (greetings, etc.)
# 2. For complex queries, it will suggest manual search
# 3. Check API status: https://duckduckgo.com/?q=test&format=json

# Workaround: Use search instead
search [your question]

3. Rate Limiting:

# DuckDuckGo API has rate limits
# Symptoms: Works initially, then stops
# Solution: Add delays between AI queries
# In NavAI.ask(), add:
time.sleep(1)  # 1 second between queries

4. Fallback to Local Answers:

# Enhance local knowledge base
# In NavAI._handle_simple_queries(), add more responses:
responses = {
    # ... existing responses
    "what is python": "Python is a high-level programming language...",
    "how to install python": "Visit python.org/downloads...",
    "python tutorials": "Try: W3Schools, Real Python, Python.org docs",
}

AI Returns "No answer found"

Improving AI Answers:

1. Rephrase Questions:

# Instead of: ai python
# Try: ai what is python programming language

# Instead of: ai weather
# Try: ai what is the weather today in [city]

# Best format: ai [question word] [topic] [specifics]

2. Use Search for Complex Questions:

# For questions AI can't answer:
# AI will suggest: "Try: 'search [your question]'"
# Follow the suggestion:
search [your question]

3. Extend AI Knowledge Base:

# Add more patterns to _handle_simple_queries
"how to use naviduck": f"{self.icons['INFO']} Type 'help' for commands...",
"naviduck features": f"{self.icons['BROWSER']} NaviDuck has: Search, AI, Tor, Bookmarks...",
"who made this": f"{self.icons['AI']} Created by DAPOWER99 on GitHub...",

4. Implement Web Search Fallback:

# When AI can't answer, automatically search
def ask_with_fallback(self, question):
    answer = self.ask(question)
    if "couldn't find a direct answer" in answer:
        # Auto-search
        search_results = self.search(question)
        if search_results:
            return f"{answer}\n\nTop result: {search_results[0]['title']}\n{search_results[0]['url']}"
    return answer

AI Too Slow or Timing Out

Performance Tuning:

1. Timeout Settings:

# In NavAI._get_duckduckgo_answer():
response = self.session.get(url, params=params, timeout=3)  # Reduce from 5

# In simple queries, return immediately
if query_lower in responses:
    return responses[query_lower]  # Instant response

2. Cache AI Responses:

# Cache frequently asked questions
ai_cache = {}

def ask(self, question):
    if question in ai_cache:
        if time.time() - ai_cache[question]['time'] < 3600:  # 1 hour
            return ai_cache[question]['answer']
    
    answer = self._ask_uncached(question)
    ai_cache[question] = {'answer': answer, 'time': time.time()}
    return answer

3. Parallel Processing (Advanced):

# Search multiple sources simultaneously
def ask_parallel(self, question):
    from concurrent.futures import ThreadPoolExecutor, as_completed
    
    def get_ddg_answer():
        return self._get_duckduckgo_answer(question)
    
    def get_wikipedia_answer():
        # Implement Wikipedia answer fetching
        pass
    
    with ThreadPoolExecutor(max_workers=2) as executor:
        futures = {
            executor.submit(get_ddg_answer): 'ddg',
            executor.submit(get_wikipedia_answer): 'wiki'
        }
        
        for future in as_completed(futures, timeout=2):
            answer = future.result()
            if answer and answer != "No answer found.":
                return answer
    
    return "No answer found."

🕸️ Network & Connectivity

Cannot Load Web Pages

Page Load Failures:

1. "Failed to load page" Error:

# Test URL accessibility:
# In NaviDuck: go https://httpbin.org/status/200
# Should work. If not:

# Check if site is up:
curl -I https://example.com
# Status should be 200

# Check if blocked by ISP/country
# Try different site: go https://www.wikipedia.org

2. SSL/TLS Certificate Issues:

# Common on older Python installations
# Update certificates:
pip install --upgrade certifi
# or
python -m pip install --upgrade pip certifi

# Temporary workaround (insecure):
# In PageLoader.load_page(), add:
verify=False  # ONLY for testing!

3. Timeout Issues:

# Increase timeout for slow sites
# In NetworkManager.get():
timeout=30  # Increase from 10

# Or implement retry logic:
def get_with_retry(self, url, max_retries=3):
    for attempt in range(max_retries):
        try:
            return self.session.get(url, timeout=10)
        except requests.exceptions.Timeout:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)  # Exponential backoff

4. DNS Resolution Problems:

# If some sites work but others don't:
# Change DNS servers to Google/Cloudflare:
# Windows: 8.8.8.8, 8.8.4.4
# Linux: Edit /etc/resolv.conf
# Router: Change DNS in router settings

Tor Connection Issues

"Tor is not installed" Error

Windows Solutions:

# 1. Install Tor Browser normally
# 2. Find tor.exe location (usually):
#    C:\Users\[User]\Desktop\Tor Browser\Browser\TorBrowser\Tor\tor.exe
# 3. Update path in TorManager.__init__:
self.tor_dir = r"C:\Users\YourName\Desktop\Tor Browser\Browser\TorBrowser\Tor"

Linux Solutions:

# Install Tor via package manager:
# Debian/Ubuntu:
sudo apt-get install tor

# RedHat/Fedora:
sudo yum install tor

# Then update path in code:
self.tor_exe = "/usr/bin/tor"

Mac Solutions:

# Install via Homebrew:
brew install tor

# Or download Tor Browser and find tor binary:
# Usually in: /Applications/TorBrowser.app/Contents/Resources/Tor/tor

"Failed to start Tor" Error

Common Causes and Fixes:

1. Port 9050 Already in Use:

# Check if port is occupied:
# Windows:
netstat -ano | findstr :9050
# Linux/Mac:
lsof -i :9050

# Kill process or change port:
# In TorManager.start_tor(), change:
"--SocksPort", "9051"  # Different port

2. Tor Already Running:

# Check if Tor is already running:
# Windows: Task Manager → look for tor.exe
# Linux: ps aux | grep tor
# Mac: Activity Monitor

# Stop existing Tor processes first

3. Permission Issues:

# Tor needs to create temp directory
# Run NaviDuck as administrator (Windows)
# Or with sudo (Linux/Mac - not recommended)

# Better: Ensure write permissions in temp location

4. Tor Binary Not Executable:

# Linux/Mac: Make tor executable
chmod +x /path/to/tor

# Or specify full path to tor binary

Tor Starts but Doesn't Work

Testing Tor Connection:

# 1. Check if Tor is actually working:
curl --socks5 127.0.0.1:9050 https://check.torproject.org/

# 2. Test with simple request:
python -c "
import requests
proxies = {'http': 'socks5h://127.0.0.1:9050', 
           'https': 'socks5h://127.0.0.1:9050'}
r = requests.get('https://httpbin.org/ip', proxies=proxies)
print('Your IP via Tor:', r.json()['origin'])
"

# 3. If tests fail, restart Tor:
tor stop
tor start

Slow Tor Speeds:

# Tor is inherently slower
# For better speeds:

# 1. Use faster search engines with Tor:
#    ddg_api and wikipedia work best with Tor

# 2. Reduce timeout for Tor requests:
#    In NetworkManager.get(), separate timeout for Tor
timeout=30 if use_tor else 10

# 3. Cache Tor results:
#    Implement caching specifically for Tor requests

Tor-Specific Search Issues

Some sites block Tor exit nodes:

# Symptoms: Works without Tor, fails with Tor
# Solutions:
# 1. Use different search engine
# 2. Use .onion sites when available
# 3. Change Tor circuit (restart Tor)
# 4. Use bridges (advanced Tor configuration)

Proxy Configuration

Using NaviDuck Behind a Proxy

System Proxy Detection:

# NaviDuck doesn't auto-detect system proxy
# To add proxy support:

# In NetworkManager.__init__():
import os
proxy = os.environ.get('HTTP_PROXY') or os.environ.get('http_proxy')
if proxy:
    self.session.proxies = {'http': proxy, 'https': proxy}

# Set environment variable before running:
# Windows:
set HTTP_PROXY=http://proxy:port
# Linux/Mac:
export HTTP_PROXY=http://proxy:port

Manual Proxy Configuration:

# Add to NetworkManager.__init__():
self.proxy = {
    'http': 'http://your-proxy:8080',
    'https': 'http://your-proxy:8080',
}

# Then in get():
response = self.session.get(url, proxies=self.proxy, timeout=timeout)

Proxy Authentication Issues

# For proxies requiring authentication:
self.proxy = {
    'http': 'http://username:password@proxy:8080',
    'https': 'http://username:password@proxy:8080',
}

# Or prompt for credentials:
if not hasattr(self, 'proxy_credentials'):
    user = get_input("Proxy username")
    password = get_input("Proxy password", hide=True)
    self.proxy = {
        'http': f'http://{user}:{password}@proxy:8080',
        'https': f'http://{user}:{password}@proxy:8080',
    }

⚡ Performance Issues

Slow Startup

Optimization Tips:

1. Reduce Initial Imports:

# Move heavy imports to where they're needed
# Instead of top-level imports:
# def some_function():
#     import heavy_module

# Lazy loading for optional features
if some_condition:
    import optional_module

2. Cache Configuration Loading:

# Cache config/data files
import pickle
import hashlib

def load_cached(filepath, max_age=3600):
    cache_file = f"{filepath}.cache"
    if os.path.exists(cache_file):
        if time.time() - os.path.getmtime(cache_file) < max_age:
            with open(cache_file, 'rb') as f:
                return pickle.load(f)
    
    # Load normally and cache
    data = load_normal(filepath)
    with open(cache_file, 'wb') as f:
        pickle.dump(data, f)
    return data

3. Profile Startup Time:

# Identify slow components
python -m cProfile -s time naviduck.py --help
# Look for functions taking >100ms

High Memory Usage

Memory Leak Detection:

1. Monitor Memory:

# Add memory monitoring
import psutil
import os

def print_memory_usage():
    process = psutil.Process(os.getpid())
    print(f"Memory: {process.memory_info().rss / 1024 / 1024:.1f} MB")
# Call periodically

2. Clear Large Data Structures:

# History and bookmarks can grow large
# Implement limits:
MAX_HISTORY = 1000
MAX_BOOKMARKS = 500

# Regularly trim:
if len(self.state.history) > MAX_HISTORY:
    self.state.history = self.state.history[-MAX_HISTORY:]

3. Fix Common Leaks:

# Requests sessions can leak memory
# Periodically recreate session:
if self.request_count > 1000:
    self.session = requests.Session()
    self.request_count = 0

Slow Search Operations

Performance Bottlenecks:

1. Network Delays:

# Reduce timeouts for faster failures
timeout=5  # Instead of 10

# Implement concurrent searches
from concurrent.futures import ThreadPoolExecutor

def fast_search(query, engines=['brave', 'ddg_api']):
    with ThreadPoolExecutor(max_workers=2) as executor:
        futures = {executor.submit(self.search, query, e): e for e in engines}
        for future in as_completed(futures, timeout=5):
            results = future.result()
            if results:
                return results

2. Parsing Optimization:

# Regex parsing can be slow
# Compile regex patterns once:
import re
LINK_PATTERN = re.compile(r'<a[^>]+href="([^"]+)"[^>]*>([^<]+)</a>')

# Then use:
matches = LINK_PATTERN.findall(html)

3. Result Caching:

# Cache search results
def cached_search(self, query, engine, ttl=300):  # 5 minutes
    cache_key = f"{query}_{engine}"
    if cache_key in self.search_cache:
        if time.time() - self.search_cache[cache_key]['time'] < ttl:
            return self.search_cache[cache_key]['results']
    
    results = self._uncached_search(query, engine)
    self.search_cache[cache_key] = {'results': results, 'time': time.time()}
    return results

UI Lag/Responsiveness Issues

Improving UI Performance:

1. Limit Displayed Items:

# Don't show too many results at once
MAX_DISPLAY_RESULTS = 10
MAX_DISPLAY_HISTORY = 15
MAX_DISPLAY_BOOKMARKS = 20

2. Optimize Screen Updates:

# Clear screen efficiently
def fast_clear():
    if os.name == 'nt':
        os.system('cls')
    else:
        print('\033[2J\033[H', end='')  # ANSI escape codes

3. Reduce Animation/Effects:

# Disable loading animations if slow
def show_loading(message):
    if self.slow_terminal:
        print(f"{message}...")
    else:
        # Show spinner
        spinner = ['|', '/', '-', '\\']
        # ...

📱 Platform-Specific Issues

Windows Problems

Common Windows Issues:

1. CMD/PowerShell Encoding Problems:

# Fix Unicode/emoji display:
# Use Windows Terminal (free from Microsoft Store)
# Or configure CMD:
chcp 65001  # UTF-8 code page
# Set font to Consolas or Cascadia Code

# In Python, force UTF-8:
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

2. Path Length Limitations:

# Windows has 260-character path limit
# Solution: Enable long paths:
# 1. Run as administrator: regedit
# 2. Navigate to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem
# 3. Create DWORD: LongPathsEnabled = 1
# Or use short paths: C:\PROGRA~1\...

3. Python Installation Conflicts:

# Multiple Python versions causing issues:
# Clear up PATH:
where python  # Shows all python executables
# Remove unwanted Python paths from Environment Variables
# Use py launcher: py -3.9 naviduck.py

4. Windows Defender False Positives:

# If Windows Defender blocks NaviDuck:
# 1. Add exclusion for naviduck.py
# 2. Or Python installation folder
# 3. Submit false positive report to Microsoft

Windows-Specific Tor Issues:

# Tor on Windows often in Program Files
# Permission issues common
# Solutions:

# 1. Run as Administrator (not recommended)
# 2. Install Tor to user directory (C:\Users\...)
# 3. Copy tor.exe to NaviDuck directory
# 4. Update TorManager path:
self.tor_exe = "tor.exe"  # If in same directory

MacOS Problems

Common Mac Issues:

1. Python 2 vs Python 3:

# Mac comes with Python 2, NaviDuck needs Python 3
python --version  # Likely 2.7
python3 --version # Should be 3.6+

# Always use:
python3 naviduck.py

# Or make alias:
alias python=python3

2. Permission Errors:

# "Permission denied" when running
chmod +x naviduck.py
# Or
python3 naviduck.py

# If installing packages:
pip3 install --user requests
# Or
sudo pip3 install requests

3. Gatekeeper Security:

# "App can't be opened" warning
# For downloaded Python scripts:
xattr -d com.apple.quarantine naviduck.py

4. Homebrew Python Issues:

# If using Homebrew Python:
brew install python
# Ensure PATH includes /usr/local/bin before /usr/bin
echo $PATH
# Fix: Add to ~/.zshrc or ~/.bash_profile:
export PATH="/usr/local/bin:$PATH"

Linux Problems

Common Linux Issues:

1. Distribution-Specific Issues:

Ubuntu/Debian:

# Missing Python 3:
sudo apt-get install python3 python3-pip
# Missing tkinter (for future GUI features):
sudo apt-get install python3-tk

Fedora/RHEL:

sudo dnf install python3 python3-pip

Arch Linux:

sudo pacman -S python python-pip

2. Permission Issues:

# Running without permissions
# Option 1: Run in user directory
cd ~
mkdir naviduck
cd naviduck

# Option 2: Install system-wide (not recommended)
sudo python3 setup.py install

3. Display/TERM Issues:

# If colors/icons don't show:
echo $TERM  # Should be xterm-256color or similar

# Fix:
export TERM=xterm-256color

# Or install better terminal:
sudo apt-get install terminator  # Ubuntu

4. SELinux/AppArmor Restrictions:

# If blocked by security modules:
# Check logs:
sudo dmesg | grep python
sudo grep python /var/log/audit/audit.log

# Temporary disable (for testing):
sudo setenforce 0  # SELinux
# Or add Python exception

🛠️ Advanced Debugging

Enabling Debug Mode

Basic Debug Output:

# Add to start of main():
import logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='naviduck_debug.log'
)

# Or print to console:
debug = True  # Set to True for debugging

def debug_print(*args):
    if debug:
        print(f"[DEBUG] {' '.join(str(arg) for arg in args)}")

Verbose Logging for Specific Components:

Network Debugging:

# In NetworkManager.get():
import http.client
http.client.HTTPConnection.debuglevel = 1

# Or use requests logging:
import logging
logging.getLogger("requests").setLevel(logging.DEBUG)
logging.getLogger("urllib3").setLevel(logging.DEBUG)

Search Engine Debugging:

# In SearchManager.search():
print(f"DEBUG: Searching {engine} for '{query}'")
print(f"DEBUG: URL: {url}")
print(f"DEBUG: Params: {params}")

# Save raw responses:
with open(f"debug_{engine}_{int(time.time())}.html", "w") as f:
    f.write(response.text)

Creating Test Cases

Automated Testing Script:

# test_naviduck.py
import subprocess
import time

def test_feature(feature, command, expected_in_output):
    print(f"Testing {feature}...")
    proc = subprocess.Popen(
        ['python', 'naviduck.py'],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    
    # Send command
    proc.stdin.write(command + "\n")
    proc.stdin.write("quit\n")
    proc.stdin.flush()
    
    # Get output
    output, error = proc.communicate(timeout=10)
    
    if expected_in_output in output:
        print(f"✓ {feature} passed")
        return True
    else:
        print(f"✗ {feature} failed")
        print(f"Output: {output[:200]}")
        return False

# Run tests
tests = [
    ("Search", "s test\n", "Search Results"),
    ("AI", "ai hello\n", "Hello"),
    ("History", "history\n", "Browsing History"),
]

all_passed = True
for test in tests:
    if not test_feature(*test):
        all_passed = False

print(f"\n{'All tests passed!' if all_passed else 'Some tests failed.'}")

Profiling Performance

CPU Profiling:

# Profile execution time
python -m cProfile -o profile.stats naviduck.py

# Analyze results
python -c "
import pstats
p = pstats.Stats('profile.stats')
p.sort_stats('time').print_stats(20)
"

# Or visual profile with snakeviz
pip install snakeviz
snakeviz profile.stats

Memory Profiling:

# Install memory profiler
pip install memory-profiler

# Add decorator to functions
from memory_profiler import profile

@profile
def search(self, query, engine=None):
    # function body

# Run with:
python -m memory_profiler naviduck.py

Network Traffic Analysis

Using Wireshark/tshark:

# Capture network traffic
# Linux:
sudo tcpdump -i any -w naviduck.pcap port 80 or port 443 or port 9050

# Analyze with Wireshark or tshark:
tshark -r naviduck.pcap -Y "http or tls" -T fields -e ip.src -e ip.dst -e http.request.uri

Python HTTP Debugging:

# Monkey-patch requests to log all traffic
import requests

original_request = requests.Session.request

def debug_request(self, method, url, **kwargs):
    print(f"[HTTP] {method} {url}")
    if 'params' in kwargs:
        print(f"  Params: {kwargs['params']}")
    response = original_request(self, method, url, **kwargs)
    print(f"  Status: {response.status_code}")
    print(f"  Size: {len(response.content)} bytes")
    return response

requests.Session.request = debug_request

Creating Diagnostic Reports

Generate System Report:

def generate_diagnostic_report():
    import platform
    import sys
    import pkg_resources
    
    report = []
    report.append("=" * 60)
    report.append("NaviDuck Diagnostic Report")
    report.append("=" * 60)
    
    # System info
    report.append(f"Platform: {platform.platform()}")
    report.append(f"Python: {sys.version}")
    report.append(f"Python Path: {sys.executable}")
    
    # Installed packages
    report.append("\nInstalled Packages:")
    for pkg in pkg_resources.working_set:
        if pkg.key in ['requests', 'beautifulsoup4', 'colorama']:
            report.append(f"  {pkg.key}=={pkg.version}")
    
    # Network test
    report.append("\nNetwork Test:")
    try:
        import requests
        r = requests.get('https://httpbin.org/ip', timeout=5)
        report.append(f"  Internet: OK (IP: {r.json()['origin']})")
    except Exception as e:
        report.append(f"  Internet: FAILED ({e})")
    
    # Tor test
    report.append("\nTor Test:")
    try:
        proxies = {'http': 'socks5h://127.0.0.1:9050', 
                   'https': 'socks5h://127.0.0.1:9050'}
        r = requests.get('https://check.torproject.org/', proxies=proxies, timeout=5)
        report.append("  Tor: OK" if 'Congratulations' in r.text else "  Tor: Not using Tor")
    except:
        report.append("  Tor: Not running or not installed")
    
    # Save report
    with open('naviduck_diagnostic.txt', 'w') as f:
        f.write('\n'.join(report))
    
    print('\n'.join(report))
    print("\nReport saved to: naviduck_diagnostic.txt")

❓ Frequently Asked Questions

General Questions

Q: Is NaviDuck safe to use? A: Yes, NaviDuck is open-source and only accesses websites you explicitly visit. It doesn't collect personal data. Use Tor for maximum privacy.

Q: Does NaviDuck work on mobile? A: Not directly, but you can use Termux on Android or iSH on iOS to run Python scripts, including NaviDuck.

Q: Can I use NaviDuck without internet? A: Basic commands work offline, but search and AI features require internet. History and bookmarks are available offline.

Q: How do I update NaviDuck? A: Currently manual - download the latest version from GitHub. Future versions may include auto-update.

Q: Is there a GUI version? A: Not yet, but one is planned. The CLI interface is fully featured.

Technical Questions

Q: Why does search sometimes return no results? A: Websites may block automated requests. Try: 1) Enable Tor 2) Switch search engine 3) Check internet connection.

Q: How can I add my own search engine? A: See the Custom Search Engines Guide. Edit the SEARCH_ENGINES dictionary in the source code.

Q: Why are there no colors/icons in my terminal? A: Your terminal may not support ANSI colors or Unicode. Try: 1) Switch to emoji mode in settings 2) Use a modern terminal 3) Check TERM environment variable.

Q: How do I change the default search engine? A: Use settings command, then option 1, or directly edit ~/.naviduck_config.json.

Q: Can I use NaviDuck with a proxy? A: Yes, set HTTP_PROXY environment variable before running: export HTTP_PROXY=http://proxy:port (Linux/Mac) or set HTTP_PROXY=... (Windows).

Troubleshooting Questions

Q: NaviDuck crashes immediately on startup A: Most likely missing dependencies. Run pip install requests. If that doesn't work, check Python version (needs 3.6+).

Q: I get "CAPTCHA detected" for every search A: Your IP is being flagged. Solutions: 1) Enable Tor 2) Use different network 3) Switch to Brave search (least CAPTCHA).

Q: Tor won't start A: Check: 1) Tor Browser installed 2) Path in TorManager is correct 3) Port 9050 not in use 4) Run as admin if needed.

Q: AI always says "No answer found" A: DuckDuckGo API may be down or rate-limiting you. Try: 1) Wait and retry 2) Use search instead 3) Check internet connection.

Q: Very slow performance A: Clear history and bookmarks, enable caching, use faster search engines (ddg_api), reduce displayed items.

Feature Questions

Q: Can I import/export bookmarks? A: Bookmarks are stored in ~/.naviduck_data.json. You can manually edit this JSON file.

Q: Is there a dark mode? A: The terminal colors provide a dark theme. For true dark mode, configure your terminal's color scheme.

Q: Can I search multiple engines at once? A: Not in current version, but planned for future. Workaround: Search each engine separately.

Q: How do I customize keybindings? A: Keybindings are hardcoded (Ctrl+X to quit). Future versions may allow customization.

Q: Can I run scripts/automate NaviDuck? A: Not currently, but you can modify the source code or use expect-like tools to automate.

Advanced Questions

Q: How do I contribute to development? A: Fork on GitHub, make improvements, submit pull requests. Report issues on GitHub.

Q: Can I use NaviDuck as a library? A: Not designed as a library, but you can import components. Structure may change in future versions.

Q: Is there API documentation? A: No formal API docs yet. Read the source code - it's well-commented.

Q: How do I add new icon sets? A: Extend the Icons class with new sets, add toggle in settings.

Q: Can I use custom CSS/themING for displayed pages? A: Not currently. Pages are displayed as plain text with minimal formatting.


🆘 Getting Further Help

Official Support Channels

  1. GitHub Issues: https://github.com/DAPOWER99/NaviDuck/issues

    • Report bugs
    • Request features
    • Ask technical questions
  2. Documentation: https://github.com/DAPOWER99/NaviDuck/wiki

    • Complete guides
    • Tutorials
    • API reference (coming soon)
  3. Community:

    • GitHub Discussions (planned)
    • Code contributors welcome

Before Asking for Help

Please provide:

  1. NaviDuck version (check script header)
  2. Python version (python --version)
  3. Operating System
  4. Error message (exact text)
  5. Steps to reproduce
  6. What you've tried

Self-Help Resources

# Generate diagnostic report
python -c "
# Add the generate_diagnostic_report() function above
# Then call it
generate_diagnostic_report()
"

# Test individual components
python -c "import requests; print('requests:', requests.__version__)"
python -c "import sys; print('Python:', sys.version)"

🎯 Quick Reference Cheat Sheet

Emergency Commands

Ctrl+X     - Immediate quit (anywhere)
Ctrl+C     - Interrupt current operation
^X         - Type to quit (alternative)

Common Fixes

Problem: No search results
Fix: search brave test  # Use Brave instead

Problem: CAPTCHA
Fix: tor start  # Enable Tor

Problem: No colors/icons  
Fix: settings → option 3 → y  # Switch to emoji

Problem: App won't start
Fix: pip install requests

Problem: Tor won't start
Fix: Check path in TorManager, install Tor Browser

Useful Diagnostic Commands

# In NaviDuck:
settings    # Check configuration
engines     # Verify search engines enabled
history     # Check if saving history
tor status  # Check Tor status

# In terminal:
python --version
pip list | grep requests
curl https://duckduckgo.com  # Test internet

Last updated: 12/22/2025
Troubleshooting Guide version: 2.1

Remember: Most problems can be solved by:

  1. Reading error messages carefully
  2. Checking basic requirements (Python 3.6+, requests library)
  3. Trying alternative search engines (Brave works best)
  4. Using Tor for blocked content
  5. Checking the GitHub Issues for similar problems

Happy troubleshooting! 🔧🦆

Clone this wiki locally