High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: live agent dashboard with SSE
Mario654474cbb900
diff --git a/dashboard.go b/dashboard.gonew file mode 100644index 00000000..4b631b66--- /dev/null+++ b/dashboard.go@@ -0,0 +1,749 @@+package main++import (+ "encoding/json"+ "fmt"+ "net/http"+ "sync"+ "time"+)++// ---------------------------------------------------------------------------+// Agent Activity — tracks what each agent is doing in real time+// ---------------------------------------------------------------------------++type AgentActivity struct {+ AgentID string `json:"agentId"`+ Profile string `json:"profile,omitempty"`+ CurrentURL string `json:"currentUrl,omitempty"`+ CurrentTab string `json:"currentTab,omitempty"`+ LastAction string `json:"lastAction,omitempty"`+ LastSeen time.Time `json:"lastSeen"`+ Status string `json:"status"` // "active", "idle", "disconnected"+ ActionCount int `json:"actionCount"`+}++type AgentEvent struct {+ AgentID string `json:"agentId"`+ Profile string `json:"profile,omitempty"`+ Action string `json:"action"`+ URL string `json:"url,omitempty"`+ TabID string `json:"tabId,omitempty"`+ Detail string `json:"detail,omitempty"`+ Status int `json:"status"`+ DurationMs int64 `json:"durationMs"`+ Timestamp time.Time `json:"timestamp"`+}++type Dashboard struct {+ agents map[string]*AgentActivity+ sseConns map[chan AgentEvent]struct{}+ mu sync.RWMutex+}++func NewDashboard() *Dashboard {+ d := &Dashboard{+ agents: make(map[string]*AgentActivity),+ sseConns: make(map[chan AgentEvent]struct{}),+ }+ // Background goroutine to mark idle/disconnected agents+ go d.reaper()+ return d+}++func (d *Dashboard) reaper() {+ for {+ time.Sleep(10 * time.Second)+ d.mu.Lock()+ now := time.Now()+ for id, a := range d.agents {+ if a.Status == "disconnected" {+ continue+ }+ if now.Sub(a.LastSeen) > 5*time.Minute {+ d.agents[id].Status = "disconnected"+ } else if now.Sub(a.LastSeen) > 30*time.Second {+ d.agents[id].Status = "idle"+ }+ }+ d.mu.Unlock()+ }+}++// RecordEvent processes an agent action and broadcasts to SSE subscribers.+func (d *Dashboard) RecordEvent(evt AgentEvent) {+ d.mu.Lock()++ a, ok := d.agents[evt.AgentID]+ if !ok {+ a = &AgentActivity{AgentID: evt.AgentID}+ d.agents[evt.AgentID] = a+ }+ a.LastSeen = evt.Timestamp+ a.LastAction = evt.Action+ a.Status = "active"+ a.ActionCount+++ a.Profile = evt.Profile+ if evt.URL != "" {+ a.CurrentURL = evt.URL+ }+ if evt.TabID != "" {+ a.CurrentTab = evt.TabID+ }++ // Copy SSE channels+ chans := make([]chan AgentEvent, 0, len(d.sseConns))+ for ch := range d.sseConns {+ chans = append(chans, ch)+ }+ d.mu.Unlock()++ // Non-blocking broadcast+ for _, ch := range chans {+ select {+ case ch <- evt:+ default: // drop if slow+ }+ }+}++// GetAgents returns current state of all agents.+func (d *Dashboard) GetAgents() []AgentActivity {+ d.mu.RLock()+ defer d.mu.RUnlock()++ agents := make([]AgentActivity, 0, len(d.agents))+ for _, a := range d.agents {+ agents = append(agents, *a)+ }+ return agents+}++// ---------------------------------------------------------------------------+// HTTP Handlers+// ---------------------------------------------------------------------------++func (d *Dashboard) RegisterHandlers(mux *http.ServeMux) {+ mux.HandleFunc("GET /dashboard", d.handleDashboardUI)+ mux.HandleFunc("GET /dashboard/agents", d.handleAgents)+ mux.HandleFunc("GET /dashboard/events", d.handleSSE)+}++func (d *Dashboard) handleAgents(w http.ResponseWriter, r *http.Request) {+ jsonResp(w, 200, d.GetAgents())+}++func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {+ flusher, ok := w.(http.Flusher)+ if !ok {+ http.Error(w, "streaming not supported", http.StatusInternalServerError)+ return+ }++ w.Header().Set("Content-Type", "text/event-stream")+ w.Header().Set("Cache-Control", "no-cache")+ w.Header().Set("Connection", "keep-alive")++ ch := make(chan AgentEvent, 64)+ d.mu.Lock()+ d.sseConns[ch] = struct{}{}+ d.mu.Unlock()++ defer func() {+ d.mu.Lock()+ delete(d.sseConns, ch)+ d.mu.Unlock()+ }()++ // Send current agent state as initial event+ agents := d.GetAgents()+ data, _ := json.Marshal(agents)+ fmt.Fprintf(w, "event: init\ndata: %s\n\n", data)+ flusher.Flush()++ for {+ select {+ case evt := <-ch:+ data, _ := json.Marshal(evt)+ fmt.Fprintf(w, "event: action\ndata: %s\n\n", data)+ flusher.Flush()+ case <-r.Context().Done():+ return+ }+ }+}++func (d *Dashboard) handleDashboardUI(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "text/html")+ w.Write([]byte(dashboardHTML))+}++// ---------------------------------------------------------------------------+// Tracking Middleware — extracts agent ID from header or query+// ---------------------------------------------------------------------------++func (d *Dashboard) TrackingMiddleware(pm *ProfileManager, next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ start := time.Now()++ // Skip dashboard routes+ if r.URL.Path == "/dashboard" || r.URL.Path == "/dashboard/agents" || r.URL.Path == "/dashboard/events" {+ next.ServeHTTP(w, r)+ return+ }++ sw := &statusWriter{ResponseWriter: w, code: 200}+ next.ServeHTTP(sw, r)++ // Extract agent identity+ agentID := r.Header.Get("X-Agent-Id")+ if agentID == "" {+ agentID = r.URL.Query().Get("agentId")+ }+ if agentID == "" {+ agentID = "anonymous"+ }++ profile := r.Header.Get("X-Profile")+ if profile == "" {+ profile = r.URL.Query().Get("profile")+ }++ // Build detail string for interesting actions+ detail := ""+ switch r.URL.Path {+ case "/navigate":+ detail = r.URL.Query().Get("url")+ case "/actions":+ detail = "batch action"+ case "/snapshot":+ sel := r.URL.Query().Get("selector")+ if sel != "" {+ detail = "selector=" + sel+ }+ }++ evt := AgentEvent{+ AgentID: agentID,+ Profile: profile,+ Action: r.Method + " " + r.URL.Path,+ URL: r.URL.Query().Get("url"),+ TabID: r.URL.Query().Get("tabId"),+ Detail: detail,+ Status: sw.code,+ DurationMs: time.Since(start).Milliseconds(),+ Timestamp: start,+ }++ d.RecordEvent(evt)++ // Also record in profile tracker if profile specified+ if profile != "" {+ pm.tracker.Record(profile, ActionRecord{+ Timestamp: start,+ Method: r.Method,+ Endpoint: r.URL.Path,+ URL: r.URL.Query().Get("url"),+ TabID: r.URL.Query().Get("tabId"),+ DurationMs: time.Since(start).Milliseconds(),+ Status: sw.code,+ })+ }+ })+}++// ---------------------------------------------------------------------------+// Dashboard HTML+// ---------------------------------------------------------------------------++const dashboardHTML = `<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>🦀 Pinchtab Dashboard</title>+<style>+ * { margin: 0; padding: 0; box-sizing: border-box; }+ body {+ font-family: 'SF Mono', 'Fira Code', monospace;+ background: #0a0a0a;+ color: #e0e0e0;+ min-height: 100vh;+ }+ header {+ background: #111;+ border-bottom: 2px solid #f5c542;+ padding: 16px 24px;+ display: flex;+ align-items: center;+ gap: 16px;+ }+ header h1 { font-size: 20px; color: #f5c542; }+ header .status { font-size: 13px; color: #888; }+ header .status .dot {+ display: inline-block;+ width: 8px; height: 8px;+ border-radius: 50%;+ background: #4ade80;+ margin-right: 4px;+ animation: pulse 2s infinite;+ }+ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.4; }+ }++ .container { display: flex; height: calc(100vh - 60px); }++ /* Left panel — agents */+ .agents-panel {+ width: 340px;+ border-right: 1px solid #222;+ overflow-y: auto;+ padding: 16px;+ }+ .agents-panel h2 {+ font-size: 13px;+ text-transform: uppercase;+ letter-spacing: 1px;+ color: #888;+ margin-bottom: 12px;+ }+ .agent-card {+ background: #151515;+ border: 1px solid #222;+ border-radius: 8px;+ padding: 14px;+ margin-bottom: 10px;+ cursor: pointer;+ transition: border-color 0.2s;+ }+ .agent-card:hover, .agent-card.selected { border-color: #f5c542; }+ .agent-card .agent-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 8px;+ }+ .agent-card .agent-name { font-weight: bold; font-size: 15px; }+ .agent-card .agent-status {+ font-size: 11px;+ padding: 2px 8px;+ border-radius: 10px;+ font-weight: 600;+ }+ .agent-status.active { background: #064e3b; color: #4ade80; }+ .agent-status.idle { background: #422006; color: #fbbf24; }+ .agent-status.disconnected { background: #1c1917; color: #666; }+ .agent-card .agent-url {+ font-size: 12px;+ color: #888;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ margin-bottom: 4px;+ }+ .agent-card .agent-meta {+ font-size: 11px;+ color: #555;+ display: flex;+ gap: 12px;+ }++ /* Right panel — activity feed */+ .feed-panel {+ flex: 1;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .feed-header {+ padding: 16px 24px;+ border-bottom: 1px solid #222;+ display: flex;+ justify-content: space-between;+ align-items: center;+ }+ .feed-header h2 { font-size: 14px; color: #888; text-transform: uppercase; letter-spacing: 1px; }+ .feed-header .filter-btns { display: flex; gap: 6px; }+ .feed-header .filter-btn {+ background: #1a1a1a;+ border: 1px solid #333;+ color: #aaa;+ padding: 4px 10px;+ border-radius: 4px;+ font-size: 11px;+ cursor: pointer;+ font-family: inherit;+ }+ .feed-header .filter-btn.active { border-color: #f5c542; color: #f5c542; }++ .feed-list {+ flex: 1;+ overflow-y: auto;+ padding: 8px 24px;+ }+ .event-row {+ display: grid;+ grid-template-columns: 90px 100px 1fr 70px 60px;+ gap: 12px;+ padding: 8px 0;+ border-bottom: 1px solid #1a1a1a;+ font-size: 13px;+ align-items: center;+ animation: fadeIn 0.3s ease;+ }+ @keyframes fadeIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; } }+ .event-row .time { color: #555; font-size: 11px; }+ .event-row .agent {+ color: #f5c542;+ font-weight: 600;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .event-row .action-detail {+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .event-row .action-detail .method {+ display: inline-block;+ padding: 1px 5px;+ border-radius: 3px;+ font-size: 10px;+ font-weight: bold;+ margin-right: 4px;+ }+ .method.GET { background: #1a3a2a; color: #4ade80; }+ .method.POST { background: #1a2a3a; color: #60a5fa; }+ .method.DELETE { background: #3a1a1a; color: #f87171; }+ .event-row .duration { color: #666; text-align: right; font-size: 12px; }+ .event-row .status-code { text-align: right; font-size: 12px; }+ .status-code.ok { color: #4ade80; }+ .status-code.err { color: #f87171; }++ /* Profiles panel (bottom) */+ .profiles-bar {+ border-top: 1px solid #222;+ padding: 12px 24px;+ display: flex;+ gap: 10px;+ overflow-x: auto;+ background: #0d0d0d;+ }+ .profile-chip {+ background: #1a1a1a;+ border: 1px solid #333;+ border-radius: 6px;+ padding: 8px 14px;+ font-size: 12px;+ white-space: nowrap;+ cursor: pointer;+ transition: border-color 0.2s;+ }+ .profile-chip:hover { border-color: #f5c542; }+ .profile-chip .pname { font-weight: bold; color: #e0e0e0; }+ .profile-chip .psize { color: #555; margin-left: 8px; }+ .profile-chip .psource { color: #f5c542; font-size: 10px; margin-left: 6px; }++ .empty-state {+ text-align: center;+ color: #444;+ padding: 60px;+ font-size: 14px;+ }+ .empty-state .crab { font-size: 48px; margin-bottom: 12px; }++ /* Profile management modal */+ .modal-overlay {+ display: none;+ position: fixed;+ inset: 0;+ background: rgba(0,0,0,0.7);+ z-index: 100;+ justify-content: center;+ align-items: center;+ }+ .modal-overlay.open { display: flex; }+ .modal {+ background: #151515;+ border: 1px solid #333;+ border-radius: 12px;+ padding: 24px;+ width: 420px;+ max-width: 90vw;+ }+ .modal h3 { color: #f5c542; margin-bottom: 16px; }+ .modal input, .modal select {+ width: 100%;+ background: #0a0a0a;+ border: 1px solid #333;+ color: #e0e0e0;+ padding: 10px;+ border-radius: 6px;+ font-family: inherit;+ font-size: 13px;+ margin-bottom: 12px;+ }+ .modal .btn-row { display: flex; gap: 8px; justify-content: flex-end; }+ .modal button {+ background: #f5c542;+ color: #0a0a0a;+ border: none;+ padding: 8px 18px;+ border-radius: 6px;+ font-weight: bold;+ cursor: pointer;+ font-family: inherit;+ }+ .modal button.secondary { background: #333; color: #e0e0e0; }+</style>+</head>+<body>+<header>+ <h1>🦀 Pinchtab</h1>+ <div class="status"><span class="dot"></span>Live</div>+</header>++<div class="container">+ <div class="agents-panel">+ <h2>Agents</h2>+ <div id="agents-list">+ <div class="empty-state"><div class="crab">🦀</div>No agents connected yet.<br>Make an API call with <code>X-Agent-Id</code> header.</div>+ </div>+ </div>++ <div class="feed-panel">+ <div class="feed-header">+ <h2>Activity Feed</h2>+ <div class="filter-btns">+ <button class="filter-btn active" data-filter="all">All</button>+ <button class="filter-btn" data-filter="navigate">Navigate</button>+ <button class="filter-btn" data-filter="snapshot">Snapshot</button>+ <button class="filter-btn" data-filter="actions">Actions</button>+ </div>+ </div>+ <div id="feed-list" class="feed-list">+ <div class="empty-state"><div class="crab">🦀</div>Waiting for events...</div>+ </div>+ </div>+</div>++<div class="profiles-bar" id="profiles-bar"></div>++<!-- Profile management modal -->+<div class="modal-overlay" id="modal">+ <div class="modal">+ <h3 id="modal-title">Manage Profile</h3>+ <div id="modal-body"></div>+ </div>+</div>++<script>+const MAX_EVENTS = 500;+const events = [];+const agents = {};+let selectedAgent = null;+let currentFilter = 'all';++// SSE connection+function connect() {+ const es = new EventSource('/dashboard/events');++ es.addEventListener('init', (e) => {+ const list = JSON.parse(e.data);+ list.forEach(a => { agents[a.agentId] = a; });+ renderAgents();+ });++ es.addEventListener('action', (e) => {+ const evt = JSON.parse(e.data);+ events.unshift(evt);+ if (events.length > MAX_EVENTS) events.pop();++ // Update agent state+ if (!agents[evt.agentId]) {+ agents[evt.agentId] = { agentId: evt.agentId, actionCount: 0, status: 'active' };+ }+ const a = agents[evt.agentId];+ a.lastAction = evt.action;+ a.lastSeen = evt.timestamp;+ a.currentUrl = evt.url || a.currentUrl;+ a.currentTab = evt.tabId || a.currentTab;+ a.profile = evt.profile || a.profile;+ a.status = 'active';+ a.actionCount++;++ renderAgents();+ renderFeed();+ });++ es.onerror = () => {+ es.close();+ setTimeout(connect, 3000);+ };+}++function renderAgents() {+ const el = document.getElementById('agents-list');+ const ids = Object.keys(agents);+ if (ids.length === 0) return;++ el.innerHTML = ids.map(id => {+ const a = agents[id];+ const sel = selectedAgent === id ? 'selected' : '';+ const ago = a.lastSeen ? timeAgo(new Date(a.lastSeen)) : '—';+ return ` + "`" + `+ <div class="agent-card ${sel}" onclick="selectAgent('${id}')">+ <div class="agent-header">+ <span class="agent-name">${esc(id)}</span>+ <span class="agent-status ${a.status}">${a.status}</span>+ </div>+ <div class="agent-url">${esc(a.currentUrl || 'No URL yet')}</div>+ <div class="agent-meta">+ <span>${a.profile ? '📁 ' + esc(a.profile) : ''}</span>+ <span>📊 ${a.actionCount} actions</span>+ <span>${ago}</span>+ </div>+ </div>+ ` + "`" + `;+ }).join('');+}++function renderFeed() {+ const el = document.getElementById('feed-list');+ let filtered = events;++ if (selectedAgent) {+ filtered = filtered.filter(e => e.agentId === selectedAgent);+ }+ if (currentFilter !== 'all') {+ filtered = filtered.filter(e => e.action.toLowerCase().includes(currentFilter));+ }++ if (filtered.length === 0) {+ el.innerHTML = '<div class="empty-state"><div class="crab">🦀</div>No matching events.</div>';+ return;+ }++ el.innerHTML = filtered.slice(0, 200).map(evt => {+ const parts = evt.action.split(' ');+ const method = parts[0] || '';+ const path = parts.slice(1).join(' ');+ const statusClass = evt.status < 400 ? 'ok' : 'err';+ const detail = evt.detail || evt.url || '';+ const t = new Date(evt.timestamp);+ const time = t.toLocaleTimeString();++ return ` + "`" + `+ <div class="event-row">+ <span class="time">${time}</span>+ <span class="agent">${esc(evt.agentId)}</span>+ <span class="action-detail">+ <span class="method ${method}">${method}</span>+ ${esc(path)}${detail ? ' <span style="color:#666">— ' + esc(detail) + '</span>' : ''}+ </span>+ <span class="duration">${evt.durationMs}ms</span>+ <span class="status-code ${statusClass}">${evt.status}</span>+ </div>+ ` + "`" + `;+ }).join('');+}++function selectAgent(id) {+ selectedAgent = selectedAgent === id ? null : id;+ renderAgents();+ renderFeed();+}++// Filters+document.querySelectorAll('.filter-btn').forEach(btn => {+ btn.addEventListener('click', () => {+ document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));+ btn.classList.add('active');+ currentFilter = btn.dataset.filter;+ renderFeed();+ });+});++// Load profiles+async function loadProfiles() {+ try {+ const res = await fetch('/profiles');+ const profiles = await res.json();+ const bar = document.getElementById('profiles-bar');+ if (!profiles || profiles.length === 0) {+ bar.innerHTML = '<div style="color:#555;font-size:12px;padding:4px">No profiles managed yet. Use POST /profiles/create or /profiles/import.</div>';+ return;+ }+ bar.innerHTML = profiles.map(p => ` + "`" + `+ <div class="profile-chip" onclick="showProfileModal('${esc(p.name)}')">+ <span class="pname">${esc(p.name)}</span>+ <span class="psize">${p.sizeMB.toFixed(1)}MB</span>+ <span class="psource">${p.source}</span>+ </div>+ ` + "`" + `).join('');+ } catch (e) {}+}++function showProfileModal(name) {+ const modal = document.getElementById('modal');+ const title = document.getElementById('modal-title');+ const body = document.getElementById('modal-body');+ title.textContent = 'Profile: ' + name;+ body.innerHTML = ` + "`" + `+ <p style="color:#888;margin-bottom:16px">Manage this Chrome profile.</p>+ <div class="btn-row">+ <button class="secondary" onclick="closeModal()">Close</button>+ <button class="secondary" onclick="resetProfile('${name}')">Reset</button>+ <button onclick="viewAnalytics('${name}')">Analytics</button>+ </div>+ ` + "`" + `;+ modal.classList.add('open');+}++function closeModal() {+ document.getElementById('modal').classList.remove('open');+}++async function resetProfile(name) {+ if (!confirm('Reset profile "' + name + '"? This clears session data, cookies, and cache.')) return;+ await fetch('/profiles/' + name + '/reset', { method: 'POST' });+ closeModal();+ loadProfiles();+}++async function viewAnalytics(name) {+ const res = await fetch('/profiles/' + name + '/analytics');+ const data = await res.json();+ const body = document.getElementById('modal-body');+ body.innerHTML = ` + "`" + `+ <p style="color:#888;margin-bottom:8px">${data.totalActions} total actions</p>+ ${data.suggestions.map(s => '<p style="color:#f5c542;font-size:13px;margin-bottom:4px">💡 ' + esc(s) + '</p>').join('')}+ ${data.topEndpoints ? '<h4 style="color:#888;margin-top:12px;font-size:12px">TOP ENDPOINTS</h4>' + data.topEndpoints.map(e => '<div style="font-size:12px;color:#aaa;padding:2px 0">' + esc(e.endpoint) + ' — ' + e.count + 'x, avg ' + e.avgMs + 'ms</div>').join('') : ''}+ <div class="btn-row" style="margin-top:16px">+ <button class="secondary" onclick="closeModal()">Close</button>+ </div>+ ` + "`" + `;+}++document.getElementById('modal').addEventListener('click', (e) => {+ if (e.target.classList.contains('modal-overlay')) closeModal();+});++function esc(s) { if (!s) return ''; const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }+function timeAgo(d) {+ const s = Math.floor((Date.now() - d.getTime()) / 1000);+ if (s < 5) return 'just now';+ if (s < 60) return s + 's ago';+ if (s < 3600) return Math.floor(s/60) + 'm ago';+ return Math.floor(s/3600) + 'h ago';+}++connect();+loadProfiles();+setInterval(loadProfiles, 30000);+</script>+</body>+</html>`diff --git a/dashboard_test.go b/dashboard_test.gonew file mode 100644index 00000000..79ecdaec--- /dev/null+++ b/dashboard_test.go@@ -0,0 +1,223 @@+package main++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestDashboardRecordAndGetAgents(t *testing.T) {+ d := NewDashboard()++ d.RecordEvent(AgentEvent{+ AgentID: "mario",+ Profile: "default",+ Action: "GET /snapshot",+ URL: "https://example.com",+ TabID: "tab1",+ Status: 200,+ DurationMs: 150,+ Timestamp: time.Now(),+ })++ d.RecordEvent(AgentEvent{+ AgentID: "r40",+ Action: "POST /navigate",+ URL: "https://r40.io",+ Status: 200,+ DurationMs: 80,+ Timestamp: time.Now(),+ })++ agents := d.GetAgents()+ if len(agents) != 2 {+ t.Fatalf("expected 2 agents, got %d", len(agents))+ }++ found := map[string]bool{}+ for _, a := range agents {+ found[a.AgentID] = true+ if a.Status != "active" {+ t.Errorf("agent %s should be active, got %s", a.AgentID, a.Status)+ }+ }+ if !found["mario"] || !found["r40"] {+ t.Error("expected both mario and r40 agents")+ }+}++func TestDashboardAgentUpdates(t *testing.T) {+ d := NewDashboard()++ d.RecordEvent(AgentEvent{+ AgentID: "bot", Action: "GET /snapshot", URL: "https://page1.com",+ Timestamp: time.Now(),+ })+ d.RecordEvent(AgentEvent{+ AgentID: "bot", Action: "POST /navigate", URL: "https://page2.com",+ Timestamp: time.Now(),+ })++ agents := d.GetAgents()+ if len(agents) != 1 {+ t.Fatalf("expected 1 agent, got %d", len(agents))+ }+ if agents[0].CurrentURL != "https://page2.com" {+ t.Errorf("expected URL page2.com, got %s", agents[0].CurrentURL)+ }+ if agents[0].ActionCount != 2 {+ t.Errorf("expected 2 actions, got %d", agents[0].ActionCount)+ }+}++func TestDashboardHandlerAgents(t *testing.T) {+ d := NewDashboard()+ d.RecordEvent(AgentEvent{+ AgentID: "test-agent", Action: "GET /health",+ Status: 200, Timestamp: time.Now(),+ })++ mux := http.NewServeMux()+ d.RegisterHandlers(mux)++ req := httptest.NewRequest("GET", "/dashboard/agents", nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != 200 {+ t.Fatalf("expected 200, got %d", w.Code)+ }++ var agents []AgentActivity+ json.NewDecoder(w.Body).Decode(&agents)+ if len(agents) != 1 || agents[0].AgentID != "test-agent" {+ t.Errorf("unexpected agents: %+v", agents)+ }+}++func TestDashboardUI(t *testing.T) {+ d := NewDashboard()+ mux := http.NewServeMux()+ d.RegisterHandlers(mux)++ req := httptest.NewRequest("GET", "/dashboard", nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != 200 {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ if ct := w.Header().Get("Content-Type"); ct != "text/html" {+ t.Errorf("expected text/html, got %s", ct)+ }+ body := w.Body.String()+ if len(body) < 1000 {+ t.Error("dashboard HTML seems too short")+ }+}++func TestDashboardSSEInit(t *testing.T) {+ d := NewDashboard()+ d.RecordEvent(AgentEvent{AgentID: "sse-agent", Action: "GET /health", Timestamp: time.Now()})++ mux := http.NewServeMux()+ d.RegisterHandlers(mux)++ // Use a real test server with short-lived request+ srv := httptest.NewServer(mux)+ defer srv.Close()++ ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)+ defer cancel()++ req, _ := http.NewRequestWithContext(ctx, "GET", srv.URL+"/dashboard/events", nil)+ resp, err := http.DefaultClient.Do(req)+ if err != nil && !errors.Is(err, context.DeadlineExceeded) {+ // Context deadline is expected+ return+ }+ if resp != nil {+ defer resp.Body.Close()+ if resp.Header.Get("Content-Type") != "text/event-stream" {+ t.Errorf("expected text/event-stream, got %s", resp.Header.Get("Content-Type"))+ }+ }+}++func TestTrackingMiddleware(t *testing.T) {+ d := NewDashboard()+ pm := NewProfileManager(t.TempDir())++ inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(200)+ })++ handler := d.TrackingMiddleware(pm, inner)++ req := httptest.NewRequest("GET", "/snapshot?url=https://example.com", nil)+ req.Header.Set("X-Agent-Id", "test-bot")+ req.Header.Set("X-Profile", "my-profile")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ agents := d.GetAgents()+ if len(agents) != 1 {+ t.Fatalf("expected 1 agent, got %d", len(agents))+ }+ if agents[0].AgentID != "test-bot" {+ t.Errorf("expected agent test-bot, got %s", agents[0].AgentID)+ }++ // Check profile tracker also recorded+ logs := pm.Logs("my-profile", 10)+ if len(logs) != 1 {+ t.Errorf("expected 1 profile log, got %d", len(logs))+ }+}++func TestTrackingMiddlewareAnonymous(t *testing.T) {+ d := NewDashboard()+ pm := NewProfileManager(t.TempDir())++ inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(200)+ })++ handler := d.TrackingMiddleware(pm, inner)+ req := httptest.NewRequest("GET", "/health", nil)+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ agents := d.GetAgents()+ if len(agents) != 1 || agents[0].AgentID != "anonymous" {+ t.Errorf("expected anonymous agent, got %+v", agents)+ }+}++func TestTrackingMiddlewareSkipsDashboard(t *testing.T) {+ d := NewDashboard()+ pm := NewProfileManager(t.TempDir())++ called := false+ inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ called = true+ w.WriteHeader(200)+ })++ handler := d.TrackingMiddleware(pm, inner)+ req := httptest.NewRequest("GET", "/dashboard", nil)+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if !called {+ t.Error("inner handler should be called")+ }+ agents := d.GetAgents()+ if len(agents) != 0 {+ t.Error("dashboard routes should not be tracked")+ }+}