Skip to content

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

chore: removing comments

Luigi Agosti9f30381b7ad3
diff --git a/animations_test.go b/animations_test.go
index 92c56502..771af6dd 100644
--- a/animations_test.go
+++ b/animations_test.go
@@ -6,7 +6,7 @@ import (
)
func TestDisableAnimationsCSSContent(t *testing.T) {
- // Verify the injected CSS contains the critical rules
+
if !strings.Contains(disableAnimationsCSS, "animation: none !important") {
t.Error("missing animation: none rule")
}
@@ -38,7 +38,7 @@ func TestDisableAnimationsCSSIsIIFE(t *testing.T) {
}
func TestNoAnimationsConfigDefault(t *testing.T) {
- // Default should be false (env not set in tests)
+
if noAnimations {
t.Error("noAnimations should default to false")
}
diff --git a/bridge.go b/bridge.go
index ca57030c..f3eea998 100644
--- a/bridge.go
+++ b/bridge.go
@@ -1,4 +1,14 @@
-package main
+package // TabEntry holds a chromedp context for an open tab.
+// Bridge is the central state holder for the Chrome connection, tab contexts, and per-tab snapshot caches.
+// TabContext returns the chromedp context for a tab and the resolved tabID.
+// CleanStaleTabs periodically removes tab entries whose Chrome targets no longer exist.
+// GetRefCache returns the cached snapshot refs for a tab (nil if none).
+// SetRefCache stores the snapshot ref cache for a tab.
+// DeleteRefCache removes the snapshot ref cache for a tab.
+// CreateTab opens a new tab, navigates to url, and returns its ID and context.
+// CloseTab closes a tab by ID and cleans up caches.
+// ListTargets returns all open page targets from Chrome.
+main
import (
"context"
@@ -13,35 +23,27 @@ import (
"github.com/chromedp/chromedp"
)
-// TabEntry holds a chromedp context for an open tab.
type TabEntry struct {
ctx context.Context
cancel context.CancelFunc
}
-// refCache stores the ref→backendNodeID mapping and the last snapshot nodes per tab.
-// Refs are assigned during /snapshot and looked up during /action, avoiding
-// a second a11y tree fetch that could drift.
type refCache struct {
- refs map[string]int64 // "e0" → backendNodeID
- nodes []A11yNode // last snapshot for diff
+ refs map[string]int64
+ nodes []A11yNode
}
-// Bridge is the central state holder for the Chrome connection, tab contexts,
-// and per-tab snapshot caches.
type Bridge struct {
allocCtx context.Context
browserCtx context.Context
tabs map[string]*TabEntry
snapshots map[string]*refCache
- stealthScript string // injected on every new tab
- actions map[string]ActionFunc // cached action registry (built once)
+ stealthScript string
+ actions map[string]ActionFunc
locks *lockManager
mu sync.RWMutex
}
-// injectStealth adds the stealth script to a tab context so it runs on every
-// new document load (including navigations).
func (b *Bridge) injectStealth(ctx context.Context) {
if b.stealthScript == "" {
return
@@ -56,9 +58,6 @@ func (b *Bridge) injectStealth(ctx context.Context) {
}
}
-// TabContext returns the chromedp context for a tab and the resolved tabID.
-// If tabID is empty, uses the first page target.
-// Uses RLock for cache hits, upgrades to Lock only when creating a new entry.
func (b *Bridge) TabContext(tabID string) (context.Context, string, error) {
if tabID == "" {
targets, err := b.ListTargets()
@@ -71,7 +70,6 @@ func (b *Bridge) TabContext(tabID string) (context.Context, string, error) {
tabID = string(targets[0].TargetID)
}
- // Fast path: read lock
b.mu.RLock()
if entry, ok := b.tabs[tabID]; ok && entry.ctx != nil {
b.mu.RUnlock()
@@ -79,7 +77,6 @@ func (b *Bridge) TabContext(tabID string) (context.Context, string, error) {
}
b.mu.RUnlock()
- // Slow path: write lock, double-check
b.mu.Lock()
defer b.mu.Unlock()
@@ -99,7 +96,6 @@ func (b *Bridge) TabContext(tabID string) (context.Context, string, error) {
return nil, "", fmt.Errorf("tab %s not found: %w", tabID, err)
}
- // Inject stealth script on newly attached tabs
b.injectStealth(ctx)
if noAnimations {
b.injectNoAnimations(ctx)
@@ -109,8 +105,6 @@ func (b *Bridge) TabContext(tabID string) (context.Context, string, error) {
return ctx, tabID, nil
}
-// CleanStaleTabs periodically removes tab entries whose Chrome targets
-// no longer exist. Exits when ctx is cancelled.
func (b *Bridge) CleanStaleTabs(ctx context.Context, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
@@ -147,42 +141,36 @@ func (b *Bridge) CleanStaleTabs(ctx context.Context, interval time.Duration) {
}
}
-// GetRefCache returns the cached snapshot refs for a tab (nil if none).
func (b *Bridge) GetRefCache(tabID string) *refCache {
b.mu.RLock()
defer b.mu.RUnlock()
return b.snapshots[tabID]
}
-// SetRefCache stores the snapshot ref cache for a tab.
func (b *Bridge) SetRefCache(tabID string, cache *refCache) {
b.mu.Lock()
defer b.mu.Unlock()
b.snapshots[tabID] = cache
}
-// DeleteRefCache removes the snapshot ref cache for a tab.
func (b *Bridge) DeleteRefCache(tabID string) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.snapshots, tabID)
}
-// CreateTab opens a new tab, navigates to url, and returns its ID and context.
func (b *Bridge) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
if b.browserCtx == nil {
return "", nil, nil, fmt.Errorf("no browser context available")
}
ctx, cancel := chromedp.NewContext(b.browserCtx)
- // Inject stealth script before navigation so it applies to the first page load
b.injectStealth(ctx)
if noAnimations {
b.injectNoAnimations(ctx)
}
- // Apply global resource blocking on new tabs
if blockMedia {
_ = setResourceBlocking(ctx, mediaBlockPatterns)
} else if blockImages {
@@ -206,32 +194,26 @@ func (b *Bridge) CreateTab(url string) (string, context.Context, context.CancelF
return newTargetID, ctx, cancel, nil
}
-// CloseTab closes a tab by ID and cleans up caches.
func (b *Bridge) CloseTab(tabID string) error {
b.mu.Lock()
entry, tracked := b.tabs[tabID]
b.mu.Unlock()
- // Cancel the tab's chromedp context — this is the idiomatic way to close
- // a tab in chromedp. It detaches from the target and lets Chrome clean up.
if tracked && entry.cancel != nil {
entry.cancel()
}
- // Also send target.CloseTarget via the browser context for a clean CDP close.
closeCtx, closeCancel := context.WithTimeout(b.browserCtx, 5*time.Second)
defer closeCancel()
- // Use the CDP executor directly (not chromedp.Run) to avoid context issues.
if err := target.CloseTarget(target.ID(tabID)).Do(cdp.WithExecutor(closeCtx, chromedp.FromContext(closeCtx).Browser)); err != nil {
- // Target may already be gone after cancel — that's fine.
+
if !tracked {
return nil
}
slog.Debug("close target CDP", "tabId", tabID, "err", err)
}
- // Clean up local state.
b.mu.Lock()
delete(b.tabs, tabID)
delete(b.snapshots, tabID)
@@ -240,7 +222,6 @@ func (b *Bridge) CloseTab(tabID string) error {
return nil
}
-// ListTargets returns all open page targets from Chrome.
func (b *Bridge) ListTargets() ([]*target.Info, error) {
if b.browserCtx == nil {
return nil, fmt.Errorf("no browser connection")
diff --git a/bridge_test.go b/bridge_test.go
index d7908e90..d5194285 100644
--- a/bridge_test.go
+++ b/bridge_test.go
@@ -19,14 +19,12 @@ func TestRefCacheConcurrency(t *testing.T) {
defer wg.Done()
tabID := "tab1"
- // Write
b.mu.Lock()
b.snapshots[tabID] = &refCache{refs: map[string]int64{
"e0": int64(i),
}}
b.mu.Unlock()
- // Read
b.mu.RLock()
cache := b.snapshots[tabID]
b.mu.RUnlock()
@@ -44,7 +42,6 @@ func TestRefCacheLookup(t *testing.T) {
snapshots: make(map[string]*refCache),
}
- // No cache → nil
b.mu.RLock()
cache := b.snapshots["tab1"]
b.mu.RUnlock()
@@ -52,7 +49,6 @@ func TestRefCacheLookup(t *testing.T) {
t.Error("expected nil cache for unknown tab")
}
- // Set cache
b.mu.Lock()
b.snapshots["tab1"] = &refCache{refs: map[string]int64{
"e0": 100,
@@ -60,7 +56,6 @@ func TestRefCacheLookup(t *testing.T) {
}}
b.mu.Unlock()
- // Lookup
b.mu.RLock()
cache = b.snapshots["tab1"]
b.mu.RUnlock()
diff --git a/cdp.go b/cdp.go
index 5dfcf6c9..0987b7a8 100644
--- a/cdp.go
+++ b/cdp.go
@@ -29,9 +29,9 @@ func navigatePage(ctx context.Context, url string) error {
}
return nil
}),
- // Poll document.readyState until interactive/complete or context deadline.
+
chromedp.ActionFunc(func(ctx context.Context) error {
- // Use context deadline if set, otherwise fall back to 10s.
+
deadline, ok := ctx.Deadline()
if !ok {
deadline = time.Now().Add(10 * time.Second)
@@ -51,14 +51,14 @@ func navigatePage(ctx context.Context, url string) error {
if json.Unmarshal(evalResult, &evalResp) == nil {
readyState = evalResp.Result.Value
if readyState == "interactive" || readyState == "complete" {
- return nil // Page is ready for interaction
+ return nil
}
}
}
- // Check every 200ms to avoid excessive polling
+
time.Sleep(200 * time.Millisecond)
}
- // Timeout reached, but don't fail - page might still be usable
+
return nil
}),
)
@@ -174,20 +174,20 @@ func scrollByNodeID(ctx context.Context, backendNodeID int64) error {
// URL patterns for blocking resources via Network.setBlockedURLs.
var imageBlockPatterns = []string{
- // Common image extensions
+
"*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.svg", "*.ico",
"*.bmp", "*.tiff", "*.avif", "*.jfif",
- // Common CDN image paths
+
"*/images/*", "*/img/*", "*/photos/*", "*/thumbnails/*",
"*imagedelivery.net*", "*images.unsplash.com*", "*pbs.twimg.com*",
}
var mediaBlockPatterns = append(imageBlockPatterns,
- // Fonts
+
"*.woff", "*.woff2", "*.ttf", "*.otf", "*.eot",
- // Video/Audio
+
"*.mp4", "*.webm", "*.ogg", "*.mp3", "*.wav", "*.m3u8",
- // CSS (aggressive)
+
"*.css",
)
@@ -195,7 +195,7 @@ var mediaBlockPatterns = append(imageBlockPatterns,
// Pass nil to clear the blocklist.
func setResourceBlocking(ctx context.Context, patterns []string) error {
return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- // Enable Network domain (idempotent).
+
if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Network.enable", nil, nil); err != nil {
return fmt.Errorf("network enable: %w", err)
}
diff --git a/cmd_dashboard.go b/cmd_dashboard.go
index 4091779f..6afcaebb 100644
--- a/cmd_dashboard.go
+++ b/cmd_dashboard.go
@@ -17,7 +17,7 @@ import (
// runDashboard starts a lightweight dashboard server — no Chrome, no bridge.
// It manages Pinchtab instances via the orchestrator and serves the dashboard UI.
func runDashboard() {
- dashPort := port // reuse --port / BRIDGE_PORT
+ dashPort := port
if dashPort == "" {
dashPort = "9870"
}
@@ -33,18 +33,14 @@ func runDashboard() {
mux := http.NewServeMux()
- // Dashboard UI + SSE
dashboard.RegisterHandlers(mux)
orchestrator.RegisterHandlers(mux)
profMgr.RegisterHandlers(mux)
- // Health endpoint for the dashboard itself
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
jsonResp(w, 200, map[string]string{"status": "ok", "mode": "dashboard"})
})
- // Proxy common bridge endpoints to the default instance
- // This lets the dashboard UI call /tabs, /screencast/tabs etc on the dashboard port
proxyEndpoints := []string{
"/tabs", "/snapshot", "/screenshot", "/text",
"/navigate", "/action", "/actions", "/evaluate",
@@ -53,9 +49,9 @@ func runDashboard() {
"/screencast", "/screencast/tabs",
}
for _, ep := range proxyEndpoints {
- endpoint := ep // capture
+ endpoint := ep
mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
- // Find first running instance and proxy to it
+
instances := orchestrator.List()
var target string
for _, inst := range instances {
@@ -72,7 +68,6 @@ func runDashboard() {
})
}
- // Profile observer
profileObserver := func(evt AgentEvent) {
if evt.Profile != "" {
profMgr.tracker.Record(evt.Profile, ActionRecord{
@@ -94,7 +89,6 @@ func runDashboard() {
srv := &http.Server{Addr: ":" + dashPort, Handler: handler}
- // Auto-launch default instance if configured
defaultProfile := os.Getenv("PINCHTAB_DEFAULT_PROFILE")
defaultPort := os.Getenv("PINCHTAB_DEFAULT_PORT")
if defaultPort == "" {
@@ -104,13 +98,12 @@ func runDashboard() {
defaultProfile = "default"
}
- // Ensure default profile exists
os.MkdirAll(filepath.Join(profilesDir, defaultProfile, "Default"), 0755)
autoLaunch := os.Getenv("PINCHTAB_NO_AUTO_LAUNCH") == ""
if autoLaunch {
go func() {
- // Wait for server to be ready
+
time.Sleep(500 * time.Millisecond)
headlessDefault := os.Getenv("PINCHTAB_HEADED") == ""
inst, err := orchestrator.Launch(defaultProfile, defaultPort, headlessDefault)
@@ -122,7 +115,6 @@ func runDashboard() {
}()
}
- // Shutdown
shutdownOnce := &sync.Once{}
doShutdown := func() {
shutdownOnce.Do(func() {
@@ -158,18 +150,16 @@ func runDashboard() {
// proxyRequest forwards an HTTP request to a target URL.
// For WebSocket upgrades (screencast), it does a WebSocket proxy.
func proxyRequest(w http.ResponseWriter, r *http.Request, targetURL string) {
- // Preserve query params
+
if r.URL.RawQuery != "" {
targetURL += "?" + r.URL.RawQuery
}
- // Check if this is a WebSocket upgrade (screencast)
if isWebSocketUpgrade(r) {
proxyWebSocket(w, r, targetURL)
return
}
- // Regular HTTP proxy
client := &http.Client{Timeout: 30 * time.Second}
proxyReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, r.Body)
if err != nil {
@@ -177,7 +167,6 @@ func proxyRequest(w http.ResponseWriter, r *http.Request, targetURL string) {
return
}
- // Forward headers
for k, vv := range r.Header {
for _, v := range vv {
proxyReq.Header.Add(k, v)
@@ -191,7 +180,6 @@ func proxyRequest(w http.ResponseWriter, r *http.Request, targetURL string) {
}
defer resp.Body.Close()
- // Copy response
for k, vv := range resp.Header {
for _, v := range vv {
w.Header().Add(k, v)
diff --git a/config.go b/config.go
index e8b0c7a7..33b0541b 100644
--- a/config.go
+++ b/config.go
@@ -1,4 +1,5 @@
-package main
+package // Config represents the configuration file structure.
+main
import (
_ "embed"
@@ -10,16 +11,12 @@ import (
"time"
)
-// Body size limit for POST handlers.
-const maxBodySize = 1 << 20 // 1MB
+const maxBodySize = 1 << 20
-// Target type for Chrome DevTools Protocol.
const targetTypePage = "page"
-// Snapshot filter values.
const filterInteractive = "interactive"
-// Action kinds for /action endpoint.
const (
actionClick = "click"
actionType = "type"
@@ -33,37 +30,33 @@ const (
actionHumanType = "humanType"
)
-// Tab actions for /tab endpoint.
const (
tabActionNew = "new"
tabActionClose = "close"
)
-//go:embed stealth.js
var stealthScript string
-//go:embed readability.js
var readabilityJS string
-//go:embed welcome.html
var welcomeHTML string
var (
port = envOr("BRIDGE_PORT", "9867")
- cdpURL = os.Getenv("CDP_URL") // empty = launch Chrome ourselves
+ cdpURL = os.Getenv("CDP_URL")
token = os.Getenv("BRIDGE_TOKEN")
stateDir = envOr("BRIDGE_STATE_DIR", filepath.Join(homeDir(), ".pinchtab"))
headless = os.Getenv("BRIDGE_HEADLESS") == "true"
noRestore = os.Getenv("BRIDGE_NO_RESTORE") == "true"
profileDir = envOr("BRIDGE_PROFILE", filepath.Join(homeDir(), ".pinchtab", "chrome-profile"))
chromeVersion = envOr("BRIDGE_CHROME_VERSION", "144.0.7559.133")
- timezone = os.Getenv("BRIDGE_TIMEZONE") // e.g. "America/New_York"
+ timezone = os.Getenv("BRIDGE_TIMEZONE")
blockImages = os.Getenv("BRIDGE_BLOCK_IMAGES") == "true"
- blockMedia = os.Getenv("BRIDGE_BLOCK_MEDIA") == "true" // superset: images + fonts + CSS + video
- chromeBinary = os.Getenv("CHROME_BINARY") // path to Chrome/Chromium binary
- chromeExtraFlags = os.Getenv("CHROME_FLAGS") // extra flags (space-separated)
+ blockMedia = os.Getenv("BRIDGE_BLOCK_MEDIA") == "true"
+ chromeBinary = os.Getenv("CHROME_BINARY")
+ chromeExtraFlags = os.Getenv("CHROME_FLAGS")
noAnimations = os.Getenv("BRIDGE_NO_ANIMATIONS") == "true"
- stealthLevel = envOr("BRIDGE_STEALTH", "light") // "light" or "full"
+ stealthLevel = envOr("BRIDGE_STEALTH", "light")
actionTimeout = 15 * time.Second
navigateTimeout = 30 * time.Second
shutdownTimeout = 10 * time.Second
@@ -82,7 +75,6 @@ func homeDir() string {
return h
}
-// Config represents the configuration file structure
type Config struct {
Port string `json:"port"`
CdpURL string `json:"cdpUrl,omitempty"`
@@ -95,18 +87,16 @@ type Config struct {
NavigateSec int `json:"navigateSec,omitempty"`
}
-// loadConfig loads configuration from file or environment variables
func loadConfig() {
- // Default config file location
+
configPath := envOr("BRIDGE_CONFIG", filepath.Join(homeDir(), ".pinchtab", "config.json"))
- // Try to load config file
if data, err := os.ReadFile(configPath); err == nil {
var cfg Config
if err := json.Unmarshal(data, &cfg); err != nil {
slog.Warn("invalid JSON in config file, ignoring", "path", configPath, "err", err)
} else {
- // Apply config file values (env vars take precedence)
+
if cfg.Port != "" && os.Getenv("BRIDGE_PORT") == "" {
port = cfg.Port
}
@@ -138,7 +128,6 @@ func loadConfig() {
}
}
-// defaultConfig returns a default configuration
func defaultConfig() Config {
return Config{
Port: "9867",
@@ -151,7 +140,6 @@ func defaultConfig() Config {
}
}
-// handleConfigCommand handles the 'config' subcommand
func handleConfigCommand() {
if len(os.Args) < 3 {
fmt.Println("Usage: pinchtab config <command>")
@@ -165,7 +153,6 @@ func handleConfigCommand() {
case "init":
configPath := filepath.Join(homeDir(), ".pinchtab", "config.json")
- // Check if config already exists
if _, err := os.Stat(configPath); err == nil {
fmt.Printf("Config file already exists at %s\n", configPath)
fmt.Print("Overwrite? (y/N): ")
@@ -176,13 +163,11 @@ func handleConfigCommand() {
}
}
- // Create directory if needed
if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
fmt.Printf("Error creating directory: %v\n", err)
os.Exit(1)
}
- // Write default config
cfg := defaultConfig()
data, _ := json.MarshalIndent(cfg, "", " ")
if err := os.WriteFile(configPath, data, 0644); err != nil {
diff --git a/config_test.go b/config_test.go
index 469e47f0..39c71ca4 100644
--- a/config_test.go
+++ b/config_test.go
@@ -61,16 +61,14 @@ func TestDefaultConfig(t *testing.T) {
}
func TestLoadConfig_FromFile(t *testing.T) {
- // Save original values
+
origPort := port
defer func() { port = origPort }()
- // Create a temp config file
dir := t.TempDir()
configPath := dir + "/config.json"
_ = os.WriteFile(configPath, []byte(`{"port":"7777"}`), 0644)
- // Ensure env vars don't interfere
t.Setenv("BRIDGE_PORT", "")
t.Setenv("BRIDGE_CONFIG", configPath)
@@ -88,14 +86,12 @@ func TestLoadConfig_EnvOverridesFile(t *testing.T) {
configPath := dir + "/config.json"
_ = os.WriteFile(configPath, []byte(`{"port":"7777"}`), 0644)
- // Set BRIDGE_PORT env — loadConfig should NOT override port from file
t.Setenv("BRIDGE_CONFIG", configPath)
t.Setenv("BRIDGE_PORT", "8888")
- // Simulate what happens: port was set at init from env, so set it manually
port = "8888"
loadConfig()
- // File says 7777, but env is set so loadConfig should leave port alone
+
if port != "8888" {
t.Errorf("env should override file: port = %q, want 8888", port)
}
@@ -106,21 +102,20 @@ func TestLoadConfig_InvalidJSON(t *testing.T) {
configPath := dir + "/config.json"
_ = os.WriteFile(configPath, []byte("{broken json!!!"), 0644)
- // Save and restore global state
origPort := port
defer func() { port = origPort }()
t.Setenv("BRIDGE_CONFIG", configPath)
t.Setenv("BRIDGE_PORT", "")
port = "9867"
- loadConfig() // should not panic, should keep defaults
+ loadConfig()
if port != "9867" {
t.Errorf("invalid config should not change port, got %q", port)
}
}
func TestConstants(t *testing.T) {
- // Verify constants are what handlers expect
+
if actionClick != "click" {
t.Error("actionClick mismatch")
}
diff --git a/dashboard.go b/dashboard.go
index c1388706..ba5e81d1 100644
--- a/dashboard.go
+++ b/dashboard.go
@@ -1,4 +1,9 @@
-package main
+package // DashboardConfig holds tunable timeouts for agent status transitions.
+// Shutdown stops the reaper goroutine.
+// RecordEvent processes an agent action and broadcasts to SSE subscribers.
+// GetAgents returns current state of all agents.
+// EventObserver receives agent events for additional processing (e.
+main
import (
"context"
@@ -12,42 +17,36 @@ import (
"time"
)
-// DashboardConfig holds tunable timeouts for agent status transitions.
type DashboardConfig struct {
- IdleTimeout time.Duration // time before agent marked idle (default 30s)
- DisconnectTimeout time.Duration // time before agent marked disconnected (default 5m)
- ReaperInterval time.Duration // how often to check agent status (default 10s)
- SSEBufferSize int // per-client SSE channel buffer (default 64)
+ IdleTimeout time.Duration
+ DisconnectTimeout time.Duration
+ ReaperInterval time.Duration
+ SSEBufferSize int
}
-//go:embed dashboard
var dashboardFS embed.FS
-// ---------------------------------------------------------------------------
-// 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"`
+ 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"`
}
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"`
+ 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 {
@@ -91,7 +90,6 @@ func NewDashboard(cfg *DashboardConfig) *Dashboard {
return d
}
-// Shutdown stops the reaper goroutine.
func (d *Dashboard) Shutdown() { d.cancel() }
func (d *Dashboard) reaper(ctx context.Context) {
@@ -119,7 +117,6 @@ func (d *Dashboard) reaper(ctx context.Context) {
}
}
-// RecordEvent processes an agent action and broadcasts to SSE subscribers.
func (d *Dashboard) RecordEvent(evt AgentEvent) {
d.mu.Lock()
@@ -140,23 +137,20 @@ func (d *Dashboard) RecordEvent(evt AgentEvent) {
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
+ default:
}
}
}
-// GetAgents returns current state of all agents.
func (d *Dashboard) GetAgents() []AgentActivity {
d.mu.RLock()
defer d.mu.RUnlock()
@@ -168,16 +162,11 @@ func (d *Dashboard) GetAgents() []AgentActivity {
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)
- // Serve static assets (CSS, JS) from embedded filesystem
sub, _ := fs.Sub(dashboardFS, "dashboard")
mux.Handle("GET /dashboard/", http.StripPrefix("/dashboard/", http.FileServer(http.FS(sub))))
}
@@ -208,7 +197,6 @@ func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {
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)
@@ -232,14 +220,8 @@ func (d *Dashboard) handleDashboardUI(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}
-// ---------------------------------------------------------------------------
-// Tracking Middleware — extracts agent ID from header or query
-// ---------------------------------------------------------------------------
-
-// EventObserver receives agent events for additional processing (e.g. profile tracking).
type EventObserver func(evt AgentEvent)
-// extractAgentID reads the agent identifier from X-Agent-Id header or agentId query param.
func extractAgentID(r *http.Request) string {
if id := r.Header.Get("X-Agent-Id"); id != "" {
return id
@@ -250,7 +232,6 @@ func extractAgentID(r *http.Request) string {
return "anonymous"
}
-// extractProfile reads the profile name from X-Profile header or profile query param.
func extractProfile(r *http.Request) string {
if p := r.Header.Get("X-Profile"); p != "" {
return p
@@ -258,7 +239,6 @@ func extractProfile(r *http.Request) string {
return r.URL.Query().Get("profile")
}
-// isManagementRoute returns true for routes that shouldn't be tracked in the activity feed.
func isManagementRoute(path string) bool {
return strings.HasPrefix(path, "/dashboard") ||
strings.HasPrefix(path, "/profiles") ||
@@ -267,7 +247,6 @@ func isManagementRoute(path string) bool {
path == "/welcome" || path == "/favicon.ico" || path == "/health"
}
-// actionDetail extracts a human-readable detail string from the request.
func actionDetail(r *http.Request) string {
switch r.URL.Path {
case "/navigate":
@@ -313,5 +292,3 @@ func (d *Dashboard) TrackingMiddleware(observers []EventObserver, next http.Hand
}
})
}
-
-// ---------------------------------------------------------------------------
diff --git a/dashboard_test.go b/dashboard_test.go
index fdcb264c..e040ecc0 100644
--- a/dashboard_test.go
+++ b/dashboard_test.go
@@ -14,23 +14,23 @@ func TestDashboardRecordAndGetAgents(t *testing.T) {
d := NewDashboard(nil)
d.RecordEvent(AgentEvent{
- AgentID: "mario",
- Profile: "default",
- Action: "GET /snapshot",
- URL: "https://example.com",
- TabID: "tab1",
- Status: 200,
+ AgentID: "mario",
+ Profile: "default",
+ Action: "GET /snapshot",
+ URL: "https://example.com",
+ TabID: "tab1",
+ Status: 200,
DurationMs: 150,
- Timestamp: time.Now(),
+ Timestamp: time.Now(),
})
d.RecordEvent(AgentEvent{
- AgentID: "r40",
- Action: "POST /navigate",
- URL: "https://r40.io",
- Status: 200,
+ AgentID: "r40",
+ Action: "POST /navigate",
+ URL: "https://r40.io",
+ Status: 200,
DurationMs: 80,
- Timestamp: time.Now(),
+ Timestamp: time.Now(),
})
agents := d.GetAgents()
@@ -127,7 +127,6 @@ func TestDashboardSSEInit(t *testing.T) {
mux := http.NewServeMux()
d.RegisterHandlers(mux)
- // Use a real test server with short-lived request
srv := httptest.NewServer(mux)
defer srv.Close()
@@ -137,7 +136,7 @@ func TestDashboardSSEInit(t *testing.T) {
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 {
@@ -156,7 +155,6 @@ func TestTrackingMiddleware(t *testing.T) {
w.WriteHeader(200)
})
- // Wire profile observer like main.go does
profileObs := func(evt AgentEvent) {
if evt.Profile != "" {
pm.tracker.Record(evt.Profile, ActionRecord{
@@ -183,7 +181,6 @@ func TestTrackingMiddleware(t *testing.T) {
t.Errorf("expected agent test-bot, got %s", agents[0].AgentID)
}
- // Check profile tracker also recorded via observer
logs := pm.Logs("my-profile", 10)
if len(logs) != 1 {
t.Errorf("expected 1 profile log, got %d", len(logs))
@@ -198,7 +195,7 @@ func TestTrackingMiddlewareAnonymous(t *testing.T) {
})
handler := d.TrackingMiddleware(nil, inner)
- // Use /snapshot (a real agent endpoint, not skipped)
+
req := httptest.NewRequest("GET", "/snapshot", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
@@ -218,7 +215,6 @@ func TestTrackingMiddlewareSkipsManagementRoutes(t *testing.T) {
handler := d.TrackingMiddleware(nil, inner)
- // All of these should be skipped
for _, path := range []string{"/dashboard", "/profiles", "/instances", "/health", "/welcome", "/favicon.ico"} {
req := httptest.NewRequest("GET", path, nil)
w := httptest.NewRecorder()
diff --git a/handler_actions.go b/handler_actions.go
index 3479826a..00052477 100644
--- a/handler_actions.go
+++ b/handler_actions.go
@@ -1,4 +1,5 @@
-package main
+package // ActionFunc handles a single action kind.
+main
import (
"context"
@@ -13,9 +14,6 @@ import (
"github.com/chromedp/chromedp"
)
-// ── POST /action ───────────────────────────────────────────
-
-// actionRequest is the parsed JSON body for /action.
type actionRequest struct {
TabID string `json:"tabId"`
Kind string `json:"kind"`
@@ -31,11 +29,8 @@ type actionRequest struct {
Fast bool `json:"fast"`
}
-// ActionFunc handles a single action kind.
type ActionFunc func(ctx context.Context, req actionRequest) (map[string]any, error)
-// initActionRegistry builds the action registry once. Call from main() after
-// Bridge is initialised; the result is stored in b.actions.
func (b *Bridge) initActionRegistry() {
b.actions = map[string]ActionFunc{
actionClick: func(ctx context.Context, req actionRequest) (map[string]any, error) {
@@ -209,7 +204,6 @@ func (b *Bridge) handleAction(w http.ResponseWriter, r *http.Request) {
defer tCancel()
go cancelOnClientDone(r.Context(), tCancel)
- // Resolve ref to backendNodeID from cached snapshot
if req.Ref != "" && req.NodeID == 0 && req.Selector == "" {
cache := b.GetRefCache(resolvedTabID)
if cache != nil {
@@ -257,8 +251,6 @@ func (b *Bridge) handleAction(w http.ResponseWriter, r *http.Request) {
jsonResp(w, 200, result)
}
-// ── POST /actions (batch) ──────────────────────────────────
-
type actionsRequest struct {
TabID string `json:"tabId"`
Actions []actionRequest `json:"actions"`
@@ -312,7 +304,6 @@ func (b *Bridge) handleActions(w http.ResponseWriter, r *http.Request) {
tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)
- // Resolve ref
if action.Ref != "" && action.NodeID == 0 && action.Selector == "" {
cache := b.GetRefCache(resolvedTabID)
if cache != nil {
diff --git a/handler_actions_test.go b/handler_actions_test.go
index ed13d6b2..560f13a5 100644
--- a/handler_actions_test.go
+++ b/handler_actions_test.go
@@ -122,7 +122,6 @@ func TestHandleStealthStatus_NoTabs(t *testing.T) {
t.Fatalf("failed to unmarshal response: %v", err)
}
- // Should have stealth features even without tabs
features, ok := resp["features"].(map[string]interface{})
if !ok {
t.Error("expected features map")
@@ -132,7 +131,6 @@ func TestHandleStealthStatus_NoTabs(t *testing.T) {
t.Error("expected non-empty features")
}
- // Check score exists
if _, ok := resp["score"].(float64); !ok {
t.Error("expected score")
}
@@ -160,7 +158,6 @@ func TestActionRegistry_HumanActions(t *testing.T) {
b.initActionRegistry()
registry := b.actions
- // Check new human actions exist
if _, ok := registry[actionHumanClick]; !ok {
t.Error("humanClick action not registered")
}
@@ -169,7 +166,6 @@ func TestActionRegistry_HumanActions(t *testing.T) {
t.Error("humanType action not registered")
}
- // Verify total count increased
expectedActions := []string{
actionClick, actionType, actionFill, actionPress,
actionFocus, actionHover, actionSelect, actionScroll,
diff --git a/handler_cookies.go b/handler_cookies.go
index 1322bb38..09d641ad 100644
--- a/handler_cookies.go
+++ b/handler_cookies.go
@@ -13,8 +13,6 @@ import (
"github.com/chromedp/chromedp"
)
-// ── GET /cookies ───────────────────────────────────────────
-
func (b *Bridge) handleGetCookies(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
url := r.URL.Query().Get("url")
@@ -45,7 +43,6 @@ func (b *Bridge) handleGetCookies(w http.ResponseWriter, r *http.Request) {
return
}
- // Filter by name if specified
if name != "" {
filtered := make([]*network.Cookie, 0)
for _, c := range cookies {
@@ -56,7 +53,6 @@ func (b *Bridge) handleGetCookies(w http.ResponseWriter, r *http.Request) {
cookies = filtered
}
- // Convert to simpler format
result := make([]map[string]any, len(cookies))
for i, c := range cookies {
result[i] = map[string]any{
@@ -80,8 +76,6 @@ func (b *Bridge) handleGetCookies(w http.ResponseWriter, r *http.Request) {
})
}
-// ── POST /cookies ──────────────────────────────────────────
-
type cookieRequest struct {
TabID string `json:"tabId"`
URL string `json:"url"`
diff --git a/handler_cookies_test.go b/handler_cookies_test.go
index d5a7b5b3..7098d509 100644
--- a/handler_cookies_test.go
+++ b/handler_cookies_test.go
@@ -34,7 +34,7 @@ func TestHandleSetCookies_NoTab(t *testing.T) {
}
func TestHandleGetCookies_NameFilter(t *testing.T) {
- // Verify the name query param is parsed (can't test actual filtering without Chrome)
+
b := &Bridge{}
b.tabs = make(map[string]*TabEntry)
req := httptest.NewRequest("GET", "/cookies?name=session_id&tabId=nonexistent", nil)
diff --git a/handler_snapshot.go b/handler_snapshot.go
index 1030368f..54f62752 100644
--- a/handler_snapshot.go
+++ b/handler_snapshot.go
@@ -14,17 +14,15 @@ import (
"gopkg.in/yaml.v3"
)
-// ── GET /snapshot ──────────────────────────────────────────
-
func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
filter := r.URL.Query().Get("filter")
doDiff := r.URL.Query().Get("diff") == "true"
- format := r.URL.Query().Get("format") // "text", "yaml", "compact"
- output := r.URL.Query().Get("output") // "file" to save to disk
- outputPath := r.URL.Query().Get("path") // custom file path for output=file
- selector := r.URL.Query().Get("selector") // CSS selector to scope snapshot
- maxTokensStr := r.URL.Query().Get("maxTokens") // truncate output to ~N tokens
+ format := r.URL.Query().Get("format")
+ output := r.URL.Query().Get("output")
+ outputPath := r.URL.Query().Get("path")
+ selector := r.URL.Query().Get("selector")
+ maxTokensStr := r.URL.Query().Get("maxTokens")
reqNoAnim := r.URL.Query().Get("noAnimations") == "true"
maxDepthStr := r.URL.Query().Get("depth")
maxDepth := -1
@@ -73,12 +71,11 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
return
}
- // If a CSS selector is specified, scope the tree to that element's subtree.
if selector != "" {
var scopeNodeID int64
if err := chromedp.Run(tCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
- // Use DOM.querySelector to find the element
+
p := map[string]any{"nodeId": 0, "selector": selector}
// First get the document node
var docResult json.RawMessage
@@ -133,7 +130,6 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
flat, refs := buildSnapshot(treeResp.Nodes, filter, maxDepth)
- // Truncate to maxTokens if specified (rough: 1 token ≈ 4 bytes)
truncated := false
if maxTokens > 0 {
flat, truncated = truncateToTokens(flat, maxTokens, format)
@@ -147,7 +143,6 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
}
}
- // Cache ref→nodeID mapping and nodes for this tab
b.SetRefCache(resolvedTabID, &refCache{refs: refs, nodes: flat})
var url, title string
@@ -156,16 +151,14 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
chromedp.Title(&title),
)
- // Handle file output
if output == "file" {
- // Create snapshots directory if it doesn't exist
+
snapshotDir := filepath.Join(stateDir, "snapshots")
if err := os.MkdirAll(snapshotDir, 0755); err != nil {
jsonErr(w, 500, fmt.Errorf("create snapshot dir: %w", err))
return
}
- // Generate filename with timestamp
timestamp := time.Now().Format("20060102-150405")
var filename string
var content []byte
@@ -235,11 +228,10 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
}
}
- // Write to file — use custom path if provided, otherwise default
filePath := filepath.Join(snapshotDir, filename)
if outputPath != "" {
filePath = outputPath
- // Ensure parent directory exists for custom paths
+
if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {
jsonErr(w, 500, fmt.Errorf("create output dir: %w", err))
return
@@ -250,7 +242,6 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
return
}
- // Return path instead of data
jsonResp(w, 200, map[string]any{
"path": filePath,
"size": len(content),
@@ -281,7 +272,7 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
switch format {
case "compact":
- // One-line-per-node format, minimal tokens. Similar to OpenClaw aria refs.
+
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(200)
_, _ = fmt.Fprintf(w, "# %s | %s | %d nodes", title, url, len(flat))
diff --git a/handler_stealth.go b/handler_stealth.go
index b62ba26a..ca95cd79 100644
--- a/handler_stealth.go
+++ b/handler_stealth.go
@@ -15,13 +15,11 @@ import (
"github.com/chromedp/chromedp"
)
-// ── GET /stealth/status ────────────────────────────────────
-
func (b *Bridge) handleStealthStatus(w http.ResponseWriter, r *http.Request) {
- // Actually check features by evaluating in browser
+
ctx, _, err := b.TabContext("")
if err != nil {
- // If no tab, return static analysis
+
b.sendStealthResponse(w, staticStealthFeatures(), "")
return
}
@@ -69,7 +67,6 @@ func (b *Bridge) handleStealthStatus(w http.ResponseWriter, r *http.Request) {
return
}
- // Fallback to static
b.sendStealthResponse(w, staticStealthFeatures(), "")
}
@@ -94,7 +91,7 @@ func staticStealthFeatures() map[string]bool {
func (b *Bridge) sendStealthResponse(w http.ResponseWriter, features map[string]bool, userAgent string) {
chromeFlags := []string{
- // Note: --disable-blink-features=AutomationControlled removed (deprecated Chrome 144+)
+
"--disable-features=IsolateOrigins,site-per-process",
"--disable-site-isolation-trials",
"--disable-web-security",
@@ -126,7 +123,6 @@ func (b *Bridge) sendStealthResponse(w http.ResponseWriter, features map[string]
level = "minimal"
}
- // Use provided userAgent or get from browser if empty
if userAgent == "" && len(b.tabs) > 0 {
for _, tab := range b.tabs {
ctx, cancel := context.WithTimeout(tab.ctx, 1*time.Second)
@@ -179,8 +175,6 @@ func getStealthRecommendations(features map[string]bool) []string {
return recommendations
}
-// ── POST /fingerprint/rotate ───────────────────────────────
-
type fingerprintRequest struct {
TabID string `json:"tabId"`
OS string `json:"os"`
@@ -212,10 +206,9 @@ func (b *Bridge) handleFingerprintRotate(w http.ResponseWriter, r *http.Request)
tCtx, tCancel := context.WithTimeout(ctx, 5*time.Second)
defer tCancel()
- // CDP-level overrides (undetectable — no JS property redefinition)
if err := chromedp.Run(tCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
- // UA, platform, accept-language at network level
+
err := emulation.SetUserAgentOverride(fp.UserAgent).
WithPlatform(fp.Platform).
WithAcceptLanguage(fp.Language).
@@ -230,7 +223,6 @@ func (b *Bridge) handleFingerprintRotate(w http.ResponseWriter, r *http.Request)
return
}
- // JS overrides for properties CDP doesn't cover (screen, hardware, vendor)
script := fmt.Sprintf(`
(function() {
Object.defineProperty(screen, 'width', { get: () => %d, configurable: true });
@@ -250,7 +242,7 @@ func (b *Bridge) handleFingerprintRotate(w http.ResponseWriter, r *http.Request)
}),
chromedp.Evaluate(script, nil),
); err != nil {
- // Non-fatal: CDP overrides already applied for the important bits
+
slog.Warn("JS fingerprint extras failed", "err", err)
}
diff --git a/handler_stealth_test.go b/handler_stealth_test.go
index 87871297..94d3b46a 100644
--- a/handler_stealth_test.go
+++ b/handler_stealth_test.go
@@ -17,7 +17,7 @@ func TestHandleStealthStatus_NoTab_ReturnsStatic(t *testing.T) {
if w.Code != 200 {
t.Errorf("expected 200, got %d", w.Code)
}
- // Should contain level and score
+
body := w.Body.String()
if !searchString(body, "level") || !searchString(body, "score") {
t.Errorf("expected level and score in response, got: %s", body)
@@ -36,8 +36,6 @@ func TestHandleFingerprintRotate_InvalidJSON(t *testing.T) {
}
}
-// ── generateFingerprint ────────────────────────────────────
-
func TestGenerateFingerprint_Windows(t *testing.T) {
fp := generateFingerprint(fingerprintRequest{OS: "windows"})
if fp.Platform != "Win32" {
@@ -70,11 +68,10 @@ func TestGenerateFingerprint_Random(t *testing.T) {
}
func TestGenerateFingerprint_UnknownOS(t *testing.T) {
- // Unknown OS — should return empty fingerprint (no match in map)
+
fp := generateFingerprint(fingerprintRequest{OS: "freebsd"})
- // Will have screen/language/timezone from random selection below
- // but platform/UA won't be set from the map
- _ = fp // just ensure no panic
+
+ _ = fp
}
func TestGenerateFingerprint_WithBrowser(t *testing.T) {
@@ -84,8 +81,6 @@ func TestGenerateFingerprint_WithBrowser(t *testing.T) {
}
}
-// ── getStealthRecommendations ──────────────────────────────
-
func TestGetStealthRecommendations_AllEnabled(t *testing.T) {
features := map[string]bool{
"user_agent_override": true,
@@ -115,14 +110,12 @@ func TestGetStealthRecommendations_Partial(t *testing.T) {
"timezone_spoofed": true,
}
recs := getStealthRecommendations(features)
- // Should have 4 recommendations (the 4 missing features)
+
if len(recs) != 4 {
t.Errorf("expected 4 recommendations, got %d: %v", len(recs), recs)
}
}
-// ── sendStealthResponse ────────────────────────────────────
-
func TestSendStealthResponse_HighScore(t *testing.T) {
b := &Bridge{}
b.tabs = make(map[string]*TabEntry)
@@ -160,7 +153,7 @@ func TestSendStealthResponse_LowScore(t *testing.T) {
func TestSendStealthResponse_MediumScore(t *testing.T) {
b := &Bridge{}
b.tabs = make(map[string]*TabEntry)
- // 6/10 = 60%
+
features := map[string]bool{
"a": true, "b": true, "c": true, "d": true, "e": true,
"f": true, "g": false, "h": false, "i": false, "j": false,
@@ -174,8 +167,6 @@ func TestSendStealthResponse_MediumScore(t *testing.T) {
}
}
-// ── staticStealthFeatures ──────────────────────────────────
-
func TestStaticStealthFeatures_HasEntries(t *testing.T) {
features := staticStealthFeatures()
if len(features) == 0 {
diff --git a/handler_test.go b/handler_test.go
index 6b9583c8..70a3a96a 100644
--- a/handler_test.go
+++ b/handler_test.go
@@ -14,8 +14,6 @@ func newTestBridge() *Bridge {
}
}
-// ── Validation / error path tests (no Chrome needed) ──────
-
func TestHandleNavigate_MissingURL(t *testing.T) {
b := newTestBridge()
body := `{"url": ""}`
@@ -46,7 +44,6 @@ func TestHandleNavigate_NoTab(t *testing.T) {
w := httptest.NewRecorder()
b.handleNavigate(w, req)
- // No tabs open → TabContext returns error → 404
if w.Code != 404 {
t.Errorf("expected 404, got %d", w.Code)
}
@@ -54,16 +51,12 @@ func TestHandleNavigate_NoTab(t *testing.T) {
func TestHandleAction_UnknownKind(t *testing.T) {
b := newTestBridge()
- // Use nodeId directly to skip ref resolution, and tabId to skip ListTargets
- // TabContext will fail (no browser) but we need it to succeed for this test
- // So we test the "unknown action" path via a tab with no Chrome → 404 first
- // Actually, let's just test that bad JSON and missing tab return proper codes
+
body := `{"kind": "explode", "selector": "button"}`
req := httptest.NewRequest("POST", "/action", strings.NewReader(body))
w := httptest.NewRecorder()
b.handleAction(w, req)
- // No tab → 404 (not 400), because TabContext fails first
if w.Code != 404 {
t.Errorf("expected 404, got %d", w.Code)
}
@@ -77,7 +70,6 @@ func TestHandleAction_RefNotFound_NoCache(t *testing.T) {
w := httptest.NewRecorder()
b.handleAction(w, req)
- // No tab → 404
if w.Code != 404 {
t.Errorf("expected 404, got %d", w.Code)
}
@@ -209,8 +201,6 @@ func TestHandleScreenshot_NoTab(t *testing.T) {
}
}
-// ── Cookie error paths ────────────────────────────────────
-
func TestHandleSetCookies_BadJSON(t *testing.T) {
b := newTestBridge()
req := httptest.NewRequest("POST", "/cookies", strings.NewReader("{broken"))
@@ -234,15 +224,12 @@ func TestHandleSetCookies_MissingURL(t *testing.T) {
}
}
-// ── Health & Tabs (Section 1.1, 1.6) ─────────────────────
-
func TestHandleHealth_NoBrowser(t *testing.T) {
b := newTestBridge()
req := httptest.NewRequest("GET", "/health", nil)
w := httptest.NewRecorder()
b.handleHealth(w, req)
- // No browser → status "disconnected" but still 200
if w.Code != 200 {
t.Errorf("expected 200, got %d", w.Code)
}
@@ -258,7 +245,6 @@ func TestHandleTabs_NoBrowser(t *testing.T) {
w := httptest.NewRecorder()
b.handleTabs(w, req)
- // No browser connection → 500
if w.Code != 500 {
t.Errorf("expected 500, got %d", w.Code)
}
@@ -266,7 +252,7 @@ func TestHandleTabs_NoBrowser(t *testing.T) {
func TestHandleScreenshot_QualityParam(t *testing.T) {
b := newTestBridge()
- // Quality param is parsed but no tab → 404; test it doesn't panic
+
req := httptest.NewRequest("GET", "/screenshot?quality=50", nil)
w := httptest.NewRecorder()
b.handleScreenshot(w, req)
@@ -282,7 +268,6 @@ func TestHandleScreenshot_InvalidQuality(t *testing.T) {
w := httptest.NewRecorder()
b.handleScreenshot(w, req)
- // Invalid quality falls back to default, still 404 (no tab)
if w.Code != 404 {
t.Errorf("expected 404, got %d", w.Code)
}
@@ -295,24 +280,19 @@ func TestHandleNavigate_InvalidURL(t *testing.T) {
w := httptest.NewRecorder()
b.handleNavigate(w, req)
- // No tabs → 404, but the invalid URL is accepted at parse level
- // (validation happens at Chrome level)
if w.Code != 404 {
t.Errorf("expected 404 (no tab), got %d", w.Code)
}
}
-// ── Navigate edge cases ──────────────────────────────────
-
func TestHandleNavigate_WaitTitleClamp(t *testing.T) {
- // waitTitle > 30 should be clamped; this tests the parse path
+
b := newTestBridge()
body := `{"url": "https://example.com", "waitTitle": 999}`
req := httptest.NewRequest("POST", "/navigate", strings.NewReader(body))
w := httptest.NewRecorder()
b.handleNavigate(w, req)
- // No tabs → 404, but the parse/clamp code runs without panic
if w.Code != 404 {
t.Errorf("expected 404 (no tab), got %d", w.Code)
}
@@ -325,14 +305,11 @@ func TestHandleNavigate_NewTabNoChrome(t *testing.T) {
w := httptest.NewRecorder()
b.handleNavigate(w, req)
- // newTab with no browser context → should return 500, not panic
if w.Code != 500 {
t.Errorf("expected 500 (no browser), got %d", w.Code)
}
}
-// ── RefCache methods ──────────────────────────────────────
-
func TestGetSetDeleteRefCache(t *testing.T) {
b := newTestBridge()
diff --git a/handlers.go b/handlers.go
index c145c4a1..3709b321 100644
--- a/handlers.go
+++ b/handlers.go
@@ -16,8 +16,6 @@ import (
"github.com/chromedp/chromedp"
)
-// ── GET /health ────────────────────────────────────────────
-
func (b *Bridge) handleHealth(w http.ResponseWriter, r *http.Request) {
targets, err := b.ListTargets()
if err != nil {
@@ -27,8 +25,6 @@ func (b *Bridge) handleHealth(w http.ResponseWriter, r *http.Request) {
jsonResp(w, 200, map[string]any{"status": "ok", "tabs": len(targets), "cdp": cdpURL})
}
-// ── GET /tabs ──────────────────────────────────────────────
-
func (b *Bridge) handleTabs(w http.ResponseWriter, r *http.Request) {
targets, err := b.ListTargets()
if err != nil {
@@ -53,8 +49,6 @@ func (b *Bridge) handleTabs(w http.ResponseWriter, r *http.Request) {
jsonResp(w, 200, map[string]any{"tabs": tabs})
}
-// ── GET /screenshot ────────────────────────────────────────
-
func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
output := r.URL.Query().Get("output")
@@ -96,7 +90,6 @@ func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {
return
}
- // Handle file output
if output == "file" {
screenshotDir := filepath.Join(stateDir, "screenshots")
if err := os.MkdirAll(screenshotDir, 0755); err != nil {
@@ -136,8 +129,6 @@ func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {
})
}
-// ── GET /text ──────────────────────────────────────────────
-
func (b *Bridge) handleText(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
mode := r.URL.Query().Get("mode")
@@ -182,8 +173,6 @@ func (b *Bridge) handleText(w http.ResponseWriter, r *http.Request) {
})
}
-// ── POST /navigate ─────────────────────────────────────────
-
func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
var req struct {
TabID string `json:"tabId"`
@@ -203,7 +192,6 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
return
}
- // Compute title wait duration (default 2s, max 30s).
titleWait := time.Duration(0)
if req.WaitTitle > 0 {
if req.WaitTitle > 30 {
@@ -212,7 +200,6 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
titleWait = time.Duration(req.WaitTitle * float64(time.Second))
}
- // Per-request navigate timeout (default: global navigateTimeout, max 120s).
navTimeout := navigateTimeout
if req.Timeout > 0 {
if req.Timeout > 120 {
@@ -228,11 +215,11 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
} else if req.BlockImages != nil && *req.BlockImages {
blockPatterns = imageBlockPatterns
} else if req.BlockImages != nil && !*req.BlockImages {
- blockPatterns = nil // explicitly disabled
+ blockPatterns = nil
} else if blockMedia {
- blockPatterns = mediaBlockPatterns // global BRIDGE_BLOCK_MEDIA
+ blockPatterns = mediaBlockPatterns
} else if blockImages {
- blockPatterns = imageBlockPatterns // global BRIDGE_BLOCK_IMAGES
+ blockPatterns = imageBlockPatterns
}
if req.NewTab {
@@ -268,11 +255,10 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
defer tCancel()
go cancelOnClientDone(r.Context(), tCancel)
- // Apply resource blocking before navigation.
if blockPatterns != nil {
_ = setResourceBlocking(tCtx, blockPatterns)
} else if blockImages {
- // Clear any previous blocking if per-request disabled it.
+
_ = setResourceBlocking(tCtx, nil)
}
@@ -290,8 +276,6 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
jsonResp(w, 200, map[string]any{"url": url, "title": title})
}
-// ── POST /evaluate ─────────────────────────────────────────
-
func (b *Bridge) handleEvaluate(w http.ResponseWriter, r *http.Request) {
var req struct {
TabID string `json:"tabId"`
@@ -325,8 +309,6 @@ func (b *Bridge) handleEvaluate(w http.ResponseWriter, r *http.Request) {
jsonResp(w, 200, map[string]any{"result": result})
}
-// ── POST /tab ──────────────────────────────────────────────
-
func (b *Bridge) handleTab(w http.ResponseWriter, r *http.Request) {
var req struct {
Action string `json:"action"`
@@ -367,8 +349,6 @@ func (b *Bridge) handleTab(w http.ResponseWriter, r *http.Request) {
}
}
-// ── POST /tab/lock ─────────────────────────────────────────
-
func (b *Bridge) handleTabLock(w http.ResponseWriter, r *http.Request) {
var req struct {
TabID string `json:"tabId"`
@@ -402,8 +382,6 @@ func (b *Bridge) handleTabLock(w http.ResponseWriter, r *http.Request) {
})
}
-// ── POST /tab/unlock ───────────────────────────────────────
-
func (b *Bridge) handleTabUnlock(w http.ResponseWriter, r *http.Request) {
var req struct {
TabID string `json:"tabId"`
@@ -426,20 +404,14 @@ func (b *Bridge) handleTabUnlock(w http.ResponseWriter, r *http.Request) {
jsonResp(w, 200, map[string]any{"unlocked": true})
}
-// ── POST /shutdown ─────────────────────────────────────────
-
func (b *Bridge) handleShutdown(shutdownFn func()) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
slog.Info("shutdown requested via API")
jsonResp(w, 200, map[string]any{"status": "shutting down"})
- // Trigger shutdown in background so the response gets sent first.
go func() {
time.Sleep(100 * time.Millisecond)
shutdownFn()
}()
}
}
-
-// Shared helpers (jsonResp, jsonErr, cancelOnClientDone, waitForTitle)
-// are defined in middleware.go and cdp.go respectively.
diff --git a/handlers_extra_test.go b/handlers_extra_test.go
index 275f0c56..3fc6c43c 100644
--- a/handlers_extra_test.go
+++ b/handlers_extra_test.go
@@ -149,8 +149,6 @@ func TestHandleShutdown_CallsFunc(t *testing.T) {
}
}
-// ── Config extra tests ─────────────────────────────────────
-
func TestLoadConfig_TimeoutFromFile(t *testing.T) {
tmp := t.TempDir()
cfgPath := filepath.Join(tmp, "config.json")
@@ -168,8 +166,7 @@ func TestLoadConfig_TimeoutFromFile(t *testing.T) {
}()
loadConfig()
- // Config uses TimeoutSec/NavigateSec (int seconds), not duration strings
- // So "25s" won't parse as int — this tests the no-op path
+
}
func TestLoadConfig_ConfigFileAllFields(t *testing.T) {
@@ -223,8 +220,6 @@ func TestLoadConfig_ConfigFileAllFields(t *testing.T) {
}
}
-// ── helpers ────────────────────────────────────────────────
-
// newBridgeWithFakeTab creates a Bridge with a real context.Context tab for testing
// handler dispatch logic without needing Chrome.
func newBridgeWithFakeTab() *Bridge {
@@ -232,7 +227,7 @@ func newBridgeWithFakeTab() *Bridge {
b.tabs = make(map[string]*TabEntry)
b.snapshots = make(map[string]*refCache)
ctx, cancel := context.WithCancel(context.Background())
- _ = cancel // leaked intentionally in tests
+ _ = cancel
b.tabs["tab1"] = &TabEntry{ctx: ctx, cancel: cancel}
return b
}
diff --git a/human.go b/human.go
index 21511233..d0a3e068 100644
--- a/human.go
+++ b/human.go
@@ -15,33 +15,28 @@ import (
// humanMouseMove performs natural mouse movement with bezier curves
func humanMouseMove(ctx context.Context, fromX, fromY, toX, toY float64) error {
- // Calculate distance for movement duration
+
distance := math.Sqrt((toX-fromX)*(toX-fromX) + (toY-fromY)*(toY-fromY))
- // Base duration: 100-400ms depending on distance (faster)
baseDuration := 100 + (distance/2000)*200
- duration := baseDuration + float64(rand.Intn(100)) // Add randomness
+ duration := baseDuration + float64(rand.Intn(100))
- // Number of steps (fewer steps = faster)
- steps := int(duration / 20) // ~50fps
+ steps := int(duration / 20)
if steps < 5 {
steps = 5
}
if steps > 30 {
- steps = 30 // Cap to prevent timeout
+ steps = 30
}
- // Generate control points for bezier curve (adds curvature)
cp1X := fromX + (toX-fromX)*0.25 + (rand.Float64()-0.5)*50
cp1Y := fromY + (toY-fromY)*0.25 + (rand.Float64()-0.5)*50
cp2X := fromX + (toX-fromX)*0.75 + (rand.Float64()-0.5)*50
cp2Y := fromY + (toY-fromY)*0.75 + (rand.Float64()-0.5)*50
- // Move along bezier curve
for i := 0; i <= steps; i++ {
t := float64(i) / float64(steps)
- // Cubic bezier formula
oneMinusT := 1 - t
x := oneMinusT*oneMinusT*oneMinusT*fromX +
3*oneMinusT*oneMinusT*t*cp1X +
@@ -53,7 +48,6 @@ func humanMouseMove(ctx context.Context, fromX, fromY, toX, toY float64) error {
3*oneMinusT*t*t*cp2Y +
t*t*t*toY
- // Add small jitter to make it more human
x += (rand.Float64() - 0.5) * 2
y += (rand.Float64() - 0.5) * 2
@@ -65,7 +59,6 @@ func humanMouseMove(ctx context.Context, fromX, fromY, toX, toY float64) error {
return err
}
- // Variable delay between movements
delay := time.Duration(16+rand.Intn(8)) * time.Millisecond
time.Sleep(delay)
}
@@ -75,16 +68,15 @@ func humanMouseMove(ctx context.Context, fromX, fromY, toX, toY float64) error {
// humanClick performs a click with natural mouse movement and timing
func humanClick(ctx context.Context, x, y float64) error {
- // Start from a position near the target (more realistic than cross-screen movements)
- startOffsetX := (rand.Float64()-0.5)*200 + 50 // 50-250 pixels away
+
+ startOffsetX := (rand.Float64()-0.5)*200 + 50
startOffsetY := (rand.Float64()-0.5)*200 + 50
startX := x + startOffsetX
startY := y + startOffsetY
- // Only do movement if we're far enough away
distance := math.Sqrt(startOffsetX*startOffsetX + startOffsetY*startOffsetY)
if distance > 30 {
- // Quick jump to general area
+
if err := chromedp.Run(ctx,
chromedp.ActionFunc(func(ctx context.Context) error {
return input.DispatchMouseEvent(input.MouseMoved, startX, startY).Do(ctx)
@@ -93,16 +85,13 @@ func humanClick(ctx context.Context, x, y float64) error {
return err
}
- // Then natural movement to exact position
if err := humanMouseMove(ctx, startX, startY, x, y); err != nil {
return err
}
}
- // Small pause before click (50-200ms)
time.Sleep(time.Duration(50+rand.Intn(150)) * time.Millisecond)
- // Mouse down
if err := chromedp.Run(ctx,
chromedp.ActionFunc(func(ctx context.Context) error {
return input.DispatchMouseEvent(input.MousePressed, x, y).
@@ -114,10 +103,8 @@ func humanClick(ctx context.Context, x, y float64) error {
return err
}
- // Hold for realistic duration (30-120ms)
time.Sleep(time.Duration(30+rand.Intn(90)) * time.Millisecond)
- // Mouse up (with slight position variance)
releaseX := x + (rand.Float64()-0.5)*2
releaseY := y + (rand.Float64()-0.5)*2
@@ -149,11 +136,9 @@ func humanClickElement(ctx context.Context, nodeID cdp.NodeID) error {
return fmt.Errorf("invalid box model")
}
- // Calculate center with slight randomness
centerX := (box.Content[0] + box.Content[2]) / 2
centerY := (box.Content[1] + box.Content[5]) / 2
- // Add small random offset (humans don't click exact center)
offsetX := (rand.Float64() - 0.5) * 10
offsetY := (rand.Float64() - 0.5) * 10
@@ -164,7 +149,6 @@ func humanClickElement(ctx context.Context, nodeID cdp.NodeID) error {
func humanType(text string, fast bool) []chromedp.Action {
actions := []chromedp.Action{}
- // Base typing speed (ms per character)
baseDelay := 80
if fast {
baseDelay = 40
@@ -172,33 +156,28 @@ func humanType(text string, fast bool) []chromedp.Action {
chars := []rune(text)
for i, char := range chars {
- // Type the character
+
actions = append(actions, chromedp.KeyEvent(string(char)))
- // Calculate delay
delay := baseDelay + rand.Intn(baseDelay/2)
- // Occasionally pause longer (thinking)
if rand.Float64() < 0.05 {
delay += rand.Intn(500)
}
- // Faster for repeated characters
if i > 0 && chars[i-1] == char {
delay = delay / 2
}
- // Add delay
actions = append(actions, chromedp.Sleep(time.Duration(delay)*time.Millisecond))
- // Occasional typos and corrections (3% chance, less annoying)
if rand.Float64() < 0.03 && i < len(chars)-1 {
- // Type wrong character
+
wrongChar := rune('a' + rand.Intn(26))
actions = append(actions,
chromedp.KeyEvent(string(wrongChar)),
chromedp.Sleep(time.Duration(50+rand.Intn(100))*time.Millisecond),
- chromedp.KeyEvent("\b"), // Backspace character
+ chromedp.KeyEvent("\b"),
chromedp.Sleep(time.Duration(30+rand.Intn(70))*time.Millisecond),
)
}
diff --git a/human_test.go b/human_test.go
index 2e6857b1..f3a5a07a 100644
--- a/human_test.go
+++ b/human_test.go
@@ -7,7 +7,7 @@ import (
)
func TestHumanMouseMove(t *testing.T) {
- // Test bezier calculation
+
testCases := []struct {
name string
fromX float64
@@ -30,7 +30,7 @@ func TestHumanMouseMove(t *testing.T) {
fromY: 0,
toX: 1000,
toY: 1000,
- maxSteps: 30, // Should be capped
+ maxSteps: 30,
},
{
name: "tiny distance",
@@ -38,22 +38,20 @@ func TestHumanMouseMove(t *testing.T) {
fromY: 100,
toX: 105,
toY: 105,
- maxSteps: 5, // Should be minimum
+ maxSteps: 5,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
- // Test distance calculation
+
distance := math.Sqrt((tc.toX-tc.fromX)*(tc.toX-tc.fromX) + (tc.toY-tc.fromY)*(tc.toY-tc.fromY))
- // Test duration calculation (from human.go logic)
baseDuration := 100 + (distance/2000)*200
if baseDuration < 100 {
t.Error("base duration too low")
}
- // Test steps calculation
steps := int(baseDuration / 20)
if steps < 5 {
steps = 5
@@ -69,14 +67,10 @@ func TestHumanMouseMove(t *testing.T) {
}
}
-// Note: bezier and getTypingPattern are unexported functions.
-// We test the public-facing behavior through action handlers instead.
-
func TestTypingTiming(t *testing.T) {
- // Test that typing delays are reasonable
+
startTime := time.Now()
- // Simulate typing pattern delays
baseDelay := 50
variations := []int{0, 20, 50, 100, 150}
@@ -86,7 +80,6 @@ func TestTypingTiming(t *testing.T) {
totalDelay += delay
}
- // Average should be around 50-150ms per character
avgDelay := totalDelay / 10
if avgDelay < 30 || avgDelay > 200 {
t.Errorf("average typing delay out of range: %dms", avgDelay)
diff --git a/integration_test.go b/integration_test.go
index 119cb19c..f8b30f95 100644
--- a/integration_test.go
+++ b/integration_test.go
@@ -1,5 +1,5 @@
-//go:build integration
-
+// TestCDPTimezoneOverride verifies that Emulation.
+// TestStealthStatusEndpoint verifies the /stealth/status handler returns valid data with a live browser.
package main
import (
@@ -19,7 +19,6 @@ import (
"github.com/chromedp/chromedp"
)
-// testBridge spins up a headless Chrome and returns a ready Bridge + cleanup func.
func testBridge(t *testing.T) (*Bridge, func()) {
t.Helper()
@@ -33,7 +32,6 @@ func testBridge(t *testing.T) (*Bridge, func()) {
allocCtx, allocCancel := chromedp.NewExecAllocator(context.Background(), opts...)
browserCtx, browserCancel := chromedp.NewContext(allocCtx)
- // Inject stealth script with seed (mirrors main.go)
seed := rand.Intn(1000000000)
seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\n", seed) + stealthScript
if err := chromedp.Run(browserCtx,
@@ -62,7 +60,6 @@ func testBridge(t *testing.T) (*Bridge, func()) {
}
}
-// navigateAndWait navigates the bridge's first tab to a data URL and waits for load.
func navigateAndWait(t *testing.T, b *Bridge, dataURL string) {
t.Helper()
ctx, _, err := b.TabContext("")
@@ -86,7 +83,6 @@ func TestStealthScriptInjected(t *testing.T) {
tCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
- // navigator.webdriver is set to undefined by stealth script, not false
var result string
if err := chromedp.Run(tCtx, chromedp.Evaluate(`String(navigator.webdriver)`, &result)); err != nil {
t.Fatalf("evaluate: %v", err)
@@ -94,7 +90,7 @@ func TestStealthScriptInjected(t *testing.T) {
if result == "true" {
t.Error("navigator.webdriver should not be true (stealth script not working)")
}
- // Accept "undefined" or "false" — both indicate stealth is working
+
if result != "undefined" && result != "false" {
t.Errorf("navigator.webdriver = %q, want 'undefined' or 'false'", result)
}
@@ -104,7 +100,6 @@ func TestCanvasNoiseApplied(t *testing.T) {
b, cleanup := testBridge(t)
defer cleanup()
- // Page with a canvas
html := `data:text/html,<canvas id="c" width="200" height="50"></canvas>
<script>
var c = document.getElementById('c');
@@ -121,7 +116,6 @@ ctx.fillText('canvas fingerprint', 10, 30);
tCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
- // Get two toDataURL calls — stealth noise should make them differ
var result1, result2 string
script := `
(function() {
@@ -136,7 +130,6 @@ ctx.fillText('canvas fingerprint', 10, 30);
t.Fatalf("evaluate: %v", err)
}
- // Canvas noise adds random pixel changes per call
if result1 == result2 {
t.Error("toDataURL returned identical results — canvas noise not applied")
}
@@ -152,7 +145,6 @@ func TestFontMetricsNoise(t *testing.T) {
tCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
- // measureText should return slightly different widths due to noise
script := `
(function() {
var c = document.getElementById('c').getContext('2d');
@@ -181,9 +173,6 @@ func TestFontMetricsNoise(t *testing.T) {
t.Error("measureText result should be instanceof TextMetrics (Proxy not working)")
}
- // Font noise uses seeded PRNG — within same session, same input gives same noise.
- // Verify the Proxy wrapper works (instanceof check above) and that the width
- // is a reasonable number (not 0 or NaN).
if len(result.Widths) == 0 {
t.Fatal("no width measurements returned")
}
@@ -202,8 +191,6 @@ func TestWebGLVendorSpoofed(t *testing.T) {
tCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
- // In headless Chrome, WebGL may not be available (no GPU).
- // We test that the stealth override is installed even if WebGL context fails.
script := `
(function() {
var canvas = document.getElementById('gl');
@@ -262,7 +249,6 @@ func TestFingerprintRotation(t *testing.T) {
navigateAndWait(t, b, "data:text/html,<h1>rotate</h1>")
- // Call /fingerprint/rotate — now uses CDP-level SetUserAgentOverride (8F-7)
body := `{"os":"windows","browser":"edge","screen":"1920x1080"}`
req := httptest.NewRequest("POST", "/fingerprint/rotate", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
@@ -287,7 +273,6 @@ func TestFingerprintRotation(t *testing.T) {
t.Errorf("expected Edge UA in fingerprint, got: %s", newUA)
}
- // Verify UA changed in browser (CDP override is immediate, no navigation needed)
ctx2, _, _ := b.TabContext("")
tCtx2, cancel2 := context.WithTimeout(ctx2, 5*time.Second)
defer cancel2()
@@ -301,12 +286,10 @@ func TestFingerprintRotation(t *testing.T) {
}
}
-// TestCDPTimezoneOverride verifies that Emulation.setTimezoneOverride works at CDP level.
func TestCDPTimezoneOverride(t *testing.T) {
b, cleanup := testBridge(t)
defer cleanup()
- // Apply CDP timezone override
ctx, _, _ := b.TabContext("")
tCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
@@ -335,7 +318,6 @@ func TestCDPTimezoneOverride(t *testing.T) {
}
}
-// TestStealthStatusEndpoint verifies the /stealth/status handler returns valid data with a live browser.
func TestStealthStatusEndpoint(t *testing.T) {
b, cleanup := testBridge(t)
defer cleanup()
diff --git a/interfaces.go b/interfaces.go
index b82289c8..9ff3d7fd 100644
--- a/interfaces.go
+++ b/interfaces.go
@@ -1,4 +1,6 @@
-package main
+package // BridgeAPI is the interface handlers use to interact with Chrome.
+// TabInfo is a simplified tab descriptor for JSON responses.
+main
import (
"context"
@@ -6,22 +8,17 @@ import (
"github.com/chromedp/cdproto/target"
)
-// BridgeAPI is the interface handlers use to interact with Chrome.
-// Bridge implements this. Tests can mock it.
type BridgeAPI interface {
- // Tab management
TabContext(tabID string) (ctx context.Context, resolvedID string, err error)
ListTargets() ([]*target.Info, error)
CreateTab(url string) (tabID string, ctx context.Context, cancel context.CancelFunc, err error)
CloseTab(tabID string) error
- // Snapshot cache
GetRefCache(tabID string) *refCache
SetRefCache(tabID string, cache *refCache)
DeleteRefCache(tabID string)
}
-// TabInfo is a simplified tab descriptor for JSON responses.
type TabInfo struct {
ID string `json:"id"`
URL string `json:"url"`
diff --git a/lock.go b/lock.go
index 4e728895..12eb0a06 100644
--- a/lock.go
+++ b/lock.go
@@ -1,4 +1,9 @@
-package main
+package // TabLock represents an active lock held by an agent on a tab.
+// Lock acquires a lock on a tab for the given owner.
+// Unlock releases a lock.
+// Get returns the lock info for a tab, or nil if unlocked/expired.
+// CheckAccess returns an error if the tab is locked by someone other than owner.
+main
import (
"fmt"
@@ -6,16 +11,14 @@ import (
"time"
)
-// TabLock represents an active lock held by an agent on a tab.
type TabLock struct {
Owner string `json:"owner"`
LockedAt time.Time `json:"lockedAt"`
ExpiresAt time.Time `json:"expiresAt"`
}
-// lockManager handles tab locking with timeout-based deadlock prevention.
type lockManager struct {
- locks map[string]*TabLock // tabID → lock
+ locks map[string]*TabLock
mu sync.Mutex
}
@@ -28,8 +31,6 @@ func newLockManager() *lockManager {
return &lockManager{locks: make(map[string]*TabLock)}
}
-// Lock acquires a lock on a tab for the given owner. Returns error if already
-// locked by a different owner (and not expired).
func (lm *lockManager) Lock(tabID, owner string, timeout time.Duration) error {
if owner == "" {
return fmt.Errorf("owner required")
@@ -58,14 +59,13 @@ func (lm *lockManager) Lock(tabID, owner string, timeout time.Duration) error {
return nil
}
-// Unlock releases a lock. Only the owner (or anyone after expiry) can unlock.
func (lm *lockManager) Unlock(tabID, owner string) error {
lm.mu.Lock()
defer lm.mu.Unlock()
existing, ok := lm.locks[tabID]
if !ok {
- return nil // not locked, idempotent
+ return nil
}
if existing.Owner != owner && time.Now().Before(existing.ExpiresAt) {
@@ -76,7 +76,6 @@ func (lm *lockManager) Unlock(tabID, owner string) error {
return nil
}
-// Get returns the lock info for a tab, or nil if unlocked/expired.
func (lm *lockManager) Get(tabID string) *TabLock {
lm.mu.Lock()
defer lm.mu.Unlock()
@@ -92,7 +91,6 @@ func (lm *lockManager) Get(tabID string) *TabLock {
return lock
}
-// CheckAccess returns an error if the tab is locked by someone other than owner.
func (lm *lockManager) CheckAccess(tabID, owner string) error {
lock := lm.Get(tabID)
if lock == nil {
diff --git a/lock_handler_test.go b/lock_handler_test.go
index 5d83edf9..24d054f9 100644
--- a/lock_handler_test.go
+++ b/lock_handler_test.go
@@ -11,7 +11,6 @@ import (
func TestHandleTabLock(t *testing.T) {
b := &Bridge{locks: newLockManager()}
- // Lock a tab
body, _ := json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-a", "timeoutSec": 10})
w := httptest.NewRecorder()
r, _ := http.NewRequest("POST", "/tab/lock", bytes.NewReader(body))
@@ -30,7 +29,6 @@ func TestHandleTabLock(t *testing.T) {
t.Fatalf("expected owner=agent-a: %v", resp)
}
- // Conflict from different owner
body, _ = json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-b"})
w = httptest.NewRecorder()
r, _ = http.NewRequest("POST", "/tab/lock", bytes.NewReader(body))
@@ -45,7 +43,6 @@ func TestHandleTabUnlock(t *testing.T) {
b := &Bridge{locks: newLockManager()}
_ = b.locks.Lock("t1", "agent-a", 0)
- // Wrong owner
body, _ := json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-b"})
w := httptest.NewRecorder()
r, _ := http.NewRequest("POST", "/tab/unlock", bytes.NewReader(body))
@@ -54,7 +51,6 @@ func TestHandleTabUnlock(t *testing.T) {
t.Fatalf("expected 409, got %d", w.Code)
}
- // Correct owner
body, _ = json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-a"})
w = httptest.NewRecorder()
r, _ = http.NewRequest("POST", "/tab/unlock", bytes.NewReader(body))
@@ -67,7 +63,6 @@ func TestHandleTabUnlock(t *testing.T) {
func TestHandleTabLockValidation(t *testing.T) {
b := &Bridge{locks: newLockManager()}
- // Missing fields
body, _ := json.Marshal(map[string]any{"tabId": "t1"})
w := httptest.NewRecorder()
r, _ := http.NewRequest("POST", "/tab/lock", bytes.NewReader(body))
diff --git a/lock_test.go b/lock_test.go
index 1398d36a..a6a622b3 100644
--- a/lock_test.go
+++ b/lock_test.go
@@ -8,27 +8,22 @@ import (
func TestLockBasic(t *testing.T) {
lm := newLockManager()
- // Lock succeeds
if err := lm.Lock("tab1", "agent-a", 5*time.Second); err != nil {
t.Fatal(err)
}
- // Same owner can re-lock (extend)
if err := lm.Lock("tab1", "agent-a", 5*time.Second); err != nil {
t.Fatal(err)
}
- // Different owner blocked
if err := lm.Lock("tab1", "agent-b", 5*time.Second); err == nil {
t.Fatal("expected lock conflict")
}
- // Unlock
if err := lm.Unlock("tab1", "agent-a"); err != nil {
t.Fatal(err)
}
- // Now agent-b can lock
if err := lm.Lock("tab1", "agent-b", 5*time.Second); err != nil {
t.Fatal(err)
}
@@ -42,7 +37,6 @@ func TestLockExpiry(t *testing.T) {
}
time.Sleep(5 * time.Millisecond)
- // Expired — different owner can now lock
if err := lm.Lock("tab1", "agent-b", 5*time.Second); err != nil {
t.Fatalf("expected expired lock to allow new owner: %v", err)
}
@@ -51,24 +45,20 @@ func TestLockExpiry(t *testing.T) {
func TestLockCheckAccess(t *testing.T) {
lm := newLockManager()
- // No lock — anyone can access
if err := lm.CheckAccess("tab1", "anyone"); err != nil {
t.Fatal(err)
}
_ = lm.Lock("tab1", "agent-a", 5*time.Second)
- // Owner can access
if err := lm.CheckAccess("tab1", "agent-a"); err != nil {
t.Fatal(err)
}
- // Non-owner blocked
if err := lm.CheckAccess("tab1", "agent-b"); err == nil {
t.Fatal("expected access denied")
}
- // Empty owner blocked
if err := lm.CheckAccess("tab1", ""); err == nil {
t.Fatal("expected access denied for empty owner")
}
@@ -77,7 +67,6 @@ func TestLockCheckAccess(t *testing.T) {
func TestUnlockIdempotent(t *testing.T) {
lm := newLockManager()
- // Unlocking a non-locked tab is fine
if err := lm.Unlock("tab1", "anyone"); err != nil {
t.Fatal(err)
}
@@ -94,13 +83,13 @@ func TestUnlockWrongOwner(t *testing.T) {
func TestMaxTimeout(t *testing.T) {
lm := newLockManager()
- _ = lm.Lock("tab1", "agent-a", 10*time.Minute) // exceeds max
+ _ = lm.Lock("tab1", "agent-a", 10*time.Minute)
lock := lm.Get("tab1")
if lock == nil {
t.Fatal("expected lock")
}
- // Should be capped to maxLockTimeout (5 min)
+
maxExpiry := time.Now().Add(maxLockTimeout + time.Second)
if lock.ExpiresAt.After(maxExpiry) {
t.Fatalf("lock timeout not capped: expires %v", lock.ExpiresAt)
diff --git a/main.go b/main.go
index 5cc156ad..ca89eafd 100644
--- a/main.go
+++ b/main.go
@@ -29,7 +29,7 @@ const chromeStartTimeout = 15 * time.Second
var bridge Bridge
func main() {
- // Load configuration from file or environment
+
loadConfig()
if len(os.Args) > 1 && (os.Args[1] == "--version" || os.Args[1] == "-v") {
@@ -37,13 +37,11 @@ func main() {
os.Exit(0)
}
- // Handle config generation
if len(os.Args) > 1 && os.Args[1] == "config" {
handleConfigCommand()
os.Exit(0)
}
- // Dashboard-only mode — no Chrome, just UI + orchestrator
if len(os.Args) > 1 && os.Args[1] == "dashboard" {
runDashboard()
return
@@ -66,7 +64,6 @@ func main() {
os.Exit(1)
}
- // Remove stale Chrome lock files from unclean shutdowns.
for _, lockName := range []string{"SingletonLock", "SingletonSocket", "SingletonCookie"} {
lockPath := fmt.Sprintf("%s/%s", profileDir, lockName)
if err := os.Remove(lockPath); err == nil {
@@ -74,8 +71,6 @@ func main() {
}
}
- // Detect unclean previous exit and clear Chrome's session restore data
- // to prevent hanging on restored tabs that fail to load.
if wasUncleanExit() {
slog.Warn("previous session exited uncleanly, clearing Chrome session restore data")
clearChromeSessions()
@@ -84,12 +79,11 @@ func main() {
slog.Info("launching Chrome", "profile", profileDir, "headless", headless)
chromeOpts = []chromedp.ExecAllocatorOption{
- // Profile & basics
+
chromedp.UserDataDir(profileDir),
chromedp.NoFirstRun,
chromedp.NoDefaultBrowserCheck,
- // Advanced stealth: hide automation indicators
chromedp.Flag("exclude-switches", "enable-automation"),
chromedp.Flag("disable-infobars", true),
chromedp.Flag("disable-dev-shm-usage", true),
@@ -103,21 +97,17 @@ func main() {
chromedp.Flag("disable-sync", true),
chromedp.Flag("disable-web-security", false),
- // Performance & networking
chromedp.Flag("disable-background-networking", false),
chromedp.Flag("enable-features", "NetworkService,NetworkServiceInProcess"),
chromedp.Flag("disable-popup-blocking", true),
chromedp.Flag("no-first-run", true),
- // UI: suppress crash bar and notifications
chromedp.Flag("disable-session-crashed-bubble", true),
chromedp.Flag("hide-crash-restore-bubble", true),
chromedp.Flag("disable-device-discovery-notifications", true),
- // Random seed for consistent behavior across runs
chromedp.Flag("js-flags", "--random-seed=1157259157"),
- // Window size (UA left as Chrome default to avoid detection mismatches)
chromedp.WindowSize(1366, 768),
}
@@ -145,13 +135,10 @@ func main() {
}
defer allocCancel()
- // Prepare stealth script
stealthSeed := rand.Intn(1000000000)
seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", stealthSeed, stealthLevel) + stealthScript
bridge.stealthScript = seededScript
- // startChrome connects to Chrome with a timeout. Returns browserCtx and cancel,
- // or an error if Chrome doesn't respond within chromeStartTimeout.
startChrome := func() (context.Context, context.CancelFunc, error) {
bCtx, bCancel := chromedp.NewContext(bridge.allocCtx)
@@ -185,19 +172,16 @@ func main() {
if err != nil {
slog.Warn("Chrome startup failed, clearing sessions and retrying once", "err", err)
- // Kill the hung Chrome process and clean up.
allocCancel()
clearChromeSessions()
markCleanExit()
- // Re-create allocator for retry.
if cdpURL != "" {
bridge.allocCtx, allocCancel = chromedp.NewRemoteAllocator(context.Background(), cdpURL)
} else {
bridge.allocCtx, allocCancel = chromedp.NewExecAllocator(context.Background(), chromeOpts...)
}
- // Retry once.
browserCtx, browserCancel, err = startChrome()
if err != nil {
slog.Error("Chrome failed to start after retry",
@@ -212,7 +196,6 @@ func main() {
}
defer browserCancel()
- // CDP-level timezone override (more reliable than JS-only approach)
if timezone != "" {
if err := chromedp.Run(browserCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
@@ -231,18 +214,15 @@ func main() {
bridge.initActionRegistry()
bridge.locks = newLockManager()
- // Profile manager + dashboard + orchestrator
profilesDir := filepath.Join(filepath.Dir(profileDir), "profiles")
profMgr := NewProfileManager(profilesDir)
- dashboard := NewDashboard(nil) // use default config
+ dashboard := NewDashboard(nil)
orchestrator := NewOrchestrator(profilesDir)
- // Register the initial tab
initTargetID := chromedp.FromContext(browserCtx).Target.TargetID
bridge.tabs[string(initTargetID)] = &TabEntry{ctx: browserCtx}
slog.Info("initial tab", "id", string(initTargetID))
- // Navigate initial tab to welcome page in headed mode (after server starts)
if !headless {
go func() {
time.Sleep(200 * time.Millisecond)
@@ -251,16 +231,14 @@ func main() {
}
if !noRestore {
- // Restore in background so it doesn't block the HTTP server
+
go bridge.RestoreState()
}
- // Background tab cleanup
cleanupCtx, cleanupCancel := context.WithCancel(context.Background())
defer cleanupCancel()
go bridge.CleanStaleTabs(cleanupCtx, 30*actionTimeout)
- // Routes
mux := http.NewServeMux()
mux.HandleFunc("GET /health", bridge.handleHealth)
mux.HandleFunc("GET /tabs", bridge.handleTabs)
@@ -285,14 +263,12 @@ func main() {
_, _ = w.Write([]byte(welcomeHTML))
})
- // Profile management + dashboard + orchestrator
profMgr.RegisterHandlers(mux)
dashboard.RegisterHandlers(mux)
if os.Getenv("BRIDGE_NO_DASHBOARD") == "" {
orchestrator.RegisterHandlers(mux)
}
- // Profile tracking observer — records per-profile analytics
profileObserver := func(evt AgentEvent) {
if evt.Profile != "" {
profMgr.tracker.Record(evt.Profile, ActionRecord{
@@ -312,7 +288,6 @@ func main() {
loggingMiddleware(corsMiddleware(authMiddleware(mux))),
)}
- // Shutdown orchestration — used by both signal handler and /shutdown endpoint.
shutdownOnce := &sync.Once{}
doShutdown := func() {
shutdownOnce.Do(func() {
@@ -322,24 +297,20 @@ func main() {
bridge.SaveState()
markCleanExit()
- // Shut down HTTP server first so no new requests come in.
shutdownCtx, shutdownDone := context.WithTimeout(context.Background(), shutdownTimeout)
defer shutdownDone()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown http", "err", err)
}
- // Explicitly close Chrome by canceling the browser and allocator contexts.
browserCancel()
allocCancel()
slog.Info("chrome closed")
})
}
- // Wire up /shutdown endpoint (requires auth like all other endpoints).
mux.HandleFunc("POST /shutdown", bridge.handleShutdown(doShutdown))
- // Signal handler.
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
@@ -354,9 +325,8 @@ func main() {
slog.Info("auth disabled (set BRIDGE_TOKEN to enable)")
}
- // Startup self-check: verify the server can respond within 5s.
go func() {
- time.Sleep(500 * time.Millisecond) // let ListenAndServe bind
+ time.Sleep(500 * time.Millisecond)
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(fmt.Sprintf("http://localhost:%s/health", port))
if err != nil {
diff --git a/middleware_test.go b/middleware_test.go
index c3bc1a64..470bcf92 100644
--- a/middleware_test.go
+++ b/middleware_test.go
@@ -40,7 +40,7 @@ func TestJsonErr(t *testing.T) {
}
func TestAuthMiddleware_NoToken(t *testing.T) {
- // When token is empty, all requests pass through
+
origToken := token
token = ""
defer func() { token = origToken }()
@@ -109,7 +109,6 @@ func TestCorsMiddleware(t *testing.T) {
w.WriteHeader(200)
}))
- // OPTIONS should return 204
req := httptest.NewRequest("OPTIONS", "/test", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
@@ -120,7 +119,6 @@ func TestCorsMiddleware(t *testing.T) {
t.Error("missing CORS origin header")
}
- // GET should pass through with CORS headers
req = httptest.NewRequest("GET", "/test", nil)
w = httptest.NewRecorder()
handler.ServeHTTP(w, req)
diff --git a/orchestrator.go b/orchestrator.go
index 046de931..a5fc6cb6 100644
--- a/orchestrator.go
+++ b/orchestrator.go
@@ -1,4 +1,10 @@
-package main
+package // Launch starts a new Pinchtab instance on a named profile.
+// Stop kills a running instance.
+// List returns all instances with live status.
+// Logs returns the log buffer for an instance.
+// AllTabs aggregates tabs from all running instances.
+// ProxyScreencastURL returns the WebSocket URL for a child instance's screencast.
+main
import (
"context"
@@ -15,14 +21,10 @@ import (
"time"
)
-// ---------------------------------------------------------------------------
-// Orchestrator — manages multiple Pinchtab instances from one dashboard
-// ---------------------------------------------------------------------------
-
type Orchestrator struct {
instances map[string]*Instance
- baseDir string // ~/.pinchtab/profiles
- binary string // path to pinchtab binary (or "go run .")
+ baseDir string
+ binary string
mu sync.RWMutex
client *http.Client
}
@@ -33,7 +35,7 @@ type Instance struct {
Profile string `json:"profile"`
Port string `json:"port"`
Headless bool `json:"headless"`
- Status string `json:"status"` // "starting", "running", "stopped", "error"
+ Status string `json:"status"`
PID int `json:"pid,omitempty"`
StartedAt time.Time `json:"startedAt"`
Error string `json:"error,omitempty"`
@@ -45,7 +47,6 @@ type Instance struct {
logBuf *ringBuffer
}
-// ringBuffer keeps the last N bytes of output for log viewing.
type ringBuffer struct {
mu sync.Mutex
data []byte
@@ -73,17 +74,13 @@ func (rb *ringBuffer) String() string {
}
func NewOrchestrator(baseDir string) *Orchestrator {
- // Resolve a stable binary path:
- // 1. ~/.pinchtab/bin/pinchtab (installed)
- // 2. Build from source if go available
- // 3. os.Executable() fallback (fragile with go run)
+
binDir := filepath.Join(filepath.Dir(baseDir), "bin")
stableBin := filepath.Join(binDir, "pinchtab")
- // If stable binary doesn't exist or is older than source, rebuild
needsBuild := true
if fi, err := os.Stat(stableBin); err == nil {
- // Exists — check if it's recent enough (within 1 hour)
+
if time.Since(fi.ModTime()) < time.Hour {
needsBuild = false
}
@@ -91,7 +88,7 @@ func NewOrchestrator(baseDir string) *Orchestrator {
if needsBuild {
os.MkdirAll(binDir, 0755)
- // Try to copy current executable
+
exe, _ := os.Executable()
if exe != "" {
if data, err := os.ReadFile(exe); err == nil {
@@ -104,7 +101,7 @@ func NewOrchestrator(baseDir string) *Orchestrator {
binary := stableBin
if _, err := os.Stat(binary); err != nil {
- // Fallback
+
binary, _ = os.Executable()
if binary == "" {
binary = os.Args[0]
@@ -119,12 +116,10 @@ func NewOrchestrator(baseDir string) *Orchestrator {
}
}
-// Launch starts a new Pinchtab instance on a named profile.
func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, error) {
o.mu.Lock()
defer o.mu.Unlock()
- // Check port not already used
for _, inst := range o.instances {
if inst.Port == port && inst.Status == "running" {
return nil, fmt.Errorf("port %s already in use by instance %q", port, inst.Name)
@@ -152,13 +147,13 @@ func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, erro
"BRIDGE_PROFILE="+profilePath,
"BRIDGE_HEADLESS="+headlessStr,
"BRIDGE_NO_RESTORE=true",
- // Don't start sub-orchestrators
+
"BRIDGE_NO_DASHBOARD=true",
)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
- logBuf := newRingBuffer(64 * 1024) // 64KB log buffer
+ logBuf := newRingBuffer(64 * 1024)
cmd.Stdout = logBuf
cmd.Stderr = logBuf
@@ -184,14 +179,13 @@ func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, erro
inst.PID = cmd.Process.Pid
o.instances[id] = inst
- // Monitor process + wait for healthy
go o.monitor(inst)
return inst, nil
}
func (o *Orchestrator) monitor(inst *Instance) {
- // Wait for health check to pass
+
healthy := false
for i := 0; i < 30; i++ {
time.Sleep(500 * time.Millisecond)
@@ -216,7 +210,6 @@ func (o *Orchestrator) monitor(inst *Instance) {
}
o.mu.Unlock()
- // Wait for process to exit
err := inst.cmd.Wait()
o.mu.Lock()
if inst.Status != "stopped" {
@@ -229,7 +222,6 @@ func (o *Orchestrator) monitor(inst *Instance) {
slog.Info("instance exited", "id", inst.ID)
}
-// Stop kills a running instance.
func (o *Orchestrator) Stop(id string) error {
o.mu.Lock()
inst, ok := o.instances[id]
@@ -240,16 +232,14 @@ func (o *Orchestrator) Stop(id string) error {
inst.Status = "stopped"
o.mu.Unlock()
- // Graceful shutdown via API first
req, _ := http.NewRequest("POST", inst.URL+"/shutdown", nil)
resp, err := o.client.Do(req)
if err == nil {
resp.Body.Close()
- // Wait a moment for graceful exit
+
time.Sleep(2 * time.Second)
}
- // Force kill the whole process group (including Chrome children)
if inst.cmd.ProcessState == nil || !inst.cmd.ProcessState.Exited() {
_ = syscall.Kill(-inst.cmd.Process.Pid, syscall.SIGKILL)
inst.cancel()
@@ -258,7 +248,6 @@ func (o *Orchestrator) Stop(id string) error {
return nil
}
-// List returns all instances with live status.
func (o *Orchestrator) List() []Instance {
o.mu.RLock()
defer o.mu.RUnlock()
@@ -270,7 +259,6 @@ func (o *Orchestrator) List() []Instance {
copy.cancel = nil
copy.logBuf = nil
- // Fetch live tab count for running instances
if inst.Status == "running" {
if tabs, err := o.fetchTabs(inst.URL); err == nil {
copy.TabCount = len(tabs)
@@ -282,7 +270,6 @@ func (o *Orchestrator) List() []Instance {
return result
}
-// Logs returns the log buffer for an instance.
func (o *Orchestrator) Logs(id string) (string, error) {
o.mu.RLock()
defer o.mu.RUnlock()
@@ -294,7 +281,6 @@ func (o *Orchestrator) Logs(id string) (string, error) {
return inst.logBuf.String(), nil
}
-// AllTabs aggregates tabs from all running instances.
func (o *Orchestrator) AllTabs() []instanceTab {
o.mu.RLock()
instances := make([]*Instance, 0)
@@ -348,10 +334,6 @@ func (o *Orchestrator) fetchTabs(baseURL string) ([]remoteTab, error) {
return tabs, nil
}
-// ---------------------------------------------------------------------------
-// HTTP Handlers
-// ---------------------------------------------------------------------------
-
func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("GET /instances", o.handleList)
mux.HandleFunc("POST /instances/launch", o.handleLaunch)
@@ -416,7 +398,6 @@ func (o *Orchestrator) handleAllTabs(w http.ResponseWriter, r *http.Request) {
jsonResp(w, 200, o.AllTabs())
}
-// handleProxyScreencast proxies a WebSocket screencast from a child instance.
func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
tabID := r.URL.Query().Get("tabId")
@@ -429,13 +410,10 @@ func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Requ
return
}
- // Proxy the WebSocket connection to the child instance
- // For now, redirect — the dashboard JS will connect directly
targetURL := fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)
jsonResp(w, 200, map[string]string{"wsUrl": targetURL})
}
-// ProxyScreencastURL returns the WebSocket URL for a child instance's screencast.
func (o *Orchestrator) ScreencastURL(instanceID, tabID string) string {
o.mu.RLock()
defer o.mu.RUnlock()
@@ -446,10 +424,6 @@ func (o *Orchestrator) ScreencastURL(instanceID, tabID string) string {
return fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)
}
-// ---------------------------------------------------------------------------
-// Cleanup — stop all instances on shutdown
-// ---------------------------------------------------------------------------
-
func (o *Orchestrator) Shutdown() {
o.mu.RLock()
ids := make([]string, 0, len(o.instances))
@@ -466,7 +440,6 @@ func (o *Orchestrator) Shutdown() {
}
}
-// readAll reads response body up to limit bytes
func readAll(r io.Reader, limit int64) ([]byte, error) {
return io.ReadAll(io.LimitReader(r, limit))
}
diff --git a/profiles.go b/profiles.go
index 2364d40a..9e1825f7 100644
--- a/profiles.go
+++ b/profiles.go
@@ -1,4 +1,12 @@
-package main
+package // List returns all managed profiles.
+// Import copies an existing Chrome user data directory as a named profile.
+// Create makes a fresh empty profile directory.
+// Reset clears session data and caches but preserves bookmarks, extensions, passwords.
+// Delete removes a profile entirely.
+// Logs returns recent Chrome/Pinchtab logs for a profile.
+// Analytics returns action patterns and optimization suggestions.
+// TrackingMiddleware returns middleware that records actions per profile.
+main
import (
"encoding/json"
@@ -16,12 +24,8 @@ import (
"os/exec"
)
-// ---------------------------------------------------------------------------
-// Profile Manager — manages named Chrome profiles under ~/.pinchtab/profiles/
-// ---------------------------------------------------------------------------
-
type ProfileManager struct {
- baseDir string // e.g. ~/.pinchtab/profiles
+ baseDir string
tracker *ActionTracker
mu sync.RWMutex
}
@@ -31,7 +35,7 @@ type ProfileInfo struct {
Path string `json:"path"`
CreatedAt time.Time `json:"createdAt"`
SizeMB float64 `json:"sizeMB"`
- Source string `json:"source,omitempty"` // "imported", "created"
+ Source string `json:"source,omitempty"`
}
func NewProfileManager(baseDir string) *ProfileManager {
@@ -42,7 +46,6 @@ func NewProfileManager(baseDir string) *ProfileManager {
}
}
-// List returns all managed profiles.
func (pm *ProfileManager) List() ([]ProfileInfo, error) {
pm.mu.RLock()
defer pm.mu.RUnlock()
@@ -53,7 +56,7 @@ func (pm *ProfileManager) List() ([]ProfileInfo, error) {
}
var profiles []ProfileInfo
- // Directories that aren't profiles
+
skip := map[string]bool{"bin": true, "profiles": true}
for _, e := range entries {
if !e.IsDir() || skip[e.Name()] {
@@ -63,7 +66,7 @@ func (pm *ProfileManager) List() ([]ProfileInfo, error) {
if err != nil {
continue
}
- // Must have a Default/ subdirectory to be a valid Chrome profile
+
if _, err := os.Stat(filepath.Join(pm.baseDir, e.Name(), "Default")); err != nil {
continue
}
@@ -95,7 +98,6 @@ func (pm *ProfileManager) profileInfo(name string) (ProfileInfo, error) {
}, nil
}
-// Import copies an existing Chrome user data directory as a named profile.
func (pm *ProfileManager) Import(name, sourcePath string) error {
pm.mu.Lock()
defer pm.mu.Unlock()
@@ -105,9 +107,8 @@ func (pm *ProfileManager) Import(name, sourcePath string) error {
return fmt.Errorf("profile %q already exists", name)
}
- // Validate source looks like a Chrome profile
if _, err := os.Stat(filepath.Join(sourcePath, "Default")); err != nil {
- // Maybe it IS the Default folder
+
if _, err2 := os.Stat(filepath.Join(sourcePath, "Preferences")); err2 != nil {
return fmt.Errorf("source doesn't look like a Chrome user data dir (no Default/ or Preferences found)")
}
@@ -118,12 +119,10 @@ func (pm *ProfileManager) Import(name, sourcePath string) error {
return fmt.Errorf("copy failed: %w", err)
}
- // Mark as imported
os.WriteFile(filepath.Join(dest, ".pinchtab-imported"), []byte(sourcePath), 0644)
return nil
}
-// Create makes a fresh empty profile directory.
func (pm *ProfileManager) Create(name string) error {
pm.mu.Lock()
defer pm.mu.Unlock()
@@ -135,7 +134,6 @@ func (pm *ProfileManager) Create(name string) error {
return os.MkdirAll(filepath.Join(dest, "Default"), 0755)
}
-// Reset clears session data and caches but preserves bookmarks, extensions, passwords.
func (pm *ProfileManager) Reset(name string) error {
pm.mu.Lock()
defer pm.mu.Unlock()
@@ -145,7 +143,6 @@ func (pm *ProfileManager) Reset(name string) error {
return fmt.Errorf("profile %q not found", name)
}
- // Directories to nuke (session/cache data)
nukeDirs := []string{
"Default/Sessions",
"Default/Session Storage",
@@ -181,7 +178,6 @@ func (pm *ProfileManager) Reset(name string) error {
return nil
}
-// Delete removes a profile entirely.
func (pm *ProfileManager) Delete(name string) error {
pm.mu.Lock()
defer pm.mu.Unlock()
@@ -193,41 +189,35 @@ func (pm *ProfileManager) Delete(name string) error {
return os.RemoveAll(dir)
}
-// Logs returns recent Chrome/Pinchtab logs for a profile.
func (pm *ProfileManager) Logs(name string, limit int) []ActionRecord {
return pm.tracker.GetLogs(name, limit)
}
-// Analytics returns action patterns and optimization suggestions.
func (pm *ProfileManager) Analytics(name string) AnalyticsReport {
return pm.tracker.Analyze(name)
}
-// ---------------------------------------------------------------------------
-// Action Tracker — records API calls per profile for pattern analysis
-// ---------------------------------------------------------------------------
-
type ActionTracker struct {
mu sync.Mutex
- records map[string][]ActionRecord // profile -> records
+ records map[string][]ActionRecord
}
type ActionRecord struct {
- Timestamp time.Time `json:"timestamp"`
- Method string `json:"method"`
- Endpoint string `json:"endpoint"`
- URL string `json:"url,omitempty"` // target page URL if relevant
- TabID string `json:"tabId,omitempty"`
- DurationMs int64 `json:"durationMs"`
- Status int `json:"status"`
+ Timestamp time.Time `json:"timestamp"`
+ Method string `json:"method"`
+ Endpoint string `json:"endpoint"`
+ URL string `json:"url,omitempty"`
+ TabID string `json:"tabId,omitempty"`
+ DurationMs int64 `json:"durationMs"`
+ Status int `json:"status"`
}
type AnalyticsReport struct {
- TotalActions int `json:"totalActions"`
- Since time.Time `json:"since"`
- TopEndpoints []EndpointCount `json:"topEndpoints"`
- RepeatPatterns []RepeatPattern `json:"repeatPatterns"`
- Suggestions []string `json:"suggestions"`
+ TotalActions int `json:"totalActions"`
+ Since time.Time `json:"since"`
+ TopEndpoints []EndpointCount `json:"topEndpoints"`
+ RepeatPatterns []RepeatPattern `json:"repeatPatterns"`
+ Suggestions []string `json:"suggestions"`
}
type EndpointCount struct {
@@ -237,8 +227,8 @@ type EndpointCount struct {
}
type RepeatPattern struct {
- Pattern string `json:"pattern"`
- Count int `json:"count"`
+ Pattern string `json:"pattern"`
+ Count int `json:"count"`
AvgGapSec float64 `json:"avgGapSec"`
}
@@ -254,7 +244,7 @@ func (at *ActionTracker) Record(profile string, rec ActionRecord) {
recs := at.records[profile]
recs = append(recs, rec)
- // Keep last 10000 records per profile
+
if len(recs) > 10000 {
recs = recs[len(recs)-10000:]
}
@@ -269,7 +259,7 @@ func (at *ActionTracker) GetLogs(profile string, limit int) []ActionRecord {
if limit <= 0 || limit > len(recs) {
limit = len(recs)
}
- // Return most recent
+
start := len(recs) - limit
result := make([]ActionRecord, limit)
copy(result, recs[start:])
@@ -290,8 +280,10 @@ func (at *ActionTracker) Analyze(profile string) AnalyticsReport {
Since: recs[0].Timestamp,
}
- // Top endpoints
- epCounts := map[string]struct{ count int; totalMs int64 }{}
+ epCounts := map[string]struct {
+ count int
+ totalMs int64
+ }{}
for _, r := range recs {
v := epCounts[r.Endpoint]
v.count++
@@ -312,7 +304,6 @@ func (at *ActionTracker) Analyze(profile string) AnalyticsReport {
report.TopEndpoints = report.TopEndpoints[:10]
}
- // Detect repeated snapshot patterns (same URL polled frequently)
urlSnaps := map[string][]time.Time{}
for _, r := range recs {
if r.Endpoint == "/snapshot" && r.URL != "" {
@@ -335,7 +326,6 @@ func (at *ActionTracker) Analyze(profile string) AnalyticsReport {
})
}
- // Detect repeated navigate→snapshot sequences
navSnap := map[string]int{}
for i := 1; i < len(recs); i++ {
if recs[i-1].Endpoint == "/navigate" && recs[i].Endpoint == "/snapshot" {
@@ -352,7 +342,6 @@ func (at *ActionTracker) Analyze(profile string) AnalyticsReport {
}
}
- // Generate suggestions
for _, rp := range report.RepeatPatterns {
if strings.HasPrefix(rp.Pattern, "snapshot") && rp.AvgGapSec > 0 && rp.AvgGapSec < 10 {
report.Suggestions = append(report.Suggestions,
@@ -364,7 +353,6 @@ func (at *ActionTracker) Analyze(profile string) AnalyticsReport {
}
}
- // Check for heavy snapshot usage without selector/maxTokens
snapCount := 0
for _, r := range recs {
if r.Endpoint == "/snapshot" {
@@ -383,10 +371,6 @@ func (at *ActionTracker) Analyze(profile string) AnalyticsReport {
return report
}
-// ---------------------------------------------------------------------------
-// HTTP Handlers
-// ---------------------------------------------------------------------------
-
func (pm *ProfileManager) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("GET /profiles", pm.handleList)
mux.HandleFunc("POST /profiles/import", pm.handleImport)
@@ -476,14 +460,12 @@ func (pm *ProfileManager) handleAnalytics(w http.ResponseWriter, r *http.Request
jsonResp(w, http.StatusOK, report)
}
-// TrackingMiddleware returns middleware that records actions per profile.
func (pm *ProfileManager) TrackingMiddleware(profileName string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := &statusWriter{ResponseWriter: w, code: 200}
next.ServeHTTP(sw, r)
- // Record the action
rec := ActionRecord{
Timestamp: start,
Method: r.Method,
@@ -497,11 +479,6 @@ func (pm *ProfileManager) TrackingMiddleware(profileName string, next http.Handl
})
}
-// uses statusWriter from middleware.go
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
func profileQueryInt(r *http.Request, key string, def int) int {
s := r.URL.Query().Get(key)
if s == "" {
diff --git a/profiles_test.go b/profiles_test.go
index d2774e10..ae28980c 100644
--- a/profiles_test.go
+++ b/profiles_test.go
@@ -49,7 +49,6 @@ func TestProfileManagerImport(t *testing.T) {
dir := t.TempDir()
pm := NewProfileManager(dir)
- // Create a fake Chrome profile source
src := filepath.Join(t.TempDir(), "chrome-src")
os.MkdirAll(filepath.Join(src, "Default"), 0755)
os.WriteFile(filepath.Join(src, "Default", "Preferences"), []byte(`{}`), 0644)
@@ -82,7 +81,6 @@ func TestProfileManagerReset(t *testing.T) {
pm := NewProfileManager(dir)
pm.Create("reset-me")
- // Create some session data
sessDir := filepath.Join(dir, "reset-me", "Default", "Sessions")
os.MkdirAll(sessDir, 0755)
os.WriteFile(filepath.Join(sessDir, "session1"), []byte("data"), 0644)
@@ -100,7 +98,7 @@ func TestProfileManagerReset(t *testing.T) {
if _, err := os.Stat(cacheDir); !os.IsNotExist(err) {
t.Error("Cache dir should be removed after reset")
}
- // Profile itself should still exist
+
if _, err := os.Stat(filepath.Join(dir, "reset-me")); err != nil {
t.Error("Profile dir should still exist after reset")
}
@@ -134,12 +132,12 @@ func TestActionTracker(t *testing.T) {
for i := 0; i < 5; i++ {
at.Record("prof1", ActionRecord{
- Timestamp: time.Now().Add(time.Duration(i) * time.Second),
- Method: "GET",
- Endpoint: "/snapshot",
- URL: "https://example.com",
+ Timestamp: time.Now().Add(time.Duration(i) * time.Second),
+ Method: "GET",
+ Endpoint: "/snapshot",
+ URL: "https://example.com",
DurationMs: 100,
- Status: 200,
+ Status: 200,
})
}
@@ -160,7 +158,6 @@ func TestActionTracker(t *testing.T) {
func TestActionTrackerRepeatDetection(t *testing.T) {
at := NewActionTracker()
- // Simulate rapid polling
for i := 0; i < 10; i++ {
at.Record("poller", ActionRecord{
Timestamp: time.Now().Add(time.Duration(i) * 3 * time.Second),
diff --git a/proxy_ws.go b/proxy_ws.go
index f3379eac..31505270 100644
--- a/proxy_ws.go
+++ b/proxy_ws.go
@@ -11,11 +11,10 @@ import (
// proxyWebSocket does a raw TCP tunnel for WebSocket connections.
// This is the simplest approach — no frame parsing, just bidirectional copy.
func proxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
- // Convert http(s) to ws
+
wsTarget := strings.Replace(targetURL, "http://", "", 1)
wsTarget = strings.Replace(wsTarget, "https://", "", 1)
- // Extract host:port and path
host := wsTarget
path := "/"
if idx := strings.Index(wsTarget, "/"); idx >= 0 {
@@ -23,7 +22,6 @@ func proxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
path = wsTarget[idx:]
}
- // Connect to target
backend, err := net.Dial("tcp", host)
if err != nil {
http.Error(w, "backend unavailable", http.StatusBadGateway)
@@ -32,7 +30,6 @@ func proxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
}
defer backend.Close()
- // Hijack the client connection
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "server doesn't support hijacking", http.StatusInternalServerError)
@@ -45,7 +42,6 @@ func proxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
}
defer client.Close()
- // Forward the original HTTP upgrade request to backend
reqLine := r.Method + " " + path + " HTTP/1.1\r\n"
backend.Write([]byte(reqLine))
backend.Write([]byte("Host: " + host + "\r\n"))
@@ -56,7 +52,6 @@ func proxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
}
backend.Write([]byte("\r\n"))
- // Bidirectional copy
done := make(chan struct{}, 2)
go func() { io.Copy(client, backend); done <- struct{}{} }()
go func() { io.Copy(backend, client); done <- struct{}{} }()
diff --git a/screencast.go b/screencast.go
index e498442d..97a01edc 100644
--- a/screencast.go
+++ b/screencast.go
@@ -16,16 +16,12 @@ import (
"github.com/gobwas/ws/wsutil"
)
-// ---------------------------------------------------------------------------
-// Screencast — streams live JPEG frames from Chrome tabs over WebSocket
-// ---------------------------------------------------------------------------
-
// handleScreencast upgrades to WebSocket and streams screencast frames for a tab.
// Query params: tabId (required), quality (1-100, default 40), maxWidth (default 800), fps (1-30, default 5)
func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
if tabID == "" {
- // Use first available tab
+
b.mu.RLock()
for id := range b.tabs {
tabID = id
@@ -38,10 +34,9 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
tab, ok := b.tabs[tabID]
b.mu.RUnlock()
- // If tab isn't tracked (e.g. manually opened in headed mode), create a context for it
if !ok {
tabCtx, _ := chromedp.NewContext(b.browserCtx, chromedp.WithTargetID(target.ID(tabID)))
- // Quick ping to verify the target exists
+
if err := chromedp.Run(tabCtx); err != nil {
http.Error(w, "tab not found", 404)
return
@@ -52,13 +47,12 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
quality := queryParamInt(r, "quality", 30)
maxWidth := queryParamInt(r, "maxWidth", 800)
everyNth := queryParamInt(r, "everyNthFrame", 4)
- fps := queryParamInt(r, "fps", 1) // default 1 fps to save bandwidth
+ fps := queryParamInt(r, "fps", 1)
if fps > 30 {
fps = 30
}
minFrameInterval := time.Second / time.Duration(fps)
- // Upgrade to WebSocket
conn, _, _, err := ws.UpgradeHTTP(r, w)
if err != nil {
slog.Error("ws upgrade failed", "err", err)
@@ -71,7 +65,6 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
return
}
- // Channel for frames
frameCh := make(chan []byte, 3)
var once sync.Once
done := make(chan struct{})
@@ -81,7 +74,7 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
chromedp.ListenTarget(ctx, func(ev interface{}) {
switch e := ev.(type) {
case *page.EventScreencastFrame:
- // Ack the frame so Chrome sends the next one
+
go func() {
_ = chromedp.Run(ctx,
chromedp.ActionFunc(func(c context.Context) error {
@@ -90,29 +83,25 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
)
}()
- // Rate limit: skip frames if too fast
now := time.Now()
if now.Sub(lastFrame) < minFrameInterval {
return
}
lastFrame = now
- // Decode base64 frame data
data, err := base64.StdEncoding.DecodeString(e.Data)
if err != nil {
return
}
- // Non-blocking send
select {
case frameCh <- data:
default:
- // Drop frame if consumer is slow
+
}
}
})
- // Start screencast
err = chromedp.Run(ctx,
chromedp.ActionFunc(func(c context.Context) error {
return page.StartScreencast().
@@ -140,7 +129,6 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
slog.Info("screencast started", "tab", tabID, "quality", quality, "maxWidth", maxWidth)
- // Read pump — detect client disconnect
go func() {
for {
_, _, err := wsutil.ReadClientData(conn)
@@ -151,7 +139,6 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
}
}()
- // Write pump — send frames to WebSocket client
for {
select {
case frame := <-frameCh:
@@ -161,7 +148,7 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
case <-done:
return
case <-time.After(10 * time.Second):
- // Keepalive ping if no frames
+
if err := wsutil.WriteServerMessage(conn, ws.OpPing, nil); err != nil {
return
}
@@ -173,8 +160,8 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
// Uses CDP target discovery to find ALL tabs, not just ones in bridge.tabs.
func (b *Bridge) handleScreencastAll(w http.ResponseWriter, r *http.Request) {
type tabInfo struct {
- ID string `json:"id"`
- URL string `json:"url,omitempty"`
+ ID string `json:"id"`
+ URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
}
@@ -186,7 +173,7 @@ func (b *Bridge) handleScreencastAll(w http.ResponseWriter, r *http.Request) {
targets, err := target.GetTargets().Do(ctx)
if err != nil {
- // Fallback to bridge.tabs
+
b.mu.RLock()
defer b.mu.RUnlock()
tabs := make([]tabInfo, 0, len(b.tabs))
diff --git a/snapshot.go b/snapshot.go
index 73622969..20aaeb49 100644
--- a/snapshot.go
+++ b/snapshot.go
@@ -1,4 +1,5 @@
-package main
+package // A11yNode is a flattened accessibility tree node returned by /snapshot.
+main
import (
"encoding/json"
@@ -6,8 +7,6 @@ import (
"strings"
)
-// A11yNode is a flattened accessibility tree node returned by /snapshot.
-// Refs (e0, e1, ...) are stable within a snapshot and cached for use by /action.
type A11yNode struct {
Ref string `json:"ref"`
Role string `json:"role"`
@@ -19,9 +18,6 @@ type A11yNode struct {
NodeID int64 `json:"nodeId,omitempty"`
}
-// Raw a11y tree types — we parse CDP responses manually because the typed
-// cdproto library crashes on the "uninteresting" PropertyName value.
-
type rawAXNode struct {
NodeID string `json:"nodeId"`
Ignored bool `json:"ignored"`
@@ -54,8 +50,6 @@ func (v *rawAXValue) String() string {
return strings.Trim(string(v.Value), `"`)
}
-// interactiveRoles is the set of ARIA roles considered interactive
-// for the ?filter=interactive snapshot parameter.
var interactiveRoles = map[string]bool{
"button": true, "link": true, "textbox": true, "searchbox": true,
"combobox": true, "listbox": true, "option": true, "checkbox": true,
@@ -64,10 +58,8 @@ var interactiveRoles = map[string]bool{
"tab": true, "treeitem": true,
}
-// buildSnapshot converts raw a11y nodes into a flat list of A11yNode entries
-// and a ref→backendNodeID map. filter and maxDepth control output.
func buildSnapshot(nodes []rawAXNode, filter string, maxDepth int) ([]A11yNode, map[string]int64) {
- // Build parent map for depth calculation
+
parentMap := make(map[string]string)
for _, n := range nodes {
for _, childID := range n.ChildIDs {
@@ -147,8 +139,6 @@ func buildSnapshot(nodes []rawAXNode, filter string, maxDepth int) ([]A11yNode,
return flat, refs
}
-// formatSnapshotText renders nodes as an indented text tree.
-// Much cheaper on tokens than JSON (~40-60% reduction).
func formatSnapshotText(nodes []A11yNode) string {
var b strings.Builder
for _, n := range nodes {
@@ -179,8 +169,6 @@ func formatSnapshotText(nodes []A11yNode) string {
return b.String()
}
-// formatSnapshotCompact renders nodes in a minimal one-line-per-node format.
-// ~60-70% fewer tokens than JSON. Format: ref:role "name" [val="v"] [flags]
func formatSnapshotCompact(nodes []A11yNode) string {
var b strings.Builder
for _, n := range nodes {
@@ -208,24 +196,21 @@ func formatSnapshotCompact(nodes []A11yNode) string {
return b.String()
}
-// truncateToTokens trims nodes to stay under a rough token budget.
-// Returns the truncated slice and whether truncation occurred.
-// Token estimate: compact/text ~= len/4, json ~= len/3.
func truncateToTokens(nodes []A11yNode, maxTokens int, format string) ([]A11yNode, bool) {
tokensUsed := 0
for i, n := range nodes {
- // Estimate tokens for this node based on format
+
var nodeTokens int
switch format {
case "compact":
- // ref:role "name" ≈ compact
+
size := len(n.Ref) + 1 + len(n.Role) + len(n.Name) + len(n.Value) + 8
nodeTokens = size / 4
case "text":
size := n.Depth*2 + len(n.Ref) + 1 + len(n.Role) + len(n.Name) + len(n.Value) + 8
nodeTokens = size / 4
default:
- // JSON is more verbose
+
size := len(n.Ref) + len(n.Role) + len(n.Name) + len(n.Value) + 60
nodeTokens = size / 3
}
@@ -240,10 +225,8 @@ func truncateToTokens(nodes []A11yNode, maxTokens int, format string) ([]A11yNod
return nodes, false
}
-// filterSubtree returns only nodes that are descendants of the node with
-// the given backendDOMNodeID. Uses the a11y tree's childIds to walk the subtree.
func filterSubtree(nodes []rawAXNode, scopeBackendID int64) []rawAXNode {
- // Find the a11y node whose backendDOMNodeId matches
+
scopeAXID := ""
for _, n := range nodes {
if n.BackendDOMNodeID == scopeBackendID {
@@ -252,10 +235,9 @@ func filterSubtree(nodes []rawAXNode, scopeBackendID int64) []rawAXNode {
}
}
if scopeAXID == "" {
- return nodes // scope not found, return all
+ return nodes
}
- // BFS to find all descendant node IDs
childMap := make(map[string][]string, len(nodes))
for _, n := range nodes {
childMap[n.NodeID] = append(childMap[n.NodeID], n.ChildIDs...)
@@ -284,9 +266,6 @@ func filterSubtree(nodes []rawAXNode, scopeBackendID int64) []rawAXNode {
return result
}
-// diffSnapshot returns only nodes that changed between prev and current snapshots.
-// A node is "changed" if it's new, removed, or has different name/value/focused/disabled.
-// Returns added, changed, and removed nodes.
func diffSnapshot(prev, curr []A11yNode) (added, changed, removed []A11yNode) {
prevMap := make(map[string]A11yNode, len(prev))
for _, n := range prev {
diff --git a/snapshot_extra_test.go b/snapshot_extra_test.go
index 96c7715f..ca0ba0f2 100644
--- a/snapshot_extra_test.go
+++ b/snapshot_extra_test.go
@@ -7,8 +7,6 @@ import (
"testing"
)
-// ── formatSnapshotCompact ──────────────────────────────────
-
func TestFormatSnapshotCompact_Basic(t *testing.T) {
nodes := []A11yNode{
{Ref: "e0", Role: "button", Name: "Submit"},
@@ -54,8 +52,6 @@ func TestFormatSnapshotCompact_NoName(t *testing.T) {
}
}
-// ── truncateToTokens ───────────────────────────────────────
-
func TestTruncateToTokens_NoTruncation(t *testing.T) {
nodes := []A11yNode{
{Ref: "e0", Role: "button", Name: "OK"},
@@ -89,7 +85,7 @@ func TestTruncateToTokens_Formats(t *testing.T) {
for i := range nodes {
nodes[i] = A11yNode{Ref: "e0", Role: "button", Name: "Click me"}
}
- // JSON format estimates more tokens per node, so should truncate sooner
+
jsonResult, _ := truncateToTokens(nodes, 100, "json")
compactResult, _ := truncateToTokens(nodes, 100, "compact")
if len(jsonResult) > len(compactResult) {
@@ -107,8 +103,6 @@ func TestTruncateToTokens_Empty(t *testing.T) {
}
}
-// ── filterSubtree ──────────────────────────────────────────
-
func TestFilterSubtree_Found(t *testing.T) {
nodes := []rawAXNode{
{NodeID: "root", BackendDOMNodeID: 1, ChildIDs: []string{"child1", "child2"}},
@@ -117,7 +111,7 @@ func TestFilterSubtree_Found(t *testing.T) {
{NodeID: "grandchild", BackendDOMNodeID: 4},
{NodeID: "other", BackendDOMNodeID: 5},
}
- // Scope to child1 subtree (should include child1 + grandchild)
+
result := filterSubtree(nodes, 2)
if len(result) != 2 {
t.Errorf("expected 2 nodes, got %d", len(result))
@@ -136,7 +130,7 @@ func TestFilterSubtree_NotFound(t *testing.T) {
{NodeID: "root", BackendDOMNodeID: 1},
{NodeID: "child", BackendDOMNodeID: 2},
}
- // Non-existent scope — returns all nodes
+
result := filterSubtree(nodes, 999)
if len(result) != 2 {
t.Errorf("expected all nodes returned, got %d", len(result))
@@ -149,15 +143,13 @@ func TestFilterSubtree_RootScope(t *testing.T) {
{NodeID: "child", BackendDOMNodeID: 2, ChildIDs: []string{"grandchild"}},
{NodeID: "grandchild", BackendDOMNodeID: 3},
}
- // Scope to root — should include everything
+
result := filterSubtree(nodes, 1)
if len(result) != 3 {
t.Errorf("expected 3 nodes, got %d", len(result))
}
}
-// ── diffSnapshot ───────────────────────────────────────────
-
func TestDiffSnapshot_Added(t *testing.T) {
prev := []A11yNode{{Ref: "e0", Role: "button", Name: "OK", NodeID: 1}}
curr := []A11yNode{
@@ -204,8 +196,6 @@ func TestDiffSnapshot_Empty(t *testing.T) {
}
}
-// ── rawAXValue.String ──────────────────────────────────────
-
func TestRawAXValue_String_Normal(t *testing.T) {
v := &rawAXValue{Type: "string", Value: json.RawMessage(`"hello"`)}
if got := v.String(); got != "hello" {
@@ -229,14 +219,12 @@ func TestRawAXValue_String_NilValue(t *testing.T) {
func TestRawAXValue_String_NonString(t *testing.T) {
v := &rawAXValue{Type: "number", Value: json.RawMessage(`42`)}
- // Falls back to trimming quotes
+
if got := v.String(); got != "42" {
t.Errorf("expected 42, got %q", got)
}
}
-// ── handleSnapshot noTab ───────────────────────────────────
-
func TestHandleSnapshot_InvalidFilter(t *testing.T) {
b := &Bridge{}
b.tabs = make(map[string]*TabEntry)
diff --git a/snapshot_test.go b/snapshot_test.go
index 2b0e39dd..c67c216a 100644
--- a/snapshot_test.go
+++ b/snapshot_test.go
@@ -45,7 +45,7 @@ func TestInteractiveRoles(t *testing.T) {
}
func TestBuildSnapshot(t *testing.T) {
- // Simulate raw a11y nodes
+
nodes := []rawAXNode{
{
NodeID: "root",
@@ -84,12 +84,10 @@ func TestBuildSnapshot(t *testing.T) {
flat, refs := buildSnapshot(nodes, "", -1)
- // Should have 3 entries: WebArea, button, textbox (ignored + generic + none filtered)
if len(flat) != 3 {
t.Fatalf("expected 3 nodes, got %d: %+v", len(flat), flat)
}
- // Check refs map
if refs["e0"] != 1 {
t.Errorf("e0 should map to nodeID 1, got %d", refs["e0"])
}
@@ -100,7 +98,6 @@ func TestBuildSnapshot(t *testing.T) {
t.Errorf("e2 should map to nodeID 20, got %d", refs["e2"])
}
- // Check depth
if flat[0].Depth != 0 {
t.Errorf("root depth should be 0, got %d", flat[0].Depth)
}
@@ -108,7 +105,6 @@ func TestBuildSnapshot(t *testing.T) {
t.Errorf("button depth should be 1, got %d", flat[1].Depth)
}
- // Check focused property
if !flat[2].Focused {
t.Error("textbox should be focused")
}
@@ -181,9 +177,9 @@ func TestDiffSnapshot(t *testing.T) {
{Ref: "e2", Role: "link", Name: "Old Link", NodeID: 30},
}
curr := []A11yNode{
- {Ref: "e0", Role: "button", Name: "Submit", NodeID: 10}, // unchanged
- {Ref: "e1", Role: "textbox", Name: "Email", NodeID: 20, Value: "hi"}, // changed (value)
- {Ref: "e3", Role: "link", Name: "New Link", NodeID: 40}, // added
+ {Ref: "e0", Role: "button", Name: "Submit", NodeID: 10},
+ {Ref: "e1", Role: "textbox", Name: "Email", NodeID: 20, Value: "hi"},
+ {Ref: "e3", Role: "link", Name: "New Link", NodeID: 40},
}
added, changed, removed := diffSnapshot(prev, curr)
diff --git a/state.go b/state.go
index cec771d6..a89bdbc0 100644
--- a/state.go
+++ b/state.go
@@ -1,4 +1,8 @@
-package main
+package // TabState represents a saved tab for session persistence.
+// SessionState is the on-disk format for saved sessions.
+// SaveState writes all open tab URLs to sessions.
+// RestoreState reopens tabs from the last saved session with concurrency limiting.
+main
import (
"context"
@@ -12,20 +16,17 @@ import (
"github.com/chromedp/chromedp"
)
-// TabState represents a saved tab for session persistence.
type TabState struct {
ID string `json:"id"`
URL string `json:"url"`
Title string `json:"title"`
}
-// SessionState is the on-disk format for saved sessions.
type SessionState struct {
Tabs []TabState `json:"tabs"`
SavedAt string `json:"savedAt"`
}
-// markCleanExit patches Chrome's preferences to prevent "didn't shut down correctly" bar.
func markCleanExit() {
prefsPath := filepath.Join(profileDir, "Default", "Preferences")
data, err := os.ReadFile(prefsPath)
@@ -41,8 +42,6 @@ func markCleanExit() {
}
}
-// wasUncleanExit checks if the previous Chrome session exited uncleanly.
-// Returns true if Preferences contains exit_type:"Crashed".
func wasUncleanExit() bool {
prefsPath := filepath.Join(profileDir, "Default", "Preferences")
data, err := os.ReadFile(prefsPath)
@@ -52,8 +51,6 @@ func wasUncleanExit() bool {
return strings.Contains(string(data), `"exit_type":"Crashed"`)
}
-// clearChromeSessions removes Chrome's internal session restore data
-// (the Sessions/ folder that stores tabs to reopen after a crash).
func clearChromeSessions() {
sessionsDir := filepath.Join(profileDir, "Default", "Sessions")
if err := os.RemoveAll(sessionsDir); err != nil {
@@ -63,7 +60,6 @@ func clearChromeSessions() {
}
}
-// SaveState writes all open tab URLs to sessions.json.
func (b *Bridge) SaveState() {
targets, err := b.ListTargets()
if err != nil {
@@ -104,7 +100,6 @@ func (b *Bridge) SaveState() {
}
}
-// RestoreState reopens tabs from the last saved session with concurrency limiting.
func (b *Bridge) RestoreState() {
path := filepath.Join(stateDir, "sessions.json")
data, err := os.ReadFile(path)
@@ -120,7 +115,6 @@ func (b *Bridge) RestoreState() {
return
}
- // Limit concurrent tab creation to avoid overwhelming Chrome
const maxConcurrentTabs = 3
const maxConcurrentNavs = 2
@@ -133,19 +127,17 @@ func (b *Bridge) RestoreState() {
continue
}
- // Acquire semaphore for tab creation
tabSem <- struct{}{}
- // Small delay between tab creations to spread load
if restored > 0 {
time.Sleep(200 * time.Millisecond)
}
ctx, cancel := chromedp.NewContext(b.browserCtx)
- // Just initialize the tab context (attaches to Chrome) — don't navigate yet.
+
if err := chromedp.Run(ctx); err != nil {
cancel()
- <-tabSem // Release semaphore
+ <-tabSem
slog.Warn("restore tab failed", "url", tab.URL, "err", err)
continue
}
@@ -156,11 +148,9 @@ func (b *Bridge) RestoreState() {
b.mu.Unlock()
restored++
- // Fire-and-forget navigate with concurrency limiting
go func(tabCtx context.Context, url string) {
- defer func() { <-tabSem }() // Release tab semaphore when done
+ defer func() { <-tabSem }()
- // Acquire navigation semaphore
navSem <- struct{}{}
defer func() { <-navSem }()
diff --git a/state_test.go b/state_test.go
index 45b9ed26..5e6650d2 100644
--- a/state_test.go
+++ b/state_test.go
@@ -12,7 +12,6 @@ func TestMarkCleanExit_NoFile(t *testing.T) {
profileDir = t.TempDir()
defer func() { profileDir = origProfileDir }()
- // Should not panic when file doesn't exist
markCleanExit()
}
@@ -89,7 +88,7 @@ func TestSessionState_Marshal(t *testing.T) {
func TestSaveState_NoBrowser(t *testing.T) {
b := newTestBridge()
- // Should not panic — just logs error and returns
+
b.SaveState()
}
@@ -99,7 +98,7 @@ func TestRestoreState_NoFile(t *testing.T) {
defer func() { stateDir = origStateDir }()
b := newTestBridge()
- // Should not panic when file doesn't exist
+
b.RestoreState()
}
@@ -113,7 +112,7 @@ func TestRestoreState_EmptyTabs(t *testing.T) {
_ = os.WriteFile(filepath.Join(stateDir, "sessions.json"), data, 0644)
b := newTestBridge()
- // Should return early — no tabs to restore
+
b.RestoreState()
}
@@ -125,7 +124,7 @@ func TestRestoreState_InvalidJSON(t *testing.T) {
_ = os.WriteFile(filepath.Join(stateDir, "sessions.json"), []byte("{broken"), 0644)
b := newTestBridge()
- // Should not panic on invalid JSON
+
b.RestoreState()
}
@@ -195,6 +194,5 @@ func TestClearChromeSessions_NoDir(t *testing.T) {
profileDir = tmp
defer func() { profileDir = origProfile }()
- // Should not panic when dir doesn't exist
clearChromeSessions()
}
diff --git a/stealth_test.go b/stealth_test.go
index da9fe624..615b803e 100644
--- a/stealth_test.go
+++ b/stealth_test.go
@@ -8,12 +8,11 @@ import (
)
func TestStealthJavaScript(t *testing.T) {
- // Test that stealth.js is syntactically valid
+
content := stealthScript
- // Check for key stealth features
features := []string{
- "navigator, 'webdriver'", // Object.defineProperty
+ "navigator, 'webdriver'",
"sessionSeed",
"seededRandom",
"toDataURL",
@@ -29,7 +28,6 @@ func TestStealthJavaScript(t *testing.T) {
}
}
- // Check no duplicate sessionSeed definitions
count := strings.Count(content, "const sessionSeed")
if count != 1 {
t.Errorf("expected 1 sessionSeed definition, found %d", count)
@@ -55,7 +53,7 @@ func TestGetStealthRecommendations(t *testing.T) {
{
name: "all enabled",
features: allFeatures,
- wantRecs: 1, // Get "Stealth mode is well configured"
+ wantRecs: 1,
},
{
name: "canvas disabled",
@@ -68,7 +66,7 @@ func TestGetStealthRecommendations(t *testing.T) {
"font_spoofing": true,
"audio_noise": true,
},
- wantRecs: 1, // Just canvas
+ wantRecs: 1,
},
{
name: "multiple disabled",
@@ -81,7 +79,7 @@ func TestGetStealthRecommendations(t *testing.T) {
"font_spoofing": true,
"audio_noise": true,
},
- wantRecs: 3, // UA + lang + WebRTC
+ wantRecs: 3,
},
}
@@ -126,8 +124,8 @@ func TestGenerateFingerprint(t *testing.T) {
OS: "random",
Browser: "chrome",
},
- wantUA: "Chrome/" + chromeVersion, // Should use configured chromeVersion
- wantPlat: "", // Could be Win32, MacIntel, or Linux
+ wantUA: "Chrome/" + chromeVersion,
+ wantPlat: "",
},
}
@@ -143,7 +141,6 @@ func TestGenerateFingerprint(t *testing.T) {
t.Errorf("expected platform %s, got %s", tt.wantPlat, fp.Platform)
}
- // Check all fields are populated
if fp.UserAgent == "" {
t.Error("UserAgent is empty")
}
@@ -179,7 +176,6 @@ func TestHandleStealthStatus(t *testing.T) {
t.Fatalf("failed to unmarshal response: %v", err)
}
- // Check response structure
if resp.Level == "" {
t.Error("level is empty")
}
@@ -193,7 +189,6 @@ func TestHandleStealthStatus(t *testing.T) {
t.Error("chrome_flags is empty")
}
- // Verify score calculation
enabled := 0
for _, v := range resp.Features {
if v {