Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

chore: remove legacy agent tracking from dashboard (#102)

luigiagenta1236761072a
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index ba325dae..d6978598 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -13,7 +13,6 @@ import (
"syscall"
"time"
- "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/dashboard"
"github.com/pinchtab/pinchtab/internal/handlers"
@@ -111,24 +110,7 @@ func runDashboard(cfg *config.RuntimeConfig) {
})
}
- profileObserver := func(evt dashboard.AgentEvent) {
- if evt.Profile != "" {
- profMgr.RecordAction(evt.Profile, bridge.ActionRecord{
- Timestamp: evt.Timestamp,
- Method: strings.SplitN(evt.Action, " ", 2)[0],
- Endpoint: strings.SplitN(evt.Action, " ", 2)[1],
- URL: evt.URL,
- TabID: evt.TabID,
- DurationMs: evt.DurationMs,
- Status: evt.Status,
- })
- }
- }
-
- handler := dash.TrackingMiddleware(
- []dashboard.EventObserver{profileObserver},
- handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux))),
- )
+ handler := handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux)))
srv := &http.Server{
Addr: cfg.Bind + ":" + dashPort,
diff --git a/docs/architecture/dashboard-ui.md b/docs/architecture/dashboard-ui.md
new file mode 100644
index 00000000..fd47aa42
--- /dev/null
+++ b/docs/architecture/dashboard-ui.md
@@ -0,0 +1,419 @@
+# Dashboard UI Architecture
+
+The PinchTab dashboard is a modern React SPA that provides visual control and monitoring of Chrome instances.
+
+## Overview
+
+**Technology Stack:**
+- React 19 + TypeScript
+- Tailwind CSS v4 (dark theme)
+- Zustand (state management)
+- Vite (build)
+- Vitest (testing)
+- Hash-based routing
+
+**Build Flow:**
+```
+dashboard/src (React source)
+ ↓
+bun run build
+ ↓
+dashboard/dist (optimized bundle)
+ ↓
+scripts/build-dashboard.sh (copies to Go binary)
+ ↓
+internal/dashboard/dashboard/ (embedded)
+ ↓
+//go:embed dashboard/* (compiled into binary)
+```
+
+## Visual Guide
+
+### Overall Dashboard Layout
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ PinchTab Monitoring Agents Profiles Settings ↻ ☰ │ ← NavBar (sticky)
+├─────────────────────────────────────────────────────────────────┤
+│ │
+│ MAIN CONTENT AREA │
+│ │
+│ (One of 4 Pages Below) │
+│ │
+└─────────────────────────────────────────────────────────────────┘
+```
+
+**Features:**
+- Dark theme (#0a0a0a bg, #1a1a1a surface)
+- Orange accent (#f97316) on active/hover states
+- Responsive: Mobile hamburger, desktop horizontal tabs
+- Sticky header with refresh button (⌘R)
+
+## Layout & Pages
+
+### Navigation Bar
+- Sticky header with tabs and refresh button
+- Desktop: horizontal navigation (Monitoring, Agents, Profiles, Settings)
+- Mobile: hamburger menu + responsive layout
+- Keyboard shortcuts: ⌘1-4 (navigate), ⌘R (refresh)
+
+### 1. **Monitoring Page** (`/monitoring`) - Default
+
+Real-time instance and tab monitoring with memory tracking.
+
+**Visual Layout:**
+```
+┌─ Chart Area ─────────────────────────────┐
+│ ↑ Tabs / Memory (dual Y-axis) │
+│ │ ▂▄▆█▊▋▊▉▆▅▃▁ │ ← Solid: tabs, Dashed: memory
+│ │ ▁ ▃▅▇ ▆█▁ ▂▄▆█▁▂ │
+│ ├─────────────────────────────────────→ │
+│ │ 60 min history (polled every 30s) │
+└───────────────────────────────────────────┘
+
+┌─ Instances ───────────────────────────────┐
+│ ┌─ instance-1 ┐ ┌─ instance-2 ┐ │
+│ │ :9868 │ │ :9869 │ │ ← Shows port, tab count, memory
+│ │ 5 tabs │ │ 12 tabs │ │
+│ │ 524MB │ │ 1382MB │ │
+│ └─────────────┘ └─────────────┘ │
+│ ┌─ Selected Instance Tabs ──────────────┐ │
+│ │ └─ tab_abc123 (google.com) │ │ ← Tab list for selected instance
+│ │ └─ tab_def456 (github.com) │ │
+│ └───────────────────────────────────────┘ │
+└───────────────────────────────────────────┘
+```
+
+**Components:**
+- **Dual-Axis Chart**
+ - Left Y-axis: Tab count (solid lines)
+ - Right Y-axis: Memory in MB (dashed lines)
+ - History: 60-minute window
+ - Poll interval: 30 seconds (configurable in Settings)
+
+- **Instance List**
+ - Grid of running instances
+ - Shows: port, tab count, memory (e.g., `:9868 · 5 tabs · 524MB`)
+ - Click to select and view tabs
+
+- **Tab Details**
+ - List of tabs in selected instance
+ - Shows tab title, URL, and ID
+
+**Data Flow:**
+```
+MonitoringPage
+ ↓
+ └─ Poll /instances/metrics (every 30s)
+ └─ Poll /instances/{id}/tabs (per selected instance)
+ └─ addChartDataPoint() → store → chart re-render
+```
+
+### 2. **Agents Page** (`/agents`)
+
+Real-time view of agent activity and events.
+
+**Visual Layout:**
+
+Desktop (sm:):
+```
+┌─ Sidebar ──────┬─ Activity ─────────┐
+│ All │ Filter: │
+│ ► Agent-1 │ Navigate │
+│ Agent-2 │ Snapshot │
+│ Agent-3 │ Actions │
+│ │ │
+│ [events] │ [activity stream] │
+└────────────────┴────────────────────┘
+```
+
+Mobile:
+```
+┌─ Carousel ─────────────────┐
+│ All → A1 → A2 → A3 ← → │
+└────────────────────────────┘
+┌─ Activity ─────────────────┐
+│ Filter: All / Navigate / │
+│ Snapshot / Actions │
+│ [activity stream] │
+└────────────────────────────┘
+```
+
+**Desktop Layout (detailed):**
+```
+┌─ Sidebar ──────┬─ Activity Log ──────────┐
+│ All │ Filter: All/Navigate/ │
+│ ► Agent-1 │ Snapshot/Actions │
+│ Agent-2 │ │
+│ Agent-3 │ [Events stream via SSE] │
+│ │ │
+│ [events list] │ [activity lines] │
+└────────────────┴─────────────────────────┘
+```
+
+**Mobile Layout:**
+```
+┌─ Carousel (horizontal scroll) ─┐
+│ All → Agent-1 → Agent-2 → A-3 │
+└────────────────────────────────┘
+┌─ Activity Log below ───────────┐
+│ [events] │
+└────────────────────────────────┘
+```
+
+**Data Flow:**
+```
+App.tsx
+ ↓
+ └─ subscribeToEvents() → SSE /api/events
+ └─ init: list of agents
+ └─ action: agent performed action
+ └─ system: instance lifecycle
+ ↓
+AgentsPage receives updates
+ └─ Filter events
+ └─ Render agents + activity
+```
+
+### 3. **Profiles Page** (`/profiles`)
+
+Manage Chrome profiles and launch instances.
+
+**Visual Layout:**
+```
+┌─ Profiles Grid (2 cols desktop, 1 col mobile) ─┐
+│ ┌─────────────┐ ┌─────────────┐ │
+│ │ Chrome │ │ Firefox │ │
+│ │ id: prof-1 │ │ id: prof-2 │ │
+│ │ [Launch ▼] │ │ [Launch ▼] │ │
+│ └─────────────┘ └─────────────┘ │
+│ ┌─────────────┐ │
+│ │ Edge │ [+ Create Profile] │
+│ │ id: prof-3 │ │
+│ │ [Launch ▼] │ │
+│ └─────────────┘ │
+└────────────────────────────────────────────────┘
+
+Modals:
+[Launch Dialog] [Details Dialog] [Create Dialog]
+├ Port: 9868 ├ Name: Chrome ├ Name: [input]
+├ ☐ Headless ├ Created: 2026-03-02 ├ Use When: [input]
+├ [Launch] [Cancel] └ [Close] ├ [Create] [Cancel]
+```
+
+**Modals:**
+1. **Create Profile Dialog**
+ - Name input
+ - Use When (optional description)
+ - Create button
+
+2. **Launch Instance Dialog**
+ - Profile selection (pre-filled)
+ - Port number (default 9868)
+ - Headless toggle (default true)
+ - Launch button
+
+3. **Profile Details Modal**
+ - Profile metadata
+ - Copy buttons for ID
+ - Close button
+
+**Data Flow:**
+```
+ProfilesPage
+ ↓
+ └─ Fetch /profiles (on mount if empty)
+ └─ SSE updates (new profiles)
+ ↓
+User clicks "Launch"
+ ↓
+ └─ POST /profiles/{id}/launch with { port, headless }
+ └─ Fetch /instances (updated list)
+```
+
+### 4. **Settings Page** (`/settings`)
+
+Configure dashboard behavior.
+
+**Visual Layout:**
+```
+┌─ Settings Page ────────────────────┐
+│ ┌─ Monitoring Settings ──────────┐ │
+│ │ ☐ Memory Metrics (experimental)│ │
+│ │ Poll Interval: 30s [input] │ │
+│ │ │ │
+│ │ Server Info: │ │
+│ │ Go Runtime v1.26 │ │
+│ │ Goroutines: 15 │ │
+│ │ Heap: 12.5 MB │ │
+│ │ │ │
+│ │ [Reset] [Apply ✓] │ │ ← Disabled until changes
+│ └────────────────────────────────┘ │
+└────────────────────────────────────┘
+```
+
+**Settings:**
+- **Memory Metrics** toggle (experimental)
+ - When ON: dashboard polls memory data, chart shows memory lines
+ - When OFF: skips `/instances/metrics` calls
+
+- **Poll Interval** input
+ - Default: 30 seconds
+ - Controls chart update frequency
+
+- **Server Info Display**
+ - Go version
+ - Goroutines count
+ - Heap allocation
+
+**Behavior:**
+- All settings stored in localStorage
+- Apply/Reset buttons (disabled until changes)
+- Uses `JSON.stringify` to detect changes
+
+**Data Flow:**
+```
+SettingsPage
+ ↓
+User toggles Memory Metrics
+ ↓
+hasChanges = true → Apply button enabled
+ ↓
+Click Apply
+ ↓
+setSettings(local) → localStorage + store
+ ↓
+MonitoringPage reacts → adjusts polling behavior
+```
+
+## State Management (Zustand Store)
+
+**useAppStore** manages:
+- `instances[]` - running Chrome instances
+- `profiles[]` - available profiles
+- `agents[]` - connected agents
+- `events[]` - agent activity log
+- `settings` - dashboard preferences
+- `tabsChartData[]` - time-series for chart
+- `memoryChartData[]` - memory history
+- `serverChartData[]` - Go runtime metrics
+- `currentTabs{}` - tabs per instance
+- `currentMemory{}` - memory per instance
+
+**Persistence:**
+- `settings` persisted to localStorage
+- `tabsChartData`, `memoryChartData` kept in memory only
+- Chart data limited to last 60 points (~30 min)
+
+## API Endpoints
+
+**Dashboard calls:**
+- `GET /health` - server status
+- `GET /profiles` - list profiles
+- `GET /instances` - list running instances
+- `GET /instances/metrics` - memory per instance
+- `GET /instances/{id}/tabs` - tabs in instance
+- `POST /profiles/{id}/launch` - start instance
+- `GET /api/events` - SSE event stream (real-time)
+
+**Environment:**
+- Development: proxy via Vite (`vite.config.ts`)
+- Production: same origin (served from Go at `/dashboard/`)
+
+## Styling & Theme
+
+**Design System:**
+- Dark theme: `#0a0a0a` (bg), `#1a1a1a` (surface)
+- Orange accent: `#f97316` (primary actions)
+- Text: `#e4e4e7` (primary), `#a1a1a1` (secondary)
+- Border: `#2a2a2a` (subtle)
+
+**Tailwind Configuration:**
+- Atomic design: buttons, inputs, cards are reusable
+- Responsive: `sm:` breakpoint at 640px
+- Dark mode optimized (no light theme)
+- Custom CSS for NavBar animation, chart styling
+
+**Components Hierarchy:**
+```
+App
+ ├─ NavBar (sticky header)
+ └─ Routes
+ ├─ MonitoringPage
+ │ ├─ TabsChart (Recharts)
+ │ ├─ InstanceListItem (molecule)
+ │ └─ TabItem (molecule)
+ ├─ AgentsPage
+ │ ├─ AgentItem (molecule)
+ │ └─ ActivityLine (molecule)
+ ├─ ProfilesPage
+ │ ├─ ProfileCard (molecule)
+ │ └─ Modal (atom)
+ └─ SettingsPage
+ └─ Toolbar (atom)
+```
+
+## Testing
+
+**Unit Tests (69 total):**
+- Atoms: Badge, Button, StatusDot (7 tests each)
+- Molecules: ProfileCard, TabsChart, InstanceListItem, TabItem (3-16 tests)
+- Store: useAppStore (19 tests)
+
+**Test Framework:**
+- Vitest (via `bun run test`)
+- jsdom environment
+- Render + user interaction testing
+
+**Gap:**
+- No E2E tests for dashboard ↔ Go integration
+- Future: Playwright tests for full workflows
+
+## Performance
+
+**Optimization:**
+- Vite + code splitting (assets have hash in filename)
+- Chart data limited to 60 points (prevents memory bloat)
+- useCallback for event handlers
+- Memoization for expensive computations
+- SSE for push updates (no polling for events)
+
+**Caching:**
+- Assets: `Cache-Control: max-age=31536000, immutable` (1 year)
+- HTML: `Cache-Control: no-store` (always fresh)
+- Settings: localStorage
+
+## Development Workflow
+
+**Build:**
+```bash
+cd dashboard
+bun install
+bun run build
+```
+
+**Local Dev:**
+```bash
+cd dashboard
+bun run dev # Runs on :5173, proxies /api to :9867
+```
+
+**Test:**
+```bash
+cd dashboard
+bun run test:run
+```
+
+**CI/CD:**
+- Dashboard workflow triggers on push to `dashboard/` or `.github/workflows/dashboard.yml`
+- Lint, type check, test, build all run
+- Build artifacts uploaded for release
+
+## Future Enhancements
+
+1. **E2E Tests** - Playwright tests for full workflows
+2. **Real-time Collaboration** - Multi-user dashboard
+3. **Advanced Filtering** - Tag-based instance filtering
+4. **Custom Charts** - User-defined metrics
+5. **Dark/Light Theme** - Theme toggle
+6. **Notification Center** - Persistent alerts for important events
diff --git a/docs/index.json b/docs/index.json
index 6feeec21..c00d370f 100644
--- a/docs/index.json
+++ b/docs/index.json
@@ -18,6 +18,7 @@
"architecture": [
"architecture/pinchtab-architecture.md",
"architecture/chrome-lifecycle-and-orchestration.md",
+ "architecture/dashboard-ui.md",
"architecture/building.md"
],
"guides": [
diff --git a/internal/dashboard/dashboard.go b/internal/dashboard/dashboard.go
index e00d3e6a..605b4378 100644
--- a/internal/dashboard/dashboard.go
+++ b/internal/dashboard/dashboard.go
@@ -1,7 +1,6 @@
package dashboard
import (
- "bufio"
"context"
"embed"
"encoding/json"
@@ -9,12 +8,10 @@ import (
"io/fs"
"net/http"
"os"
- "strings"
"sync"
"time"
"github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/web"
)
type DashboardConfig struct {
@@ -27,17 +24,7 @@ type DashboardConfig struct {
//go:embed dashboard/*
var dashboardFS embed.FS
-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"`
- ActionCount int `json:"actionCount"`
-}
-
+// AgentEvent is sent via SSE when an agent performs an action.
type AgentEvent struct {
AgentID string `json:"agentId"`
Profile string `json:"profile,omitempty"`
@@ -63,7 +50,6 @@ type InstanceLister interface {
type Dashboard struct {
cfg DashboardConfig
- agents map[string]*AgentActivity
sseConns map[chan AgentEvent]struct{}
sysConns map[chan SystemEvent]struct{}
cancel context.CancelFunc
@@ -89,104 +75,9 @@ func (d *Dashboard) BroadcastSystemEvent(evt SystemEvent) {
}
}
-// SetInstanceLister sets the orchestrator for aggregating agents from child instances.
-// Also starts a background relay that subscribes to child instance SSE events.
+// SetInstanceLister sets the orchestrator for managing instances.
func (d *Dashboard) SetInstanceLister(il InstanceLister) {
d.instances = il
- go d.relayChildEvents()
-}
-
-// relayChildEvents periodically checks for running child instances and subscribes
-// to their SSE streams, re-broadcasting events through the dashboard.
-func (d *Dashboard) relayChildEvents() {
- tracked := make(map[string]context.CancelFunc) // port -> cancel
-
- ticker := time.NewTicker(5 * time.Second)
- defer ticker.Stop()
-
- for range ticker.C {
- if d.instances == nil {
- continue
- }
-
- activePorts := make(map[string]bool)
- for _, inst := range d.instances.List() {
- if inst.Status != "running" || inst.Port == "" {
- continue
- }
- activePorts[inst.Port] = true
- if _, ok := tracked[inst.Port]; !ok {
- ctx, cancel := context.WithCancel(context.Background())
- tracked[inst.Port] = cancel
- go d.subscribeChildSSE(ctx, inst.Port, inst.ProfileName)
- }
- }
-
- // Stop subscriptions for instances that are no longer running.
- for port, cancel := range tracked {
- if !activePorts[port] {
- cancel()
- delete(tracked, port)
- }
- }
- }
-}
-
-func (d *Dashboard) subscribeChildSSE(ctx context.Context, port, profileName string) {
- url := "http://127.0.0.1:" + port + "/dashboard/events"
- for {
- if ctx.Err() != nil {
- return
- }
- req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
- if err != nil {
- return
- }
- if d.childAuthToken != "" {
- req.Header.Set("Authorization", "Bearer "+d.childAuthToken)
- }
- client := &http.Client{Timeout: 0} // no timeout for SSE
- resp, err := client.Do(req)
- if err != nil {
- select {
- case <-ctx.Done():
- return
- case <-time.After(3 * time.Second):
- continue
- }
- }
- d.readSSEStream(ctx, resp, profileName)
- _ = resp.Body.Close()
-
- // Reconnect after disconnect.
- select {
- case <-ctx.Done():
- return
- case <-time.After(2 * time.Second):
- }
- }
-}
-
-func (d *Dashboard) readSSEStream(ctx context.Context, resp *http.Response, profileName string) {
- scanner := bufio.NewScanner(resp.Body)
- for scanner.Scan() {
- if ctx.Err() != nil {
- return
- }
- line := scanner.Text()
- if !strings.HasPrefix(line, "data: ") {
- continue
- }
- data := line[6:]
- var evt AgentEvent
- if err := json.Unmarshal([]byte(data), &evt); err != nil {
- continue
- }
- if evt.Profile == "" {
- evt.Profile = profileName
- }
- d.RecordEvent(evt)
- }
}
func NewDashboard(cfg *DashboardConfig) *Dashboard {
@@ -211,95 +102,21 @@ func NewDashboard(cfg *DashboardConfig) *Dashboard {
}
}
- ctx, cancel := context.WithCancel(context.Background())
+ _, cancel := context.WithCancel(context.Background())
d := &Dashboard{
cfg: c,
- agents: make(map[string]*AgentActivity),
sseConns: make(map[chan AgentEvent]struct{}),
sysConns: make(map[chan SystemEvent]struct{}),
cancel: cancel,
childAuthToken: os.Getenv("BRIDGE_TOKEN"),
}
- go d.reaper(ctx)
return d
}
func (d *Dashboard) Shutdown() { d.cancel() }
-func (d *Dashboard) reaper(ctx context.Context) {
- ticker := time.NewTicker(d.cfg.ReaperInterval)
- defer ticker.Stop()
- for {
- select {
- case <-ctx.Done():
- return
- case <-ticker.C:
- d.mu.Lock()
- now := time.Now()
- for id, a := range d.agents {
- if a.Status == "disconnected" {
- continue
- }
- if now.Sub(a.LastSeen) > d.cfg.DisconnectTimeout {
- d.agents[id].Status = "disconnected"
- } else if now.Sub(a.LastSeen) > d.cfg.IdleTimeout {
- d.agents[id].Status = "idle"
- }
- }
- d.mu.Unlock()
- }
- }
-}
-
-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
- }
-
- chans := make([]chan AgentEvent, 0, len(d.sseConns))
- for ch := range d.sseConns {
- chans = append(chans, ch)
- }
- d.mu.Unlock()
-
- for _, ch := range chans {
- select {
- case ch <- evt:
- default:
- }
- }
-}
-
-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
-}
-
func (d *Dashboard) RegisterHandlers(mux *http.ServeMux) {
// API endpoints
- mux.HandleFunc("GET /api/agents", d.handleAgents)
mux.HandleFunc("GET /api/events", d.handleSSE)
// Static files served at /dashboard/
@@ -315,10 +132,6 @@ func (d *Dashboard) RegisterHandlers(mux *http.ServeMux) {
mux.Handle("GET /dashboard/", d.withNoCache(http.HandlerFunc(d.handleDashboardUI)))
}
-func (d *Dashboard) handleAgents(w http.ResponseWriter, r *http.Request) {
- web.JSON(w, 200, d.GetAgents())
-}
-
func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
@@ -344,8 +157,8 @@ func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {
d.mu.Unlock()
}()
- agents := d.GetAgents()
- data, _ := json.Marshal(agents)
+ // Send initial empty agent list
+ data, _ := json.Marshal([]interface{}{})
_, _ = fmt.Fprintf(w, "event: init\ndata: %s\n\n", data)
flusher.Flush()
@@ -396,76 +209,3 @@ func (d *Dashboard) withLongCache(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
})
}
-
-type EventObserver func(evt AgentEvent)
-
-func extractAgentID(r *http.Request) string {
- if id := r.Header.Get("X-Agent-Id"); id != "" {
- return id
- }
- if id := r.URL.Query().Get("agentId"); id != "" {
- return id
- }
- return "anonymous"
-}
-
-func extractProfile(r *http.Request) string {
- if p := r.Header.Get("X-Profile"); p != "" {
- return p
- }
- return r.URL.Query().Get("profile")
-}
-
-func isManagementRoute(path string) bool {
- return strings.HasPrefix(path, "/dashboard") ||
- strings.HasPrefix(path, "/profiles") ||
- strings.HasPrefix(path, "/instances") ||
- strings.HasPrefix(path, "/screencast/tabs") ||
- path == "/welcome" || path == "/favicon.ico" || path == "/health"
-}
-
-func actionDetail(r *http.Request) string {
- switch r.URL.Path {
- case "/navigate":
- return r.URL.Query().Get("url")
- case "/actions":
- return "batch action"
- case "/snapshot":
- if sel := r.URL.Query().Get("selector"); sel != "" {
- return "selector=" + sel
- }
- }
- return ""
-}
-
-func (d *Dashboard) TrackingMiddleware(observers []EventObserver, next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- start := time.Now()
-
- if isManagementRoute(r.URL.Path) {
- next.ServeHTTP(w, r)
- return
- }
-
- sw := &web.StatusWriter{ResponseWriter: w, Code: 200}
- next.ServeHTTP(sw, r)
-
- evt := AgentEvent{
- AgentID: extractAgentID(r),
- Profile: extractProfile(r),
- Action: r.Method + " " + r.URL.Path,
- URL: r.URL.Query().Get("url"),
- TabID: r.URL.Query().Get("tabId"),
- Detail: actionDetail(r),
- Status: sw.Code,
- DurationMs: time.Since(start).Milliseconds(),
- Timestamp: start,
- }
-
- d.RecordEvent(evt)
-
- for _, obs := range observers {
- obs(evt)
- }
- })
-}
diff --git a/internal/dashboard/dashboard_test.go b/internal/dashboard/dashboard_test.go
index f2207842..47a5a67e 100644
--- a/internal/dashboard/dashboard_test.go
+++ b/internal/dashboard/dashboard_test.go
@@ -5,106 +5,92 @@ import (
"net/http/httptest"
"testing"
"time"
-
- "github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/profiles"
)
-func TestDashboardRecordEvent(t *testing.T) {
+func TestNewDashboard(t *testing.T) {
d := NewDashboard(nil)
- evt := AgentEvent{
- AgentID: "agent1",
- Action: "GET /test",
- Timestamp: time.Now(),
+ if d == nil {
+ t.Fatal("expected non-nil dashboard")
}
+}
- d.RecordEvent(evt)
+func TestDashboardBroadcastSystemEvent(t *testing.T) {
+ d := NewDashboard(nil)
- agents := d.GetAgents()
- if len(agents) != 1 {
- t.Fatalf("expected 1 agent, got %d", len(agents))
- }
- if agents[0].AgentID != "agent1" {
- t.Errorf("expected agent1, got %s", agents[0].AgentID)
- }
- if agents[0].Status != "active" {
- t.Errorf("expected active, got %s", agents[0].Status)
+ // Create a test handler and register it
+ mux := http.NewServeMux()
+ d.RegisterHandlers(mux)
+
+ // In a real scenario, a client would be connected to /api/events
+ // For this test, we just verify the broadcast method doesn't panic
+ evt := SystemEvent{
+ Type: "instance.started",
}
+ d.BroadcastSystemEvent(evt)
}
-func TestDashboardSSE(t *testing.T) {
+func TestDashboardSSEHandlerRegistration(t *testing.T) {
d := NewDashboard(nil)
mux := http.NewServeMux()
d.RegisterHandlers(mux)
- // Since SSE is a long-running connection, we test the registration
- go func() {
- time.Sleep(100 * time.Millisecond)
- d.RecordEvent(AgentEvent{AgentID: "agent1", Action: "test"})
- }()
+ // Verify the SSE handler is registered by checking the mux
+ // (can't easily test the full SSE flow with httptest due to streaming nature)
+ // Just verify handlers are registered without error
+}
- // We can't easily test the full SSE cycle with httptest.Recorder,
- // but we can verify the handler runs and registers the connection.
- d.mu.RLock()
- initConns := len(d.sseConns)
- d.mu.RUnlock()
+func TestDashboardShutdown(t *testing.T) {
+ d := NewDashboard(nil)
+ // Just verify it doesn't panic
+ d.Shutdown()
+}
- if initConns != 0 {
- t.Errorf("expected 0 connections, got %d", initConns)
- }
+func TestDashboardSetInstanceLister(t *testing.T) {
+ d := NewDashboard(nil)
+ d.SetInstanceLister(nil)
+ // Just verify it doesn't panic
}
-func TestTrackingMiddleware(t *testing.T) {
+func TestDashboardCacheHeaders(t *testing.T) {
d := NewDashboard(nil)
- mux := http.NewServeMux()
- mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- })
- handler := d.TrackingMiddleware(nil, mux)
+ // Test long cache (assets)
+ handler := d.withLongCache(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ }))
- req := httptest.NewRequest("GET", "/test", nil)
- req.Header.Set("X-Agent-Id", "agent-t")
+ req := httptest.NewRequest("GET", "/assets/app.js", nil)
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 != "agent-t" {
- t.Errorf("expected agent-t, got %s", agents[0].AgentID)
- }
-}
-
-func TestDashboardProfileIntegration(t *testing.T) {
- profilesDir := t.TempDir()
- profMgr := profiles.NewProfileManager(profilesDir)
- dash := NewDashboard(nil)
-
- var recorded bridge.ActionRecord
- observer := func(evt AgentEvent) {
- if evt.Profile == "prof1" {
- recorded = bridge.ActionRecord{
- Endpoint: evt.Action,
- }
- }
+ cacheControl := w.Header().Get("Cache-Control")
+ if cacheControl != "public, max-age=31536000, immutable" {
+ t.Errorf("expected long cache header, got %q", cacheControl)
}
- mux := http.NewServeMux()
- mux.HandleFunc("/action", func(w http.ResponseWriter, r *http.Request) {
+ // Test no cache (HTML)
+ handler = d.withNoCache(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
- })
-
- handler := dash.TrackingMiddleware([]EventObserver{observer}, mux)
+ }))
- req := httptest.NewRequest("POST", "/action?profile=prof1", nil)
- w := httptest.NewRecorder()
+ req = httptest.NewRequest("GET", "/dashboard", nil)
+ w = httptest.NewRecorder()
handler.ServeHTTP(w, req)
- if recorded.Endpoint != "POST /action" {
- t.Errorf("expected POST /action, got %q", recorded.Endpoint)
+ cacheControl = w.Header().Get("Cache-Control")
+ if cacheControl != "no-store" {
+ t.Errorf("expected no-store cache header, got %q", cacheControl)
}
- _ = profMgr
+}
+
+func TestDashboardShutdownTimeout(t *testing.T) {
+ d := NewDashboard(&DashboardConfig{
+ IdleTimeout: 10 * time.Millisecond,
+ DisconnectTimeout: 20 * time.Millisecond,
+ ReaperInterval: 5 * time.Millisecond,
+ SSEBufferSize: 8,
+ })
+
+ d.Shutdown()
+ time.Sleep(50 * time.Millisecond) // Verify shutdown completes
}