Metadata-Version: 2.1
Name: whyslow-cli
Version: 0.1.2
Summary: Diagnose WHY your internet is slow, unstable, or unavailable — not just how fast it is.
Author: WhyIsMyInternetSlow Contributors
License: MIT
Project-URL: Homepage, https://github.com/why-is-my-internet-slow/why-slow
Project-URL: Repository, https://github.com/why-is-my-internet-slow/why-slow
Project-URL: Issues, https://github.com/why-is-my-internet-slow/why-slow/issues
Keywords: network,diagnostics,internet,dns,latency,cli
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: System :: Networking
Classifier: Topic :: Utilities
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: typer[all]>=0.9
Requires-Dist: rich>=13
Requires-Dist: pydantic>=2
Requires-Dist: psutil>=5
Requires-Dist: dnspython>=2.4
Requires-Dist: httpx>=0.25
Requires-Dist: aiosqlite>=0.19
Requires-Dist: speedtest-cli>=2.1.3
Requires-Dist: pystray>=0.19.5
Requires-Dist: pillow>=10.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: pytest-mock>=3; extra == "dev"

# WhyIsMyInternetSlow (why-slow)

A production-quality Python CLI application and **Automated Network Diagnostics, Repair & AI Intelligence Suite** that diagnoses **why** your internet connection is slow, unstable, or completely unavailable, providing automated repairs and explaining root causes in plain language.

Unlike standard speed test tools that only report bandwidth, `why-slow` performs a comprehensive layered health inspection from your local device outward to localize the exact point of performance degradation.

---

## Why not just use a speed test?

Traditional internet speed tests measure raw download and upload bandwidth under ideal test conditions. However, bandwidth is only one component of internet performance:
1. **DNS Latency**: If your DNS resolution takes 500ms, every new page load will feel extremely sluggish, even with a 1Gbps fiber connection.
2. **Local Network Latency**: Slow Wi-Fi links or congested routers introduce latency and jitter, disrupting video calls and gaming before traffic ever reaches your ISP.
3. **Packet Loss**: Intermittent packet loss causes protocol retransmissions, leading to stuttering streams and periodic stalling.
4. **Destination Outages**: Sometimes, the internet is fine, but one specific server is slow or experiencing suboptimal routing.

`why-slow` pinpoints these exact issues so you don't waste time troubleshooting the wrong link.

---

## Features

- **Layered Diagnostics**: Inspects connectivity sequentially:
  `Device` ➜ `Wi-Fi/Ethernet` ➜ `Router/Gateway` ➜ `ISP/Internet` ➜ `DNS` ➜ `Website`
- **Visual Traceroute**: Hop-by-hop latency visualization with automatic bottleneck detection.
- **Local Network Scanner**: Discovers active devices, IP/MAC addresses, and manufacturers on your LAN.
- **Bufferbloat & Bandwidth**: Tests download/upload speeds (via Cloudflare/Speedtest) and measures latency under load.
- **Graceful Degradation**: Works locally without crashing when there is no internet connection.
- **Concurrently Executed Checks**: Uses `asyncio` to test DNS, external latency, packet loss, and HTTP baselines simultaneously for speed.
- **Interactive Terminal Menu**: Run `why-slow` in any terminal to launch a rich interactive selector menu — no need to memorize flags or subcommands.
- **Rule-Based Reasoning**: Decoupled engine evaluates heuristics to rank primary and secondary issues without relying on cloud backends or LLMs.
- **AI-Powered Deep Analysis (Optional)**: Opt-in `--ai` layer for deep contextual analysis, root-cause reasoning, symptom interaction analysis, and ISP call scripts. Supports OpenAI, Gemini, Claude, Mistral, and local Ollama with zero external SDK dependencies.
- **Polished Rich UI**: Professional ASCII art banner, colored health bar, network route diagram, AI analysis panel, and structured findings.
- **HTML & JSON Reports**: Outputs styled HTML reports (`--html`) or raw JSON (`--json`) for archiving and integrations.
- **SQLite Monitoring & Tray App**: Continuously logs network health samples to persistent local storage over time, accessible via CLI or a system tray companion app.

---

## Platform Support

Platform-specific network commands (gateway discovery, Wi-Fi stats, pings, traceroutes) are supported across:
- **macOS** (via `system_profiler SPAirPortDataType` / `airport`, `/sbin/ping`, `netstat`)
- **Linux** (via `nmcli`, `iwconfig`, `ip route`, `/proc/net/wireless`)
- **Windows** (via `netsh wlan`, `ipconfig`, `tracert`)

Unsupported platforms or metrics gracefully fall back to structured "unsupported" results rather than crashing.

---

## Installation

### Via PyPI (Recommended)
```bash
pip install whyslow-cli
```

### From Source
```bash
git clone https://github.com/why-is-my-internet-slow/why-slow.git
cd why-slow
pip install -e ".[dev]"
```

---

## Usage

### 1. Interactive Menu & Full Diagnostics
Simply type `why-slow` in your terminal to open an interactive selector menu:
```bash
why-slow
# or explicitly:
why-slow menu
why-slow -i
```

Or run non-interactively directly:
```bash
why-slow diagnose
```

#### Example Output:
#### Example Output:
```
╭───────────────────────── ◆ why-slow ◆ ─────────────────────────╮
│                                                                │
│   __        ___          ____  _                               │
│   \ \      / / |_ _   _ / ___|| | _____      __                │
│    \ \ /\ / /| __| | | |\___ \| |/ _ \ \ /\ / /                │
│     \ V  V / | |_| |_| | ___) | | (_) \ V  V /                 │
│      \_/\_/   \__|\__, ||____/|_|\___/ \_/\_/                  │
│                   |___/                                        │
│                                                                │
│    WhyIsMyInternetSlow  v0.1.0  —  Network Diagnostic Toolkit  │
│    github.com/user/why-slow  |  MIT License                    │
│                                                                │
│    ▸ Comprehensive Diagnostics                                 │
│                                                                │
╰──────── diagnostics • traceroute • lan-scan • monitor ─────────╯

Network Health
████████████████░░░░  80/100

Device              ✓ Connected (Wi-Fi: en0)
Router/Gateway      ✓ Reachable (2.3 ms)
DNS Resolution      ⚠ 340 ms
Packet Loss         ✓ 0.0% loss
Latency/Jitter      ✓ 14.2 ms
Wi-Fi Interface     ✓ SSID: MyHomeWifi (-45 dBm)
Web (HTTP/HTTPS)    ✓ 120 ms
Bandwidth (Speed)   ✓ ↓ 120.5 Mbps | ↑ 25.0 Mbps

Device → Wi-Fi → Router → Internet → DNS
   ✓        ✓       ✓         ✓       ⚠

PRIMARY ISSUE
Slow DNS resolution detected
Your internet connection has good bandwidth and latency, but domain-name lookups are taking unusually long. This can make websites feel slow when they first begin loading.

Evidence:
  • Average DNS latency: 340 ms
  • Average internet latency: 14 ms

Suggested actions:
  1. Compare DNS performance with alternative resolvers (e.g., Cloudflare 1.1.1.1 or Google 8.8.8.8).
  2. Consider switching to a faster DNS provider.
  3. Flush your DNS cache.
  4. Restart the router if the problem persists.
```

### 2. Run quick diagnostics
Runs only local and lightweight external checks quickly (skips HTTP, routing, and bandwidth diagnostics).
```bash
why-slow quick
```

### 3. Test a specific destination
Analyze path quality and HTTP response timings to a requested host, determining if slowness is local or target-specific.
```bash
why-slow test github.com
```

### 4. Visual Traceroute
Analyze the route to a specific domain or IP address, featuring proportional latency bars and automatic bottleneck jump detection.
```bash
why-slow traceroute 8.8.8.8
```

### 5. Local Network Scan (Dual Engine)
Scan your local subnet to find active devices, hostnames, MAC addresses, vendors, and open ports/services.
```bash
# Quick IP/MAC/Vendor discovery
why-slow lan-scan

# Native fast socket port scan for active services (HTTP, SSH, SMB, Plex, etc.)
why-slow lan-scan --ports

# Deep Nmap service version & OS fingerprinting audit
why-slow lan-scan --nmap
```

### 6. DNS Benchmark & Optimization
Benchmark lookup latency and success rates across 8+ public DNS providers (Cloudflare, Google, Quad9, OpenDNS, AdGuard) and compare against your system DNS.
```bash
why-slow dns-benchmark
```

### 7. Major Service Outage Checker
Check HTTP response health and outages across major cloud platforms, dev tools, social media, work, and gaming services (AWS, GitHub, Zoom, Steam, Reddit).
```bash
why-slow service-status
# Or filter by category:
why-slow service-status --category dev
```

### 8. Network Quick-Fix & Repair
Execute safe, automated cross-platform network troubleshooting steps (flush DNS cache, renew DHCP lease) and verify latency improvements pre/post repair.
```bash
why-slow fix
why-slow fix --yes
```

### 9. Wi-Fi Channel & Congestion Analyzer
Scan nearby Wi-Fi access points, measure signal strength (RSSI), and analyze channel congestion to recommend optimal 2.4GHz & 5GHz Wi-Fi channels.
```bash
why-slow wifi-scan
```

### 10. Real-Time Live TUI Dashboard
Launch an interactive real-time updating terminal UI dashboard displaying live ping sparkline graphs, DNS latency, and event logs.
```bash
why-slow live
```

### 11. Active Bandwidth & Connection Hog Finder
Scan active system sockets and processes to identify local applications (Cloud Sync, P2P/Torrents, Media Streamers, Browsers) holding high connection density or hogging network resources. Interactively terminate hog processes directly from your terminal.
```bash
why-slow connections
why-slow connections --top 10

# Interactively prompt to kill a hog process by PID:
why-slow connections --kill
```

### 12. Monitor continuously (watch)
Stores timestamped connectivity, latency, packet loss, and DNS status logs to a local SQLite database. Bandwidth tests are excluded to avoid data usage.
```bash
why-slow watch --interval 30
```

### 13. Generate historical report
Summarizes recent latency spikes, drops, and worst performance periods from SQLite database.
```bash
why-slow report --hours 24
```

### 14. System Tray App
Launch a lightweight menubar/system tray companion app to view status at a glance.
```bash
why-slow tray
```

### 15. Export Reports (HTML / JSON)
Produce beautiful standalone HTML reports or structured JSON for third-party integrations:
```bash
why-slow diagnose --html report.html
why-slow diagnose --json
```

### 16. Embedded Local Web Dashboard
Launch a modern, glassmorphic single-page web dashboard in your default browser at `http://127.0.0.1:8080`.
Features live health score gauge, network route topology, DNS benchmark charts, subnet device scanner, network hog process manager, quick-fix actions, and historical monitoring trends.
```bash
why-slow web
# Custom host/port or skip auto-opening browser:
why-slow web --port 8888 --no-open
```

### 15. AI-Powered Deep Analysis (`--ai`)
Perform deep contextual network analysis using your preferred LLM provider:
```bash
# Configure your API key once (stored securely in ~/.config/why-slow/config.toml)
why-slow ai-config set-key openai sk-...
# or for Gemini:
why-slow ai-config set-key gemini AIza...
# or for local Ollama (no key needed):
why-slow ai-config set-provider ollama

# Run diagnostics with AI analysis
why-slow diagnose --ai

# Override provider or model on the fly
why-slow diagnose --ai --ai-provider claude --ai-model claude-sonnet-4-20250514

# Check AI configuration
why-slow ai-config show
```

---

## Architecture & System Design

For full architectural details, see the dedicated [ARCHITECTURE.md](ARCHITECTURE.md) document.

```mermaid
graph TD
    subgraph UI ["User & Interface Layer"]
        CLI["CLI Entrypoint (Typer)<br>why-slow / netdiagnose / netfix"]
        Menu["Interactive Landing Screen Menu"]
        TUI["Real-Time Live TUI Dashboard"]
        CLI --> Menu
        CLI --> TUI
    end

    subgraph Core ["Core Processing Engine"]
        Orchestrator["Diagnostic Orchestrator (asyncio)"]
        Scoring["Health Scoring Engine (0-100)"]
        DiagnosisEngine["Rule-Based Reasoning Engine"]
        AIEngine["AI Deep Diagnostics Engine<br>(OpenAI / Gemini / Claude / Ollama)"]

        CLI --> Orchestrator
        Orchestrator --> Scoring
        Orchestrator --> DiagnosisEngine
        Orchestrator --> AIEngine
    end

    subgraph Diagnostics ["Layered Diagnostic Suite"]
        ConnCheck["Connectivity & Gateway"]
        DNSBench["DNS Benchmark & Resolvers"]
        ServiceCheck["Major Service Outage Checker"]
        RepairEngine["Network Quick-Fix Repair"]
        WifiScan["Wi-Fi Channel Analyzer"]
        LANScan["Dual-Engine LAN & Port Scanner"]
        ConnHogs["Connection Hog Finder"]
        Bandwidth["Bandwidth & Speedtest"]

        Orchestrator --> ConnCheck
        Orchestrator --> DNSBench
        Orchestrator --> ServiceCheck
        Orchestrator --> RepairEngine
        Orchestrator --> WifiScan
        Orchestrator --> LANScan
        Orchestrator --> ConnHogs
        Orchestrator --> Bandwidth
    end

    subgraph Platform ["Platform Adapters"]
        Adapter["PlatformAdapter (Abstract)"]
        MacOS["macOS Adapter"]
        Linux["Linux Adapter"]
        Windows["Windows Adapter"]

        Diagnostics --> Adapter
        Adapter --> MacOS
        Adapter --> Linux
        Adapter --> Windows
    end

    subgraph Reporting ["Reporting & Persistence"]
        RichTerminal["Rich Terminal Reporter"]
        HTMLReporter["HTML Report Generator"]
        JSONReporter["JSON Serializer"]
        SQLiteDB[("SQLite Monitoring DB")]

        Scoring --> RichTerminal
        Scoring --> HTMLReporter
        Scoring --> JSONReporter
        ConnCheck --> SQLiteDB
    end
```

### Directory Structure

```
src/why_slow/
├── cli.py               # Typer CLI entry points, subcommands & interactive menu
├── ai/                  # Multi-provider LLM analysis engine
│   ├── config.py        # API key & model configuration management
│   ├── providers.py     # Unified HTTP REST client (OpenAI, Gemini, Claude, Mistral, Ollama)
│   ├── prompts.py       # Diagnostic report prompt engineering
│   └── analyzer.py      # AI analysis orchestrator & section parser
├── core/
│   ├── config.py        # Configurable thresholds and target sets
│   ├── models.py        # Structured Pydantic diagnostic results
│   ├── scoring.py       # Health score weight math (0-100)
│   └── orchestrator.py  # Concurrency/Short-circuit engine
├── diagnostics/         # Independent check modules returning models
│   ├── connectivity.py  # Device interface & gateway check
│   ├── dns.py           # Basic DNS resolution check
│   ├── dns_benchmark.py # Multi-resolver speed comparison & ranking
│   ├── service_status.py# Major online service outage checker
│   ├── repair.py        # Network quick-fix repair orchestrator
│   ├── wifi_analyzer.py # Nearby AP scan & channel congestion analysis
│   ├── lan_scan.py      # Dual-engine ARP discovery & port scanner
│   ├── connections.py   # Active socket inspection & connection hog finder
│   ├── latency.py       # Ping latency & jitter measurements
│   ├── packet_loss.py   # Loss percentage checks
│   ├── wifi.py          # Wi-Fi link signal & RSSI diagnostics
│   ├── http.py          # Web endpoint TTFB & HTTP timing checks
│   ├── bandwidth.py     # Download/Upload speed test (Cloudflare / Speedtest)
│   └── routing.py       # Visual hop-by-hop traceroute
├── platform/            # Platform-specific OS adapters
│   ├── base.py          # Abstract base class
│   ├── macos.py         # macOS native network commands & airport utility
│   ├── linux.py         # Linux nmcli, resolvectl, iwlist commands
│   └── windows.py       # Windows netsh & ipconfig commands
├── diagnosis/           # Heuristics parsing results
│   ├── engine.py        # Finding ranker
│   ├── rules.py         # Static logical rulesets
│   └── recommendations.py
├── monitoring/          # SQLite recorders
│   ├── storage.py       # Database storage backend
│   ├── monitor.py       # Continuous background polling loop
│   └── tray.py          # System tray companion app
└── reporting/           # UI formatting outputs
    ├── terminal.py      # Rich terminal layouts & drawings
    ├── live_dashboard.py# Real-time updating TUI dashboard
    ├── html_report.py   # Standalone HTML report generator
    └── json_report.py   # JSON serializations
```

---

## Privacy Model

- **No Telemetry**: No tracking, usage analytics, or error reporting is uploaded.
- **No Accounts**: Fully local execution; no sign-in or configuration credentials needed.
- **External Endpoints Used**:
  - Cloudflare/Google/Quad9 IPs (`1.1.1.1`, `8.8.8.8`, `9.9.9.9`) for raw ping.
  - Public DNS Resolvers (`1.1.1.1`, `8.8.8.8`) for resolver speed comparison.
  - Connectivity Check endpoints (`connectivitycheck.gstatic.com`, `google.com`, `cloudflare.com`, `httpbin.org`) for HTTP latency baselines.

---

## Contributing Guide

1. Fork this repository.
2. Setup environment: `pip install -e ".[dev]"`
3. Run tests before committing: `pytest`
4. Submit a Pull Request.

---

## Roadmap

- [x] Concurrently run DNS, Latency, and HTTP checks.
- [x] SQLite monitoring database and history reporter.
- [x] Platform adapters for Wi-Fi and gateways on macOS, Linux, and Windows.
- [x] Speedtest bandwidth provider integration.
- [x] Bufferbloat detection test under loaded local ping.
- [x] System tray companion app reading database reports.
- [x] Visual traceroute with bottleneck detection.
- [x] HTML report generation.
