merge(F9): docs (AGENTBRIDGE/TRAFFIC_INSPECTOR) + openapi + E2E specs + CHANGELOG (Group A)

This commit is contained in:
diegosouzapw
2026-05-28 10:26:02 -03:00
9 changed files with 2417 additions and 5 deletions

View File

@@ -1,11 +1,64 @@
# Changelog
## [Unreleased]
## [Unreleased] — Group A: AgentBridge + Traffic Inspector (planos 11+12)
### Added
- **AgentBridge** (`/dashboard/tools/agent-bridge`) — MITM proxy consolidating 9 IDE agents
(Antigravity, Kiro, GitHub Copilot, OpenAI Codex, Cursor IDE, Zed Industries, Claude Code,
Open Code, Trae stub) with server card, per-agent setup wizard, model mapping table,
bypass list, upstream CA cert support, and redirect from legacy `/dashboard/system/mitm-proxy`.
See `docs/frameworks/AGENTBRIDGE.md`.
- **Traffic Inspector** (`/dashboard/tools/traffic-inspector`) — LLM-aware HTTPS debugger with
4 capture modes (AgentBridge hook, Custom Hosts DNS, HTTP_PROXY :8080, System-wide proxy),
DevTools split UI, 7 detail tabs (Conversation, Headers, Request, Response, Timing, LLM Details,
Stats), resizable panels, session recording (.har/.jsonl export), SSE stream merger,
conversation normalizer (multi-provider), system-prompt fingerprint colorization, and annotations.
See `docs/frameworks/TRAFFIC_INSPECTOR.md`.
- **MITM handler base + 9 agent handlers** (`src/mitm/handlers/`) — `MitmHandlerBase` abstract
class with `hookBufferStart`/`hookBufferUpdate` for Traffic Inspector integration; concrete
handlers for all 9 agents.
- **MITM targets registry** (`src/mitm/targets/`) — declarative `MitmTarget` shape per agent;
emits `DATA_DIR/mitm/targets.json` for dynamic `server.cjs` resolution.
- **Traffic Inspector core** (`src/mitm/inspector/`) — `TrafficBuffer` in-memory ring,
`kindDetector`, `sseMerger` (MIT port from chouzz/llm-interceptor), `conversationNormalizer`
(MIT port), `contextKey` fingerprinting, `httpProxyServer`, `systemProxyConfig`.
- **AgentBridge passthrough + bypass** (`src/mitm/passthrough.ts`) — TCP tunnel for
non-mapped hosts; bypass list with default sensitive-host patterns + user-defined patterns.
- **Upstream CA cert** (`src/mitm/upstreamTrust.ts`) — `AGENTBRIDGE_UPSTREAM_CA_CERT` for
corporate TLS environments.
- **Secret masking** (`src/mitm/maskSecrets.ts`) — sk-/Bearer/generic token masking before
any log or Traffic Inspector broadcast.
- **DB migrations 073075** — `agent_bridge_state`, `agent_bridge_mappings`,
`agent_bridge_bypass`, `inspector_custom_hosts`, `inspector_sessions`,
`inspector_session_requests`.
- **~28 API routes** under `/api/tools/agent-bridge/` (12 routes) and
`/api/tools/traffic-inspector/` (16+ routes). All LOCAL_ONLY + SPAWN_CAPABLE.
- **i18n** PT-BR + EN for all new keys in `agentBridge.*` and `trafficInspector.*` namespaces;
all other locales fall back to EN automatically.
- **E2E smoke tests** — `tests/e2e/agent-bridge.spec.ts`,
`tests/e2e/traffic-inspector.spec.ts`, `tests/e2e/agent-bridge-traffic-cross.spec.ts`
(skip-gated on CI by `RUN_AGENT_BRIDGE_E2E` / `RUN_TRAFFIC_INSPECTOR_E2E` / `RUN_CROSS_E2E`).
- **Documentation** — `docs/frameworks/AGENTBRIDGE.md` and `docs/frameworks/TRAFFIC_INSPECTOR.md`;
`docs/architecture/REPOSITORY_MAP.md` updated; `docs/reference/openapi.yaml` updated with
~28 new routes and 20+ new schemas.
### Changed
- Sidebar Tools group: added `agent-bridge` and `traffic-inspector` items after `cloud-agents`.
- `/api/tools/agent-bridge/` and `/api/tools/traffic-inspector/` added to `LOCAL_ONLY_API_PREFIXES`
and `SPAWN_CAPABLE_PREFIXES` in `src/server/authz/routeGuard.ts`.
- `.env.example`: documented 9 new env vars (`AGENTBRIDGE_UPSTREAM_CA_CERT`,
`INSPECTOR_BUFFER_SIZE`, `INSPECTOR_HTTP_PROXY_PORT`, `INSPECTOR_HTTP_PROXY_AUTOSTART`,
`INSPECTOR_TLS_INTERCEPT`, `INSPECTOR_SYSTEM_PROXY_GUARD_MINUTES`, `INSPECTOR_MAX_BODY_KB`,
`INSPECTOR_MASK_SECRETS`, `INSPECTOR_LLM_HOSTS_EXTRA`, `INSPECTOR_INTERNAL_INGEST_TOKEN`).
---
## [3.8.6] — 2026-05-27
## [3.8.6] — 2026-05-27
### ✨ New Features
- **logs:** add clean log history action button to Logs page dashboard (#2799 — thanks @apoapostolov)

View File

@@ -101,7 +101,9 @@ src/
├── shared/ # Shared between server and client where safe (constants, types, validation, contracts, utils)
├── i18n/ # next-intl config + per-locale message JSON (30+ locales)
├── middleware/ # Next.js middleware (request enrichment, locale detection)
├── mitm/ # MITM proxy helpers (Linux cert install, antigravity stealth)
├── mitm/ # MITM proxy core: cert gen/install, handlers, targets, inspector, masks, passthrough
│ ├── handlers/ # 9 IDE-agent handler classes extending MitmHandlerBase (antigravity, kiro, copilot, codex, cursor, zed, claudeCode, openCode, trae)
│ └── inspector/ # Traffic capture layer: buffer (in-memory ring), sseMerger, conversationNormalizer, kindDetector, contextKey, httpProxyServer, systemProxyConfig
├── models/ # Model adapter glue (legacy shim)
├── scripts/ # In-tree maintenance scripts (e.g., backfillAggregation)
├── sse/ # Legacy SSE handlers/services (chat.ts, chatHelpers.ts, services/auth.ts)
@@ -120,9 +122,13 @@ src/
| `app/api/v1/` | Public OpenAI-compat API (~25 sub-routes: chat, completions, embeddings, files, batches, audio, images, videos, music, rerank, moderations, search, ws, agents, accounts, providers, etc.) |
| `app/api/v1beta/` | Gemini-style API endpoints |
| `app/api/` (non-v1) | Management/admin routes (~60 directories: providers, combos, settings, mcp, a2a, evals, memory, skills, webhooks, compliance, resilience, monitoring, tunnels, cli-tools, etc.) |
| `app/api/tools/agent-bridge/` | AgentBridge REST API — 12 routes (server control, agent state/DNS/mappings, bypass, cert, upstream-CA). LOCAL_ONLY + SPAWN_CAPABLE. See `docs/frameworks/AGENTBRIDGE.md §7`. |
| `app/api/tools/traffic-inspector/` | Traffic Inspector REST + WS API — 16+ routes (requests, sessions, hosts, capture-modes, export, ws). LOCAL_ONLY + SPAWN_CAPABLE. See `docs/frameworks/TRAFFIC_INSPECTOR.md §8`. |
| `app/a2a/` | A2A JSON-RPC 2.0 entry point (`POST /a2a`) |
| `app/.well-known/agent.json/` | A2A Agent Card (discovery) |
| `app/(dashboard)/dashboard/` | Dashboard UI pages (~30 pages: providers, combos, settings, memory, skills, webhooks, evals, audit, batch, cache, costs, health, system, etc.) |
| `app/(dashboard)/dashboard/tools/agent-bridge/` | AgentBridge dashboard page — server card, 9 agent cards, setup wizard, model mapping, bypass list. i18n PT-BR + EN. See `docs/frameworks/AGENTBRIDGE.md`. |
| `app/(dashboard)/dashboard/tools/traffic-inspector/` | Traffic Inspector dashboard page — DevTools split, 7 detail tabs, 4 capture mode toggles, session recorder, context colorization. i18n PT-BR + EN. See `docs/frameworks/TRAFFIC_INSPECTOR.md`. |
| `app/docs/` | Embedded documentation viewer (renders `docs/*.md`) |
| `app/landing/` | Marketing landing page |
| `app/login/`, `forgot-password/`, `forbidden/` | Auth-related pages |

View File

@@ -0,0 +1,406 @@
---
title: "AgentBridge"
version: 3.8.6
lastUpdated: 2026-05-28
---
# AgentBridge
AgentBridge is OmniRoute's MITM (Man-in-the-Middle) proxy that intercepts HTTPS traffic from IDE AI agents and reroutes it through OmniRoute's unified routing engine. It supports **9 IDE agents** — Antigravity, Kiro, GitHub Copilot, OpenAI Codex, Cursor, Zed, Claude Code, Open Code, and Trae (investigating) — making OmniRoute the broadest-coverage MITM proxy for AI coding assistants on the market.
**Dashboard location:** `/dashboard/tools/agent-bridge`
**Sidebar group:** Tools (after Cloud Agents)
**See also:** [`TRAFFIC_INSPECTOR.md`](./TRAFFIC_INSPECTOR.md) — monitor all intercepted traffic in real-time.
---
## §1 Overview
### What is AgentBridge?
When an IDE agent (e.g., GitHub Copilot, Cursor, Claude Code) makes an API call, it connects directly to the upstream AI provider (OpenAI, Anthropic, etc.). AgentBridge intercepts that connection transparently at the TLS level — without requiring any agent configuration change — and rewrites the request through OmniRoute.
This means you can:
- **Reroute any agent to any provider**: Copilot talking to OpenAI? Redirect it to Anthropic Claude, Gemini, or any of OmniRoute's 160+ providers.
- **Apply model mappings**: `gemini-3-flash``claude-sonnet-4.7` transparently at the handler level.
- **Observe all agent traffic**: every intercepted request is published to the [Traffic Inspector](./TRAFFIC_INSPECTOR.md).
- **Apply OmniRoute resilience**: combo routing, circuit breakers, fallbacks, and cost tracking work for IDE agent traffic too.
### Positioning vs. the market
| Feature | 9router | anti-api | llm-interceptor | **OmniRoute AgentBridge** |
|---------|:-------:|:--------:|:---------------:|:-------------------------:|
| Antigravity | ✓ | ✓ | — | ✓ |
| GitHub Copilot | ✓ | ✓ | — | ✓ |
| Kiro (AWS) | ✓ | ✓ | — | ✓ |
| OpenAI Codex | — | ✓ | — | ✓ |
| Cursor IDE | ✓ | ✓ | — | ✓ |
| Zed Industries | — | ✓ | — | ✓ |
| Claude Code | — | — | ✓ | ✓ |
| Open Code | — | — | ✓ | ✓ |
| Trae | — | — | — | 🔍 Investigating |
| Dashboard UI | ✓ | ✗ | ✗ | ✓ |
| Traffic Inspector | ✗ | ✗ | ✓ | ✓ |
| OmniRoute routing | ✗ | ✗ | ✗ | ✓ |
| Model mapping UI | ✗ | ✗ | ✗ | ✓ |
| Bypass list | ✗ | ✗ | ✓ | ✓ |
| Upstream CA cert | ✗ | ✗ | ✓ | ✓ |
---
## §2 Architecture
### 2.1 Components overview
```
IDE Agent (VS Code / Cursor / etc.)
│ HTTPS (port 443)
/etc/hosts — 127.0.0.1 api.githubcopilot.com ← DNS redirect
src/mitm/server.cjs (port 443, CJS child process)
│ resolves target by Host header SNI
│ generates per-SNI TLS cert signed by AgentBridge CA
├── Bypass list match? → TCP passthrough (no decrypt)
├── Target match? → fetch → OmniRoute router (port 20128)
│ └── handler.intercept() — TypeScript
│ ├── maskSecrets() on request body/headers
│ ├── TrafficBuffer.push() — publishes to Traffic Inspector
│ └── fetchRouter() → /v1/chat/completions
└── No match? → TCP passthrough (no decrypt)
```
### 2.2 MITM server (`src/mitm/server.cjs`)
The core MITM server runs as a Node.js CJS child process (to avoid rewriting the existing CJS codebase). It:
- Listens on port 443 (requires privilege or `authbind`/`setcap`)
- Receives CONNECT tunnels from the OS (via `/etc/hosts` DNS redirect)
- Generates per-SNI TLS certificates signed by the AgentBridge CA (`DATA_DIR/mitm/ca.crt`)
- Resolves the target agent by Host header via `targets/index.ts` registry
- Dispatches to the TypeScript handler layer via HTTP to `http://127.0.0.1:20128`
`TARGET_HOSTS` is loaded from `DATA_DIR/mitm/targets.json` (written by `targets/index.ts` at boot), allowing dynamic updates without restarting the CJS server.
### 2.3 Handler base (`src/mitm/handlers/base.ts`)
All agent handlers extend `MitmHandlerBase`:
```ts
export abstract class MitmHandlerBase {
abstract readonly agentId: AgentId;
abstract intercept(
req: IncomingMessage,
res: ServerResponse,
body: Buffer,
mappedModel: string,
): Promise<void>;
// Protected helpers: fetchRouter, pipeSSE, hookBufferStart, hookBufferUpdate
}
```
Each handler calls `hookBufferStart()` before proxying and `hookBufferUpdate()` when complete. These push `InterceptedRequest` entries into `globalTrafficBuffer` (see [Traffic Inspector](./TRAFFIC_INSPECTOR.md) §4).
### 2.4 Targets registry (`src/mitm/targets/`)
Each agent has a declarative target file:
```ts
// src/mitm/targets/copilot.ts
export const COPILOT_TARGET: MitmTarget = {
id: "copilot",
name: "GitHub Copilot",
hosts: ["api.githubcopilot.com", "copilot-proxy.githubusercontent.com"],
port: 443,
endpointPatterns: ["/chat/completions", "/v1/chat/completions"],
defaultModels: [
{ id: "gpt-4o", name: "GPT-4o", alias: "gpt-4o" },
],
handler: () => import("../handlers/copilot"),
riskNoticeKey: "providers.riskNotice.oauth",
};
```
The registry (`targets/index.ts`) exports `ALL_TARGETS` and emits `DATA_DIR/mitm/targets.json` on boot.
### 2.5 Passthrough and bypass list (`src/mitm/passthrough.ts`)
**Bypass list** (checked first, with precedence over target match):
- Default patterns: banking hosts, `.gov.`, OAuth/SSO providers (Okta, Auth0), etc.
- User patterns: stored in DB table `agent_bridge_bypass`
- Bypassed hosts receive a transparent TCP tunnel — TLS is **never decrypted**
**Passthrough default** (no target match and not in bypass):
- Also receives a TCP tunnel — connections are never broken
- Prevents the AgentBridge from disrupting general system HTTPS traffic
Routing precedence:
```
bypass list → target match → passthrough
```
### 2.6 Upstream CA cert (`src/mitm/upstreamTrust.ts`)
For corporate network environments with a custom CA:
```bash
AGENTBRIDGE_UPSTREAM_CA_CERT=/path/to/corporate-ca.pem
```
When set, configures `undici`'s global dispatcher with the extra CA cert, allowing AgentBridge to reach upstream providers through corporate TLS termination proxies.
### 2.7 Secret masking (`src/mitm/maskSecrets.ts`)
Applied to all request bodies and headers **before** they enter the Traffic Inspector buffer or any log:
- `sk-` / `ak-` / `pk-` prefixed tokens (OpenAI/Anthropic-style)
- `Authorization: Bearer <token>` headers
- Generic long tokens (≥40 chars)
---
## §3 Setup
### 3.1 Start/stop the MITM server
Use the AgentBridge Server Card at `/dashboard/tools/agent-bridge`:
| Action | Description |
|--------|-------------|
| Start Server | Spawns `src/mitm/server.cjs` on port 443 |
| Stop Server | Gracefully shuts down the child process |
| Restart Server | Stop + start (picks up target changes) |
| Trust Cert | Installs `DATA_DIR/mitm/ca.crt` into OS trust store |
| Download Cert | Downloads `ca.crt` for manual installation |
| Regenerate Cert | Creates a new CA keypair (all existing per-agent certs are invalidated) |
### 3.2 Trust the certificate
The AgentBridge CA certificate must be trusted by the OS before IDEs will accept the MITM connection.
**Linux (NSS — Chrome/Firefox):**
```bash
certutil -A -d sql:$HOME/.pki/nssdb -n "OmniRoute AgentBridge" -t CT,, -i ~/.omniroute/mitm/ca.crt
```
**macOS (Keychain):**
```bash
sudo security add-trusted-cert -d -r trustRoot \
-k /Library/Keychains/System.keychain ~/.omniroute/mitm/ca.crt
```
**Windows (certmgr):**
```powershell
certutil -addstore -f Root $env:USERPROFILE\.omniroute\mitm\ca.crt
```
Or use the "Trust Cert" button in the dashboard (runs the appropriate command for your OS, with sudo prompt if needed).
### 3.3 DNS routing
For each agent you want to intercept, its API host(s) must resolve to `127.0.0.1`. AgentBridge manages `/etc/hosts` entries automatically when you toggle DNS for an agent in the Setup Wizard.
Example `/etc/hosts` entries for GitHub Copilot:
```
127.0.0.1 api.githubcopilot.com
127.0.0.1 copilot-proxy.githubusercontent.com
```
### 3.4 Model mapping
Use the Model Mapping Table in each agent card to define source → target mappings:
| Source model (agent native) | Target model (OmniRoute) |
|-----------------------------|--------------------------|
| `gpt-4o` | `claude-sonnet-4.7` |
| `*` (wildcard) | `claude-haiku-4.7` |
Wildcard `*` maps any unrecognized model to the specified target. Persisted in `agent_bridge_mappings` table.
### 3.5 Risk notice
AgentBridge intercepts credentials (OAuth tokens, API keys) that the IDE uses to authenticate with upstream providers. These are **masked before logging** (see §2.7) but are visible to OmniRoute's MITM layer. First activation of each agent shows a dismissible risk notice modal.
---
## §4 Per-agent reference
| # | Agent | Status | Hosts intercepted | Auth type |
|---|-------|--------|-------------------|-----------|
| 1 | **Antigravity** | ✅ Supported | `daily-cloudcode-pa.googleapis.com`, `cloudcode-pa.googleapis.com` | Firebase OAuth |
| 2 | **Kiro (AWS)** | ✅ Supported | `prod.kiro.aws`, `dev.kiro.aws` | AWS SigV4 |
| 3 | **GitHub Copilot** | ✅ Supported | `api.githubcopilot.com`, `copilot-proxy.githubusercontent.com` | GitHub OAuth |
| 4 | **OpenAI Codex** | ✅ Supported | `api.openai.com` (Codex paths), `chatgpt.com` | OpenAI key |
| 5 | **Cursor IDE** | ✅ Supported | `api2.cursor.sh`, `api.cursor.sh` | Cursor OAuth |
| 6 | **Zed Industries** | ✅ Supported | `api.zed.dev`, `llm.zed.dev` | Zed OAuth |
| 7 | **Claude Code** | ✅ Supported | `api.anthropic.com` (opt-in) | Anthropic key |
| 8 | **Open Code** | ✅ Supported | `openrouter.ai`, `api.openai.com` (zen paths) | API key |
| 9 | **Trae** | 🔍 Investigating | TBD — see §8 | TBD |
### Setup wizard steps (per agent)
Each agent card has a 3-step setup wizard:
1. **Verify prerequisites** — Server running? Cert trusted? IDE installed (auto-detected)?
2. **Enable DNS** — Adds `/etc/hosts` entries (requires sudo). Shows exactly which lines will be added.
3. **Map models** — Optional model mapping table. Wildcards accepted.
### Agent detection
For agents 18, AgentBridge attempts to auto-detect IDE installation:
```ts
export async function detectAgent(agentId: AgentId): Promise<DetectionResult>
// Returns: { installed: boolean, version?: string, path?: string }
```
Detection uses OS-specific paths and binary checks (e.g., `code --list-extensions | grep github.copilot` for Copilot, `~/.config/antigravity/` for Antigravity).
---
## §5 Security
### Hard Rules applied
| Rule | Application |
|------|-------------|
| **#12** `sanitizeErrorMessage` | All handler errors are sanitized before response or buffer entry |
| **#13** Shell env-passing | `/etc/hosts` edits use `env` option — no string interpolation of paths |
| **#15 + #17** `isLocalOnlyPath()` | `/api/tools/agent-bridge/` is LOCAL_ONLY + SPAWN_CAPABLE — loopback enforced before auth |
### Bypass list for sensitive hosts
The bypass list ensures that financial institutions, OAuth/SSO providers, and other sensitive hosts are **never decrypted**. Their TLS traffic passes through as a transparent TCP tunnel — OmniRoute never sees the plaintext.
Default bypass patterns include:
- `*.bank.*`, `*.gov.*` (financial/government)
- `*.okta.com`, `*.auth0.com`, `*.microsoft.com` (SSO/identity)
- `*.apple.com`, `*.icloud.com` (Apple system services)
User-added bypass patterns are stored in `agent_bridge_bypass` table and take precedence over everything.
### Secret masking
`maskSecrets()` from `src/mitm/maskSecrets.ts` is applied:
- On every request body before `TrafficBuffer.push()`
- On every header before logging or broadcasting
Patterns: `sk-`/`ak-`/`pk-` prefix tokens, `Bearer` tokens, and generic tokens ≥40 characters.
### Upstream CA cert
When `AGENTBRIDGE_UPSTREAM_CA_CERT` is set, the file is read at startup. If the path exists but the file is unreadable, AgentBridge logs a clear error and refuses to start (prevents silent TLS failures in corporate environments).
### Known limitations
- **Port 443 requires privilege**: On Linux, AgentBridge needs `setcap 'cap_net_bind_service=+ep'` on the Node binary, or run via `authbind`. The Setup Wizard displays OS-specific instructions.
- **IDE restart required**: After DNS redirect, the IDE must be restarted for the new host resolution to take effect.
- **Hardcoded OAuth tokens**: Some agents (Kiro, Antigravity) store OAuth refresh tokens locally. These are transparent to AgentBridge — it sees the Bearer token in each request, which is masked before logging.
---
## §6 Troubleshooting
### Port 443 conflict
If another process is already listening on port 443 (web server, VPN, etc.):
```bash
lsof -i :443 # find the process
sudo fuser -k 443/tcp # force-kill (use with care)
```
Alternatively, configure a non-privileged port in AgentBridge settings and set up `iptables` / `pf` redirect rules.
### Certificate not trusted
If the IDE shows TLS errors after starting AgentBridge:
1. Verify the cert was installed: `security find-certificate -c "OmniRoute AgentBridge"` (macOS) or `certutil -L -d sql:$HOME/.pki/nssdb` (Linux/NSS)
2. Some apps maintain their own trust store (Firefox, Chrome on Linux). Run "Trust Cert" again and check the NSS/Firefox-specific cert store.
3. Restart the IDE after trusting — in-flight TLS sessions use the old trust state.
### DNS not propagated
Check that `/etc/hosts` was updated:
```bash
grep "omniroute\|127.0.0.1.*github\|127.0.0.1.*cursor" /etc/hosts
```
Flush DNS cache:
```bash
# macOS
sudo dscacheutil -flushcache && sudo killall -HUP mDNSResponder
# Linux (systemd-resolved)
sudo systemctl restart systemd-resolved
# Windows
ipconfig /flushdns
```
### IDE not detected
Auto-detection uses common installation paths. If detection fails but the IDE is installed:
- Check if the IDE binary is in a non-standard location
- The Setup Wizard still works — detection failure just means the badge won't show the install path
### Handler errors (upstream fetch fails)
If AgentBridge intercepts but all requests fail:
1. Verify at least one provider is connected at `/dashboard/providers`
2. Check OmniRoute server logs: `APP_LOG_LEVEL=debug` in `.env`
3. Verify `OMNIROUTE_BASE_URL` points to the correct router endpoint (default: `http://127.0.0.1:20128`)
---
## §7 API reference
All routes are `LOCAL_ONLY` (loopback-only, enforced before auth) and `SPAWN_CAPABLE`. See `src/server/authz/routeGuard.ts`.
Base path: `/api/tools/agent-bridge/`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/tools/agent-bridge/agents` | List all 9 agents with current state |
| GET | `/api/tools/agent-bridge/state` | Global server state (running, port, cert info) |
| POST | `/api/tools/agent-bridge/server` | Start/stop/restart server (`action: "start"\|"stop"\|"restart"\|"trust-cert"\|"regenerate-cert"`) |
| GET | `/api/tools/agent-bridge/agents/{id}/state` | State of one agent (dns_enabled, cert_trusted, etc.) |
| POST | `/api/tools/agent-bridge/agents/{id}/dns` | Enable/disable DNS for agent (`{enabled: boolean}`) |
| GET | `/api/tools/agent-bridge/agents/{id}/mappings` | Model mappings for agent |
| PUT | `/api/tools/agent-bridge/agents/{id}/mappings` | Update model mappings |
| GET | `/api/tools/agent-bridge/bypass` | List bypass patterns |
| PUT | `/api/tools/agent-bridge/bypass` | Update bypass patterns |
| POST | `/api/tools/agent-bridge/cert` | Download or regenerate CA cert |
| GET | `/api/tools/agent-bridge/upstream-ca` | Get configured upstream CA path |
| POST | `/api/tools/agent-bridge/upstream-ca` | Set upstream CA cert path |
Full OpenAPI schemas: `docs/reference/openapi.yaml` → tag `AgentBridge`.
---
## §8 Roadmap
### Trae investigation
Trae is a relatively new AI coding assistant. Before implementing a handler:
1. Identify the binary/extension in VS Code / JetBrains marketplaces or as a standalone app
2. Capture traffic with mitmproxy to discover API hosts and endpoint shapes
3. Determine authentication mechanism
4. Assess go/no-go based on TOS and API discoverability
Until investigation completes, the Trae card in the dashboard shows a "Investigating" badge with a "Report viability" link. The handler stub at `src/mitm/handlers/trae.ts` throws a structured `Not yet implemented` error.
### Backlog agents (MITM required — no custom base URL support)
The following tools do not support custom base URLs in their current versions, making MITM the only interception path. Viability assessment is pending:
- **Windsurf** (Codeium/Cognition)
- **Amp** (Sourcegraph)
- **Amazon Q / Kiro CLI** (AWS Bedrock — separate from Kiro IDE)
- **Cowork** (Anthropic desktop)
Note: GitHub Copilot CLI ≥v1.0.19 supports `COPILOT_PROVIDER_BASE_URL` — use direct config instead of MITM for that tool.

View File

@@ -0,0 +1,421 @@
---
title: "Traffic Inspector"
version: 3.8.6
lastUpdated: 2026-05-28
---
# Traffic Inspector
Traffic Inspector is OmniRoute's built-in HTTPS traffic debugger — a Charles Proxy / mitmweb / HTTP Toolkit-like tool that is **LLM-aware** and **agent-aware**. It lives at `/dashboard/tools/traffic-inspector` and receives live traffic from up to 4 simultaneous capture sources.
**Dashboard location:** `/dashboard/tools/traffic-inspector`
**Sidebar group:** Tools (after AgentBridge)
**See also:** [`AGENTBRIDGE.md`](./AGENTBRIDGE.md) — AgentBridge is capture mode 1.
---
## §1 Overview
### What makes Traffic Inspector unique
| Feature | mitmweb | Charles | Fiddler | **OmniRoute Traffic Inspector** |
|---------|:-------:|:-------:|:-------:|:-------------------------------:|
| Web-based | ✓ | ✗ | ✗ | ✓ |
| Open-source | ✓ | ✗ | partial | ✓ |
| **Agent-aware** (knows if request is from Antigravity/Copilot/etc.) | ✗ | ✗ | ✗ | ✓ |
| **LLM-aware** (parses OpenAI/Anthropic/Gemini shape, tokens, model) | ✗ | ✗ | ✗ | ✓ |
| **Model mapping visible** (gemini-3-flash → claude-sonnet-4.7) | ✗ | ✗ | ✗ | ✓ |
| **Proxy/upstream latency split** | partial | ✗ | ✗ | ✓ |
| **Integrated with OmniRoute** routing, fallback, cost | ✗ | ✗ | ✗ | ✓ |
| **System-wide proxy debug** (any app on the machine) | ✓ | ✓ | ✓ | ✓ |
| **Custom host capture** (per-host DNS redirect) | ✓ | ✓ | ✓ | ✓ |
| **HTTP_PROXY env mode** | ✓ | ✓ | ✓ | ✓ |
| **Conversation view** (multi-turn bubbles, tool_use/tool_result) | ✗ | ✗ | ✗ | ✓ |
| **SSE stream merger** (reconstruct from delta events) | ✗ | ✗ | ✗ | ✓ |
| **Session recording** (named, exportable .har/.jsonl) | ✗ | ✓ | ✓ | ✓ |
### Architecture in one paragraph
The `TrafficBuffer` (`src/mitm/inspector/buffer.ts`) is a shared in-memory ring buffer (default 1000 entries, configurable via `INSPECTOR_BUFFER_SIZE`). All capture sources write to it via `push()`. The buffer classifies each entry using `kindDetector.ts` (determines if it's an LLM request), computes a `contextKey` (SHA-256 fingerprint of the system prompt), and broadcasts to all WebSocket subscribers via `globalTrafficBuffer.subscribe()`. The dashboard connects via `GET /api/tools/traffic-inspector/ws` and receives a snapshot on connect, followed by `new`/`update`/`clear` events.
---
## §2 Capture modes
Traffic Inspector supports **4 simultaneous capture sources**. Each is independently toggleable.
### Mode 1 — AgentBridge (default, always on)
**Source:** AgentBridge handlers (`src/mitm/handlers/base.ts`)
**Mechanism:** Every `intercept()` call in `MitmHandlerBase` calls `hookBufferStart()` before forwarding and `hookBufferUpdate()` on completion. Zero extra config — works as soon as AgentBridge is running.
**Reach:** The 9 IDE agents configured in AgentBridge
**Note:** `source` field in `InterceptedRequest` = `"agent-bridge"`
### Mode 2 — Custom Hosts (DNS redirect)
**Source:** User-defined host list (`inspector_custom_hosts` table)
**Mechanism:** Adding a host via the UI adds `127.0.0.1 <host>` to `/etc/hosts` (requires sudo). The existing AgentBridge MITM server (port 443) generates a SNI cert dynamically for the new host.
**Reach:** Any application using the added host — no app config change needed
**Note:** `source` = `"custom-host"`
Example use cases:
- Monitor `api.openai.com` from Python scripts
- Debug `my-internal-llm.company.com`
- Capture traffic from mobile devices on the same network (via ARP spoofing — advanced)
### Mode 3 — HTTP_PROXY listener (port 8080)
**Source:** Applications using `HTTP_PROXY`/`HTTPS_PROXY` environment variables
**Mechanism:** Secondary listener at port 8080 (`src/mitm/inspector/httpProxyServer.ts`) that acts as a standard explicit HTTP/HTTPS proxy. Accepts `CONNECT` tunnels (HTTPS) and direct HTTP requests.
**Reach:** Any application that respects `HTTP_PROXY` env — no DNS change, no sudo
**Note:** `source` = `"http-proxy"`
```bash
# Quick capture for a single command:
HTTPS_PROXY=http://127.0.0.1:8080 curl https://api.openai.com/v1/models
# Persistent capture in a shell session:
export HTTP_PROXY=http://127.0.0.1:8080
export HTTPS_PROXY=http://127.0.0.1:8080
```
**TLS limitation:** HTTPS `CONNECT` tunnels are captured as metadata only (host, port, timing) — TLS body is not decrypted by default. Enable "Decrypt HTTPS in proxy mode" toggle (opt-in, requires AgentBridge cert to be trusted) for full body inspection.
**Port conflict:** If port 8080 is in use, AgentBridge returns a 409 with a structured error. Change the port via `INSPECTOR_HTTP_PROXY_PORT` env var.
### Mode 4 — System-wide proxy (advanced, opt-in)
**Source:** OS-level proxy settings (applies to all apps on the machine)
**Mechanism:** Uses OS APIs to redirect all HTTP/HTTPS traffic through the HTTP_PROXY listener:
- **macOS:** `networksetup -setwebproxy / -setsecurewebproxy`
- **Linux:** `gsettings set org.gnome.system.proxy` + `/etc/environment`
- **Windows:** `netsh winhttp set proxy 127.0.0.1:8080`
**Reach:** Every application on the machine that respects system proxy settings
**Note:** `source` = `"system-proxy"`
**Safety mechanisms:**
- Auto-disable timer (default 30 min, configurable via `INSPECTOR_SYSTEM_PROXY_GUARD_MINUTES`)
- Previous system proxy state is saved in DB and restored on revert
- Dashboard shows "Reverting system proxy" prompt if user navigates away while active
- UI shows `⚠ Advanced` badge + explicit confirmation checkbox
### Capture mode comparison
| Mode | Setup | Sudo? | Reach | Notes |
|------|-------|:-----:|-------|-------|
| 1. AgentBridge | Automatic | Once (cert+hosts) | 9 IDE agents | Default on |
| 2. Custom Hosts | Per-host input | Yes (hosts file) | Any app using that host | Persisted in DB |
| 3. HTTP_PROXY | `export HTTPS_PROXY=...` | No | Apps respecting env | Port 8080, no TLS decrypt by default |
| 4. System-wide | Toggle + confirm | Yes | All apps on machine | Auto-disable in 30 min |
---
## §3 UI
### 3.1 Layout
```
┌─ Traffic Inspector ─────────────────────────────────────────────────────┐
│ ┌─ Capture sources toolbar ─────────────────────────────────────────┐ │
│ │ [✓ AgentBridge] [✓ Custom hosts (3)] [○ HTTP_PROXY] [○ System]│ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ ┌─ Filter/control bar ──────────────────────────────────────────────┐ │
│ │ Profile: (●) LLM only (○) Custom (○) All │ │
│ │ [⎉ Pause] [🗑 Clear] [⬇ .har] [● REC session] ● live 482/1k │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
├══◀▶══════════════════════════════╬══════════════════════════════════════╤╡
│ REQUEST LIST (resizable) ║ DETAIL PANE ▲ │
│ ────────────────────────────── │ ║ [Conversation][Headers][Request] │ │
│ ▎ 14:32 POST 200 12k AG openai ║ [Response][Timing][LLM][Stats] │ │
│ ▎ 14:31 POST 200 8k CP openai ║ ▼ │
│ ▎ 14:31 POST 503 ⚠ KR ... ║ │
│ ▎ 14:30 GET 200 3k 🌐 custom ║ │
└══════════════════════════════════╝══════════════════════════════════════╝
```
### 3.2 Request list (left panel)
- **Virtualized** (`useVirtualList` + `ResizeObserver`): handles 1000 items without freezing
- **Auto-scroll** with toggle to pause while inspecting
- **Color-coded status**: green (2xx), yellow (3xx), red (4xx/5xx), gray (in-flight)
- **Agent emoji**: 🔵 Antigravity, 🟢 Copilot, 🟠 Kiro, 🟣 Codex, 🔷 Cursor, 🟤 Zed, 🟡 Claude Code, ⚫ Open Code, 🌐 custom host
- **Context color bar**: 1px left border colored by `contextKey` (SHA-256 of system prompt) — visually groups related conversations
- **Lazy body**: only the selected request's body is materialized in the detail tabs (avoids rendering 1000 × 1MB bodies)
### 3.3 Detail pane — 7 tabs
| Tab | Content | Notes |
|-----|---------|-------|
| **Conversation** | Multi-turn chat bubbles (system/user/assistant + tool_use/tool_result) | Normalized from any provider format; only shown for `detectedKind === "llm"` |
| **Headers** | Request + response header tables | Sensitive headers (Authorization, Cookie, api-key) masked by default; "Show secrets" toggle |
| **Request** | Raw body, JSON tree view, model field badge | Pretty-printed JSON or raw text |
| **Response** | Raw body or SSE event list; toggle "Raw ↔ Merged" | SSE merger reconstructs final message from delta events |
| **Timing** | Waterfall: proxy overhead vs upstream latency | Total, TTFB, and size |
| **LLM Details** | Provider, model, messages count, tokens in/out, cost estimate, mapped target | Only shown for LLM requests |
| **Stats** | Recharts: latency timeline, token bar chart, tool call scatter | Only shown when a recorded session is loaded |
### 3.4 Toolbar controls
| Control | Action |
|---------|--------|
| ⎉ Pause | Stops rendering new requests; "X new" badge accumulates |
| 🗑 Clear | Clears the UI list (server buffer is not affected) |
| ⬇ Export .har | Downloads current filtered list as HAR file |
| ● Record session | Starts a named recording session |
| Profile selector | LLM only / Custom hosts / All |
| Host filter | Substring match on `host` field |
| Agent filter | Dropdown: All / per-agent |
| Status filter | All / 2xx / 3xx / 4xx / 5xx / error |
| Source filter | All / agent-bridge / custom-host / http-proxy / system-proxy |
### 3.5 Resizable panels
- List and detail pane separated by a drag handle
- List width: min 280px, max 720px, persisted in `localStorage` (`inspector.listWidth`)
- Collapsible to a 48px rail (icon-only); click a row in the rail to expand
---
## §4 LLM-aware features
### 4.1 Kind detector (`src/mitm/inspector/kindDetector.ts`)
Classifies each request as `"llm"`, `"app"`, or `"unknown"` using 4 signals:
1. **Host registry** — ~18 known LLM API hostnames (OpenAI, Anthropic, Gemini, Groq, Mistral, Together, Fireworks, Cohere, Perplexity, Hugging Face, OpenRouter, xAI, Moonshot, etc.)
2. **Path patterns**`/v1/chat/completions`, `/v1/messages`, `/generateContent`, `/v1/responses`, etc.
3. **Body shape** — detects `messages[]` (OpenAI/Claude), `contents[]` (Gemini), `prompt`, `input` fields
4. **User-agent hints**`codex`, `claude`, `gemini`, `antigravity`, `kiro`, `copilot`, `cursor` in UA string
Custom hosts added via Mode 2 inherit their `kind` from the form input (defaults to `"custom"`).
### 4.2 SSE merger (`src/mitm/inspector/sseMerger.ts`)
**MIT port from [chouzz/llm-interceptor](https://github.com/chouzz/llm-interceptor)**
Reconstructs the final assistant message from raw SSE delta events:
- **Anthropic**: accumulates `content_block_delta` by index; handles `text_delta`, `input_json_delta` (tool calls), `thinking_delta`
- **OpenAI**: accumulates `choices[i].delta.content` and `tool_calls` by index
- **Gemini**: accumulates `candidates[i].content.parts`
- **Unknown**: returns raw events as-is
The Response tab shows a toggle: **"Raw events ↔ Merged"**.
### 4.3 Conversation normalizer (`src/mitm/inspector/conversationNormalizer.ts`)
**MIT port from [chouzz/llm-interceptor](https://github.com/chouzz/llm-interceptor)**
Converts OpenAI, Anthropic, and Gemini message formats to a single `NormalizedConversation` before rendering:
```ts
interface NormalizedConversation {
request: NormalizedTurn[]; // messages / contents / prompt from request body
response: NormalizedTurn[]; // assistant response (merged via sseMerger)
contextKey: string | null; // SHA-256 system-prompt fingerprint
}
```
Block types: `text`, `tool_use`, `tool_result`. The Conversation tab uses this shape regardless of provider.
### 4.4 Context key colorization (`src/mitm/inspector/contextKey.ts`)
- Computes `SHA-256` of the system prompt (first `role:system` message, or `system` field, or Gemini `systemInstruction`)
- Returns a 12-character hex prefix (`"a3f9c2..."`)
- Frontend maps the key to a deterministic HSL color for the left-border bar
- **Filtro "same context"**: clicking the `ctx #a3f` chip adds a filter to show only requests with the same fingerprint
This makes it easy to visually distinguish different "personas" or tasks running in the same agent session.
### 4.5 LLM metadata extraction
For LLM requests, the LLM Details tab extracts:
```ts
interface LlmMetadata {
provider: string | null; // "openai" | "anthropic" | "gemini" | ...
apiKind: string | null; // "chat.completions" | "messages" | "embeddings" | ...
model: string | null; // from request body or response
messages: number; // turn count
tokensIn: number | null; // usage.prompt_tokens / usage.input_tokens
tokensOut: number | null; // usage.completion_tokens / usage.output_tokens
streamed: boolean; // true if SSE response
mappedTo: string | null; // x-omniroute-mapped header
costEstimateUsd: number | null; // estimated cost based on OmniRoute pricing
}
```
---
## §5 Sessions
### 5.1 Recording a session
1. Click **"● Record session"** in the toolbar → enter a name (optional)
2. Live tail continues normally; a red pulsing indicator shows `◉ REC · <name> · 00:42 · 23 reqs`
3. Click **"⏹ Stop"** → the session snapshot is saved to `inspector_sessions` + `inspector_session_requests`
### 5.2 Viewing a recorded session
The **Sessions** dropdown in the toolbar lists saved sessions. Selecting one:
- Loads the session's snapshot (frozen state)
- A banner shows: `Viewing recorded session "<name>" — [Back to live]`
- The Stats tab becomes available with Recharts aggregates
### 5.3 Export formats
Each session can be exported as:
| Format | Use |
|--------|-----|
| **HAR** (HTTP Archive 1.2) | Compatible with Chrome DevTools, Charles, Fiddler — import for offline analysis |
| **JSONL** | One `InterceptedRequest` per line — compatible with `llm-interceptor` format |
Export via `GET /api/tools/traffic-inspector/sessions/{id}/export.har` or the ⬇ button in the Sessions dropdown.
---
## §6 Security
Traffic Inspector shows **all intercepted HTTPS traffic**, including authorization headers and request bodies. The following controls are in place:
| Control | Details |
|---------|---------|
| **LOCAL_ONLY** | All routes and the WebSocket endpoint are loopback-only (enforced in `routeGuard.ts` before auth) |
| **Secret masking** | `maskSecrets()` applied to all headers and bodies before `TrafficBuffer.push()` — enabled by default (`INSPECTOR_MASK_SECRETS=true`) |
| **Body size cap** | Bodies > `INSPECTOR_MAX_BODY_KB` (default 1024 KB) are truncated with `"(truncated for performance)"` notice |
| **Sensitive header masking** | `authorization`, `cookie`, `api-key`, `x-api-key`, `proxy-authorization``Bearer ***` in Headers tab; "Show secrets" toggle |
| **CSP** | Strict Content Security Policy on Traffic Inspector pages to prevent XSS via injected response bodies |
| **No persistence by default** | The `TrafficBuffer` is in-memory and lost on server restart. Sessions are persisted only when explicitly recorded |
### Hard Rules applied
| Rule | Application |
|------|-------------|
| **#12** `sanitizeErrorMessage` | All HTTP error responses from Traffic Inspector routes are sanitized |
| **#15 + #17** `isLocalOnlyPath()` | `/api/tools/traffic-inspector/` is LOCAL_ONLY + SPAWN_CAPABLE (system proxy commands) |
### Known limitations
- **System-wide proxy mode** affects all applications on the machine, including VPN clients and SSO. Always use with the auto-disable timer. Do not use on shared machines.
- **CONNECT tunnel HTTPS**: Mode 3 (HTTP_PROXY) captures only tunnel metadata for HTTPS destinations unless TLS interception is enabled. This is by design — transparent capture without the AgentBridge cert being trusted would break TLS verification for those apps.
- **Hardcoded strings in some components**: Some UI components (F7/F8) have a small number of hardcoded strings not yet covered by i18n keys. These are documented as a Known Limitation in the i18n gap report; they will be migrated in a follow-up pass. Affected strings are UI decorative labels that don't require translation for functional use.
---
## §7 Troubleshooting
### WebSocket disconnection
If the live tail shows "Disconnected":
1. Check the server is still running: `GET /api/tools/traffic-inspector/capture-modes`
2. Reload the page — the WebSocket reconnects and receives a fresh snapshot
3. If the server was restarted, the in-memory buffer was cleared — old entries are gone unless a session was recorded
### Port 8080 conflict
If HTTP_PROXY mode fails to start:
```bash
lsof -i :8080 # find the process
```
Change the port:
```bash
# .env
INSPECTOR_HTTP_PROXY_PORT=8888
```
### System proxy not reverted
If OmniRoute crashes while system-wide proxy mode is active:
**macOS:**
```bash
networksetup -setwebproxystate Wi-Fi off
networksetup -setsecurewebproxystate Wi-Fi off
```
**Linux (GNOME):**
```bash
gsettings set org.gnome.system.proxy mode 'none'
```
**Windows:**
```cmd
netsh winhttp reset proxy
```
The dashboard will also offer "Revert system proxy" on next load if it detects the DB state indicates proxy was active.
### Buffer full
When the buffer reaches `INSPECTOR_BUFFER_SIZE` (default 1000), new entries rotate out the oldest. If important requests are being lost:
- Increase `INSPECTOR_BUFFER_SIZE` (e.g., 5000) — trades memory for retention
- Record a session to persist the relevant window to DB
---
## §8 API reference
All routes are `LOCAL_ONLY` (loopback-only) and `SPAWN_CAPABLE` (system proxy commands). See `src/server/authz/routeGuard.ts`.
Base path: `/api/tools/traffic-inspector/`
### Request management
| Method | Path | Description |
|--------|------|-------------|
| GET | `/requests` | List requests (filterable: `?profile=llm&host=&agent=&status=&source=&sessionId=`) |
| GET | `/requests/{id}` | Single request details |
| DELETE | `/requests` | Clear the in-memory buffer |
| POST | `/requests/{id}/replay` | Re-execute the same request through OmniRoute router |
| PUT | `/requests/{id}/annotation` | Save or update a note on a request |
### WebSocket
| Method | Path | Description |
|--------|------|-------------|
| GET | `/ws` | Live WebSocket stream. Sends `snapshot` on connect, then `new`/`update`/`clear` events |
### Export
| Method | Path | Description |
|--------|------|-------------|
| GET | `/export.har` | Export current filtered list as HAR 1.2 |
### Custom hosts
| Method | Path | Description |
|--------|------|-------------|
| GET | `/hosts` | List custom hosts |
| POST | `/hosts` | Add host (auto-edits `/etc/hosts`) |
| DELETE | `/hosts/{host}` | Remove host |
| PATCH | `/hosts/{host}` | Toggle `enabled` |
### Capture modes
| Method | Path | Description |
|--------|------|-------------|
| GET | `/capture-modes` | State of all 4 capture modes |
| POST | `/capture-modes/http-proxy` | Start/stop HTTP_PROXY listener (`{action: "start"\|"stop"}`) |
| POST | `/capture-modes/system-proxy` | Apply/revert system-wide proxy (`{action: "apply"\|"revert"}`) |
| POST | `/capture-modes/tls-intercept` | Toggle HTTPS body decryption in proxy mode |
### Sessions
| Method | Path | Description |
|--------|------|-------------|
| POST | `/sessions` | Start recording (`{name?: string}`) |
| PATCH | `/sessions/{id}` | Stop or rename (`{action: "stop"\|"rename", name?: string}`) |
| GET | `/sessions` | List all saved sessions |
| GET | `/sessions/{id}` | Session snapshot (all requests) |
| DELETE | `/sessions/{id}` | Delete session |
| GET | `/sessions/{id}/export.har` | Export session as HAR 1.2 |
### Internal ingest (D4 fallback)
| Method | Path | Description |
|--------|------|-------------|
| POST | `/internal/ingest` | Accepts intercepted request from `server.cjs` passthrough path; requires `INSPECTOR_INTERNAL_INGEST_TOKEN` header |
Full OpenAPI schemas: `docs/reference/openapi.yaml` → tag `Traffic Inspector`.

File diff suppressed because it is too large Load Diff

View File

@@ -25,7 +25,7 @@ export interface OpenApiEndpoint {
hasRequestBody: boolean;
}
export const OPENAPI_VERSION = "3.8.0";
export const OPENAPI_VERSION = "3.8.6";
export const OPENAPI_TITLE = "OmniRoute API";
export const OPENAPI_ENDPOINTS: OpenApiEndpoint[] = [
@@ -173,8 +173,7 @@ export const OPENAPI_ENDPOINTS: OpenApiEndpoint[] = [
path: "/api/v1/providers/{provider}/models",
method: "GET",
summary: "List models for a specific provider",
description:
"Returns only models for the selected provider with provider prefix removed from each model id.",
description: "Returns only models for the selected provider with provider prefix removed from each model id.",
tag: "Models",
tags: ["Models"],
requiresAuth: true,

View File

@@ -0,0 +1,155 @@
/**
* E2E — Cross-page smoke: AgentBridge → Traffic Inspector
*
* Verifies that the integration between AgentBridge and Traffic Inspector
* works end-to-end:
* 1. AgentBridge page is accessible
* 2. "View in Traffic Inspector" link/button navigates to the Inspector
* 3. Traffic Inspector receives/shows source=agent-bridge entries when
* an AgentBridge capture is active
*
* CI behaviour: marked `.skip` unless `RUN_CROSS_E2E=1` is set.
* These tests are best-effort: they verify page-level integration, not
* live MITM traffic (which requires real IDE agent activity).
*
* To run locally:
* RUN_CROSS_E2E=1 npx playwright test tests/e2e/agent-bridge-traffic-cross.spec.ts
*/
import { test, expect, type Page } from "@playwright/test";
const SKIP = !process.env["RUN_CROSS_E2E"];
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
async function isAuthenticated(page: Page): Promise<boolean> {
return !page.url().includes("/login");
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
test.describe("AgentBridge ↔ Traffic Inspector cross-page integration", () => {
test.skip(SKIP, "Set RUN_CROSS_E2E=1 to run cross-page E2E tests");
test("sidebar shows both agent-bridge and traffic-inspector entries", async ({ page }) => {
await page.goto("/dashboard");
await page.waitForLoadState("networkidle");
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
// Both Tools items should be in the sidebar
const agentBridgeLink = page.locator(
"a[href*='agent-bridge'], [data-testid='sidebar-agent-bridge']"
).first();
const inspectorLink = page.locator(
"a[href*='traffic-inspector'], [data-testid='sidebar-traffic-inspector']"
).first();
await expect(agentBridgeLink).toBeVisible({ timeout: 5000 });
await expect(inspectorLink).toBeVisible({ timeout: 5000 });
});
test("View in Traffic Inspector link from AgentBridge navigates correctly", async ({ page }) => {
await page.goto("/dashboard/tools/agent-bridge");
await page.waitForLoadState("networkidle");
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
// Look for a "View traffic" / "Traffic Inspector" link on the AgentBridge page
const viewTrafficLink = page.locator(
"a[href*='traffic-inspector'], a:has-text('Traffic Inspector'), [data-testid='view-traffic-link']"
).first();
const isVisible = await viewTrafficLink.isVisible({ timeout: 5000 }).catch(() => false);
if (!isVisible) {
// Quick links section may not render without providers configured
test.skip();
return;
}
await viewTrafficLink.click();
await page.waitForLoadState("networkidle");
expect(page.url()).toContain("traffic-inspector");
});
test("Traffic Inspector source filter includes agent-bridge option", async ({ page }) => {
await page.goto("/dashboard/tools/traffic-inspector");
await page.waitForLoadState("networkidle");
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
// Source filter dropdown should list agent-bridge as an option
const sourceFilter = page.locator(
"[data-testid='source-filter'], select[name='source'], [aria-label*='source']"
).first();
const isVisible = await sourceFilter.isVisible({ timeout: 5000 }).catch(() => false);
if (!isVisible) {
test.skip();
return;
}
// Open the dropdown
await sourceFilter.click();
const agentBridgeOption = page.locator(
"option[value='agent-bridge'], [data-value='agent-bridge'], li:has-text('Agent Bridge'), li:has-text('agent-bridge')"
).first();
await expect(agentBridgeOption).toBeVisible({ timeout: 3000 });
});
test("AgentBridge server control buttons exist and are interactable", async ({ page }) => {
await page.goto("/dashboard/tools/agent-bridge");
await page.waitForLoadState("networkidle");
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
// Start / Stop / Restart buttons should be present in server card
const startBtn = page.locator(
"button:has-text('Start'), button:has-text('Start Server'), [data-testid='start-server-btn']"
).first();
const isVisible = await startBtn.isVisible({ timeout: 5000 }).catch(() => false);
if (!isVisible) {
test.skip();
return;
}
// Verify button is not disabled in an error state
const disabled = await startBtn.getAttribute("disabled");
// We just check it exists and is rendered — not clicking (would spawn the MITM server)
await expect(startBtn).toBeVisible();
expect(disabled === null || disabled === "false").toBe(true);
});
test("navigating from Inspector back to AgentBridge preserves state", async ({ page }) => {
// Navigate to Inspector first
await page.goto("/dashboard/tools/traffic-inspector");
await page.waitForLoadState("networkidle");
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
// Then navigate to AgentBridge
await page.goto("/dashboard/tools/agent-bridge");
await page.waitForLoadState("networkidle");
// Page should render without errors
const errorBoundary = page.locator("[data-testid='error-boundary'], text=Something went wrong");
await expect(errorBoundary).not.toBeVisible();
await expect(page.locator("body")).toBeVisible();
});
test("Traffic Inspector shows AgentBridge mode as always-on in capture sources", async ({ page }) => {
await page.goto("/dashboard/tools/traffic-inspector");
await page.waitForLoadState("networkidle");
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
// AgentBridge capture mode should be shown as active/always-on
const agentBridgeToggle = page.locator(
"[data-testid='capture-agent-bridge'], [aria-label*='AgentBridge'], text=AgentBridge"
).first();
await expect(agentBridgeToggle).toBeVisible({ timeout: 5000 });
});
});

View File

@@ -0,0 +1,160 @@
/**
* E2E — AgentBridge page smoke tests
*
* These tests require the OmniRoute server to be running at http://localhost:20128
* (or the URL in PLAYWRIGHT_BASE_URL / baseURL in playwright.config.ts).
*
* CI behaviour: tests are marked `.skip` unless the env var
* `RUN_AGENT_BRIDGE_E2E=1` is set, since they require a full server process
* AND port 443 privileges (or mock). In CI the unit/integration suites provide
* functional coverage; the E2E layer verifies UI navigation and wiring.
*
* To run locally:
* RUN_AGENT_BRIDGE_E2E=1 npx playwright test tests/e2e/agent-bridge.spec.ts
*/
import { test, expect, type Page } from "@playwright/test";
const SKIP = !process.env["RUN_AGENT_BRIDGE_E2E"];
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
async function navigateToAgentBridge(page: Page): Promise<void> {
await page.goto("/dashboard/tools/agent-bridge");
// Wait for the page to settle (auth redirect or dashboard render)
await page.waitForLoadState("networkidle");
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
test.describe("AgentBridge page", () => {
test.skip(SKIP, "Set RUN_AGENT_BRIDGE_E2E=1 to run AgentBridge E2E tests");
test("page renders and shows heading", async ({ page }) => {
await navigateToAgentBridge(page);
// Should render AgentBridge heading (login may redirect first — tolerate both)
const url = page.url();
if (url.includes("/login")) {
// Server is auth-protected; the page route itself exists
await expect(page.locator("body")).toBeVisible();
return;
}
await expect(page.locator("h1, [data-testid='agent-bridge-heading']").first()).toBeVisible();
});
test("page renders 9 agent cards (or empty-providers state)", async ({ page }) => {
await navigateToAgentBridge(page);
const url = page.url();
if (url.includes("/login")) {
test.skip();
return;
}
// Either: 9 agent cards are visible
// OR: empty-providers state is shown (no providers configured yet)
const agentCards = page.locator("[data-testid='agent-card']");
const emptyState = page.locator("[data-testid='empty-providers-state'], [data-testid='agent-bridge-empty']");
const cardCount = await agentCards.count();
const emptyVisible = await emptyState.isVisible().catch(() => false);
expect(cardCount === 9 || emptyVisible).toBe(true);
});
test("each agent card shows agent name", async ({ page }) => {
await navigateToAgentBridge(page);
const url = page.url();
if (url.includes("/login")) {
test.skip();
return;
}
const agentCards = page.locator("[data-testid='agent-card']");
const count = await agentCards.count();
if (count === 0) {
// Empty providers state — skip the rest
test.skip();
return;
}
expect(count).toBe(9);
// Spot-check: Antigravity and GitHub Copilot cards exist
await expect(page.locator("text=Antigravity").first()).toBeVisible();
await expect(page.locator("text=Copilot, text=GitHub Copilot").first()).toBeVisible().catch(async () => {
// Accept either name variant
await expect(page.locator("text=Copilot").first()).toBeVisible();
});
});
test("AgentBridge Server Card is visible", async ({ page }) => {
await navigateToAgentBridge(page);
const url = page.url();
if (url.includes("/login")) {
test.skip();
return;
}
const serverCard = page.locator(
"[data-testid='agent-bridge-server-card'], [data-testid='server-card']"
);
await expect(serverCard.first()).toBeVisible();
});
test("Setup wizard opens when Setup button is clicked", async ({ page }) => {
await navigateToAgentBridge(page);
const url = page.url();
if (url.includes("/login")) {
test.skip();
return;
}
const agentCards = page.locator("[data-testid='agent-card']");
const count = await agentCards.count();
if (count === 0) {
test.skip();
return;
}
// Click "Setup wizard" on the first card that has one visible
const setupButton = page.locator("[data-testid='setup-wizard-btn'], button:has-text('Setup wizard')").first();
const isVisible = await setupButton.isVisible().catch(() => false);
if (!isVisible) {
// All agents already set up — skip wizard open test
test.skip();
return;
}
await setupButton.click();
// Wizard modal should appear
const wizard = page.locator("[data-testid='setup-wizard'], [role='dialog']").first();
await expect(wizard).toBeVisible({ timeout: 5000 });
});
test("DNS toggle interaction does not crash the page", async ({ page }) => {
await navigateToAgentBridge(page);
const url = page.url();
if (url.includes("/login")) {
test.skip();
return;
}
const dnsToggle = page.locator("[data-testid='dns-toggle']").first();
const isVisible = await dnsToggle.isVisible().catch(() => false);
if (!isVisible) {
test.skip();
return;
}
// Click the toggle — may show a sudo prompt modal or update state
await dnsToggle.click();
// Page should not crash (no error boundary)
await expect(page.locator("[data-testid='error-boundary']")).not.toBeVisible();
await page.waitForTimeout(500);
await expect(page.locator("body")).toBeVisible();
});
test("redirect from /dashboard/system/mitm-proxy to agent-bridge", async ({ page }) => {
// Old mitm-proxy URL should redirect or show moved notice
await page.goto("/dashboard/system/mitm-proxy");
await page.waitForLoadState("networkidle");
const url = page.url();
// Should redirect to agent-bridge or show a moved banner
const isRedirected = url.includes("agent-bridge");
const hasBanner = await page.locator("text=moved, text=AgentBridge").first().isVisible().catch(() => false);
expect(isRedirected || hasBanner).toBe(true);
});
});

View File

@@ -0,0 +1,212 @@
/**
* E2E — Traffic Inspector page smoke tests
*
* These tests require the OmniRoute server to be running at the configured base URL.
* The WebSocket tests use a mock event source rather than a live MITM capture to
* avoid needing port 443 privileges.
*
* CI behaviour: marked `.skip` unless `RUN_TRAFFIC_INSPECTOR_E2E=1` is set.
*
* To run locally:
* RUN_TRAFFIC_INSPECTOR_E2E=1 npx playwright test tests/e2e/traffic-inspector.spec.ts
*/
import { test, expect, type Page } from "@playwright/test";
const SKIP = !process.env["RUN_TRAFFIC_INSPECTOR_E2E"];
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
async function navigateToInspector(page: Page): Promise<void> {
await page.goto("/dashboard/tools/traffic-inspector");
await page.waitForLoadState("networkidle");
}
async function isAuthenticated(page: Page): Promise<boolean> {
return !page.url().includes("/login");
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
test.describe("Traffic Inspector page", () => {
test.skip(SKIP, "Set RUN_TRAFFIC_INSPECTOR_E2E=1 to run Traffic Inspector E2E tests");
test("page renders with heading", async ({ page }) => {
await navigateToInspector(page);
if (!(await isAuthenticated(page))) {
await expect(page.locator("body")).toBeVisible();
return;
}
await expect(
page.locator("h1, [data-testid='traffic-inspector-heading']").first()
).toBeVisible();
});
test("capture sources toolbar is visible", async ({ page }) => {
await navigateToInspector(page);
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
const toolbar = page.locator(
"[data-testid='capture-sources-toolbar'], [data-testid='capture-toolbar']"
).first();
await expect(toolbar).toBeVisible({ timeout: 5000 });
});
test("filter bar is visible (profile selector + pause + clear)", async ({ page }) => {
await navigateToInspector(page);
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
// Profile selector
const profileSelector = page.locator(
"[data-testid='profile-selector'], [aria-label*='profile'], text=LLM only"
).first();
await expect(profileSelector).toBeVisible({ timeout: 5000 });
// Pause or Clear button should exist
const pauseOrClear = page.locator(
"button:has-text('Pause'), button:has-text('Clear'), [data-testid='pause-btn'], [data-testid='clear-btn']"
).first();
await expect(pauseOrClear).toBeVisible();
});
test("request list panel renders (may be empty)", async ({ page }) => {
await navigateToInspector(page);
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
// Left panel should be present (virtualized list container)
const requestList = page.locator(
"[data-testid='request-list'], [data-testid='streaming-list']"
).first();
await expect(requestList).toBeVisible({ timeout: 5000 });
});
test("detail pane and tabs are visible", async ({ page }) => {
await navigateToInspector(page);
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
const detailPane = page.locator(
"[data-testid='detail-pane'], [data-testid='details-panel']"
).first();
await expect(detailPane).toBeVisible({ timeout: 5000 });
// At least Headers and Request tabs should exist
const headersTab = page.locator(
"button[role='tab']:has-text('Headers'), [data-testid='tab-headers']"
).first();
await expect(headersTab).toBeVisible();
const requestTab = page.locator(
"button[role='tab']:has-text('Request'), [data-testid='tab-request']"
).first();
await expect(requestTab).toBeVisible();
});
test("clicking a request row (if any) updates the detail pane", async ({ page }) => {
await navigateToInspector(page);
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
// Wait for any rows to appear (up to 5s)
const firstRow = page.locator(
"[data-testid='request-row'], [data-testid='request-list'] > *"
).first();
const hasRows = await firstRow.isVisible({ timeout: 5000 }).catch(() => false);
if (!hasRows) {
// Empty buffer — skip row interaction test
test.skip();
return;
}
await firstRow.click();
// Detail pane should now show non-empty content
const detailPane = page.locator("[data-testid='detail-pane'], [data-testid='details-panel']").first();
await expect(detailPane).not.toBeEmpty();
});
test("Record session button starts recording", async ({ page }) => {
await navigateToInspector(page);
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
const recBtn = page.locator(
"button:has-text('Record session'), button:has-text('REC'), [data-testid='rec-btn']"
).first();
const isVisible = await recBtn.isVisible().catch(() => false);
if (!isVisible) {
test.skip();
return;
}
await recBtn.click();
// Should show recording indicator
const recIndicator = page.locator(
"[data-testid='rec-indicator'], text=REC, [data-testid='session-recorder-bar']"
).first();
await expect(recIndicator).toBeVisible({ timeout: 3000 });
// Stop recording
const stopBtn = page.locator(
"button:has-text('Stop'), [data-testid='stop-rec-btn']"
).first();
if (await stopBtn.isVisible().catch(() => false)) {
await stopBtn.click();
}
});
test("Export .har button is present", async ({ page }) => {
await navigateToInspector(page);
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
const exportBtn = page.locator(
"button:has-text('.har'), button:has-text('Export'), [data-testid='export-har-btn']"
).first();
await expect(exportBtn).toBeVisible({ timeout: 5000 });
});
test("WebSocket live indicator is shown (connected or disconnected)", async ({ page }) => {
await navigateToInspector(page);
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
// Either a green "live" dot or a "disconnected" message should be visible
const liveIndicator = page.locator(
"[data-testid='ws-status'], text=live, text=Disconnected, [data-testid='live-indicator']"
).first();
await expect(liveIndicator).toBeVisible({ timeout: 8000 });
});
test("Replay button appears when a request is selected", async ({ page }) => {
await navigateToInspector(page);
if (!(await isAuthenticated(page))) {
test.skip();
return;
}
const firstRow = page.locator(
"[data-testid='request-row']"
).first();
const hasRows = await firstRow.isVisible({ timeout: 5000 }).catch(() => false);
if (!hasRows) {
test.skip();
return;
}
await firstRow.click();
const replayBtn = page.locator(
"button:has-text('Replay'), [data-testid='replay-btn']"
).first();
await expect(replayBtn).toBeVisible({ timeout: 3000 });
});
});