Skip to content

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

feat: implement simple-autorestart strategy (#118)

Djain9124467ce8bf308
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index 520f3b61..6f9ac5d0 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -18,7 +18,13 @@ import (
"github.com/pinchtab/pinchtab/internal/handlers"
"github.com/pinchtab/pinchtab/internal/orchestrator"
"github.com/pinchtab/pinchtab/internal/profiles"
+ "github.com/pinchtab/pinchtab/internal/strategy"
"github.com/pinchtab/pinchtab/internal/web"
+
+ // Register strategies via init().
+ _ "github.com/pinchtab/pinchtab/internal/strategy/autorestart"
+ _ "github.com/pinchtab/pinchtab/internal/strategy/explicit"
+ _ "github.com/pinchtab/pinchtab/internal/strategy/simple"
)
// runDashboard starts a lightweight dashboard server — no Chrome, no bridge.
@@ -55,9 +61,36 @@ func runDashboard(cfg *config.RuntimeConfig) {
mux := http.NewServeMux()
dash.RegisterHandlers(mux)
- orch.RegisterHandlers(mux)
profMgr.RegisterHandlers(mux)
+ // Strategy-based routing: if a known strategy is configured, let it handle
+ // instance management and shorthand route registration. Otherwise fall back
+ // to the default manual route setup for backward compatibility.
+ var activeStrategy strategy.Strategy
+ if cfg.Strategy != "" {
+ strat, err := strategy.New(cfg.Strategy)
+ if err != nil {
+ slog.Warn("unknown strategy, falling back to default", "strategy", cfg.Strategy, "err", err)
+ } else {
+ // Inject orchestrator dependency.
+ type orchSetter interface {
+ SetOrchestrator(o *orchestrator.Orchestrator)
+ }
+ if setter, ok := strat.(orchSetter); ok {
+ setter.SetOrchestrator(orch)
+ }
+ strat.RegisterRoutes(mux)
+ activeStrategy = strat
+ slog.Info("strategy activated", "strategy", strat.Name())
+ }
+ }
+
+ // If no strategy handled route registration, register default routes.
+ if activeStrategy == nil {
+ orch.RegisterHandlers(mux)
+ registerDefaultProxyRoutes(mux, orch)
+ }
+
// Root returns health check (API-first design)
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
web.JSON(w, 200, map[string]any{
@@ -76,41 +109,6 @@ func runDashboard(cfg *config.RuntimeConfig) {
web.JSON(w, 200, map[string]any{"metrics": handlers.SnapshotMetrics()})
})
- // Special handler for /tabs - return empty list if no instances
- mux.HandleFunc("GET /tabs", func(w http.ResponseWriter, r *http.Request) {
- target := orch.FirstRunningURL()
- if target == "" {
- // No instances running, return empty tabs list
- web.JSON(w, 200, map[string]interface{}{"tabs": []interface{}{}})
- return
- }
- proxyRequest(w, r, target+"/tabs")
- })
-
- proxyEndpoints := []string{
- "GET /snapshot", "GET /screenshot", "GET /text",
- "POST /navigate", "POST /action", "POST /actions", "POST /evaluate",
- "POST /tab", "POST /tab/lock", "POST /tab/unlock",
- "GET /cookies", "POST /cookies",
- "GET /download", "POST /upload",
- "GET /stealth/status", "POST /fingerprint/rotate",
- "GET /screencast", "GET /screencast/tabs",
- "POST /find", "POST /macro",
- }
- for _, ep := range proxyEndpoints {
- endpoint := ep
- mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
- target := orch.FirstRunningURL()
- if target == "" {
- web.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
- return
- }
- // Extract path from endpoint (remove method prefix)
- path := r.URL.Path
- proxyRequest(w, r, target+path)
- })
- }
-
handler := handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux)))
srv := &http.Server{
@@ -122,10 +120,22 @@ func runDashboard(cfg *config.RuntimeConfig) {
IdleTimeout: 120 * time.Second,
}
+ // Start strategy lifecycle if active. For strategies like simple-autorestart,
+ // Start() launches the initial instance and begins crash monitoring.
+ // When a strategy handles auto-launch, skip the manual auto-launch below.
+ strategyHandlesLaunch := false
+ if activeStrategy != nil {
+ if err := activeStrategy.Start(context.Background()); err != nil {
+ slog.Error("strategy start failed", "strategy", activeStrategy.Name(), "err", err)
+ } else {
+ strategyHandlesLaunch = true
+ }
+ }
+
autoLaunch := strings.EqualFold(os.Getenv("PINCHTAB_AUTO_LAUNCH"), "1") ||
strings.EqualFold(os.Getenv("PINCHTAB_AUTO_LAUNCH"), "true") ||
strings.EqualFold(os.Getenv("PINCHTAB_AUTO_LAUNCH"), "yes")
- if autoLaunch {
+ if autoLaunch && !strategyHandlesLaunch {
defaultProfile := os.Getenv("PINCHTAB_DEFAULT_PROFILE")
defaultProfileExplicit := defaultProfile != ""
defaultPort := os.Getenv("PINCHTAB_DEFAULT_PORT")
@@ -158,14 +168,19 @@ func runDashboard(cfg *config.RuntimeConfig) {
}
slog.Info("auto-launched instance", "profile", profileToLaunch, "id", inst.ID, "port", inst.Port, "headless", headlessDefault)
}()
- } else {
- slog.Info("dashboard auto-launch disabled", "hint", "set PINCHTAB_AUTO_LAUNCH=1 to enable")
+ } else if !strategyHandlesLaunch {
+ slog.Info("dashboard auto-launch disabled", "hint", "set PINCHTAB_AUTO_LAUNCH=1 or PINCHTAB_STRATEGY=simple-autorestart to enable")
}
shutdownOnce := &sync.Once{}
doShutdown := func() {
shutdownOnce.Do(func() {
slog.Info("shutting down dashboard...")
+ if activeStrategy != nil {
+ if err := activeStrategy.Stop(); err != nil {
+ slog.Warn("strategy stop failed", "err", err)
+ }
+ }
dash.Shutdown()
orch.Shutdown()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -301,3 +316,40 @@ func periodicHealthCheck(orch *orchestrator.Orchestrator) {
)
}
}
+
+// registerDefaultProxyRoutes adds the default shorthand proxy routes
+// when no strategy is handling route registration.
+func registerDefaultProxyRoutes(mux *http.ServeMux, orch *orchestrator.Orchestrator) {
+ // Special handler for /tabs — return empty list if no instances.
+ mux.HandleFunc("GET /tabs", func(w http.ResponseWriter, r *http.Request) {
+ target := orch.FirstRunningURL()
+ if target == "" {
+ web.JSON(w, 200, map[string]any{"tabs": []any{}})
+ return
+ }
+ proxyRequest(w, r, target+"/tabs")
+ })
+
+ proxyEndpoints := []string{
+ "GET /snapshot", "GET /screenshot", "GET /text",
+ "POST /navigate", "POST /action", "POST /actions", "POST /evaluate",
+ "POST /tab", "POST /tab/lock", "POST /tab/unlock",
+ "GET /cookies", "POST /cookies",
+ "GET /download", "POST /upload",
+ "GET /stealth/status", "POST /fingerprint/rotate",
+ "GET /screencast", "GET /screencast/tabs",
+ "POST /find", "POST /macro",
+ }
+ for _, ep := range proxyEndpoints {
+ endpoint := ep
+ mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
+ target := orch.FirstRunningURL()
+ if target == "" {
+ web.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
+ return
+ }
+ path := r.URL.Path
+ proxyRequest(w, r, target+path)
+ })
+ }
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index d399e1a7..a4fda600 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -42,7 +42,7 @@ type RuntimeConfig struct {
WaitNavDelay time.Duration
// Orchestrator settings (dashboard mode only).
- Strategy string // "simple" (default) or "explicit"
+ Strategy string // "simple" (default), "explicit", or "simple-autorestart"
AllocationPolicy string // "fcfs" (default), "round_robin", "random"
}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index 5df73990..d5bf21d9 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -49,26 +49,35 @@ type Orchestrator struct {
childAuthToken string
portAllocator *PortAllocator
idMgr *idutil.Manager
- onEvent EventHandler
+ eventHandlers []EventHandler
instanceMgr *instance.Manager
}
-// OnEvent sets the event handler for instance lifecycle events.
+// OnEvent adds an event handler for instance lifecycle events.
+// Multiple handlers can be registered; all will be called in order.
func (o *Orchestrator) OnEvent(handler EventHandler) {
o.mu.Lock()
defer o.mu.Unlock()
- o.onEvent = handler
+ o.eventHandlers = append(o.eventHandlers, handler)
}
func (o *Orchestrator) emitEvent(eventType string, inst *bridge.Instance) {
o.mu.RLock()
- handler := o.onEvent
+ handlers := make([]EventHandler, len(o.eventHandlers))
+ copy(handlers, o.eventHandlers)
o.mu.RUnlock()
- if handler != nil {
- handler(InstanceEvent{Type: eventType, Instance: inst})
+ evt := InstanceEvent{Type: eventType, Instance: inst}
+ for _, handler := range handlers {
+ handler(evt)
}
}
+// EmitEvent allows external components (e.g. strategies) to broadcast
+// lifecycle events through the orchestrator's event system.
+func (o *Orchestrator) EmitEvent(eventType string, inst *bridge.Instance) {
+ o.emitEvent(eventType, inst)
+}
+
type InstanceInternal struct {
bridge.Instance
URL string
@@ -315,6 +324,7 @@ func (o *Orchestrator) Stop(id string) error {
}
if inst.Status == "stopped" && !instanceIsActive(inst) {
o.mu.Unlock()
+ o.markStopped(id)
return nil
}
inst.Status = "stopping"
diff --git a/internal/strategy/autorestart/autorestart.go b/internal/strategy/autorestart/autorestart.go
new file mode 100644
index 00000000..c6e9c763
--- /dev/null
+++ b/internal/strategy/autorestart/autorestart.go
@@ -0,0 +1,469 @@
+// Package autorestart implements the "simple-autorestart" allocation strategy.
+//
+// It behaves like the "simple" strategy (single instance, shorthand proxy)
+// but adds automatic crash recovery: if the managed Chrome instance exits
+// unexpectedly, the strategy re-launches it with exponential backoff.
+//
+// Configuration is done via AutorestartConfig passed to WithConfig, or
+// via defaults (3 max restarts, 2s initial backoff, 5 min stable period).
+package autorestart
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/orchestrator"
+ "github.com/pinchtab/pinchtab/internal/strategy"
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+const (
+ defaultMaxRestarts = 3
+ defaultInitBackoff = 2 * time.Second
+ defaultStableAfter = 5 * time.Minute
+ defaultProfileName = "default"
+ healthPollInterval = 500 * time.Millisecond
+ healthPollTimeout = 30 * time.Second
+)
+
+func init() {
+ strategy.MustRegister("simple-autorestart", func() strategy.Strategy {
+ return New(AutorestartConfig{})
+ })
+}
+
+// AutorestartConfig configures the autorestart behavior.
+type AutorestartConfig struct {
+ MaxRestarts int // Max consecutive restarts before giving up (0 = use default 3)
+ InitBackoff time.Duration // Initial backoff between restarts (0 = use default 2s)
+ StableAfter time.Duration // Reset counter after running this long (0 = use default 5m)
+ ProfileName string // Profile to launch (empty = "default")
+ Headless bool // Chrome headless mode
+ HeadlessSet bool // Whether Headless was explicitly set (false = use default true)
+}
+
+// RestartState tracks the restart state of the managed instance.
+type RestartState struct {
+ InstanceID string `json:"instanceId"`
+ RestartCount int `json:"restartCount"`
+ MaxRestarts int `json:"maxRestarts"`
+ LastCrash time.Time `json:"lastCrash,omitempty"`
+ LastStart time.Time `json:"lastStart"`
+ Status string `json:"status"` // "running", "restarting", "crashed", "stopped"
+}
+
+// Strategy monitors a single Chrome instance and auto-restarts on crash.
+type Strategy struct {
+ orch *orchestrator.Orchestrator
+ config AutorestartConfig
+
+ mu sync.Mutex
+ instanceID string // Currently managed instance ID
+ restartCount int // Consecutive restart count
+ lastCrash time.Time // Last crash timestamp
+ lastStart time.Time // Last successful start timestamp
+ deliberate bool // True if stop was deliberate (not a crash)
+ restarting bool // True while a restart is in progress (prevents re-entrancy)
+ ctx context.Context
+ cancel context.CancelFunc
+}
+
+// New creates a new autorestart strategy with the given config.
+func New(cfg AutorestartConfig) *Strategy {
+ if cfg.MaxRestarts <= 0 {
+ cfg.MaxRestarts = defaultMaxRestarts
+ }
+ if cfg.InitBackoff <= 0 {
+ cfg.InitBackoff = defaultInitBackoff
+ }
+ if cfg.StableAfter <= 0 {
+ cfg.StableAfter = defaultStableAfter
+ }
+ if cfg.ProfileName == "" {
+ cfg.ProfileName = defaultProfileName
+ }
+ if !cfg.HeadlessSet {
+ cfg.Headless = true
+ }
+
+ return &Strategy{
+ config: cfg,
+ }
+}
+
+func (s *Strategy) Name() string { return "simple-autorestart" }
+
+// SetOrchestrator injects the orchestrator after construction.
+func (s *Strategy) SetOrchestrator(o *orchestrator.Orchestrator) {
+ s.orch = o
+}
+
+// Start begins the autorestart lifecycle: launches an initial instance
+// and subscribes to orchestrator events for crash detection.
+func (s *Strategy) Start(ctx context.Context) error {
+ s.mu.Lock()
+ s.ctx, s.cancel = context.WithCancel(ctx)
+ s.mu.Unlock()
+
+ // Subscribe to orchestrator events for crash detection.
+ s.orch.OnEvent(func(evt orchestrator.InstanceEvent) {
+ s.handleEvent(evt)
+ })
+
+ // Launch the initial instance.
+ go s.launchInitial()
+
+ // Start the stability checker.
+ go s.stabilityLoop()
+
+ return nil
+}
+
+// Stop gracefully shuts down the strategy.
+func (s *Strategy) Stop() error {
+ s.mu.Lock()
+ s.deliberate = true
+ if s.cancel != nil {
+ s.cancel()
+ }
+ s.mu.Unlock()
+ return nil
+}
+
+// RegisterRoutes adds shorthand endpoints that proxy to the managed instance.
+func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
+ s.orch.RegisterHandlers(mux)
+
+ shorthandRoutes := []string{
+ "POST /navigate", "GET /navigate",
+ "GET /snapshot", "GET /screenshot", "GET /text",
+ "GET /pdf", "POST /pdf",
+ "POST /action", "POST /actions", "POST /evaluate",
+ "POST /find",
+ "GET /cookies", "POST /cookies",
+ "GET /download", "POST /upload",
+ "POST /tab", "POST /tab/lock", "POST /tab/unlock",
+ "GET /stealth/status", "POST /fingerprint/rotate",
+ "GET /screencast", "GET /screencast/tabs",
+ "POST /macro",
+ }
+ for _, route := range shorthandRoutes {
+ mux.HandleFunc(route, s.proxyToManaged)
+ }
+
+ mux.HandleFunc("GET /tabs", s.handleTabs)
+ mux.HandleFunc("GET /autorestart/status", s.handleStatus)
+}
+
+// State returns the current restart state for observability.
+func (s *Strategy) State() RestartState {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ status := "running"
+ if s.restartCount >= s.config.MaxRestarts {
+ status = "crashed"
+ } else if s.restarting {
+ status = "restarting"
+ } else if s.instanceID == "" {
+ status = "starting"
+ }
+
+ return RestartState{
+ InstanceID: s.instanceID,
+ RestartCount: s.restartCount,
+ MaxRestarts: s.config.MaxRestarts,
+ LastCrash: s.lastCrash,
+ LastStart: s.lastStart,
+ Status: status,
+ }
+}
+
+// --- Internal ---
+
+// launchInitial launches the first instance (or after strategy start).
+func (s *Strategy) launchInitial() {
+ s.mu.Lock()
+ ctx := s.ctx
+ s.mu.Unlock()
+
+ if ctx == nil || ctx.Err() != nil {
+ return
+ }
+
+ inst, err := s.orch.Launch(s.config.ProfileName, "", s.config.Headless, nil)
+ if err != nil {
+ slog.Error("autorestart: initial launch failed", "profile", s.config.ProfileName, "err", err)
+ return
+ }
+
+ s.mu.Lock()
+ s.instanceID = inst.ID
+ s.lastStart = time.Now()
+ s.mu.Unlock()
+
+ slog.Info("autorestart: instance launched", "id", inst.ID, "profile", s.config.ProfileName)
+}
+
+// handleEvent processes orchestrator lifecycle events.
+func (s *Strategy) handleEvent(evt orchestrator.InstanceEvent) {
+ s.mu.Lock()
+ managedID := s.instanceID
+ deliberate := s.deliberate
+ restarting := s.restarting
+ ctx := s.ctx
+ s.mu.Unlock()
+
+ // Only handle events for the managed instance.
+ if evt.Instance == nil || evt.Instance.ID != managedID {
+ return
+ }
+
+ // Skip if a restart is already in progress (prevents duplicate handling
+ // when both instance.error and instance.stopped fire for the same crash).
+ if restarting {
+ return
+ }
+
+ switch evt.Type {
+ case "instance.stopped":
+ if deliberate {
+ slog.Info("autorestart: instance stopped deliberately", "id", managedID)
+ return
+ }
+ // Instance exited unexpectedly — check if we should restart.
+ s.handleCrash(ctx, managedID)
+
+ case "instance.error":
+ if deliberate {
+ return
+ }
+ s.handleCrash(ctx, managedID)
+ }
+}
+
+// handleCrash decides whether to restart the crashed instance.
+func (s *Strategy) handleCrash(ctx context.Context, crashedID string) {
+ if ctx == nil || ctx.Err() != nil {
+ return
+ }
+
+ s.mu.Lock()
+ s.restarting = true
+ s.restartCount++
+ s.lastCrash = time.Now()
+ count := s.restartCount
+ maxRestarts := s.config.MaxRestarts
+ backoff := s.config.InitBackoff * time.Duration(1<<uint(count-1))
+ s.mu.Unlock()
+
+ if count > maxRestarts {
+ slog.Error("autorestart: max restarts exceeded, giving up",
+ "id", crashedID,
+ "restartCount", count-1,
+ "maxRestarts", maxRestarts,
+ )
+ s.mu.Lock()
+ s.restarting = false
+ s.mu.Unlock()
+ if s.orch != nil {
+ s.orch.EmitEvent("instance.crashed", &bridge.Instance{
+ ID: crashedID,
+ Status: "crashed",
+ })
+ }
+ return
+ }
+
+ slog.Warn("autorestart: instance crashed, scheduling restart",
+ "id", crashedID,
+ "attempt", count,
+ "maxRestarts", maxRestarts,
+ "backoff", backoff,
+ )
+
+ // Emit restarting event.
+ if s.orch != nil {
+ s.orch.EmitEvent("instance.restarting", &bridge.Instance{
+ ID: crashedID,
+ Status: "restarting",
+ })
+ }
+
+ // Wait for backoff period (respecting cancellation).
+ select {
+ case <-time.After(backoff):
+ case <-ctx.Done():
+ return
+ }
+
+ s.restartInstance()
+}
+
+// restartInstance launches a new instance to replace the crashed one.
+func (s *Strategy) restartInstance() {
+ s.mu.Lock()
+ ctx := s.ctx
+ oldID := s.instanceID
+ s.mu.Unlock()
+
+ if ctx == nil || ctx.Err() != nil {
+ s.mu.Lock()
+ s.restarting = false
+ s.mu.Unlock()
+ return
+ }
+
+ // Clean up the old crashed instance so the orchestrator releases the
+ // profile slot and allocated port before we attempt a new launch.
+ if oldID != "" {
+ if err := s.orch.Stop(oldID); err != nil {
+ slog.Debug("autorestart: stop old instance (may already be gone)", "id", oldID, "err", err)
+ }
+ }
+
+ inst, err := s.orch.Launch(s.config.ProfileName, "", s.config.Headless, nil)
+ if err != nil {
+ slog.Error("autorestart: restart failed",
+ "oldId", oldID,
+ "err", err,
+ )
+ s.mu.Lock()
+ s.restarting = false
+ s.mu.Unlock()
+ return
+ }
+
+ s.mu.Lock()
+ s.instanceID = inst.ID
+ s.lastStart = time.Now()
+ count := s.restartCount
+ s.restarting = false
+ s.mu.Unlock()
+
+ slog.Info("autorestart: instance restarted",
+ "oldId", oldID,
+ "newId", inst.ID,
+ "attempt", count,
+ )
+
+ // Emit restarted event for dashboard/SSE consumers.
+ s.orch.EmitEvent("instance.restarted", inst)
+}
+
+// stabilityLoop resets the restart counter after the instance runs stably.
+func (s *Strategy) stabilityLoop() {
+ ticker := time.NewTicker(30 * time.Second)
+ defer ticker.Stop()
+
+ for {
+ s.mu.Lock()
+ ctx := s.ctx
+ s.mu.Unlock()
+
+ if ctx == nil {
+ return
+ }
+
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ s.mu.Lock()
+ if s.restartCount > 0 && !s.lastStart.IsZero() && time.Since(s.lastStart) > s.config.StableAfter {
+ slog.Info("autorestart: instance stable, resetting restart counter",
+ "id", s.instanceID,
+ "stableFor", time.Since(s.lastStart).Round(time.Second),
+ )
+ s.restartCount = 0
+ }
+ s.mu.Unlock()
+ }
+ }
+}
+
+// proxyToManaged ensures the managed instance is running, then proxies.
+func (s *Strategy) proxyToManaged(w http.ResponseWriter, r *http.Request) {
+ target, err := s.ensureRunning()
+ if err != nil {
+ web.Error(w, 503, err)
+ return
+ }
+ proxyHTTP(w, r, target+r.URL.Path)
+}
+
+// ensureRunning returns the URL of the managed instance if running.
+func (s *Strategy) ensureRunning() (string, error) {
+ if s.orch == nil {
+ return "", fmt.Errorf("no orchestrator configured")
+ }
+ if target := s.orch.FirstRunningURL(); target != "" {
+ return target, nil
+ }
+ return "", fmt.Errorf("instance not ready (may be restarting)")
+}
+
+func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
+ target := s.orch.FirstRunningURL()
+ if target == "" {
+ web.JSON(w, 200, map[string]any{"tabs": []any{}})
+ return
+ }
+ proxyHTTP(w, r, target+"/tabs")
+}
+
+func (s *Strategy) handleStatus(w http.ResponseWriter, r *http.Request) {
+ web.JSON(w, 200, s.State())
+}
+
+// proxyHTTP forwards a request to the target URL.
+func proxyHTTP(w http.ResponseWriter, r *http.Request, targetURL string) {
+ if r.URL.RawQuery != "" {
+ targetURL += "?" + r.URL.RawQuery
+ }
+
+ client := &http.Client{Timeout: 60 * time.Second}
+ proxyReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, r.Body)
+ if err != nil {
+ web.Error(w, 502, fmt.Errorf("proxy error: %w", err))
+ return
+ }
+ for k, vv := range r.Header {
+ for _, v := range vv {
+ proxyReq.Header.Add(k, v)
+ }
+ }
+
+ resp, err := client.Do(proxyReq)
+ if err != nil {
+ web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
+ return
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ for k, vv := range resp.Header {
+ for _, v := range vv {
+ w.Header().Add(k, v)
+ }
+ }
+ w.WriteHeader(resp.StatusCode)
+
+ buf := make([]byte, 32*1024)
+ for {
+ n, readErr := resp.Body.Read(buf)
+ if n > 0 {
+ _, _ = w.Write(buf[:n])
+ if f, ok := w.(http.Flusher); ok {
+ f.Flush()
+ }
+ }
+ if readErr != nil {
+ break
+ }
+ }
+}
diff --git a/internal/strategy/autorestart/autorestart_test.go b/internal/strategy/autorestart/autorestart_test.go
new file mode 100644
index 00000000..27e62150
--- /dev/null
+++ b/internal/strategy/autorestart/autorestart_test.go
@@ -0,0 +1,553 @@
+package autorestart
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/orchestrator"
+)
+
+// fakeBridge creates a test server that mimics a bridge instance.
+func fakeBridge(t *testing.T) *httptest.Server {
+ t.Helper()
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{"proxied": true, "path": r.URL.Path})
+ }))
+}
+
+func TestStrategy_Name(t *testing.T) {
+ s := New(AutorestartConfig{})
+ if s.Name() != "simple-autorestart" {
+ t.Errorf("expected 'simple-autorestart', got %q", s.Name())
+ }
+}
+
+func TestStrategy_DefaultConfig(t *testing.T) {
+ s := New(AutorestartConfig{})
+ if s.config.MaxRestarts != defaultMaxRestarts {
+ t.Errorf("expected MaxRestarts=%d, got %d", defaultMaxRestarts, s.config.MaxRestarts)
+ }
+ if s.config.InitBackoff != defaultInitBackoff {
+ t.Errorf("expected InitBackoff=%s, got %s", defaultInitBackoff, s.config.InitBackoff)
+ }
+ if s.config.StableAfter != defaultStableAfter {
+ t.Errorf("expected StableAfter=%s, got %s", defaultStableAfter, s.config.StableAfter)
+ }
+ if s.config.ProfileName != defaultProfileName {
+ t.Errorf("expected ProfileName=%q, got %q", defaultProfileName, s.config.ProfileName)
+ }
+ if !s.config.Headless {
+ t.Error("expected Headless=true by default")
+ }
+}
+
+func TestStrategy_CustomConfig(t *testing.T) {
+ s := New(AutorestartConfig{
+ MaxRestarts: 5,
+ InitBackoff: 1 * time.Second,
+ StableAfter: 10 * time.Minute,
+ ProfileName: "myprofile",
+ Headless: false,
+ HeadlessSet: true,
+ })
+
+ if s.config.MaxRestarts != 5 {
+ t.Errorf("expected MaxRestarts=5, got %d", s.config.MaxRestarts)
+ }
+ if s.config.InitBackoff != 1*time.Second {
+ t.Errorf("expected InitBackoff=1s, got %s", s.config.InitBackoff)
+ }
+ if s.config.StableAfter != 10*time.Minute {
+ t.Errorf("expected StableAfter=10m, got %s", s.config.StableAfter)
+ }
+ if s.config.ProfileName != "myprofile" {
+ t.Errorf("expected ProfileName=myprofile, got %q", s.config.ProfileName)
+ }
+ if s.config.Headless {
+ t.Error("expected Headless=false when explicitly set")
+ }
+}
+
+func TestStrategy_State_InitialStatus(t *testing.T) {
+ s := New(AutorestartConfig{})
+ state := s.State()
+
+ if state.Status != "starting" {
+ t.Errorf("expected initial status 'starting', got %q", state.Status)
+ }
+ if state.RestartCount != 0 {
+ t.Errorf("expected initial restartCount=0, got %d", state.RestartCount)
+ }
+ if state.MaxRestarts != defaultMaxRestarts {
+ t.Errorf("expected maxRestarts=%d, got %d", defaultMaxRestarts, state.MaxRestarts)
+ }
+}
+
+func TestStrategy_HandleCrash_IncrementsCounter(t *testing.T) {
+ s := New(AutorestartConfig{
+ MaxRestarts: 5,
+ InitBackoff: 1 * time.Millisecond, // Fast for testing
+ })
+ s.ctx, s.cancel = context.WithCancel(context.Background())
+ defer s.cancel()
+
+ // Set orchestrator so emitting events doesn't panic
+ orch := orchestrator.NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ s.orch = orch
+
+ // Simulate a crash without an actual running instance (launch will fail, but counter increments)
+ s.instanceID = "inst_test123"
+ s.handleCrash(s.ctx, "inst_test123")
+
+ s.mu.Lock()
+ count := s.restartCount
+ crashed := s.lastCrash
+ s.mu.Unlock()
+
+ if count != 1 {
+ t.Errorf("expected restartCount=1, got %d", count)
+ }
+ if crashed.IsZero() {
+ t.Error("expected lastCrash to be set")
+ }
+}
+
+func TestStrategy_HandleCrash_MaxRestartsExceeded(t *testing.T) {
+ var eventsMu sync.Mutex
+ var events []string
+
+ // Create a minimal orchestrator to capture events
+ orch := orchestrator.NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ orch.OnEvent(func(evt orchestrator.InstanceEvent) {
+ eventsMu.Lock()
+ events = append(events, evt.Type)
+ eventsMu.Unlock()
+ })
+
+ s := New(AutorestartConfig{
+ MaxRestarts: 2,
+ InitBackoff: 1 * time.Millisecond,
+ })
+ s.orch = orch
+ s.ctx, s.cancel = context.WithCancel(context.Background())
+ defer s.cancel()
+
+ s.instanceID = "inst_test123"
+
+ // Simulate crashes beyond the limit
+ s.restartCount = 2 // Already at max
+
+ s.handleCrash(s.ctx, "inst_test123")
+
+ s.mu.Lock()
+ count := s.restartCount
+ s.mu.Unlock()
+
+ if count != 3 {
+ t.Errorf("expected restartCount=3, got %d", count)
+ }
+
+ // Should have emitted "instance.crashed" event
+ time.Sleep(50 * time.Millisecond) // Allow event goroutine to fire
+ eventsMu.Lock()
+ found := false
+ for _, e := range events {
+ if e == "instance.crashed" {
+ found = true
+ }
+ }
+ eventsMu.Unlock()
+
+ if !found {
+ t.Error("expected 'instance.crashed' event when max restarts exceeded")
+ }
+}
+
+func TestStrategy_HandleEvent_IgnoresUnmanagedInstances(t *testing.T) {
+ s := New(AutorestartConfig{})
+ s.ctx, s.cancel = context.WithCancel(context.Background())
+ defer s.cancel()
+
+ s.instanceID = "inst_managed"
+
+ // Fire event for a different instance
+ s.handleEvent(orchestrator.InstanceEvent{
+ Type: "instance.stopped",
+ Instance: &bridge.Instance{ID: "inst_other"},
+ })
+
+ s.mu.Lock()
+ count := s.restartCount
+ s.mu.Unlock()
+
+ if count != 0 {
+ t.Errorf("expected restartCount=0 (unmanaged instance), got %d", count)
+ }
+}
+
+func TestStrategy_HandleEvent_DeliberateStopSkipsRestart(t *testing.T) {
+ s := New(AutorestartConfig{})
+ s.ctx, s.cancel = context.WithCancel(context.Background())
+ defer s.cancel()
+
+ s.instanceID = "inst_managed"
+ s.deliberate = true
+
+ s.handleEvent(orchestrator.InstanceEvent{
+ Type: "instance.stopped",
+ Instance: &bridge.Instance{ID: "inst_managed"},
+ })
+
+ s.mu.Lock()
+ count := s.restartCount
+ s.mu.Unlock()
+
+ if count != 0 {
+ t.Errorf("expected restartCount=0 (deliberate stop), got %d", count)
+ }
+}
+
+func TestStrategy_HandleEvent_NilInstanceIgnored(t *testing.T) {
+ s := New(AutorestartConfig{})
+ s.ctx, s.cancel = context.WithCancel(context.Background())
+ defer s.cancel()
+
+ // Should not panic
+ s.handleEvent(orchestrator.InstanceEvent{
+ Type: "instance.stopped",
+ Instance: nil,
+ })
+}
+
+func TestStrategy_StabilityReset(t *testing.T) {
+ s := New(AutorestartConfig{
+ StableAfter: 50 * time.Millisecond, // Short for testing
+ })
+
+ s.instanceID = "inst_test"
+ s.restartCount = 2
+ s.lastStart = time.Now().Add(-100 * time.Millisecond) // Already past stable period
+
+ s.ctx, s.cancel = context.WithCancel(context.Background())
+ defer s.cancel()
+
+ // Run stability check manually (simulating what the loop does)
+ s.mu.Lock()
+ if s.restartCount > 0 && !s.lastStart.IsZero() && time.Since(s.lastStart) > s.config.StableAfter {
+ s.restartCount = 0
+ }
+ count := s.restartCount
+ s.mu.Unlock()
+
+ if count != 0 {
+ t.Errorf("expected restartCount reset to 0, got %d", count)
+ }
+}
+
+func TestStrategy_StabilityNoResetTooEarly(t *testing.T) {
+ s := New(AutorestartConfig{
+ StableAfter: 1 * time.Hour, // Very long
+ })
+
+ s.instanceID = "inst_test"
+ s.restartCount = 2
+ s.lastStart = time.Now() // Just started
+
+ // Stability check should NOT reset
+ s.mu.Lock()
+ if s.restartCount > 0 && !s.lastStart.IsZero() && time.Since(s.lastStart) > s.config.StableAfter {
+ s.restartCount = 0
+ }
+ count := s.restartCount
+ s.mu.Unlock()
+
+ if count != 2 {
+ t.Errorf("expected restartCount=2 (not yet stable), got %d", count)
+ }
+}
+
+func TestStrategy_Stop_SetsDeliberate(t *testing.T) {
+ s := New(AutorestartConfig{})
+ s.ctx, s.cancel = context.WithCancel(context.Background())
+
+ if err := s.Stop(); err != nil {
+ t.Fatalf("Stop failed: %v", err)
+ }
+
+ s.mu.Lock()
+ if !s.deliberate {
+ t.Error("expected deliberate=true after Stop")
+ }
+ s.mu.Unlock()
+}
+
+func TestStrategy_EnsureRunning_NoOrch(t *testing.T) {
+ s := New(AutorestartConfig{})
+ _, err := s.ensureRunning()
+ if err == nil {
+ t.Error("expected error when no orchestrator")
+ }
+}
+
+func TestStrategy_ProxyToManaged_NoOrch_Returns503(t *testing.T) {
+ s := New(AutorestartConfig{})
+ req := httptest.NewRequest("GET", "/snapshot", nil)
+ rec := httptest.NewRecorder()
+ s.proxyToManaged(rec, req)
+
+ if rec.Code != 503 {
+ t.Errorf("expected 503, got %d: %s", rec.Code, rec.Body.String())
+ }
+}
+
+func TestStrategy_HandleTabs_NoInstances(t *testing.T) {
+ srv := fakeBridge(t)
+ defer srv.Close()
+
+ req := httptest.NewRequest("GET", "/tabs", nil)
+ rec := httptest.NewRecorder()
+ proxyHTTP(rec, req, srv.URL+"/tabs")
+
+ if rec.Code != 200 {
+ t.Errorf("expected 200, got %d", rec.Code)
+ }
+}
+
+func TestProxyHTTP_ForwardsRequest(t *testing.T) {
+ srv := fakeBridge(t)
+ defer srv.Close()
+
+ req := httptest.NewRequest("GET", "/snapshot", nil)
+ rec := httptest.NewRecorder()
+ proxyHTTP(rec, req, srv.URL+"/snapshot")
+
+ if rec.Code != 200 {
+ t.Errorf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+
+ var resp map[string]any
+ _ = json.Unmarshal(rec.Body.Bytes(), &resp)
+ if resp["path"] != "/snapshot" {
+ t.Errorf("expected path /snapshot, got %v", resp["path"])
+ }
+}
+
+func TestProxyHTTP_ForwardsQueryParams(t *testing.T) {
+ srv := fakeBridge(t)
+ defer srv.Close()
+
+ req := httptest.NewRequest("GET", "/screenshot?raw=true", nil)
+ rec := httptest.NewRecorder()
+ proxyHTTP(rec, req, srv.URL+"/screenshot")
+
+ if rec.Code != 200 {
+ t.Errorf("expected 200, got %d", rec.Code)
+ }
+}
+
+func TestProxyHTTP_UnreachableReturns502(t *testing.T) {
+ req := httptest.NewRequest("GET", "/snapshot", nil)
+ rec := httptest.NewRecorder()
+ proxyHTTP(rec, req, "http://localhost:1/snapshot")
+
+ if rec.Code != 502 {
+ t.Errorf("expected 502, got %d", rec.Code)
+ }
+}
+
+func TestStrategy_HandleStatus(t *testing.T) {
+ s := New(AutorestartConfig{MaxRestarts: 3})
+ s.instanceID = "inst_test"
+ s.restartCount = 1
+ s.lastStart = time.Now()
+
+ req := httptest.NewRequest("GET", "/autorestart/status", nil)
+ rec := httptest.NewRecorder()
+ s.handleStatus(rec, req)
+
+ if rec.Code != 200 {
+ t.Fatalf("expected 200, got %d", rec.Code)
+ }
+
+ var state RestartState
+ if err := json.Unmarshal(rec.Body.Bytes(), &state); err != nil {
+ t.Fatalf("failed to parse status response: %v", err)
+ }
+
+ if state.InstanceID != "inst_test" {
+ t.Errorf("expected instanceId=inst_test, got %q", state.InstanceID)
+ }
+ if state.RestartCount != 1 {
+ t.Errorf("expected restartCount=1, got %d", state.RestartCount)
+ }
+ if state.MaxRestarts != 3 {
+ t.Errorf("expected maxRestarts=3, got %d", state.MaxRestarts)
+ }
+ if state.Status != "running" {
+ t.Errorf("expected status=running, got %q", state.Status)
+ }
+}
+
+func TestStrategy_State_CrashedStatus(t *testing.T) {
+ s := New(AutorestartConfig{MaxRestarts: 2})
+ s.instanceID = "inst_test"
+ s.restartCount = 2 // At max
+
+ state := s.State()
+ if state.Status != "crashed" {
+ t.Errorf("expected status=crashed when restartCount>=maxRestarts, got %q", state.Status)
+ }
+}
+
+func TestStrategy_ExponentialBackoff(t *testing.T) {
+ s := New(AutorestartConfig{
+ InitBackoff: 100 * time.Millisecond,
+ })
+
+ // Simulate increasing backoff values
+ tests := []struct {
+ restartCount int
+ wantBackoff time.Duration
+ }{
+ {0, 100 * time.Millisecond}, // 100ms * 2^0
+ {1, 200 * time.Millisecond}, // 100ms * 2^1
+ {2, 400 * time.Millisecond}, // 100ms * 2^2
+ {3, 800 * time.Millisecond}, // 100ms * 2^3
+ {4, 1600 * time.Millisecond}, // 100ms * 2^4
+ }
+
+ for _, tt := range tests {
+ backoff := s.config.InitBackoff * time.Duration(1<<uint(tt.restartCount))
+ if backoff != tt.wantBackoff {
+ t.Errorf("restartCount=%d: expected backoff=%s, got %s", tt.restartCount, tt.wantBackoff, backoff)
+ }
+ }
+}
+
+func TestStrategy_HandleCrash_RestartingEvent(t *testing.T) {
+ var eventsMu sync.Mutex
+ var events []string
+
+ orch := orchestrator.NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ orch.OnEvent(func(evt orchestrator.InstanceEvent) {
+ eventsMu.Lock()
+ events = append(events, evt.Type)
+ eventsMu.Unlock()
+ })
+
+ s := New(AutorestartConfig{
+ MaxRestarts: 5,
+ InitBackoff: 1 * time.Millisecond,
+ })
+ s.orch = orch
+ s.ctx, s.cancel = context.WithCancel(context.Background())
+ defer s.cancel()
+
+ s.instanceID = "inst_test123"
+
+ // First crash — should emit "instance.restarting"
+ s.handleCrash(s.ctx, "inst_test123")
+
+ time.Sleep(50 * time.Millisecond)
+ eventsMu.Lock()
+ found := false
+ for _, e := range events {
+ if e == "instance.restarting" {
+ found = true
+ }
+ }
+ eventsMu.Unlock()
+
+ if !found {
+ t.Error("expected 'instance.restarting' event on first crash")
+ }
+}
+
+func TestStrategy_ContextCancellation(t *testing.T) {
+ s := New(AutorestartConfig{
+ InitBackoff: 10 * time.Second, // Long backoff
+ })
+ ctx, cancel := context.WithCancel(context.Background())
+ s.ctx = ctx
+ s.cancel = cancel
+ s.instanceID = "inst_test"
+
+ // Cancel context immediately
+ cancel()
+
+ // handleCrash should return quickly due to context cancellation
+ done := make(chan struct{})
+ go func() {
+ s.handleCrash(ctx, "inst_test")
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ // Success — returned quickly
+ case <-time.After(2 * time.Second):
+ t.Error("handleCrash did not respect context cancellation")
+ }
+}
+
+func TestStrategy_State_RestartingStatus(t *testing.T) {
+ s := New(AutorestartConfig{MaxRestarts: 3})
+ s.instanceID = "inst_test"
+ s.restarting = true
+
+ state := s.State()
+ if state.Status != "restarting" {
+ t.Errorf("expected status=restarting, got %q", state.Status)
+ }
+}
+
+func TestStrategy_HandleEvent_SkipsDuplicateDuringRestart(t *testing.T) {
+ s := New(AutorestartConfig{})
+ s.ctx, s.cancel = context.WithCancel(context.Background())
+ defer s.cancel()
+
+ s.instanceID = "inst_managed"
+ s.restarting = true // Already restarting
+
+ // Sending another stopped event should be ignored
+ s.handleEvent(orchestrator.InstanceEvent{
+ Type: "instance.stopped",
+ Instance: &bridge.Instance{ID: "inst_managed"},
+ })
+
+ s.mu.Lock()
+ count := s.restartCount
+ s.mu.Unlock()
+
+ if count != 0 {
+ t.Errorf("expected restartCount=0 (skipped during restart), got %d", count)
+ }
+}
+
+// --- Mock runner for orchestrator tests ---
+
+type mockRunner struct {
+ portAvail bool
+}
+
+type mockCmd struct{}
+
+func (m *mockCmd) Wait() error { return nil }
+func (m *mockCmd) PID() int { return 1234 }
+func (m *mockCmd) Cancel() {}
+
+func (r *mockRunner) Run(_ context.Context, _ string, _ []string, _, _ io.Writer) (orchestrator.Cmd, error) {
+ return &mockCmd{}, nil
+}
+
+func (r *mockRunner) IsPortAvailable(_ string) bool {
+ return r.portAvail
+}
diff --git a/internal/strategy/strategy_test.go b/internal/strategy/strategy_test.go
index fa506307..fbb6fea1 100644
--- a/internal/strategy/strategy_test.go
+++ b/internal/strategy/strategy_test.go
@@ -6,6 +6,7 @@ import (
"github.com/pinchtab/pinchtab/internal/strategy"
// Register strategies via init()
+ _ "github.com/pinchtab/pinchtab/internal/strategy/autorestart"
_ "github.com/pinchtab/pinchtab/internal/strategy/explicit"
_ "github.com/pinchtab/pinchtab/internal/strategy/simple"
)
@@ -30,6 +31,16 @@ func TestRegistry_SimpleRegistered(t *testing.T) {
}
}
+func TestRegistry_SimpleAutorestartRegistered(t *testing.T) {
+ s, err := strategy.New("simple-autorestart")
+ if err != nil {
+ t.Fatalf("simple-autorestart strategy not registered: %v", err)
+ }
+ if s.Name() != "simple-autorestart" {
+ t.Errorf("expected name 'simple-autorestart', got %q", s.Name())
+ }
+}
+
func TestRegistry_UnknownStrategy(t *testing.T) {
_, err := strategy.New("nonexistent")
if err == nil {
@@ -49,4 +60,7 @@ func TestRegistry_Names(t *testing.T) {
if !found["simple"] {
t.Error("simple not in names")
}
+ if !found["simple-autorestart"] {
+ t.Error("simple-autorestart not in names")
+ }
}